diff --git a/docs/development.md b/docs/development.md index 7873419..2cc7c5f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -201,8 +201,9 @@ case-sensitive, and an unknown one is ignored. | `RX_VK_SETTLE_GATE=1`, `=2` | (Triforce, 11-22, off by default; the performance audit's SYNC-29, after Source A's; `gpu/vk/settle_gate.h`) A CPU read that lets the stopped queues whose waits are met go on (the readback's look, which `RX_VK_RB_SETTLE=1` turns on, and the two looks made for a range a texture may be in) takes the order's lock whenever a queue is stopped, and that lock is held through whole replays and presents. With the gate a site looks only while a queue is stopped **and** the CPU has signalled an event since the last finished look, or a stopped queue waits on an event whose value is read from guest memory; any other met wait was met by a signal in the stream, and the thread that replayed it looked before it let the lock go. `1`: the readback's look; `2`: the texture sites' too (new ground: those looks order the exposure meter's readback, so `2` needs the lab's flicker count). Unset or `0`: every look as before. The `RX_VK_LAB_AB` knobs `settlegate` and `texgate` are `1` and `2` in their phases (`rbsettle+settlegate` is the pair the audit asks for). The 3000-readback line and the texture catch-ups' 300-call line count the looks made and skipped | | `RX_VK_READBACK_LATE=[,]`, `RX_VK_LOG_READBACK_RANGES=1` | (Triforce, 11-22, the performance audit's SYNC-19, after Source A's; `gpu/vk/readback_late.h`) Ranges the CPU reads back **without** the wait for their write-back, from what guest memory holds (the last write-back made): a rule is a size in hex (`3980`: every range of 0x3980 bytes, the culling camera block Source A reads late by default) or `newest` (a range whose writer is the newest submission handed out: the game cannot have waited for it). **Unset: no rule**, every readback waits as before, until the lab has run it where the waits are long (a handheld, an AMD iGPU, a weak discrete card); `=0`: none either. The `RX_VK_LAB_AB` knob `rblate` is `3980` in its phases. A late read hands the game the frame before's values, and when the CPU resets a range read late the pending write-back lands over its reset (the exposure meter's flashes): `newest` can catch that meter, so it is never a default. `RX_VK_LOG_READBACK_RANGES=1`: with every 3000-readback line, the 12 ranges that waited longest (readbacks, waits, ms, how often their writer was the newest submission, how often read late), to find such ranges on other hardware; nothing is noted without it | | `RX_VK_WB_WAIT_REC=1`, `=2` | (Triforce, off by default; the handoff's §12.9, `gpu/vk/wb_rec_wait.h`) A wait for a write-back still on the GPU (a capture's late pages on the game's submitting thread, a read or binding of a page put off) ends once the recording its submission was finished in is done on the GPU, not when the submissions' timeline reaches it: that timeline is held below any submission stopped at an event wait, and the lab's Market had 20-46 ms waits of the game's thread with the GPU 4 submissions behind. Whatever the switch, the wait for the recording comes first and the rest is counted: the stall line's `N of them X ms after their writer's recording was done`, the `late:` line's `ms of the wait after the recording that finished it was done`, the frame trace's `wb_held_ms`. Off: the captures' late-page wait orders something not known yet (`RX_VK_LATE_NEW`), so it is tried with the lab's flicker count first. (Triforce, 11-22, the performance audit's SYNC-122, after Source B's) The reads' side: a readback whose write-back is not recorded yet waited on the submissions' timeline with no bound and no second look; it is counted now (the 3000-readback line's second line), and the stall line names the held part by caller (takes, reads, binds, readbacks). The variable is a mode: `1` as above, and such a readback waits in 1 ms slices, looks its writer's recording up between them and ends with it; `2` is the check, where no wait ends earlier and the readback's slices count the part after the recording was done (what `1` would not have waited); unset, `0` or any other text: off, one wait as before. The check of the pages a later write-back changes (the audit's SYNC-101) is not built. `RX_VK_TL_REC=1` and the lab knob `tlrec` ended a capture's wait at a submission's first part, before its burst's write-backs were recorded: they now end it at the recording the submission was finished in, as `=1` here does; `RX_VK_TL_REC=2` keeps the old lookup | -| `RX_VK_RB_REC_END=0` | (Triforce, 11-27; `gpu/vk/wb_rec_wait.h` `readback_wait`, `tests/test_readback_rec_end.py`) **11-28: modes.** Unset or `=2` (the default): the last-part wait below only for a range the CPU writes after reading it (the exposure meter; the pages the write watch's collections name, `vk_memory.cpp` `memory_rb_cpu_written`), the first part, as before, for a range it only reads (a frame late at worst). `=1`: every readback, as 0.8.5 (its worker-thread reads of read-only results waited ~5 ms each, 98 -> 82 fps in Hyrule Field at the owner's settings). `=0`: off, as 0.8.5.1. A CPU readback of GPU results waits for the **last** part of the recording that writes it back. A recording made in parts (`RX_VK_CHUNK`'s counted parts, 240 draws on NVIDIA's driver, or Threaded rendering's pass-end parts) writes back at each part's end, all under the recording's one value, and the readback's wait looked that value up in a table that keeps the first part (`RX_VK_REC_LAST`, off, keeps a later one only when the value comes again). A read that came between the first part's submit and the last one's got what guest memory held then: OoT's exposure meter read as 0 where the GPU's sum was still to come, then the sum landed over the CPU's next 0 and the next frame added to it. In a still view the picture flashed brighter for a frame and stepped down: 3 times at Hyrule Field in a four-scene held-camera benchmark run (`HOS_BENCH_PAN=0`), on v0.8.4 too. Now the readback looks up the newest part submitted and whether it ended the recording: an ended recording's last part is waited for; one that goes on, the part found (the old wait), then 1 ms slices of the submissions' timeline between looks until it ends or the timeline reaches the value. A value not recorded yet goes to the fallback as before. `RX_VK_LOG_READBACK_ZERO=1` now says the writer's recording's first part, newest part and the recordings done at a zero read; the 3000-readback line counts the reads that waited past a part. Measured on an RTX 5090 (held camera): the meter's zero reads after a wait went from 0-10 a run to 0 in 4 runs, and Hyrule Field's flashes from 3 a run to 0. The rule waits 350-550 times a run, 2-5 ms each, on the game's worker threads, nearly all at a scene's load and in its first seconds. Frame rate unchanged (144.5 against 143.2 fps, 3 runs each); Hyrule Field's p99 frame time 9-13% higher. Waiting only for the part that wrote the range would be cheaper (not done). The rule's branches stay out of `invalidate` and submit_recording's registration, so that the renderer's play profile still matches them. `0`: the first part, as before | +| `RX_VK_RB_REC_END=0` | (Triforce, 11-27; `gpu/vk/wb_rec_wait.h` `readback_wait`, `tests/test_readback_rec_end.py`) **11-28: modes.** Unset: `=3` where a submission's parts end at the game's render passes (`RX_VK_PART_PASS_END`: NVIDIA's driver's default, or Threaded rendering; since 11-29, the owner's decision), else `=2`. `=2`: the last-part wait below only for a range the CPU writes after reading it (the exposure meter; the pages the write watch's collections name, `vk_memory.cpp` `memory_rb_cpu_written`), the first part, as before, for a range it only reads (a frame late at worst). `=1`: every readback, as 0.8.5 (its worker-thread reads of read-only results waited ~5 ms each, 98 -> 82 fps in Hyrule Field at the owner's settings). `=0`: off, as 0.8.5.1. **11-29: `=3`** (the default with the pass-end parts, with `RX_VK_PART_RB=32`). Mode 2, and a range the CPU only reads waits for the part that copied it back (`readback_range_wait`; `vk_memory.cpp` `memory_wb_part_seq`, the part's batch noted at its submit), not the recording's first part; while no part submitted has copied it, the newest part and 1 ms slices as below, until its part is known or the recording ends. Why: with the parts ending at the game's render passes (`RX_VK_PART_PASS_END`, NVIDIA's driver's default since 11-29) the first part is ~32 draws, and a read-only result written back in a later part was read as it was a frame before. One of them moves OoT's exposure: with the camera moving the whole picture went ~5 levels brighter for 15 presents and back, 3 times in 30 s at Kakariko (a moving-camera picture check, 160 x 90 shots of every present), never with `=1` or the counted parts. The 3000-readback line counts these waits and those whose part came after the first. A CPU readback of GPU results waits for the **last** part of the recording that writes it back. A recording made in parts (`RX_VK_CHUNK`'s counted parts, 240 draws on NVIDIA's driver, or Threaded rendering's pass-end parts) writes back at each part's end, all under the recording's one value, and the readback's wait looked that value up in a table that keeps the first part (`RX_VK_REC_LAST`, off, keeps a later one only when the value comes again). A read that came between the first part's submit and the last one's got what guest memory held then: OoT's exposure meter read as 0 where the GPU's sum was still to come, then the sum landed over the CPU's next 0 and the next frame added to it. In a still view the picture flashed brighter for a frame and stepped down: 3 times at Hyrule Field in a four-scene held-camera benchmark run (`HOS_BENCH_PAN=0`), on v0.8.4 too. Now the readback looks up the newest part submitted and whether it ended the recording: an ended recording's last part is waited for; one that goes on, the part found (the old wait), then 1 ms slices of the submissions' timeline between looks until it ends or the timeline reaches the value. A value not recorded yet goes to the fallback as before. `RX_VK_LOG_READBACK_ZERO=1` now says the writer's recording's first part, newest part and the recordings done at a zero read; the 3000-readback line counts the reads that waited past a part. Measured on an RTX 5090 (held camera): the meter's zero reads after a wait went from 0-10 a run to 0 in 4 runs, and Hyrule Field's flashes from 3 a run to 0. The rule waits 350-550 times a run, 2-5 ms each, on the game's worker threads, nearly all at a scene's load and in its first seconds. Frame rate unchanged (144.5 against 143.2 fps, 3 runs each); Hyrule Field's p99 frame time 9-13% higher. Waiting only for the part that wrote the range would be cheaper (not done). The rule's branches stay out of `invalidate` and submit_recording's registration, so that the renderer's play profile still matches them. `0`: the first part, as before | | `RX_VK_LATE_QUEUE=1` or `0` | (Triforce, 11-20; 11-23) A capture's late pages (pages a submission still on the GPU writes back: OoT's exposure meter and the per-frame pools) waited for at the queue's next submit, not at the capture's take (`gpu/vk/vk_memory.cpp` `late_queue_on`). Unset: at the queue, except while the replay's submits are held (`RX_VK_BATCH`, on by default with Mesa's RADV): there a held submit applies no fix, the fixes wait for the batch's flush and copy guest memory the game has written again for its next frame, and the replay reads those slots live meanwhile: the lighting and exposure flicker on Linux AMD from 50-90 s into play in v0.7.0. `1`: at the queue with held submits too (v0.7.0 as shipped); `0`: at the take on every driver, as before 11-20. The log says `vk: late pages' wait ...` when it is first asked and when the answer changes | +| `RX_VK_LATE_PART=1` | (Triforce, 11-29, the performance session; `gpu/vk/vk_replay.cpp` `late_fix_part_wait`, `gpu/vk/vk_memory.cpp` `late_pages_part`, `tests/test_readback_rec_end.py`; **off unless set**, the `RX_VK_LAB_AB` knob `latepart`) The queue's wait for the late pages (`RX_VK_LATE_QUEUE`, above) waits for the part that wrote the pages back last, on the recordings' timeline, not for their value, which a recording made in parts signals with its last part. The part is found at the take, where the fix is put off (its recording was sent whole by then, so no later part of it writes the pages again): the newest part among the write-backs still in flight over the fix's pages; one not known (its part not submitted, the list cut) or none found: the value, as before. The `vk: RX_VK_LATE_PART (600 takes)` line counts the waits made at a part and the fixes whose part was not known. Measured (RTX 5090, a held camera, 200 s, paired phases): +0.61% at Lake Hylia (0.031 ± 0.037 ms a frame), +0.45% at the Market (the owner's options), +0.69% at Kakariko (the defaults): the pages are written back in one of a frame's last parts, so the wait is ~0.1 ms shorter (0.70 -> ~0.55 ms each at Lake Hylia). Every fix's part was known. The moving-camera picture check clean (Kakariko 6.0, the Market 8.4). Not measured: other cards; with `RX_VK_BATCH` (no fix is put off while submits are held) | | `RX_VK_LATE_INLINE=1` | (Triforce, 11-22, the performance audit's MEM-80, after Source B's; `gpu/vk/late_inline.h`; **off unless set**, not yet run in the game) A late page (one the CPU wrote while a submission still on the GPU writes it back) is waited for and taken again by default (`RX_VK_LATE_QUEUE`: at the queue's next submit). `RX_VK_LATE_NEW=1` (knob `latenew`) turns four no-wait rules on, each of which brought brightness steps back at the Castle Town save. This turns on the partial rule alone (knob `lateinline`): a page only part of which a submission on the GPU writes back has its other parts synced from the capture, no wait; pages of pools with no mirror, texture storage, pages written back whole and pages whose write-backs' ranges are not known are waited for as by default. The partial rule, here and under `RX_VK_LATE_NEW`, now asks which ranges are still on the GPU against the progress the capture read before its copies, not a second read at the take: a write-back done between the two counts as in flight, and its range is not synced from the older copy. `RX_VK_LOG_LATE` shows the pages waited for | | `RX_VK_PASS_TIMING=1` or `2` | GPU time per pass (2: per program too), logged every 600 presents | | `RX_VK_SLOW_LOG=` | The replay's times for each frame that took longer than this | @@ -237,7 +238,8 @@ a frame; the two knobs are now asked once a phase and once a submission. | `RX_VK_NO_SPILLING_RATE=1` | (Triforce, the performance audit's PIPE-55, after Source A's; Linux build only) The Linux build sets `shader_spilling_rate=2` in its environment before the Vulkan instance is made (`gpu/vk/mesa_spilling.h`, `gpu/vk/vk_main.cpp` `create_instance`), unless the player has set that variable. Only Mesa's Intel shader compiler reads it: a program whose registers do not fit is built in fewer, larger steps (Source A, an Iris Xe: one compute program not built after 20 minutes and 13 GB, 32 s and 1.7 GB at rate 2). `=1` sets nothing, so the driver keeps its own rate. On Mesa's Intel driver the log has `vk: Mesa's Intel compiler spills at rate ...`. The Windows build sets nothing: under Proton, add `shader_spilling_rate=2` to the launch options. Not run on an Intel GPU here | | `RX_VK_DRIVER_FAULTS=0` or `2` | (Triforce, 11-22, the performance audit's PIPE-57, after Source A's; `gpu/vk/driver_faults.h`) On AMD's own Windows driver only (`VK_DRIVER_ID_AMD_PROPRIETARY`), unless `0`: a program whose pipeline build faulted inside the driver is not asked of the driver again this run, and its key is appended to `triforce_driver_faults.txt` beside the executable (one line: vendor, driver version, program) by the fault's handler, before a fault during the start's shader work restarts the game, so the next start with that driver skips it instead of faulting again (`vk: driver faults: N programs ... kept out of it`; delete the file to try them again, another driver version ignores its lines). And one build of a program is inside the driver at a time: a second waits outside it, a probe of the caches is told a compile is required. `2`: on every driver (the lab's); `0`: nowhere. On other drivers nothing of it runs (`gpu/vk/vk_draw.cpp` `fault_quarantine`, `build_graphics`, `guarded_graphics`) | | `RX_VK_PASS_BARRIER=game` or `full` | The barrier a draw pass starts with (`gpu/vk/pass_barrier.h`). `game`: a pass right after another, with nothing recorded between (no barrier of the game's, no copy, clear, uniform update or dispatch), waits for the earlier work in its fragment stages only, so its vertex, task and mesh work may overlap the earlier pass's fragments; a pass the replay itself split off for a hazard (`a pass of its own` in the log) and `RX_VK_BARRIER_EVERY_DRAW`'s keep a full one. (Triforce, P4) "Nothing recorded between" is the command buffer's own count (`RX_VK_BARRIER_CONTEXT`), so beside the Replay helper threads too. `full`: a full barrier at every pass start, as before. Unset: `game` with NVIDIA's driver, `full` on every other card. The log's `vk: pass barriers:` line says which, and the frame statistics' `pass starts ordered in their fragment stages only` how many a frame | -| `RX_VK_CHUNK=` | (Triforce, 11-22, the performance audit's SYNC-66, after Source B's; `gpu/vk/barrier_rules.h` `part_draws`) How many draws and dispatches a part of a long submission has in a serial replay: the GPU starts on the first part while the rest is recorded, and each split costs a queue submit, two full barriers and the part's bookkeeping (about 27 a frame at 120). Unset: the driver's default, **240 on NVIDIA's driver** (its driver id, `VK_DRIVER_ID_NVIDIA_PROPRIETARY`, on Windows and Linux; 11-26, measured on v0.8.3: RTX 5090 at 2560 x 1440, the benchmark's four scenes with the camera held, `RX_VK_PARALLEL=0`, the knob `chunk:240` against 120 in neighbouring phases: 0.37, 0.18, 0.21 and 0.08 ms off the frame at Lake Hylia, the Market, Hyrule Field and Kakariko, +0.8 to +3.1% fps; on v0.8.4 (11-27, the same way, 300 s a scene): 0.55 ± 0.20 ms at Lake Hylia (6.3% fps), 0.42 ± 0.03 ms in the Market (5.1%), 0.26 ± 0.06 ms at Kakariko (3.5%), and at Hyrule Field, the fastest scene (183 fps), 120 was 0.05 ± 0.03 ms faster (0.9%); with this PC's default helpers 0.05 to 0.06 ms (0.8%, at Lake Hylia not significant); with the GPU slowed to about half busy (`RX_VK_SIM_GPU_SLOW=8`) 0.45 ± 0.06 ms at Lake Hylia (5.2%); 480 was mixed and 960 lost about 1.2 ms everywhere, the write-backs the game waits for starting too late; fewer cuts change which occlusion counts arrive in time, fewer straddling a split and some finishing later, and a count is written only when whole, so none is ever hidden; measured only on that RTX 5090 desktop, with the replay thread alone but for the default helpers' figure: 4-core and laptop PCs, NVIDIA's Linux driver and capped frame rates are not measured) and **120 on every other driver** (NVK, Dozen and Venus on an NVIDIA card too) until the lab has measured one (Source B cuts at 128 where the GPU idles while the CPU records and at 4096 on desktop drivers); `0`: whole submissions, never split; `120`: the size before, whatever the default says (on NVIDIA's driver too). The size, its default and the knob apply where parts are cut by count: with Threaded rendering off (the default) or `RX_VK_PART_PASS_END=0`. With Threaded rendering on and `RX_VK_PART_PASS_END` unset, a part ends where the game ends its render pass, from 120 draws (the first part from 32) to 512 (the log's `vk: a submission's parts end where the game has ended its render pass` line), and neither default is read: leave `RX_VK_CHUNK` unset there, because any value turns those parts off: a number above 0, 120 too, cuts every n draws wherever that falls, inside the game's passes too, and any other value (0, empty, negative) gives whole submissions (`RX_VK_PART_PASS_END=1` gives those parts on any run, and the variable is then read only in the knob's phases). The size was read once into a static: now the `RX_VK_LAB_AB` knob `chunk:` changes it in its phases while the variable is unset (`RX_VK_LAB_AB=chunk:120,chunk:480` with `RX_VK_PARALLEL=0` and Threaded rendering off; with Threaded rendering's parts on, the knob's phases are counted and the phases between end at the game's passes, so add `RX_VK_PART_PASS_END=0` to compare sizes). The log's first `vk: a submission's parts:` line says the size in force and the driver's default, and when Threaded rendering's parts decide instead | +| `RX_VK_CHUNK=` | (Triforce, 11-22, the performance audit's SYNC-66, after Source B's; `gpu/vk/barrier_rules.h` `part_draws`) How many draws and dispatches a part of a long submission has in a serial replay: the GPU starts on the first part while the rest is recorded, and each split costs a queue submit, two full barriers and the part's bookkeeping (about 27 a frame at 120). Unset: the driver's default, **240 on NVIDIA's driver** (its driver id, `VK_DRIVER_ID_NVIDIA_PROPRIETARY`, on Windows and Linux; 11-26, measured on v0.8.3: RTX 5090 at 2560 x 1440, the benchmark's four scenes with the camera held, `RX_VK_PARALLEL=0`, the knob `chunk:240` against 120 in neighbouring phases: 0.37, 0.18, 0.21 and 0.08 ms off the frame at Lake Hylia, the Market, Hyrule Field and Kakariko, +0.8 to +3.1% fps; on v0.8.4 (11-27, the same way, 300 s a scene): 0.55 ± 0.20 ms at Lake Hylia (6.3% fps), 0.42 ± 0.03 ms in the Market (5.1%), 0.26 ± 0.06 ms at Kakariko (3.5%), and at Hyrule Field, the fastest scene (183 fps), 120 was 0.05 ± 0.03 ms faster (0.9%); with this PC's default helpers 0.05 to 0.06 ms (0.8%, at Lake Hylia not significant); with the GPU slowed to about half busy (`RX_VK_SIM_GPU_SLOW=8`) 0.45 ± 0.06 ms at Lake Hylia (5.2%); 480 was mixed and 960 lost about 1.2 ms everywhere, the write-backs the game waits for starting too late; fewer cuts change which occlusion counts arrive in time, fewer straddling a split and some finishing later, and a count is written only when whole, so none is ever hidden; measured only on that RTX 5090 desktop, with the replay thread alone but for the default helpers' figure: 4-core and laptop PCs, NVIDIA's Linux driver and capped frame rates are not measured) and **120 on every other driver** (NVK, Dozen and Venus on an NVIDIA card too) until the lab has measured one (Source B cuts at 128 where the GPU idles while the CPU records and at 4096 on desktop drivers); `0`: whole submissions, never split; `120`: the size before, whatever the default says (on NVIDIA's driver too). The size, its default and the knob apply where parts are cut by count: with Threaded rendering off (the default) on a driver other than NVIDIA's, or `RX_VK_PART_PASS_END=0` (on NVIDIA's driver the 240 above is in force only then, since 11-29). With Threaded rendering on, or on NVIDIA's driver (the `RX_VK_PART_PASS_END` row), and `RX_VK_PART_PASS_END` unset, a part ends where the game ends its render pass, from 120 draws (the first part from 32) to 512 (the log's `vk: a submission's parts end where the game has ended its render pass` line), and neither default is read: leave `RX_VK_CHUNK` unset there, because any value turns those parts off: a number above 0, 120 too, cuts every n draws wherever that falls, inside the game's passes too, and any other value (0, empty, negative) gives whole submissions (`RX_VK_PART_PASS_END=1` gives those parts on any run, and the variable is then read only in the knob's phases). The size was read once into a static: now the `RX_VK_LAB_AB` knob `chunk:` changes it in its phases while the variable is unset (`RX_VK_LAB_AB=chunk:120,chunk:480` with `RX_VK_PARALLEL=0` and Threaded rendering off; with Threaded rendering's parts on, the knob's phases are counted and the phases between end at the game's passes, so add `RX_VK_PART_PASS_END=0` to compare sizes). The log's first `vk: a submission's parts:` line says the size in force and the driver's default, and when Threaded rendering's parts decide instead | +| `RX_VK_PART_PASS_END=0` or `=1`, `RX_VK_PART_FIRST=`, `RX_VK_PART_MIN=`, `RX_VK_PART_MAX=`, `RX_VK_PART_RB=`, `RX_VK_PART_IDLE=` | (Triforce; `gpu/vk/vk_replay.cpp` `pass_end_parts`, `maybe_split`; **on by default on NVIDIA's driver since 11-29** (`gpu/vk/barrier_rules.h` `part_pass_end_default`, by the driver id as for `RX_VK_CHUNK`'s 240) and with Threaded rendering on; off by default on every other driver) A long submission's parts end where the game has ended its render pass instead of every `RX_VK_CHUNK` draws wherever that falls: a submission's first part from `RX_VK_PART_FIRST` (32) draws and dispatches, the rest from `RX_VK_PART_MIN` (120), at `RX_VK_PART_MAX` (512) at the latest. Why on NVIDIA's driver: the frame trace (`HOS_FT`) at Lake Hylia showed the GPU idle about 0.9 ms of a 5.4 ms frame once the submission that waits on another queue's event was released: the work it had held was recorded as one burst and reached the GPU only at the first 240-draw cut, while a first part from 32 starts the GPU sooner. Measured 11-29 on v0.8.5.2 (RTX 5090, driver 621.40, Windows, 16 threads; the benchmark's seven places with the camera turning, 3 runs of each arm interleaved, `=1` against unset, which cut every 240): with the defaults 183.8 (183.6-184.0) to 193.8 (193.6-194.3) fps, +5.5%, every scene faster (+1.6% at Kokiri to +7.6% at Kakariko), the 1% lows +3.9% (+1.6 to +7.0%); with ULTRA HD and Evil HD on 170.2 (169.2-170.7) to 178.8 (177.9-179.3), +5.1% (+0.8% at Kokiri, +4.9 to +6.8% elsewhere), the 1% lows +3.6% (Kokiri -2.1%, inside the runs' spread); the median frame 0.1 to 0.45 ms shorter, frames over 8 ms fewer in every scene but Kokiri with ULTRA HD (12.6 against 14.4 in 1000), and frames over 10 to 12 ms, under 4 in 1000 everywhere, a few more with ULTRA HD at the Deku Tree, Kokiri and Death Mountain Trail and fewer or as many elsewhere. In the run at a held camera (`=1` with the `RX_VK_LAB_AB` knob `chunk:240`, 200 s, each knob phase against the phases beside it): the 240-draw cut cost 0.385 ± 0.017 ms a frame at Lake Hylia with ULTRA HD (6.97% fps, 63 pairs), 0.371 ± 0.021 ms there with the GPU slowed (`RX_VK_SIM_GPU_SLOW=8`, 6.6%), and nothing measurable in two slower views, the Market with ULTRA HD (137 fps, 0.049 ± 0.056 ms) and Kakariko with the defaults (155 fps, 0.012 ± 0.038 ms). The picture: a shot of every present at four places with the camera held had no flash, step or blink the unset run did not have. **11-29 afternoon: a flicker with the camera moving.** The whole picture went ~5 levels brighter for 15 presents and back (3 of 4 moving-camera runs at Kakariko; 160 x 90 shots of every present): a readback of a range the CPU only reads waited for the first part, here ~32 draws, and read a result written back in a later part as it was a frame before (`RX_VK_RB_REC_END=3`'s row). **`RX_VK_PART_RB=`** (32 unset where `RX_VK_RB_REC_END` is 3, the default with these parts; `=0`, or another mode set, off; the `RX_VK_LAB_AB` knob `partrb:`): a part that queues the write-back of a page the CPU reads back (`vk_memory.cpp` `rb_write_note`, at the written binding) ends from draws, not `RX_VK_PART_MIN`, so that `=3`'s wait for it is shorter. In the run at a held camera with `RX_VK_RB_REC_END=3` (200 s, paired phases): `partrb:32` +8.5% at Death Mountain Trail (0.450 ± 0.157 ms a frame), +1.7% at Lake Hylia, -0.4% at the Market (ULTRA HD on), -0.8% at Kakariko (the defaults); `partrb:1` +6.5%, -1.7%, -0.8%, -0.6%. **`RX_VK_PART_IDLE=`** (off unset; `partidle:`): a part ends from draws once the GPU has done everything sent (the recordings' timeline at `rec_seq`, `part_min_now`): +0.7%, -1.0%, +0.1%, -0.2%, nothing measurable. Both are asked through calls, so `maybe_split` and the binding keep their control flow (and their renderer profile). The benchmark tour (RTX 5090, 180 s, the PC quiet; mode 2 against `RX_VK_RB_REC_END=3 RX_VK_PART_RB=32`): ULTRA HD and Evil HD on 176.4 against 177.8 fps (+0.8%; rounds of +5.2%, +1.2%, -3.9%), the defaults 188.7 against 185.1 (-1.9%, 2 rounds): within the spread. The moving-camera picture check clean with both (Kakariko 6.2). Both the default with these parts since 11-29 (the owner's decision); `RX_VK_RB_REC_END=2` gives the parts as `3f9728b` made them (it turns `RX_VK_PART_RB` off too). Not measured: other NVIDIA cards, laptops, 4-core PCs, NVIDIA's Linux driver, capped frame rates. `=0`: counted parts (`RX_VK_CHUNK` or the driver's default) on any run, the size before 11-29 on NVIDIA's driver; `=1`: these parts on any run and driver, `RX_VK_CHUNK` set too (then read only in the `RX_VK_LAB_AB` knob `chunk:`'s phases); unset with `RX_VK_CHUNK` set: counted parts. The log's `vk: a submission's parts end where the game has ended its render pass` line says when they are in force and why | | `RX_VK_SPLIT_BARRIER=pass` or `full` | (Triforce) A long submission goes to the GPU in parts (`RX_VK_CHUNK`: 240 draws and dispatches on NVIDIA's driver, 120 on every other); `gpu/vk/barrier_rules.h`. `pass`: a pass open at a part's split goes on in the next part, begun again with the same targets behind a barrier of its attachments' outputs alone and with what its draws sampled and wrote, so the GPU does not drain between two draws of one of the game's passes; where the part's end records anything (its uniform updates, its write-backs) or an event's write is held, the full barriers as before. A parallel replay's segments are not split into parts: each begins and ends with a full barrier, so nothing goes on across a segment's edge. `full`: a full barrier at each part's end and the next one's start, as before. Unset: `full` on every card ((Triforce, 11-22, SYNC-66) this row said `pass` with NVIDIA's driver; `pass` has been off unless set since 11-16, when the lab's Market showed no gain from it: `barrier_rules.h` `split_in_pass`). The log's `vk: a submission's parts:` lines say which and, every 3,600 splits, how many went on in their pass and how many of those parts had uploads (whose own full barriers order them after the part before all the same) | | `RX_VK_GPU_WAITS=0` | (Triforce, 11-22, the performance audit's SYNC-27; on by default; not yet run in the game) The host's calls that block on the GPU are made without being timed, as before. By default each is timed where it is wrapped (`gpu/vk/vk_work.h`, `gpu/vk/gpu_wait_kinds.h`) and summed by kind: `vkWaitForFences` and `vkWaitSemaphores` with a timeout above 0 (fences, timelines), `vkQueueWaitIdle` and `vkDeviceWaitIdle` (idle), `vkGetQueryPoolResults` with the wait bit (queries). Polls count nothing, a wait inside a wait counts once, and the low-latency sleep's wait is left out as pacing. After each 120-present line the log has `vk: host waits for the GPU: ... ms a frame (fences, timelines, idle, queries; all threads)`, which counts what that line's "GPU-bound wait" (the recording slots' waits alone) does not, and the frame trace has `gpu_waits_ms`. The cost is two clock reads a blocking wait. The `RX_VK_LAB_AB` knob `nogpuwaits` turns the count off in its phases | | `RX_VK_ORDER_WAKE=1` | (Triforce, 11-22, the performance audit's SYNC-59; off unless set; not yet run in the game) A queue stopped at a wait for an event goes on when a submit finds the wait met. A signal of the CPU's (`nvnEventSignal`) wakes no one: the stop waits for the order thread's next `Sleep(1)`, or a game thread's wait yields up to 3 ms and then forces it. With the switch (`gpu/vk/vk_replay.cpp` `sync_watch`, `event_signal_queued`) the order thread waits on an auto-reset event, 1 ms at most, which the signal sets while a queue is stopped: one `SetEvent`, no lock and no replay on the signalling thread. And a game thread's wait for stopped work that sees a signal pending lets the queues whose waits are met go on first, as `sync_settle` does; nothing is forced. The order line counts the wakes and those that let work on: under about one a second, leave it off. The `RX_VK_LAB_AB` knob `orderwake` turns it on in its phases | @@ -431,7 +433,7 @@ a frame; the two knobs are now asked once a phase and once a submission. | `RX_VK_FSR4_FG=0/1/4` | AMD's frame generation, the Frame generation row's AMD FSR (`gpu/vk/vk_fsr4.cpp` `fsr4fg`): 0 never in this run (`RX_VK_FSR4=0` too, which keeps AMD's library unloaded); 1, as without it, the newest frame generation AMD's library lists for the card, FSR 4's where listed (RX 9000), else FSR 3.1's (3.1.6 on RX 6000 and 7000), the row naming it ("AMD FSR (3.1.6)") and the log the version in use; 4 FSR 4's alone, as before (FG-1) | | `TRIFORCE_MENU_AHEAD=0` | (Triforce) What the options' rows ask of NVIDIA's and AMD's libraries (whether DLSS, FSR 4 and FSR 4's frame generation run here: NGX's start, AMD's loader) asked at the options' open on the presenting thread, as before, and not once on a thread of its own as soon as the game runs (`gpu/vk/vk_menu.cpp` `menu_ahead`; its log line says how long each took). For comparing: the first open waited about 2 s for them in test11 | | `RX_VK_AA=<0..3>`, `RX_VK_AA_KEEP=1` | The anti-aliasing for one run, over the Insert menu's Anti-aliasing row: 0 the game's own SMAA, 1 none, 2 FXAA, 3 SMAA at its Ultra preset in its place (`gpu/vk/aa_rows.h`, `gpu/vk/vk_aa.cpp`). Unset, the row decides; with DLSS, DLAA or FSR drawing from the tone mapped picture (Upscale before bloom off) the game's SMAA is left out (none: they want jittered frames no other anti-aliasing has been over), and before the bloom it runs as the game's; the switch goes over both, for an A/B (`RX_VK_AA=0`: the game's SMAA under the upscaler). The game's SMAA is three compute programs known by their keys (game build `e0f3ccfa`): with another choice in effect its composition is replaced and its edge and weight passes are left out, and `RX_VK_AA_KEEP=1` keeps those two running. The log says `vk: aa:` when a composition is first replaced, why one was left to the game, and when none was found for a minute | -| `RX_VK_THREADED=0`, `=1`, `=auto` | (Triforce; **off by default**, the Debug tab's Threaded rendering row, Off, On or Auto, which this goes over for the run) The renderer's threads as one design (`gpu/vk/threaded_rendering.h`), each piece one Triforce has, driven from here: the replay on its thread (`RX_VK_ASYNC=1`), the recorder thread (`RX_VK_RECORDER=thread`; since 11-27 not handed a part at a time, `RX_VK_RECORDER_PARTS` below), a submission's parts ending where the game ends its render pass (`RX_VK_PART_MIN`, `RX_VK_PART_FIRST`, `RX_VK_PART_MAX`), the present thread (`RX_VK_PRESENT_THREAD`) asking for the next image right after each present (`RX_VK_ACQUIRE_AHEAD`). Each of those switches, when set, still goes over it. Auto: on from 4 physical cores in the process's affinity; with no buffer-pool mirrors the recorder thread alone from 6; off with `RX_VK_CAPTURE=0`, `RX_VK_LOW_SPEC`, `RX_VK_DUMP` or `RX_VK_BENCH`. `=0` (or the row Off): everything as before. The log's `vk: Threaded rendering:` line says what this run took. The lab's A/B is `RX_VK_THREADED=0` against `=1` | +| `RX_VK_THREADED=0`, `=1`, `=auto` | (Triforce; **Auto by default since options_version 11** (11-29, the owner's decision; `gpu/vk/vk_menu.cpp` `menu_init` turns an older options file's Off into Auto once, On or Auto chosen stays), the Debug tab's Threaded rendering row, Off, On or Auto, which this goes over for the run) The renderer's threads as one design (`gpu/vk/threaded_rendering.h`), each piece one Triforce has, driven from here: the replay on its thread (`RX_VK_ASYNC=1`), the recorder thread (`RX_VK_RECORDER=thread`; since 11-27 not handed a part at a time, `RX_VK_RECORDER_PARTS` below), a submission's parts ending where the game ends its render pass (`RX_VK_PART_MIN`, `RX_VK_PART_FIRST`, `RX_VK_PART_MAX`), the present thread (`RX_VK_PRESENT_THREAD`) asking for the next image right after each present (`RX_VK_ACQUIRE_AHEAD`). Each of those switches, when set, still goes over it. Auto: on from 4 physical cores in the process's affinity; with no buffer-pool mirrors the recorder thread alone from 6; off with `RX_VK_CAPTURE=0`, `RX_VK_LOW_SPEC`, `RX_VK_DUMP` or `RX_VK_BENCH`. `=0` (or the row Off): everything as before. The log's `vk: Threaded rendering:` line says what this run took. The lab's A/B is `RX_VK_THREADED=0` against `=1`. Measured 11-29 (RTX 5090, 8 cores, the benchmark tour, `=0` against `=1`, 2 rounds, with the readbacks' fix for the parts' flicker, `RX_VK_RB_REC_END` above): +8.4% fps with the owner's options (186.6 -> 202.2), +4.7% with the defaults (195.0 -> 204.2), every scene up, the 1% low better in 13 of 14 rows; with the camera moving 183.3 fps against 165-167, the picture the same. The benchmark tour (`HOS_BENCHMARK`) takes the row as play does (`RX_VK_BENCH` is another bench); the lab's RX 7900 XT (11-27): the picture right, no gain. Not measured: other cards since | | `RX_VK_ASYNC=1` | The replay on a thread of its own instead of the game's submitting thread (off by default). The game still presents only once the GPU has run its frame, so nothing is released early. (Triforce, `gpu/vk/async_rules.h`; not yet run in the game) With it on, each with a switch of its own to put it back: a signal of the CPU's takes its capture on the game's thread only when a submission handed over before it may still wait for that event, which the host tells at the submit (`RX_VK_ASYNC_EVENT_NOTES=0`: at every signal while the thread has work, as before; the `vk: the replay thread: ... signals of the CPU's` line counts both); the submit's capture shares its copies with the copy helpers and has them all made before the hand-over (`RX_VK_ASYNC_CAPTURE_BEHIND=0`: every copy on the game's thread); the game's submit keeps its virtual core for the hand-over (`HOS_ASYNC_KEEP_CORE=0`: given up and taken again); the game's present poll waits for the replay thread asleep and looks at its event between yields only once the GPU has the frame (`HOS_PRESENT_POLL=0`: the game's own sleeps); a present runs the jobs behind it until the frame's stopped work has gone on and then makes go only what was already stopped at the present before (`RX_VK_PRESENT_DRAIN=1`: every present forces every stopped queue past its wait, as before; `=0`: none does; `RX_VK_PRESENT_WAIT_MS`, 8: how long it runs the jobs behind); and the thread looks for its next job for 100 µs before it sleeps (`RX_VK_ASYNC_SPIN_US=<0..1000>`). Still open, and why it stays off: after a ten-area tour the player's character is drawn black for one frame, 0 to 3 times a minute at the Market (`gpu/vk/async_rules.h` has what the lab ruled out). Two diagnostics for it: `RX_VK_LOG_READBACK_ZERO=1` logs each readback of GPU results that is all 0 where it was not at its readback before, and `RX_VK_REGION_TRAP=1` (with `RX_VK_PASS_TRACE=1` and the frame log) logs the passes of the last frames and writes their render conditions to `region_cond_.txt` when the picture's bottom middle goes dark for a frame, eight times a run. `RX_VK_ASYNC_FORCED=1`: the thread as it was before 11-14, every catch-up forcing | | `RX_VK_OCC_QUERY=0`, `RX_VK_OCC_QUERY_SKIP=[,...]`, `RX_VK_OCC_COND=0`, `RX_VK_OCC_LOG_COND=1`, `RX_VK_OCC_GATE=0` | (on by default since 11-17: +2.7 to +4.6% fps in every scene measured, 10-12% fewer draws, no flicker added; `RX_VK_OCC_QUERY=0` turns it off) The game's samples-passed reports (which objects show; a count of 0 is not drawn) get their real counts: the replay still writes each report as it passes it with 4096 (`RX_VK_OCC_FIXED`, everything visible), and the draws from its reset are counted by Vulkan occlusion queries (precise where the card has them); once the GPU is done with the recording that holds them the count is written into the report's record over the 4096, as NX2navi writes it at completion. The done recordings are found with one look at the recordings' timeline (nothing waits) as a game's fence wait ends (the game reads its counts after it), at each recording's begin and each present, at the latest when the recording's slot comes round. The game's report records rotate (a ring: an address is another object's at its next report), so a count is written only while its report is still the newest at its address, and only when it is whole (every query available, no draw left out, reset and report in one recording, read back within 8 presents); otherwise the record keeps its 4096. The game also predicates draws and clears on these words (render conditions), decided as NX2navi decides them: a word whose newest report is a samples-passed one whose count is still to come is unknown and the condition renders; a word whose count was written (or for which none comes) is read from memory as before, where a written 0 skips the draws and clears it gates. A count goes in only over the value the replay left in the word (a compare-and-write: never over the game's CPU re-arming the record), and a record rewritten in the stream after its report (a small buffer clear, a report of another counter type) gets no count. A parallel replay's segments signal the recordings' timeline and are sealed as they are submitted, so their counts are written too. The count word is written as the replay writes a report (`guest_cpu_write`, and the word kept out of the mirrors' write-backs). With hostQueryReset (Vulkan 1.2) a recording's queries are reset on the CPU once read, only those it used. `RX_VK_OCC_QUERY_SKIP`: report addresses that keep the fixed answer (the log's `occlusion query sites` lines list the first 64 addresses with their counts). The log's `occlusion queries` line every 600 presents: the reports, how many were counted whole and why not, the counts written at completion (and of them 0), those not written and why (lost, superseded by a later report at the address, late, a render condition's), the mean latency in presents and how many were written after the next present, where the done recordings were found, and the render conditions on samples-passed words (rendered because a count was pending, rendered or skipped from a written count, from memory with no count to come, as before in the knob's off phases) with the draws and clears they skipped. `RX_VK_OCC_COND=0`: a condition on a samples-passed word always renders (the counts are still written), to tell the counts from the skips. `RX_VK_OCC_LOG_COND=1`: one such condition in 499 logged (300 lines), with both words, their sources (pending, written, memory) and the present. (11-22) `RX_VK_OCC_GATE=0` turns off (on by default since its lab A/B: no fps lost at the Market): a count over a draw that a written count's condition left out (between the reset and its report) is the skip's 0, not the object's, and a condition on it renders; the count is still written for the game's CPU. Why: the game's CPU reads a count after its frame wait and draws a hidden object's proxy instead of the object, but most counts land after it has read the 4096, so it goes on drawing the object under the condition, the condition reads the skip's 0 and the object stays hidden (tickets 11-21: items and trees in the Forest Temple, black interiors; `RX_VK_OCC_QUERY=0` showed them). The line's second half counts these counts (counted whole, written, of them 0), the conditions that read one and those the switch rendered, on or off. Cost with it on: a hidden object under such a condition is drawn every other frame instead of never. Lab: the knob `occq` in `RX_VK_LAB_AB` runs the queries the whole run and writes the counts of the reports made in its phases (`gpu/vk/occ_answer.h`, `vk_replay.cpp` "occlusion queries") | | `RX_VK_OCC_DEPTH_ONLY=1` | (Triforce, 11-22, the performance audit's GPUWORK-01, after Source A's; off unless set) Only the occlusion windows whose draws write no colour are counted. The game's occlusion tests draw depth only, but a query here opens at a window's first draw in the pass and stays open to the report or the pass's end, so it can enclose draws that write colour, and a query's end waits for the work it encloses. With the switch, a window's first draw that writes a colour target gives its count up: the open query ends before that draw, no query begins again until the next reset, and the report is incomplete, so its record keeps the 4096 placeholder and what it gates is drawn. Fewer objects are culled with it (Source A: 4% fewer for 0.25 ms of GPU time), never one missing; whether that pays here is for a measurement to say, which is why it is off. The lab's knob `occdepth` (`RX_VK_LAB_AB`) is the switch in its phases. Counted either way, in a third `vk: occlusion queries` line every 600 presents: the counting windows that met a colour draw, the colour draws recorded under an open query, the counts given up and the reports kept 4096 for it (`gpu/vk/occ_answer.h` `Counter::colour_draw`; `gpu/vk/vk_replay.cpp` `occ_draw_colour`; `gpu/vk/vk_draw.cpp` `draw`) | @@ -651,7 +653,7 @@ number is not the obvious one: | `vibration_curve` | hundredths, 20 to 150: the power on the motors' rumble, 100 is 1.00 (none) | | `walk_key` | 0 Off, 1 Caps Lock, 2 Shift, 3 Ctrl, 4 Tab | | `walk_scale` | hundredths, 20 to 90: 51 is 0.51 of the stick's travel | -| `robust_buffers` | 0 Auto (on), 1 Off, 2 On | +| `robust_buffers` | 0 Auto (off since 11-17), 1 Off (the default), 2 On. With Intel's Windows driver robust buffer access is on whatever it says (11-30, `gpu/vk/vk_vendor.h` `robust_buffers`: Arc B570, Pro B70 and A770 lost the device at the file select without it); `RX_VK_ROBUST=0` or `1` over both | | `game_speed` | 0 Per frame, 1 Real time | | `text_speed` | 0 Normal, 1 2x, 2 4x, 3 Instant | | `achievements` | 1 on, 0 off: whether anything is earned (`host/achievements.c`, option id 175); at once | diff --git a/gpu/vk/barrier_rules.h b/gpu/vk/barrier_rules.h index 127b1e5..444d516 100644 --- a/gpu/vk/barrier_rules.h +++ b/gpu/vk/barrier_rules.h @@ -123,8 +123,9 @@ inline bool split_start_full(bool carry, bool recorded_between) { /// none is ever hidden. NVIDIA's driver is the device's driver id (VK_DRIVER_ID_NVIDIA_PROPRIETARY, one id on Windows and /// Linux), not the card's vendor: NVK, Dozen and Venus on an NVIDIA card, and every other driver (AMD, Intel, RADV and the /// Deck), keep 120 until the lab has measured them. These sizes apply where parts are cut by count: Threaded rendering off -/// (and RX_VK_PART_PASS_END not 1, which gives the pass-end parts on any run), or RX_VK_PART_PASS_END=0. With Threaded -/// rendering on and RX_VK_PART_PASS_END unset a part ends where the game ends its render pass and neither size is read +/// on a driver other than NVIDIA's (and RX_VK_PART_PASS_END not 1, which gives the pass-end parts on any run), or +/// RX_VK_PART_PASS_END=0. With Threaded rendering on, or on NVIDIA's driver since 11-29 (part_pass_end_default, below), and +/// RX_VK_PART_PASS_END unset a part ends where the game ends its render pass and neither size is read /// (vk_replay.cpp pass_end_parts); any RX_VK_CHUNK turns those parts off, so leave it unset there. Where parts are counted, /// RX_VK_CHUNK=120 is the old size on NVIDIA's driver too, and the knob chunk:120 compares it inside a run; with the pass-end /// parts on, the knob's phases are counted and the phases between end at the game's passes, so the knob compares those two. @@ -143,6 +144,17 @@ inline int64_t part_draws(bool env_set, int64_t env_value, int64_t knob_or_defau /// As the size was read before: the variable's number, 120 unset (since 11-26 the unset size on NVIDIA's driver is /// kPartDrawsNvidia: part_draws_default) inline int64_t part_draws_before(const char* env) { return env ? std::atoll(env) : 120; } +/// ((Triforce, 11-29, the performance session) RX_VK_PART_PASS_END unset, Threaded rendering off: whether a submission's parts +/// end where the game ends its render pass (vk_replay.cpp pass_end_parts: the first part from 32 draws and dispatches, the +/// rest from 120, at 512 at the latest) instead of every part_draws_default draws wherever that falls. On NVIDIA's driver (the +/// driver id, as part_draws_default). The frame trace at Lake Hylia showed why: the Presentation Thread's 8-handle submission +/// stops at an event another queue's later submission signals, and when that one comes the stopped work is recorded as one +/// burst that reached the GPU only at the 240-draw cut: the GPU sat idle ~0.9 ms of a 5.4 ms frame, and the next frame's +/// readbacks wait for that work. With the first part at 32 the GPU starts while the rest is recorded. Measured on the RTX +/// 5090 at 2560 x 1440 (the benchmark's seven-scene tour, camera turning, three rounds a side, interleaved): see +/// docs/development.md's RX_VK_PART_PASS_END row. Every other driver keeps the parts cut by count until the lab has measured +/// it. RX_VK_PART_PASS_END=0: cut by count, as before; =1: the pass-end parts on any driver +inline bool part_pass_end_default(uint32_t driver_id) { return driver_id == kDriverNvidiaProprietary; } /// RX_VK_EVENT_BARRIER: "late" the rule on any card; "full" (or any other value) as before; unset or empty: with the pass barrier's /// game mode (pass_barrier::game: NVIDIA's driver unless RX_VK_PASS_BARRIER says otherwise) diff --git a/gpu/vk/dlss_actor.h b/gpu/vk/dlss_actor.h index 357eedc..988d703 100644 --- a/gpu/vk/dlss_actor.h +++ b/gpu/vk/dlss_actor.h @@ -90,6 +90,168 @@ inline std::vector pair_by_place(const std::vector& now, const std: return pairs; } +/// (Triforce) The most copies of one model paired by place: pair_by_place and ambiguous_by_place cost copies x copies a model +/// (1000 copies took 11 ms a frame). A model with more has all its copies get the camera's motion (unsure_copies), as before +/// copies were paired by place. 256: the key's n-th stops at 255 (key()) +constexpr size_t kCopyCap = 256; + +/// (Triforce) How near another copy has to be to leave a pair in doubt, in ambiguous_by_place: within kTieFactor times the +/// distance the copy itself moved since the frame before, plus kTieSlack. Both in world units, as a copy's own move since the +/// frame before is, so it is not tuned to a screen (a copy that moved far among static ones is sure; one that moved little +/// beside another about as near is not) +constexpr double kTieFactor = 2.0, kTieSlack = 0.05; + +/// (Triforce) Which of this frame's copies, paired by place (pairs: pair_by_place's), have no sure pair: another copy of the +/// frame before is about as near (within kTieFactor times the distance moved, plus kTieSlack), or another copy of this frame is about as near +/// that same copy of the frame before. A copy that moved on its own among static ones is sure (its own old place is nearest by +/// far); copies at one place (the origin of every copy of a piece of ground, or of a model whose place is not what was read) +/// are never sure. Those take the camera's motion. Copies without a pair are not flagged (they have none: the camera's) +inline std::vector ambiguous_by_place(const std::vector& now, const std::vector& then, + const std::vector& pairs) { + std::vector out(now.size(), 0); + const auto distance = [&](const Placed& a, const Placed& b) { + double d = 0.0; + for (int c = 0; c < 3; c++) { + const double e = (double)a.place[c] - (double)b.place[c]; + d += e * e; + } + return std::sqrt(d); + }; + for (size_t i = 0; i < now.size() && i < pairs.size(); i++) { + const int j = pairs[i]; + if (j < 0 || j >= (int)then.size()) continue; + const double limit = kTieFactor * distance(now[i], then[j]) + kTieSlack; + for (size_t k = 0; k < then.size() && !out[i]; k++) + if ((int)k != j && distance(now[i], then[k]) <= limit) out[i] = 1; + for (size_t m = 0; m < now.size() && !out[i]; m++) + if (m != i && distance(now[m], then[j]) <= limit) out[i] = 1; + } + return out; +} + +/// (Triforce) For RX_VK_DLSS_TRACE: how a model's copies are spread: how many differ from all before them (by over 0.001), and the +/// least (over 0.001) and greatest distance between two of them. Tells whether what was read as a place is one +struct Spread { + int distinct = 0; + float min_gap = 0.0f, max_gap = 0.0f; +}; +inline Spread origin_spread(const std::vector& copies) { + Spread s; + double lo = 0.0, hi = 0.0; + for (size_t i = 0; i < copies.size(); i++) { + bool fresh = true; + for (size_t j = 0; j < i; j++) { + double d = 0.0; + for (int c = 0; c < 3; c++) { + const double e = (double)copies[i].place[c] - (double)copies[j].place[c]; + d += e * e; + } + d = std::sqrt(d); + if (!std::isfinite(d)) continue; + if (d > 0.001) { + lo = lo > 0.0 ? std::min(lo, d) : d; + hi = std::max(hi, d); + } else fresh = false; + } + s.distinct += fresh; + } + s.min_gap = (float)lo, s.max_gap = (float)hi; + return s; +} + +/// (Triforce) Which of this frame's scene draws have no sure draw of their own the frame before: a copy without a place (not +/// skinned, so pair_by_place can't tell it apart) of a model drawn more than once this frame, or the frame before (had: the +/// frame before drew that key; asked for the model's second draw, n-th 1). Its n-th draw the frame before is then only a +/// guess: the game draws a model's copies (trees, rocks, pieces of ground) in another order as the camera turns, and a copy +/// paired by n-th takes its neighbour's positions as its own frame before. Frame generation then draws it part way to the +/// neighbour (a tree's afterimage beside another tree, ground smeared along outlines). Those get the camera's motion +/// instead, as the draws with no frame before do. keys: this frame's scene draws (key()); placed[i]: it has a place +template +std::vector unsure_copies(const std::vector& keys, const std::vector& placed, Had&& had) { + std::vector out(keys.size(), 0); + std::vector models(keys.size()); + for (size_t i = 0; i < keys.size(); i++) models[i] = keys[i] >> 8; + std::vector sorted = models; + std::sort(sorted.begin(), sorted.end()); + for (size_t i = 0; i < keys.size(); i++) { + if (placed[i]) continue; + const auto r = std::equal_range(sorted.begin(), sorted.end(), models[i]); + out[i] = r.second - r.first > 1 || had((keys[i] & ~0xffull) | 1); + } + return out; +} + +/// (Triforce) Limits for object_place, from the 2026-11-28 in-game diagnostic (62 models: every object buffer's 3x3 was +/// rotation-scale, its axes well over kAxisMin long, pairwise |cos| near 0): a translation beyond kPlaceMax, or a 3x3 whose +/// rows and whose columns are both short or far from orthogonal, is not a world matrix +constexpr float kPlaceMax = 1e5f, kAxisMin = 1e-4f, kAxisCosMax = 0.05f; + +/// (Triforce) True if the three vectors of the 3x3 of m (a 3x4 row-major matrix) taken along rows (step 4, next 1) or columns +/// (step 1, next 4) are all over kAxisMin long and pairwise |cos| under kAxisCosMax +inline bool orthogonal_axes(const float m[12], int step, int next) { + double len[3]; + for (int r = 0; r < 3; r++) { + double d = 0.0; + for (int c = 0; c < 3; c++) d += (double)m[r * step + c * next] * m[r * step + c * next]; + len[r] = std::sqrt(d); + if (!(len[r] > kAxisMin)) return false; + } + for (int r = 0; r < 3; r++) { + const int q = (r + 1) % 3; + double dot = 0.0; + for (int c = 0; c < 3; c++) dot += (double)m[r * step + c * next] * m[q * step + c * next]; + if (!(std::fabs(dot) / (len[r] * len[q]) < kAxisCosMax)) return false; + } + return true; +} + +/// (Triforce) The place a non-skinned draw's object buffer holds: m, its first 12 floats, a 3x4 row-major world matrix (rows at +/// +0x00, +0x10, +0x20 of 4 floats, the translation last in each: m[3], m[7], m[11]; the floats at +0x40 are not a place). +/// Taken only if all 12 are finite (infinities and NaN would otherwise pass the comparisons' edge cases), the translation is +/// under kPlaceMax, and the 3x3 is rotation-scale: its rows or its columns are orthogonal (R*diag(s) has orthogonal columns, +/// diag(s)*R orthogonal rows). Else false and out is untouched +inline bool object_place(const float m[12], float out[3]) { + for (int i = 0; i < 12; i++) + if (!std::isfinite(m[i])) return false; + const int t[3] = {3, 7, 11}; + for (int a = 0; a < 3; a++) + if (!(std::fabs(m[t[a]]) < kPlaceMax)) return false; + if (!orthogonal_axes(m, 4, 1) && !orthogonal_axes(m, 1, 4)) return false; + for (int a = 0; a < 3; a++) out[a] = m[t[a]]; + return true; +} + +/// (Triforce) Which of this frame's scene draws without a skin are placed by their object's origin: those whose origin was read +/// (readable[i]) of a model with copies (drawn 2+ times this frame, or its 2nd the frame before: had(key of its 2nd)), and not +/// over kCopyCap of them, whose copies keep the camera's motion by unsure_copies instead +template +std::vector place_by_origin(const std::vector& keys, const std::vector& readable, Had&& had) { + std::vector out(keys.size(), 0); + std::vector sorted; + for (size_t i = 0; i < keys.size(); i++) + if (readable[i]) sorted.push_back(keys[i] >> 8); + std::sort(sorted.begin(), sorted.end()); + for (size_t i = 0; i < keys.size(); i++) { + if (!readable[i]) continue; + const auto r = std::equal_range(sorted.begin(), sorted.end(), keys[i] >> 8); + const size_t n = (size_t)(r.second - r.first); + out[i] = n <= kCopyCap && (n > 1 || had((keys[i] & ~0xffull) | 1)); + } + return out; +} + +/// (Triforce) Which draws placed by origin (by_origin) had a second copy the frame before (had) that was not placed (placed: +/// its origin was not readable, so nothing to pair it by): their pair is a guess, flagged as unsure_copies flagged it +template +std::vector lost_second_copy(const std::vector& keys, const std::vector& by_origin, Had&& had, Placed&& placed) { + std::vector out(keys.size(), 0); + for (size_t i = 0; i < keys.size(); i++) { + const uint64_t second = (keys[i] & ~0xffull) | 1; + out[i] = by_origin[i] && had(second) && !placed(second); + } + return out; +} + /// (Triforce) Where a skinned draw is, to tell copies of one model apart: its origin (3 floats) plus the mean of its bones' /// translations (nbones 3 x 4 row-major matrices: world = sum(w B p) + origin). A model placed by its origin differs there; /// copies placed by their bones at one origin (the game's copies of one model share an origin, the Gossip Stones among them) diff --git a/gpu/vk/mem_parts.h b/gpu/vk/mem_parts.h index 4883a53..2f363d8 100644 --- a/gpu/vk/mem_parts.h +++ b/gpu/vk/mem_parts.h @@ -219,9 +219,12 @@ inline bool query_used_on(const char* query_used, const char* census, const char return !(query_used && query_used[0] == '0' && !query_used[1]) && census_on; } /// (11-22) Whether the precompile keeps every pipeline for a PC of under 20 GB (vk_draw.cpp precompile_keeps_all): on a discrete -/// GPU with the game told its mapped pages are used (query_on), which lets old areas go; total 0: not known -inline bool keep_all_small_pc(bool discrete, uint64_t total, bool query_on) { - return discrete && query_on && total && total < (20ull << 30); +/// GPU with the game told its mapped pages are used (query_on), which lets old areas go; total 0: not known. +/// ((Triforce, 11-30) Not on AMD's driver (amd): it holds each kept pipeline's code itself (own_for_keep, above), and #bug-tracker's +/// RX 580s of 16 GB kept 16,963 of them (the renderer's census, v0.8.5.2) while their RAM ran out ("The Game is using all of my +/// ram", "Computer keeps crashing during the shader compilation phase"); the RAM rule decides there, by what is free) +inline bool keep_all_small_pc(bool discrete, uint64_t total, bool query_on, bool amd = false) { + return discrete && !amd && query_on && total && total < (20ull << 30); } /// (11-22, after Casual Gamer's fix) Whether the retired imports kept for good (vk_memory.cpp retired_imports_give_back: Windows, diff --git a/gpu/vk/tex_pack_bc7.h b/gpu/vk/tex_pack_bc7.h new file mode 100644 index 0000000..24b0d20 --- /dev/null +++ b/gpu/vk/tex_pack_bc7.h @@ -0,0 +1,268 @@ +// ((Triforce, 11-28) Evil HD's texture pack as BC7, prepared once (vk_texture.cpp texpack). No Vulkan here: tests/test_tex_pack_bc7.py +// builds it alone. +// +// The owner's "A texture pack should just reduce fps and have all the textures showing instead of popping in random textures as +// hd ... its not even constant". The pack's PNGs held as RGBA8 at twice the game's size were ~19 GB for the 2,011 pack textures +// one Hyrule Field visit sees: more than any card holds beside the game, so a budget picked a changing few. As BC7 (8 bits a texel, +// a quarter) they are 4.7 GB, 2.7 GB without the 231 that are 1024 or more already (tier). Decoding a PNG and encoding it took +// 66 + 162 ms for a 2048 x 2048 on one thread of a Ryzen with 24, so it is done once for the whole pack (prepare: every core but +// a few, a minute or two there), into triforce_texpack/bc7/.bc7, and a texture's file is then read as it is and uploaded. +// +// The encoder is the WebGPU back end's (gpu/render/rx_bc7.cpp: BC7 mode 6, the colours' main axis, one least-squares refit). +#pragma once +#include +#include +#include +#include +#include +#include + +namespace mkwvk::tex_pack_bc7 { + +// ---- the encoder (rx_bc7.cpp's, unchanged) ---- +namespace enc { +constexpr int kWeights[16] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}; +struct Fit { + int q[2][4]; + int p[2]; + uint8_t index[16]; + int64_t error; +}; +inline void quantize(const float e[4], int q[4], int& p) { + int64_t best = INT64_MAX; + for (int pb = 0; pb < 2; pb++) { + int64_t err = 0; + int t[4]; + for (int c = 0; c < 4; c++) { + t[c] = std::clamp((int)((e[c] - pb) * 0.5f + 0.5f), 0, 127); + const float d = e[c] - (float)(t[c] * 2 + pb); + err += (int64_t)(d * d * 16.0f); + } + if (err < best) { + best = err; + p = pb; + std::memcpy(q, t, sizeof t); + } + } +} +inline void choose_indices(const uint8_t px[16][4], Fit& f) { + int pal[16][4]; + for (int k = 0; k < 16; k++) + for (int c = 0; c < 4; c++) { + const int a = f.q[0][c] * 2 + f.p[0], b = f.q[1][c] * 2 + f.p[1]; + pal[k][c] = ((64 - kWeights[k]) * a + kWeights[k] * b + 32) >> 6; + } + f.error = 0; + for (int i = 0; i < 16; i++) { + int best = 0; + int64_t best_err = INT64_MAX; + for (int k = 0; k < 16; k++) { + int64_t e = 0; + for (int c = 0; c < 4; c++) { + const int d = px[i][c] - pal[k][c]; + e += d * d; + } + if (e < best_err) best_err = e, best = k; + } + f.index[i] = (uint8_t)best; + f.error += best_err; + } +} +inline Fit fit_endpoints(const uint8_t px[16][4], const float e0[4], const float e1[4]) { + Fit f; + quantize(e0, f.q[0], f.p[0]); + quantize(e1, f.q[1], f.p[1]); + choose_indices(px, f); + return f; +} +inline void put(uint64_t (&w)[2], int& pos, uint64_t v, int n) { + if (pos < 64) { + w[0] |= v << pos; + if (pos + n > 64) w[1] |= v >> (64 - pos); + } else { + w[1] |= v << (pos - 64); + } + pos += n; +} +inline void encode_block(const uint8_t px[16][4], uint8_t out[16]) { + float mean[4] = {0, 0, 0, 0}; + for (int i = 0; i < 16; i++) + for (int c = 0; c < 4; c++) mean[c] += px[i][c]; + for (float& m : mean) m *= 1.0f / 16.0f; + float cov[4][4] = {}; + for (int i = 0; i < 16; i++) { + float d[4]; + for (int c = 0; c < 4; c++) d[c] = px[i][c] - mean[c]; + for (int a = 0; a < 4; a++) + for (int b = 0; b < 4; b++) cov[a][b] += d[a] * d[b]; + } + float axis[4] = {cov[0][0], cov[1][1], cov[2][2], cov[3][3]}; + for (int it = 0; it < 8; it++) { + float n[4] = {0, 0, 0, 0}; + for (int a = 0; a < 4; a++) + for (int b = 0; b < 4; b++) n[a] += cov[a][b] * axis[b]; + float m = 0; + for (float v : n) m = std::max(m, std::fabs(v)); + if (m < 1e-6f) break; + for (int a = 0; a < 4; a++) axis[a] = n[a] / m; + } + float len = 0; + for (float v : axis) len += v * v; + len = std::sqrt(len); + float tmin = 0, tmax = 0; + if (len > 1e-6f) { + for (float& v : axis) v /= len; + tmin = 1e30f, tmax = -1e30f; + for (int i = 0; i < 16; i++) { + float t = 0; + for (int c = 0; c < 4; c++) t += (px[i][c] - mean[c]) * axis[c]; + tmin = std::min(tmin, t), tmax = std::max(tmax, t); + } + } + float e0[4], e1[4]; + for (int c = 0; c < 4; c++) { + e0[c] = std::clamp(mean[c] + axis[c] * tmin, 0.0f, 255.0f); + e1[c] = std::clamp(mean[c] + axis[c] * tmax, 0.0f, 255.0f); + } + Fit best = fit_endpoints(px, e0, e1); + if (best.error > 64) { + float aa = 0, ab = 0, bb = 0, ax[4] = {0, 0, 0, 0}, bx[4] = {0, 0, 0, 0}; + for (int i = 0; i < 16; i++) { + const float b = kWeights[best.index[i]] / 64.0f, a = 1.0f - b; + aa += a * a, ab += a * b, bb += b * b; + for (int c = 0; c < 4; c++) ax[c] += a * px[i][c], bx[c] += b * px[i][c]; + } + const float det = aa * bb - ab * ab; + if (std::fabs(det) > 1e-6f) { + float r0[4], r1[4]; + for (int c = 0; c < 4; c++) { + r0[c] = std::clamp((bb * ax[c] - ab * bx[c]) / det, 0.0f, 255.0f); + r1[c] = std::clamp((aa * bx[c] - ab * ax[c]) / det, 0.0f, 255.0f); + } + const Fit refit = fit_endpoints(px, r0, r1); + if (refit.error < best.error) best = refit; + } + } + if (best.index[0] & 8) { + std::swap(best.q[0], best.q[1]); + std::swap(best.p[0], best.p[1]); + for (uint8_t& k : best.index) k = (uint8_t)(15 - k); + } + uint64_t w[2] = {0, 0}; + int pos = 0; + put(w, pos, 1u << 6, 7); + for (int c = 0; c < 4; c++) { + put(w, pos, (uint64_t)best.q[0][c], 7); + put(w, pos, (uint64_t)best.q[1][c], 7); + } + put(w, pos, (uint64_t)best.p[0], 1); + put(w, pos, (uint64_t)best.p[1], 1); + put(w, pos, best.index[0], 3); + for (int i = 1; i < 16; i++) put(w, pos, best.index[i], 4); + std::memcpy(out, w, 16); +} +} // namespace enc + +/// The bytes of a w x h level as BC7: 16 a block of 4 x 4, partial blocks whole +inline uint64_t level_bytes(uint32_t w, uint32_t h) { return (uint64_t)((w + 3) / 4) * ((h + 3) / 4) * 16; } +/// The levels of a w x h chain down to 1 x 1 +inline uint32_t full_levels(uint32_t w, uint32_t h) { + uint32_t n = 1; + while ((std::max(w, h) >> n) > 0) n++; + return n; +} + +/// A tightly packed RGBA8 w x h picture as BC7 blocks (out: level_bytes(w, h)) +inline void encode(const uint8_t* rgba, uint32_t w, uint32_t h, uint8_t* out) { + const uint32_t bw = (w + 3) / 4, bh = (h + 3) / 4; + uint8_t px[16][4]; + for (uint32_t by = 0; by < bh; by++) + for (uint32_t bx = 0; bx < bw; bx++) { + for (uint32_t y = 0; y < 4; y++) + for (uint32_t x = 0; x < 4; x++) { + const uint32_t sx = std::min(bx * 4 + x, w - 1), sy = std::min(by * 4 + y, h - 1); + std::memcpy(px[y * 4 + x], rgba + ((size_t)sy * w + sx) * 4, 4); + } + enc::encode_block(px, out + ((size_t)by * bw + bx) * 16); + } +} + +/// The next level of an RGBA8 picture: each texel the mean of the 2 x 2 above (an odd edge's last texel repeated), the +/// renderer's blit did the same with a linear filter +inline std::vector half(const std::vector& rgba, uint32_t w, uint32_t h, uint32_t* ow, uint32_t* oh) { + const uint32_t nw = std::max(1u, w / 2), nh = std::max(1u, h / 2); + std::vector o((size_t)nw * nh * 4); + for (uint32_t y = 0; y < nh; y++) + for (uint32_t x = 0; x < nw; x++) { + const uint32_t x0 = std::min(x * 2, w - 1), x1 = std::min(x * 2 + 1, w - 1); + const uint32_t y0 = std::min(y * 2, h - 1), y1 = std::min(y * 2 + 1, h - 1); + for (int c = 0; c < 4; c++) { + const uint32_t s = rgba[((size_t)y0 * w + x0) * 4 + c] + rgba[((size_t)y0 * w + x1) * 4 + c] + + rgba[((size_t)y1 * w + x0) * 4 + c] + rgba[((size_t)y1 * w + x1) * 4 + c]; + o[((size_t)y * nw + x) * 4 + c] = (uint8_t)((s + 2) / 4); + } + } + *ow = nw, *oh = nh; + return o; +} + +// ---- the prepared file: triforce_texpack/bc7/.bc7 ---- +// "TFB7", version, width, height, levels (each uint32), the source PNG's size (uint64: the pack's file changed, the file is +// made again), then each level's blocks in order, level 0 first +constexpr uint32_t kMagic = 0x37424654; // ("TFB7" little-endian) +constexpr uint32_t kVersion = 1; +constexpr size_t kHeader = 4 * 5 + 8; +struct Header { + uint32_t w = 0, h = 0, levels = 0; + uint64_t png_size = 0; +}; +inline uint64_t file_bytes(uint32_t w, uint32_t h, uint32_t levels) { + uint64_t n = kHeader; + for (uint32_t l = 0; l < levels; l++) n += level_bytes(std::max(1u, w >> l), std::max(1u, h >> l)); + return n; +} +inline void write_header(uint8_t* p, const Header& hd) { + const uint32_t v[5] = {kMagic, kVersion, hd.w, hd.h, hd.levels}; + std::memcpy(p, v, sizeof v); + std::memcpy(p + sizeof v, &hd.png_size, 8); +} +/// A file's header, checked against its length (false: not one, or cut short) +inline bool read_header(const uint8_t* p, size_t n, Header* hd) { + if (n < kHeader) return false; + uint32_t v[5]; + std::memcpy(v, p, sizeof v); + if (v[0] != kMagic || v[1] != kVersion || !v[2] || !v[3] || !v[4] || v[4] > full_levels(v[2], v[3])) return false; + hd->w = v[2], hd->h = v[3], hd->levels = v[4]; + std::memcpy(&hd->png_size, p + sizeof v, 8); + return file_bytes(hd->w, hd->h, hd->levels) == n; +} + +// ---- which textures, by the card's video memory (its device-local heap: the same on every run, where what the driver allows +// moves with the other programs open, 9.4 to 11.3 GB in one run on the owner's 12 GB card; no budget choosing a changing few) ---- +// kAll: every pack texture. kNoBig: those of 1024 or more a side stay the game's (at Hyrule Field 4.7 -> 2.7 GB). kSmall: only +// those under 512. kNone: the pack is not used (the card cannot hold it beside the game) +enum Tier { kNone = 0, kSmall = 1, kNoBig = 2, kAll = 3 }; +// Measured 11-28 on the owner's 12 GB card, every pack texture (kAll): at most 822 MB of them drawn at once (the Market, Hyrule +// Field 775 MB), never near the emergency line. The 4.7 GB above is every texture one visit sees, not those held at once +inline Tier tier_for(uint64_t heap_mb) { + if (heap_mb >= 11000) return kAll; // (12 GB cards and up: the owner's RTX 4070 SUPER) + if (heap_mb >= 7500) return kNoBig; // (8 and 10 GB: ~0.5 GB of them) + if (heap_mb >= 5500) return kSmall; // (6 GB) + return kNone; +} +inline const char* tier_name(Tier t) { + return t == kAll ? "every pack texture" : t == kNoBig ? "those under 1024 a side (the bigger ones stay the game's)" + : t == kSmall ? "those under 512 a side" : "none (too little video memory beside the game)"; +} +/// Whether a game texture of w x h takes its pack file at this tier +inline bool tier_wants(Tier t, uint32_t w, uint32_t h) { + const uint32_t side = std::max(w, h); + return t == kAll || (t == kNoBig && side < 1024) || (t == kSmall && side < 512); +} +/// RX_VK_TEX_PACK_TIER=<0-3>: another tier (the lab's); unset or another word: by the card +inline int tier_env(const char* e) { + if (!e || !*e || e[1] || e[0] < '0' || e[0] > '3') return -1; + return e[0] - '0'; +} + +} // namespace mkwvk::tex_pack_bc7 diff --git a/gpu/vk/threaded_rendering.h b/gpu/vk/threaded_rendering.h index 90e5b40..a89f496 100644 --- a/gpu/vk/threaded_rendering.h +++ b/gpu/vk/threaded_rendering.h @@ -1,6 +1,7 @@ // (Triforce) Threaded rendering, the Debug tab's row (vk_menu.cpp, threaded_rendering= in triforce_options.ini) and its switch -// RX_VK_THREADED (over the row: 0 or off, 1 or on, 2 or auto): one rule for every reader. Off by default, the row and the switch -// both: Off changes nothing at all, every piece below keeps its own switch and default as before. +// RX_VK_THREADED (over the row: 0 or off, 1 or on, 2 or auto): one rule for every reader. The row is Auto by default since +// options_version 11 (11-29, the owner: "Yes default"; vk_menu.cpp menu_init turns an older file's Off into Auto once); unset, the +// switch leaves it to the row. Off changes nothing at all, every piece below keeps its own switch and default as before. // // What On turns on, as one design (the threads of a renderer of the same base, rewritten there as one: a render thread for the // replay, the recorder thread beside it handed whole parts, the presents on a thread of their own, parts that end where the @@ -20,16 +21,18 @@ // finished frames, in order (RX_VK_PRESENT_CHECK=1 counts any present that is not) // the parts a submission's part ends where the game has ended its render pass, from 120 draws (the first part // from 32), at 512 at the latest (vk_replay.cpp maybe_split; RX_VK_PART_MIN, RX_VK_PART_FIRST, -// RX_VK_PART_MAX), not every RX_VK_CHUNK draws wherever that falls +// RX_VK_PART_MAX), not every RX_VK_CHUNK draws wherever that falls. ((Triforce, 11-29) On NVIDIA's +// driver these parts are the default with Off too: barrier_rules.h part_pass_end_default) // // Each piece's own switch, when set, still goes over this (RX_VK_ASYNC, RX_VK_RECORDER, RX_VK_RECORDER_PARTS, // RX_VK_PRESENT_THREAD, RX_VK_ACQUIRE_AHEAD, RX_VK_CHUNK). The replay helper threads (the parallel replay) are not part of it: // with the render thread on there are none, whatever their row says (vk_replay.cpp par_threads_max; RX_VK_PARALLEL or // RX_VK_PARALLEL_AUTO still goes over this). // -// Off (the default) as before: the replay on the game's submitting thread, the recorder as Triforce chooses it +// Off as before: the replay on the game's submitting thread, the recorder as Triforce chooses it // On all of the above, whatever the CPU -// Auto decided from the physical cores the process may run on (its affinity mask, a core's SMT siblings counted once): +// Auto (the default) decided from the physical cores the process may run on (its affinity mask, a core's SMT siblings +// counted once): // kAutoCores (4) or more: all of the above; // fewer: off, as Off. // With no buffer-pool mirrors (an integrated GPU, RX_VK_MIRROR=0) the render thread, which runs a frame behind the @@ -41,7 +44,9 @@ // render thread alone 67.6 / 67.9 fps against 65.5 / 65.0 serial; from 6 cores both threads 72.9 / 72.4 against 67.4 / 68.4. // After the rewrite (a Ryzen 7 5700X3D held to 4 cores, RX 9070 XT): both threads 78.7 fps against the render thread alone's // 64.6 (4 cores, 8 threads). The recorder alone at 6 or more cores without mirrors: +18.0% 1% lows, +5.6% fps in the Market. -// Not measured here: the coordinator's lab A/B is RX_VK_THREADED=0 against RX_VK_THREADED=1. +// (11-29, an RTX 5090, 8 cores, the benchmark tour, RX_VK_THREADED=0 against 1, 2 rounds) +8.4% fps with the owner's options +// (186.6 -> 202.2), +4.7% with the defaults (195.0 -> 204.2), every scene up, the 1% low better in 13 of 14 rows; with the camera +// moving 183.3 fps against 165-167, the picture the same. The coordinator's lab A/B is RX_VK_THREADED=0 against RX_VK_THREADED=1. // Read once, at the start (vk_main.cpp threaded_choice): a change of the row applies at the next start. // Plain code with no Vulkan or system calls: tests/test_threaded_rendering.py compiles it alone. #pragma once @@ -53,7 +58,7 @@ namespace mkwvk::threaded { -enum { OFF = 0, ON = 1, AUTO = 2 }; // (the row's values, in its order: Off, On, Auto; 0 the default) +enum { OFF = 0, ON = 1, AUTO = 2 }; // (the row's values, in its order: Off, On, Auto; 2 the default since options_version 11) /// Auto's tier, in physical cores the process may run on: from here the render thread and the recorder thread constexpr unsigned kAutoCores = 4; diff --git a/gpu/vk/title_tabs.h b/gpu/vk/title_tabs.h index 99b4734..114801e 100644 --- a/gpu/vk/title_tabs.h +++ b/gpu/vk/title_tabs.h @@ -78,4 +78,33 @@ inline int at(const Layout& l, float x, float y) { return -1; } +// ((Triforce, 11-30) two players, on an Xbox and a PlayStation controller: "The X is supposed to open up the Mod Menu but +// instead it is opening up the save selection; the Y is supposed to open up the Save selection but instead it's opening up +// the Mod menu". A tab opens with the pad input the Switch's X or Y is bound to (vk_menu.cpp menu_tick: the top face button +// for Mods by default, Y on an Xbox pad, Triangle on a PlayStation one), but its prompt was the Switch button's own code +// (U+E042, U+E043), which is that input's icon only in a font the host pointed at this run's controls at the start +// (host/prompts.c cmap4_bind). In the game's own font (no prompts folder from Setup: "the game shows its own icons"), and +// on a key's cap without a font ("X", "Y"), it is the Switch's letter: on an Xbox or PlayStation pad, the other button's +// name. Controls changed during the run were not followed either (the overlay reads the font once). The prompt now names +// the input itself, as the button test reads it: the icon font's own icon of that input on the face shown, else its name) +constexpr unsigned kPadBase = 0xF700; // (the font's own face's icon of each pad input: host/prompts.c PAD_BASE) +constexpr unsigned kFaceBase = 0xF800, kFaceCodes = 32; // (each controller face's icons: host/prompts.c FACE_BASE, FACE_CODES) +/// The icon font's codes that may have the icon of pad input `input` on controller face `face` (HOS_PROMPT_*; faces: how many +/// faces have icons there, inputs: how many pad inputs have one), the first to look for first: that face's own (a font with +/// every face's, nx2/prompt_assets.py faces_font), then the font's own face's (one built before those). 0 0 for none +inline void icon_codes(int face, int input, int faces, int inputs, unsigned out[2]) { + out[0] = out[1] = 0; + if (face < 0 || face >= faces || input < 0 || input >= inputs || input >= (int)kFaceCodes) return; + out[0] = kFaceBase + kFaceCodes * (unsigned)face + (unsigned)input; + out[1] = kPadBase + (unsigned)input; +} +/// code as UTF-8 in out (the text ImGui draws); "" for 0 or a code past U+FFFF (the icons are all under it) +inline const char* utf8(unsigned code, char out[4]) { + if (!code || code > 0xFFFF) out[0] = 0; + else if (code < 0x80) out[0] = (char)code, out[1] = 0; + else if (code < 0x800) out[0] = (char)(0xC0 | code >> 6), out[1] = (char)(0x80 | (code & 0x3F)), out[2] = 0; + else out[0] = (char)(0xE0 | code >> 12), out[1] = (char)(0x80 | (code >> 6 & 0x3F)), out[2] = (char)(0x80 | (code & 0x3F)), out[3] = 0; + return out; +} + } // namespace mkwvk::title_tabs diff --git a/gpu/vk/vk_api.h b/gpu/vk/vk_api.h index 37a9ba3..2a8350a 100644 --- a/gpu/vk/vk_api.h +++ b/gpu/vk/vk_api.h @@ -328,6 +328,11 @@ enum { HOS_OPT_STEADY_ROW = 430 }; none. Where the render targets' pool is held to its size (host/nn_applet.c hos_rt_pool_pinned), host/nn_vi.c takes no 3D larger than this run has had at the menu's Apply; the menu says so (gpu/vk/vk_menu.cpp menu_option_set) */ enum { HOS_OPT_RES_HELD = 431 }; +/* ((Triforce, 11-30) HOS_OPT_COMPARE_PLAY: the ReShade comparison asked for inside the pause menu's Options. option: 1 while the + menu waits for the game's menus to close (host/nn_hid.c compare_to_play taps their Back), else 0; option_set by the host: 2 + in play (the comparison opens over the game), 3 the menus did not close (it opens where it is). gpu/vk/vk_menu.cpp. No new + function: MKWVK_API_VERSION stays */ +enum { HOS_OPT_COMPARE_PLAY = 432 }; /* (Triforce) More rows of how the game plays (gpu/vk/vk_menu.cpp; 200 to 239 are theirs), each an option: what the row is set to, the game's own at its default. HOS_OPT_FOV: the System tab's Field of view row, percent of the game's own vertical angle in play, 50 to 150, 100 the game's own (host/oot_fov.c). HOS_OPT_TEXT_SIZE: its Text size row, 0 the game's own @@ -343,10 +348,12 @@ enum { HOS_OPT_RES_HELD = 431 }; 0 Auto, 1 Stereo, 2 5.1, 3 Mono: the layout is read from the file at the start (host/nn_audio.c au_menu_output), only Mono is asked for here, at each block mixed (audio_mono). HOS_OPT_MUTE_BACKGROUND: its Mute in background row, 1 no sound while another window has the focus (host/nn_audio.c master_volume). HOS_OPT_MIC_GAIN: its Microphone gain row, - percent of what the microphone gives, 25 to 400, 100 its own (host/nn_audio_in.c pump, host/mic_gain.h) */ + percent of what the microphone gives, 25 to 400, 100 its own (host/nn_audio_in.c pump, host/mic_gain.h). + HOS_OPT_AMIIBO_UNLIMITED: the System tab's Unlimited amiibo uses row (its NFC group), 0 the game's own (a figure gives its + reward once a day), 1 a figure can be scanned again at once, any number of times (host/oot_amiibo_uses.c) */ enum { HOS_OPT_FOV = 200, HOS_OPT_TEXT_SIZE, HOS_OPT_CAMERA_CENTERING, HOS_OPT_DAMAGE_TAKEN, HOS_OPT_SKIP_OPENING, HOS_OPT_SKIP_TITLE, HOS_OPT_AUTOSAVE, HOS_OPT_CHEAT_SPEED, HOS_OPT_AUDIO_OUTPUT, HOS_OPT_MUTE_BACKGROUND, - HOS_OPT_MIC_GAIN }; + HOS_OPT_MIC_GAIN, HOS_OPT_AMIIBO_UNLIMITED }; /* ((Triforce) 11-24) A bug capture's settings changed from the defaults (host/bug_capture.c, capture.txt; 286 to 289 the bug capture's). HOS_OPT_BUG_SETTINGS, option_set 1: the menu writes down its rows that are not at their defaults, as it shows them, "Name: value (default: value)" a line each, or one line that says none is; option: the next byte of that text, diff --git a/gpu/vk/vk_draw.cpp b/gpu/vk/vk_draw.cpp index 6f41bb8..ac933a3 100644 --- a/gpu/vk/vk_draw.cpp +++ b/gpu/vk/vk_draw.cpp @@ -658,6 +658,65 @@ struct SimTurfTally { std::unordered_set ever[2]; }; SimTurfTally sim_turf_tally; +// ---- ((Triforce, 11-29) a list some program reads through the GAME'S OWN descriptor: one the IR pass left as it is (the +// pool producer 3de6d86ec7e6720e on his PC: "pools 0 made, N absent" all session). Such a program indexes the blade list +// with the game's cap (record = 143359 - i for a reverse list) but takes its count from the header, which a grown private +// list fills past that cap: i past 143359 reads far outside the buffer, the blade records it then follows are garbage, and +// the dispatch never ends. 11-29 his crash: device lost (Windows TDR, LiveKernelEvent 141) in that dispatch, the frame +// after both blade lists grew 143360 -> 165056. So a list read so is held at the game's size: the grow is refused, a list +// already grown is made the game's size again at its producer's next dispatch. A patched program reads a list's header +// through the game's descriptor by design (headers stay in the game's buffers): only a stage with no turf descriptor of its +// own counts. Exact address: the pass's private descriptor and the game's are read from the same constant-bank words ---- +constexpr size_t kSimTurfLiveSlots = 2 * kSimTurfPrivateMax; +std::atomic sim_turf_live_addr[kSimTurfLiveSlots]{}; // (the private lists' addresses, 0 = none; lock-free reads) +std::atomic sim_turf_live_held[kSimTurfLiveSlots]{}; // (that address already held at the game's size) +std::atomic sim_turf_live_n{0}; +std::unordered_set sim_turf_game_read; // (addresses an unpatched program read: under sim_turf_mu, whole run) +/// RX_VK_SIM_TURF_HOLD=0: no hold (the lists grow whoever reads them: the 11-29 hang back; an A/B only) +bool sim_turf_hold_on() { + static const bool on = [] { + const char* e = getenv("RX_VK_SIM_TURF_HOLD"); + return !(e && e[0] == '0'); + }(); + return on; +} +/// The lock-free copy of the private lists' addresses, after any change (under sim_turf_mu) +void sim_turf_publish() { + size_t n = 0; + for (int kind = 0; kind < 2; kind++) + for (const SimTurfPrivate& g : sim_turf_private[kind]) + if (n < kSimTurfLiveSlots) { + sim_turf_live_held[n].store(sim_turf_game_read.count(g.addr) != 0, std::memory_order_relaxed); + sim_turf_live_addr[n++].store(g.addr, std::memory_order_relaxed); + } + const size_t live = n; + while (n < kSimTurfLiveSlots) sim_turf_live_addr[n++].store(0, std::memory_order_relaxed); + sim_turf_live_n.store((uint32_t)live, std::memory_order_release); +} +/// A list held at the game's size (above): its policy may not pass the game's cap +void sim_turf_hold(SimTurfPrivate& g, bool pool) { + g.policy.limit(pool ? Shader::Optimization::kSimTurfPoolCap : Shader::Optimization::kSimTurfBladeCap); +} +/// An unpatched stage binds the game's descriptor at addr: hold the private list there, if any, at the game's size +void sim_turf_game_reader(uint64_t addr, uint64_t prog) { + if (!addr || !sim_turf_live_n.load(std::memory_order_acquire)) return; + size_t slot = kSimTurfLiveSlots; + for (size_t i = 0; i < kSimTurfLiveSlots; i++) + if (sim_turf_live_addr[i].load(std::memory_order_relaxed) == addr) { slot = i; break; } + if (slot == kSimTurfLiveSlots || sim_turf_live_held[slot].load(std::memory_order_relaxed)) return; + std::lock_guard lk(sim_turf_mu); + sim_turf_game_read.insert(addr); + for (int kind = 0; kind < 2; kind++) + for (SimTurfPrivate& g : sim_turf_private[kind]) + if (g.addr == addr) { + const uint32_t before = g.policy.capacity(); + sim_turf_hold(g, kind == 1); + logf("vk: simulated turf: prog %016llx reads the %s at %#llx through the game's own descriptor (a variant the " + "pass left as it is): the list held at the game's %u records (now %u)", (unsigned long long)prog, + kind ? "pool" : "blade list", (unsigned long long)addr, g.policy.maximum(), before); + } + sim_turf_publish(); +} /// The most records a list may hold. A list's reader runs a workgroup for every `group` records, in one indirect command the /// game's program writes from the list's length: a pool's mesh draw, a blade list's dispatch. Past what the device takes in /// one the command is invalid (AMD's 65535 mesh groups are 2,097,120 pool records, and a longer pool's turf flickered all over). @@ -787,6 +846,7 @@ VkDescriptorBufferInfo sim_turf_private_binding(uint64_t addr, uint32_t enc, uin v.emplace_back(pool, sim_turf_max_records(pool, salign)); SimTurfPrivate& n = v.back(); n.addr = addr, n.used = frame; + if (sim_turf_game_read.count(addr)) sim_turf_hold(n, pool); // ((Triforce, 11-29) sim_turf_game_reader) if (!sim_turf_resize(n, pool, salign)) { v.pop_back(); static std::atomic failed{0}; @@ -807,8 +867,10 @@ VkDescriptorBufferInfo sim_turf_private_binding(uint64_t addr, uint32_t enc, uin v.emplace_back(pool, sim_turf_max_records(pool, salign)); SimTurfPrivate& replacement = v.back(); replacement.addr = addr, replacement.used = frame; + if (sim_turf_game_read.count(addr)) sim_turf_hold(replacement, pool); // ((Triforce, 11-29) sim_turf_game_reader) if (!sim_turf_resize(replacement, pool, salign)) { v.pop_back(); + sim_turf_publish(); return none; } g = &replacement; @@ -819,6 +881,7 @@ VkDescriptorBufferInfo sim_turf_private_binding(uint64_t addr, uint32_t enc, uin } g->addr = addr, g->used = frame; sim_turf_tally.ever[pool].insert(addr); + sim_turf_publish(); // ((Triforce, 11-29) the lock-free addresses sim_turf_game_reader checks) return sim_turf_bound_result(*g, addr, enc, pool, creator); } @@ -6662,6 +6725,10 @@ void build_descriptors(const NvnState& s, const Program& p, bool keep = false, b w.pBufferInfo = &dwr.bufs[first]; dwr.writes.push_back(w); } + // ((Triforce, 11-29) sim_turf_game_reader: a stage with no turf descriptor of its own, while private lists exist) + const bool turf_unpatched = sim_turf_live_n.load(std::memory_order_relaxed) && sim_turf_hold_on() && + std::none_of(info.storage_buffers_descriptors.begin(), info.storage_buffers_descriptors.end(), + [](const auto& x) { return Shader::IsSimTurfStorage(x); }); for (const auto& d : info.storage_buffers_descriptors) { FINE_SCOPE(FT_STORAGE); FINE_N(FC_SSBO_DESCS, d.count); @@ -6701,6 +6768,7 @@ void build_descriptors(const NvnState& s, const Program& p, bool keep = false, b const uint64_t addr = stage_cbuf_word(s, st, d.cbuf_index, off) | (uint64_t)stage_cbuf_word(s, st, d.cbuf_index, off + 4) << 32; uint64_t size = stage_cbuf_word(s, st, d.cbuf_index, off + 8); + if (turf_unpatched) sim_turf_game_reader(addr, p.key); // ((Triforce, 11-29) a turf list read the game's way) // ((Triforce) desc_keep.h: a single storage buffer the program only reads, kept with its address and size. The // rest of what follows is for tables, written buffers, the bare and wide ones and the diagnostics, none of them kept) desc_keep::Elem* const ke = kp && d.count == 1 && !d.is_written && !info.native_global_bounds && !sim_turf ? &kp->e[jb + k] : nullptr; @@ -11522,6 +11590,7 @@ static void push_capture(VkCommandBuffer cmd, const Program& p, const NvnState& CaptureDraw k; k.depth = at.depth, k.vbuf = s.vbuf[0].address, k.program = p.key, k.count = d.count; k.camera = s.ubo[0][0].addr, k.camera_size = s.ubo[0][0].size; + k.object = s.ubo[0][1].addr, k.object_size = s.ubo[0][1].size; // (Triforce: a copy's place, for temporal_capture_draw) if (d.indexed) k.ibuf = d.ibuf, k.itype = d.itype, k.base_vertex = d.base_vertex; else k.ibuf = 0, k.itype = dlss_actor::kNoIndices, k.base_vertex = d.first; // (vertex i: first + i) // (as the draw's dynamic state has it: dyn_state) @@ -14850,13 +14919,13 @@ bool precompile_keeps_all() { const bool discrete = dev.props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU; const bool query_on = mem_parts::query_used_on(getenv("HOS_MEM_QUERY_USED"), getenv("HOS_MEM_CENSUS"), getenv("HOS_MEM_GIVE_BACK")); - if (!e && mem_parts::keep_all_small_pc(discrete, ms.ullTotalPhys, query_on)) { + const bool amd = dev.props.vendorID == 0x1002; // ((Triforce, 11-30) not the small PC's rule on AMD's driver: mem_parts.h + if (!e && mem_parts::keep_all_small_pc(discrete, ms.ullTotalPhys, query_on, amd)) { logf("vk: precompile: the pipelines it builds are kept for the session: a discrete GPU in a PC of %llu MB (under 20 GB), " "the game told its mapped pages are used (RX_VK_PRECOMPILE_KEEP=auto: by the RAM available, =0: never)", (unsigned long long)(ms.ullTotalPhys >> 20)); return true; } - const bool amd = dev.props.vendorID == 0x1002; const uint64_t cache_read = pcache_read_ws.load(), own = mem_parts::own_for_keep(ws, cache_read, amd); const bool keep = mem_parts::keep_all_pipelines(ms.ullTotalPhys, ms.ullAvailPhys, own); logf("vk: precompile: %s: %llu MB of RAM available and %llu MB held by the game already (%llu MB in all, %llu MB of it " diff --git a/gpu/vk/vk_internal.h b/gpu/vk/vk_internal.h index add44b8..a9bc3ed 100644 --- a/gpu/vk/vk_internal.h +++ b/gpu/vk/vk_internal.h @@ -463,6 +463,12 @@ void late_fix_flush_locked(); void vk_late_queue_stats(int64_t* waits, int64_t* wait_ns, int64_t* timeouts); uint64_t memory_late_fix_pending(); void memory_late_fix_apply(uint64_t done); +/// ((Triforce, 11-29, the performance session) RX_VK_LATE_PART (the lab knob latepart): whether the late pages' fixes wait for +/// the part that wrote their pages back last, not their value; that part over the pending fixes (its number on the recordings' +/// timeline; 0: one of them not known, so the value); and the waits made so (vk_replay.cpp late_fix_part_wait) +bool memory_late_part_on(); +uint64_t memory_late_fix_part(); +void vk_late_part_stats(int64_t* waits, int64_t* wait_ns, int64_t* unknown); void memory_note_event_word(uint64_t gpu); // ((Triforce, 11-26) RX_VK_LATE_EVENTS: a GPU-signalled event word's page (vk_memory.cpp) /// ((Triforce, wp20) of this thread's last vk_timeline_wait, the part after the writer's recording was done (ns): wb_rec_wait.h) int64_t vk_timeline_wait_held_last(); diff --git a/gpu/vk/vk_main.cpp b/gpu/vk/vk_main.cpp index 8f95cf9..19da14c 100644 --- a/gpu/vk/vk_main.cpp +++ b/gpu/vk/vk_main.cpp @@ -269,7 +269,7 @@ static unsigned process_physical_cores() { // and, for Auto, whether the run is safe for it: the capture off (RX_VK_CAPTURE=0: a replay behind the game is right only from the // capture), RX_VK_LOW_SPEC, a frame dump (RX_VK_DUMP), the bench (RX_VK_BENCH); then, only when Auto would pick the threads, the // buffer pools' mirrors, which read the device (asked at pick_device, after it is known: a reader before it gets Auto off). -// On is the player's word: nothing is checked for it. Off, the default: every reader as before +// On is the player's word: nothing is checked for it. Off: every reader as before. Auto is the row's default (options_version 11) const threaded::Choice& threaded_choice() { static const threaded::Choice choice = [] { menu_init(); @@ -672,8 +672,9 @@ bool create_device() { // culling pass 53caac5f faulted the device while a save loaded, about one start in three, and the scene's lighting read garbage // for single frames (the black flashes); with it, neither in A/B runs at the same GPU time. Lichii's OoT branch keeps it on too. // The 'Robust buffers' row of triforce_options.ini chooses (0 Auto: off since 11-17, the owner's call; 1 Off; 2 On); RX_VK_ROBUST=0 or 1 - // over it. Off is null descriptors only: some NVIDIA cards ran slower with it on, issues 394, 418, 419) - static const bool robust = []() -> bool { + // over it. Off is null descriptors only: some NVIDIA cards ran slower with it on, issues 394, 418, 419. ((Triforce, 11-30) + // And on with Intel's Windows driver whatever the row says, below the vendor fixes: vk_vendor.h robust_buffers) + static const bool robust_row = []() -> bool { if (const char* e = getenv("RX_VK_ROBUST")) return atoi(e) != 0; char exe[MAX_PATH]; const DWORD n = game_module_path(exe, MAX_PATH); // (the game folder, not bin beside the launcher: vk_paths.h) @@ -692,8 +693,7 @@ bool create_device() { // ((Triforce) 11-17, the owner's "keep robust buffers off by default": Auto is off now; only On (2) turns it on) return v == 2; }(); - const bool robust_ok = robust && robust2.robustBufferAccess2 && f.features.robustBufferAccess; - robust2.robustBufferAccess2 = robust_ok ? VK_TRUE : VK_FALSE; + bool robust = robust_row, robust_ok = false; // (with the vendor fixes, below) robust2.robustImageAccess2 = VK_FALSE; dev.null_descriptor = dev.null_descriptor && robust2.nullDescriptor; pv.transformFeedbackPreservesProvokingVertex = VK_FALSE; @@ -735,9 +735,15 @@ bool create_device() { amd_older = amd_older_compiler(facts); dev.amd_older_compiler = amd_older; vendor_fixes_env(dev.fixes, [](const char* name) -> const char* { return getenv(name); }); - logf("vk: vendor fixes for %s (%s): out-of-bounds texel fetches 0 %d, NaN tests by bits %d, gather offset %d", - drv.driverName, drv.driverInfo, (int)dev.fixes.fetch_bounds, (int)dev.fixes.nan_bits, (int)dev.fixes.gather_offset); + logf("vk: vendor fixes for %s (%s): out-of-bounds texel fetches 0 %d, NaN tests by bits %d, gather offset %d, robust " + "buffers %d", drv.driverName, drv.driverInfo, (int)dev.fixes.fetch_bounds, (int)dev.fixes.nan_bits, + (int)dev.fixes.gather_offset, (int)dev.fixes.robust_buffers); } + // ((Triforce, 11-30) the Robust buffers row (robust_row), or the vendor fix: Intel's Windows driver lost the device at the + // file select without it (vk_vendor.h robust_buffers); RX_VK_ROBUST=0 turns both off) + robust = robust || dev.fixes.robust_buffers; + robust_ok = robust && robust2.robustBufferAccess2 && f.features.robustBufferAccess; + robust2.robustBufferAccess2 = robust_ok ? VK_TRUE : VK_FALSE; // ((Triforce, 11-18, EstebanGGM's port of NX2navi issue #67) AMD's older proprietary shader compiler (vk_vendor.h // amd_older_compiler) applies alpha to coverage while the dynamic state says off: white stippling over foliage, grass, Link's // hair and tunic on RX 470-590 (#bug-tracker "Texture glitch again ... (RX 580)", 11-18 screenshots). There the state goes in @@ -870,7 +876,9 @@ bool create_device() { logf("vk: %s programs use the compute fallback (RX_VK_TASK_MESH_FALLBACK=0: native%s)", dev.mesh_only_fallback ? "mesh-only and task + mesh" : "task + mesh", dev.mesh_only_fallback ? "; RX_VK_MESH_ONLY_FALLBACK=0: task + mesh alone" : ""); - if (robust) logf("vk: robust buffer access %s", robust_ok ? "on" : "not supported"); + if (robust) + logf("vk: robust buffer access %s%s", robust_ok ? "on" : "not supported", + robust_row ? "" : " (Intel's Windows driver: whatever the Robust buffers row says; RX_VK_ROBUST=0: off)"); f.features.robustBufferAccess = robust_ok ? VK_TRUE : VK_FALSE; // (off by default: the game's accesses stay in their buffers) dev.features = f.features; dev.sparse_images = (families[dev.queue_family].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) && f.features.sparseBinding && diff --git a/gpu/vk/vk_memory.cpp b/gpu/vk/vk_memory.cpp index 22a592d..69e5a86 100644 --- a/gpu/vk/vk_memory.cpp +++ b/gpu/vk/vk_memory.cpp @@ -3672,6 +3672,11 @@ std::atomic wb_batch_now{0}; std::map wb_batch_seq; // batch -> its part's number on the recordings' timeline std::vector wb_runs_recent; // (wb_pages_mu held) uint64_t wb_runs_lost = 0; // (the ranges of submissions up to this value were dropped unseen) +// ((Triforce, 11-29, the performance session) a write-back queued in this part covers a page the CPU reads back (rb_watch, below): +// the part may end sooner (vk_replay.cpp part_min_now: RX_VK_PART_RB, the lab knob partrb), so that its copy reaches the reader +// sooner. Set at the written binding that queues it (the mirrors' writebacks), cleared at the part's end (memory_end_submission) +std::atomic part_rb_write{false}; +bool rb_watched(uint64_t lo, uint64_t hi); void wb_pages_note(uint64_t guest_lo, uint64_t guest_hi, uint64_t value) { static const bool off = getenv("RX_VK_NO_READBACK_WAIT") != nullptr; if (off || !value || guest_hi <= guest_lo) return; @@ -4499,7 +4504,41 @@ struct LateFix { VmaAllocation alloc = nullptr; size_t nbytes = 0; std::vector> slots; // (slot, guest page), by slot + uint64_t part = 0; // ((Triforce, 11-29) RX_VK_LATE_PART: the part that wrote the pages back last (late_pages_part); 0 not known }; +/// ((Triforce, 11-29, the performance session) RX_VK_LATE_PART=1, or the lab knob latepart: a late fix waits for the part that +/// wrote its pages back last (vk_replay.cpp late_fix_part_wait), not for its value. Off unset +bool memory_late_part_on() { + static const bool env = [] { + const char* e = getenv("RX_VK_LATE_PART"); + const bool on = e && *e && atoi(e) != 0; + if (on) logf("vk: the late pages' fixes wait for the part that wrote their pages back last (RX_VK_LATE_PART=1; unset: their value)"); + return on; + }(); + return env || lab_ab::on("latepart"); +} +/// ((Triforce, 11-29) The part (its number on the recordings' timeline) after which every write-back still in flight over the +/// fix's pages is done: the newest part among the recent runs past done that cover one of them. 0 when one is not known (its +/// part not submitted, or the list was cut while it was on the GPU) or none is found: the fix waits for its value, as before. +/// One pass over the runs, the pages sorted (wb_pages_mu: taken here; the take's pools_mu held, the order of its other takes) +uint64_t late_pages_part(const std::vector>& slots, uint64_t done) { + static thread_local std::vector pages; + pages.clear(); + for (const auto& s : slots) pages.push_back(s.second); + std::sort(pages.begin(), pages.end()); + std::lock_guard lk(wb_pages_mu); + if (wb_runs_lost > done) return 0; + uint64_t part = 0; + for (const WbRun& r : wb_runs_recent) { + if (r.value <= done || r.hi <= r.lo) continue; + const auto it = std::lower_bound(pages.begin(), pages.end(), (uint32_t)(r.lo >> kPageShift)); + if (it == pages.end() || (uint64_t)*it > (r.hi - 1) >> kPageShift) continue; + const auto b = wb_batch_seq.find(r.batch); + if (b == wb_batch_seq.end()) return 0; + part = std::max(part, b->second); + } + return part; +} std::mutex late_fix_mu; std::deque late_fixes; // (late_fix_mu; in take order, values rising) std::atomic late_fix_top{0}; // (the highest value a pending fix waits for; 0: none) @@ -4524,6 +4563,16 @@ bool late_fix_slot_pending(WriteGen gen, uint32_t slot, uint64_t* value) { return false; } uint64_t memory_late_fix_pending() { return late_fix_top.load(std::memory_order_acquire); } +/// ((Triforce, 11-29) RX_VK_LATE_PART: the newest of the pending fixes' parts; 0 when one of them is not known +uint64_t memory_late_fix_part() { + std::lock_guard lk(late_fix_mu); + uint64_t part = 0; + for (const LateFix& f : late_fixes) { + if (!f.part) return 0; + part = std::max(part, f.part); + } + return part; +} /// the pending fixes whose value done has reached: their late pages copied again from guest memory into their slots (as the take /// did after its wait). The queue's lock held (vk_replay.cpp), before anything goes to the queue void memory_late_fix_apply(uint64_t done) { @@ -5264,6 +5313,7 @@ bool take_capture(std::unique_ptr c, uint64_t value, uint64_t completed f.value = lq_value, f.gen = g, f.map = (uint8_t*)c->map, f.alloc = c->alloc, f.nbytes = c->nbytes; f.slots = std::move(lq_slots); std::sort(f.slots.begin(), f.slots.end()); + if (memory_late_part_on()) f.part = late_pages_part(f.slots, vk_timeline_completed()); // ((11-29) RX_VK_LATE_PART) std::lock_guard fl(late_fix_mu); late_fixes.push_back(std::move(f)); late_fix_top.store(late_fixes.back().value, std::memory_order_release); @@ -5349,6 +5399,11 @@ bool take_capture(std::unique_ptr c, uint64_t value, uint64_t completed (long long)st_lq_deferred.exchange(0), (long long)st_lq_tex.exchange(0), (long long)st_lq_unsent.exchange(0), (long long)st_lq_full.exchange(0), (long long)st_lq_reads.exchange(0), (long long)st_lq_applied.exchange(0), (long long)qw, qns / 1e6 / 600, (long long)qto); + int64_t pw, pns, pun; // ((Triforce, 11-29) RX_VK_LATE_PART's waits at the pages' part, and the fixes whose part was not known + vk_late_part_stats(&pw, &pns, &pun); + if (pw || pun) + logf("vk: RX_VK_LATE_PART (600 takes): %lld queue waits at the part that wrote the late pages back (%.3f ms a take), " + "%lld at their value, the part not known", (long long)pw, pns / 1e6 / 600, (long long)pun); } st_tk_all = st_tk_stamp = st_tk_copy = st_tk_late = st_tk_lock = 0, st_tk_late_n = 0; st_late_needed = st_late_skipped = st_late_same = st_late_part = 0; @@ -6852,6 +6907,28 @@ std::atomic rb_collections{0}; std::atomic rb_watch_any{false}; constexpr uint64_t kRbCpuRecent = 4096; // (collections, a few seconds of play: a page the CPU stopped writing goes back) constexpr uint64_t kRbWatchMax = 0x10000; // (the largest range watched: results, not textures) +// ((Triforce, 11-29) the watched pages' bounds for wb_pages_note's question without the lock, and the question: does +// [lo, hi) cover a read-back page (wb_pages_mu held there; rb_cpu_mu is still a leaf: nothing is taken under it) +std::atomic rb_watch_lo_a{~0u}, rb_watch_hi_a{0}; +bool rb_watched(uint64_t lo, uint64_t hi) { + if (hi <= lo || !rb_watch_any.load(std::memory_order_relaxed)) return false; + const uint64_t p0 = lo >> kPageShift, p1 = (hi - 1) >> kPageShift; + if (p1 < rb_watch_lo_a.load(std::memory_order_relaxed) || p0 > rb_watch_hi_a.load(std::memory_order_relaxed)) return false; + std::lock_guard lk(rb_cpu_mu); + if (p1 - p0 < rb_watch.size()) { + for (uint64_t p = p0; p <= p1; p++) + if (rb_watch.count((uint32_t)p)) return true; + return false; + } + for (const auto& [p, at] : rb_watch) + if (p >= p0 && p <= p1) return true; + return false; +} +/// The written binding's write-back [lo, hi) queued in this part: part_rb_write once it covers a read-back page. Its branches +/// here, not in the binding: the renderer's play profile matches the binding by a hash of its control flow (a call keeps it) +void rb_write_note(uint64_t lo, uint64_t hi) { + if (!part_rb_write.load(std::memory_order_relaxed) && rb_watched(lo, hi)) part_rb_write.store(true, std::memory_order_relaxed); +} } void memory_rb_watch(uint64_t guest, uint64_t size) { if (!size || size > kRbWatchMax) return; @@ -6871,6 +6948,7 @@ void memory_rb_watch(uint64_t guest, uint64_t size) { if (rb_watch.size() > 4096 || rb_ranges_seen.size() > 16384) { // (a safety net: a game that reads back very many ranges starts over) rb_watch.clear(), rb_watch_lo = ~0u, rb_watch_hi = 0, rb_ranges_seen.clear(); } + rb_watch_lo_a.store(rb_watch_lo, std::memory_order_relaxed), rb_watch_hi_a.store(rb_watch_hi, std::memory_order_relaxed); rb_watch_any.store(!rb_watch.empty(), std::memory_order_relaxed); } /// A collection's pages, the ones the CPU wrote since the one before: the read-back pages among them noted @@ -7731,6 +7809,7 @@ BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) { } else { writebacks.push_back({p, off, wb_end, tl_event_write, early_wb_segment(p->lo + off, p->lo + wb_end, tl_event_write)}); } + rb_write_note(p->lo + off, p->lo + wb_end); // ((Triforce, 11-29) a read-back page's write-back in this part, above } rb_hazard_locked(p->lo + off, p->lo + std::min(off + size, p->hi - p->lo)); // (memory_rb_refresh) const uint64_t np = (p->hi - p->lo + 4095) >> 12; @@ -9606,6 +9685,7 @@ void msync_pass_report() { void memory_end_submission(VkCommandBuffer cmd) { std::lock_guard lk(pools_mu); + part_rb_write.store(false, std::memory_order_relaxed); // ((Triforce, 11-29) the next part's own, rb_write_note wb_batch_now.fetch_add(1, std::memory_order_relaxed); // ((Triforce, 11-28) this part's batch of write-backs: WbRun.batch { // (every 600 submissions: how the mirror syncs' dirty pages were read) static int64_t n, l_live, l_cap; @@ -10406,6 +10486,8 @@ void memory_part_submitted(uint64_t seq) { wb_batch_seq[wb_batch_now.load(std::memory_order_relaxed)] = seq; while (wb_batch_seq.size() > 8192) wb_batch_seq.erase(wb_batch_seq.begin()); } +/// ((Triforce, 11-29) whether a write-back queued in the part being recorded covers a page the CPU reads back (rb_write_note) +bool memory_part_rb_write() { return part_rb_write.load(std::memory_order_relaxed); } /// ((Triforce, 11-28) The part (its number on the recordings' timeline) whose write-back last covered any of [guest, guest + size) /// among submission value's, 0 when none is known (the range not written back under value yet, or its part not submitted) uint64_t memory_wb_part_seq(uint64_t guest, uint64_t size, uint64_t value) { diff --git a/gpu/vk/vk_menu.cpp b/gpu/vk/vk_menu.cpp index 12dcb56..a80ffb8 100644 --- a/gpu/vk/vk_menu.cpp +++ b/gpu/vk/vk_menu.cpp @@ -118,6 +118,7 @@ #endif namespace mkwvk { +bool texpack_prepare_text(char* out, size_t cap); // ((Triforce, 11-28) vk_texture.cpp: the texture pack's prepare, at the foot of the screen HWND app_window(); int texture_detail_auto(); // (vk_texture.cpp: what the video memory gives this card, -1 before the first texture) int display_refresh_mhz(); // (vk_main.cpp: the window's display, mHz; 0 when not known) @@ -138,6 +139,8 @@ int applied_dlss() { return __atomic_load_n(&applied_rows[0], __ATOMIC_RELAXED); int applied_resolution() { return __atomic_load_n(&applied_rows[1], __ATOMIC_RELAXED); } int applied_upscale_pre() { return __atomic_load_n(&applied_rows[2], __ATOMIC_RELAXED); } int menu_steady_row() { return __atomic_load_n(&opts.steady_fps, __ATOMIC_RELAXED); } +static std::atomic compare_play{0}; // ((Triforce, 11-30) the ReShade comparison's way to play: see compare_from_game +int menu_compare_play() { return compare_play.load(std::memory_order_relaxed) == 1; } namespace { @@ -2081,10 +2084,9 @@ Row rows[] = { {TAB_GRAPHICS, "Grass distance", &opts.grass_distance, 0, 3, 1, tx_grass_distance, "How far away short grass blades reach, such as Kokiri Forest's tufts and the moss on its stones. The game stops them at " "about 20 m. Higher extends their reach for some GPU time. Changes at once."}, - // ((Triforce, 11-24) opens the Simulated turf page, the TAB_SIM_TURF rows: vk_sim_turf.cpp, sim_turf_settings.h) - {TAB_GRAPHICS, "Simulated turf", nullptr, 0, 0, 0, nullptr, - "The broad field grass the game's wind and fluid simulation moves: the dense carpet that bends and ripples around Link. " - "Its fade, density and blades, area by area. Grass distance is the separate short blades."}, + // ((Triforce, 11-30) the row that opened the Simulated turf page (TAB_SIM_TURF) is gone, and the page's file is not read + // (vk_sim_turf.cpp sim_turf_init): its area edits grew the turf lists past the game's caps, and a turf program the IR pass + // left as it is read past them: the GPU hung (11-29, device lost). Every area's turf is the game's own again {TAB_GRAPHICS, "Shadow resolution", &opts.shadow_res, 0, 2, 1, tx_shadow_res, "The size of the sun's shadow maps: higher keeps the shadows of thin things near you, such as chains, fences and leaves, " "smooth instead of stair-stepped, for more video memory and a little GPU time. Highest also makes them shimmer less while " @@ -2255,6 +2257,12 @@ Row rows[] = { {TAB_SYSTEM, kNfcTag, nullptr, 0, 0, 0, nullptr, "Hold one of your own amiibo to the game's reader: choose a dump (.bin, or a Flipper .nfc) from the folder \"amiibo\" in the game folder, " "then use amiibo in the game. Choose it again to take it off."}, + // ((Triforce) host/oot_amiibo_uses.c: the game's once-a-day check of a figure answered "not used today"; taken at once, + // at the next scan) + {TAB_SYSTEM, "Unlimited amiibo uses", &opts.amiibo_unlimited, 0, 1, 1, tx_onoff, + "Off: each figure gives its reward once a day, as in the game. On: a figure can be scanned again at once, any number of " + "times, and gives its reward each time (choose it again under NFC tag for each scan). Your dumps are not changed.", + nullptr, false, true}, MENU_HEADING(TAB_SYSTEM, "Online"), {TAB_SYSTEM, "Discord status", &opts.discord, 0, 1, 1, tx_onoff, "Shows \"Playing Triforce\" and the time played in your Discord status, while Discord runs on this PC.", nullptr, false, @@ -2479,7 +2487,9 @@ Row rows[] = { "restart.", nullptr, true, true}, // ((Triforce) Threaded rendering: threaded_rendering.h, vk_main.cpp threaded_choice; RX_VK_THREADED over it. Read at the start; // Off by default again (11-24): the owner saw whole-screen flashes with it on in play that the frame log (taken before the - // window's image) does not show; +3% fps on a moving tour in the lab. On again once the flashes are fixed) + // window's image) does not show; +3% fps on a moving tour in the lab. Auto by default since options_version 11 (11-29, the + // owner: "Yes default"): the owner played Auto with the readbacks' fix for the parts' flicker (vk_replay.cpp + // rb_rec_end_mode) and saw no flicker; tour +8.4% fps with the owner's options, +4.7% with the defaults (RTX 5090)) {TAB_DEBUG, "Threaded rendering", &opts.threaded_rendering, 0, 2, 1, tx_threaded, "Experimental. The graphics work runs on threads of its own: the game's commands are turned into the graphics card's on a " "render thread while the game goes on with its next frame, the driver's calls are made by a recorder thread beside it, " @@ -2539,6 +2549,11 @@ std::atomic game_options_ns{0}; // (prof_now at the last frame the ho // ((Triforce, 11-20) that screen chosen from the pause menu (the host's word 2): its guides band may end sooner, game_grid.h // kPauseGuideBandRight) std::atomic game_options_from_pause{false}; +// ((Triforce, 11-30) the ReShade comparison asked inside the pause menu's Options (compare_leaves_menus): 1 while the host leaves +// the game's menus for play (host/nn_hid.c compare_to_play, option HOS_OPT_COMPARE_PLAY), 2 in play, 3 they stayed; 0 none. +// compare_from_game: the comparison opened so, whose Back closes the options as well (the game's menus are gone). compare_play +// itself is above the namespace, beside menu_compare_play +bool compare_from_game = false; bool embed_open = false; // (our tabs are open from inside the game's Options: leaving them is its own tab again) int64_t embed_since = 0; // (when that screen was first seen running: the tabs fade in over its opening) constexpr int kGameTab = 99; // (the tabs' hit for the game's own tab) @@ -3092,6 +3107,15 @@ std::string apply_list_shown(const char* last) { } /// A row's mark of a change not in force yet: one that takes a restart, or Apply bool row_pending(const Row& r) { return restart_changed(r) || apply_changed(r); } +/// ((Triforce, 11-30) The Compare ReShade Preset row confirmed inside the pause menu's Options: the game is paused there and its +/// scene draws nothing, and the preset is laid on the gameplay picture alone (vk_draw.cpp reshade_picture), so the comparison +/// over those screens showed the Options and the pause menu and no change at all ("ReShade Compare not taking you to gameplay +/// screen", #bug-tracker 11-30, v0.8.5.2). Then the options close and the host leaves the game's menus as Back leaves them +/// (compare_play, host/nn_hid.c compare_to_play), and the comparison opens over the game. Not from the title's Options (no +/// play to go to), nor with a question the close would ask (Apply's, the restart's): the comparison where it is, as before +bool compare_leaves_menus() { + return embed_open && game_options_from_pause.load(std::memory_order_relaxed) && !apply_ask() && !restart_ask(); +} /// What runs is the choice now, for the rows in mask (a bit a slot): applied_rows, and the slots' start values void applied_take(unsigned mask) { for (int i = 0; i < kRows; i++) { @@ -3664,8 +3688,9 @@ void save() { // migrate leaves it as it is)) static_assert(merged_rows::kVersion == 8, "the options file's version as merged_rows.h migrates to it"); // (Triforce) 9: stock and native output numbers share one schema, see output_sizes.h; 10: Plus is Tab alone, Enter no - // longer its second key, see host/nn_hid.c binds_load (the keys alone: every rule here that reads a 9 reads a 10 the same)) - out += "options_version=10\n"; + // longer its second key, see host/nn_hid.c binds_load (the keys alone: every rule here that reads a 9 reads a 10 the same); + // 11: Threaded rendering Auto by default, see menu_init (every rule that reads a 10 reads an 11 the same)) + out += "options_version=11\n"; out += others; if (!can_bind()) out += kept; // (the stick's and the camera's rows, HOS_KEY_MOVE_* and HOS_KEY_CAM_*, have no pad_ line; (Triforce, 11-24) the @@ -3957,6 +3982,25 @@ const std::vector& bindable_keys() { bool tune_mode = false; int page = 0; // 0 the options, 1 the controls, 3 the teleport list, 4 the inventory, 5 the restart question (2: was the // debug tools' own page, now on the Debug tab), 6 (Triforce) a name page: Game flags, Cutscenes, Scan amiibo +/// ((Triforce, 11-30) The Mouse sensitivity's every change in the log, with what made it and what the options and the input were +/// doing then: a player's sensitivity "goes back to 0.1 by itself", his file at 0.30 after he had set 1.10 to 1.20, and nothing +/// in his logs said who wrote it (#bug-tracker 11-30, v0.8.4 and v0.8.5.2). 0.30 is eight or nine of the row's own 0.10 steps +/// down from those, and no ten presses of the host's - and = keys (x0.8, x1.25, kept in hundredths) reach it from 1.10 or 1.20 +/// (- alone: 0.29, 0.32), so the row, the launcher or another writer of the file it is, which this tells apart. why: the +/// writer; told by each (the end of menu_tick's input: the row, its slider; menu_option_set: the host's keys; menu_init: the +/// file read at the start) and at the top of each tick for any other ("another writer") +void sens_watch(const char* why) { + static std::atomic seen{-1}; // (the menu's thread and the host's, menu_option_set, both call it) + const int now = __atomic_load_n(&opts.mouse_sens, __ATOMIC_RELAXED), last = seen.exchange(now, std::memory_order_relaxed); + if (now == last) return; + if (last < 0) logf("menu: Mouse sensitivity %.2f at the start%s", now / 100.0, strstr(why, "file") ? ", from the options file" : ""); + else + logf("menu: Mouse sensitivity %.2f -> %.2f (%s; the options %s, page %d, tab %d, row %d, inside the game's Options %d; " + "held: Left %d Right %d mouse left %d, pads %#x)", + last / 100.0, now / 100.0, why, open_now.load() ? "open" : "shut", page, cur_tab, tab_selected[cur_tab], embed_open ? 1 : 0, + (GetAsyncKeyState(VK_LEFT) & 0x8000) != 0, (GetAsyncKeyState(VK_RIGHT) & 0x8000) != 0, + (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0, menu_pad_raw); +} /// (Triforce) Whether the Mods screen's search takes the keyboard's text now (mods_text_wanted): the keys bound to the Switch's /// L, R and B (R and Shift by default) type there, so they are not our tabs and Back then (menu_tick), and the guides name /// the menu's own Q, E and Esc (ui_ctx), as the Mods screen had them before the bound keys came @@ -6572,23 +6616,39 @@ void draw_title_mods(ui::Ctx& c, bool sel, float cx, float cy, float k, float pi } /// ((Triforce) The title's tabs, Mods and Save Select at the picture's top left (title_tabs.h): each the title's own entry's /// words (draw_title_mods, the same font and size, cream with the dark edge; lit as a chosen entry's words are while the mouse -/// is over it or its Decide plays), and under it, with a controller, the icon of the button that opens it: the game's own of -/// what the Switch's X (Mods) and Y (Save Select) are bound to, as its guides show a binding. c: the grid's column, as the -/// entry's; decide: Mods' Decide plays (its tab lit until its screen comes)) +/// is over it or its Decide plays), and under it, with a controller, the prompt of the button that opens it: the pad input +/// the Switch's X (Mods) and Y (Save Select) are bound to, as menu_tick reads it, in the icon font's own icon of that input +/// on the face shown, else its name on a key's cap (title_tabs.h icon_codes: (11-30) not the Switch button's own code, the +/// Switch's letter wherever the font was not pointed at this run's controls). c: the grid's column, as the entry's; decide: +/// Mods' Decide plays (its tab lit until its screen comes)) bool game_prompts_pad(); // (below: the prompts are a controller's) game_grid::Place title_grid; // (the grid the title's entry is drawn on now: draw_mods_row's callers say) void draw_title_tabs(ui::Ctx& c, bool decide) { static const char* const labels[title_tabs::kTabs] = {"Mods", "Save Select"}; - static const char* const icons[title_tabs::kTabs] = {ui::kIconX, ui::kIconY}; - static const char* const names[title_tabs::kTabs] = {"X", "Y"}; // (no icon font: the Switch's names, as the guides' A and B) + static const int buttons[title_tabs::kTabs] = {HOS_SW_X, HOS_SW_Y}; // (the Switch's top face button and its left one) + static_assert(title_tabs::kFaceCodes * HOS_PROMPT_KEYBOARD + title_tabs::kFaceBase <= 0x10000 && HOS_PAD_N <= (int)title_tabs::kFaceCodes, + "title_tabs.h icon_codes: the controller faces' icons as host/prompts.c has them"); const game_grid::Map m = game_grid::map_of(title_grid); const int n = files_tab_shown() ? 2 : 1; const bool pad = game_prompts_pad(); + const int face = host && host->prompt_face ? host->prompt_face() : -1; // (the face the game shows now) const float unit = ui::lu(c, 1), px = ui::lu(c, kTitleText * ui::kType), ipx = ui::lu(c, title_tabs::kIcon); float lw[title_tabs::kTabs] = {}, iw[title_tabs::kTabs] = {}; + char icons[title_tabs::kTabs][4] = {}; // (each tab's icon in the font, UTF-8: "" none, its input's name instead) + const char* names[title_tabs::kTabs] = {}; // (the input's name, on a key's cap: pad_name, the face's own words) + bool bound[title_tabs::kTabs] = {}; // (its button has a pad input that menu_tick takes: else no prompt) for (int i = 0; i < n; i++) { + const int input = host && host->binding ? host->binding(HOS_BIND_PAD, buttons[i], 0) : -1; + bound[i] = hos_pad_bindable(input); + unsigned codes[2]; + title_tabs::icon_codes(face, input, HOS_PROMPT_KEYBOARD, HOS_PAD_N, codes); + for (unsigned code : codes) + if (!icons[i][0] && code && c.f.glyph && c.f.glyph->IsGlyphInFont((ImWchar)code)) title_tabs::utf8(code, icons[i]); + names[i] = pad_name(input); lw[i] = ui::size_of(c.f.body, px, labels[i]).x; - iw[i] = !pad ? 0.0f : c.f.glyph ? ui::size_of(c.f.glyph, ipx, icons[i]).x : ui::lu(c, 62); + iw[i] = !pad || !bound[i] ? 0.0f + : icons[i][0] ? ui::size_of(c.f.glyph, ipx, icons[i]).x + : ui::glyph(c, 0, 0, ui::Prompt{ui::kKey, "", names[i]}, false); } const title_tabs::Layout l = title_tabs::place(title_tabs::picture_left(title_grid, m), title_tabs::picture_top(title_grid, m), unit, lw, iw, n, pad); // (drawn inside the whole picture: its corner may be left of the column, where the window's clip rectangle left out @@ -6605,8 +6665,8 @@ void draw_title_tabs(ui::Ctx& c, bool decide) { const float show = title_anim.shown; title_label = "Quit Game", title_entry = 0, title_corner = false; std::swap(title_anim, title_tab_anim[i]); - if (!pad || show <= 0) continue; - if (c.f.glyph) { // (the icon, a dark copy a little under it: the title's sky is bright behind it) + if (!pad || !bound[i] || show <= 0) continue; + if (icons[i][0]) { // (the icon, a dark copy a little under it: the title's sky is bright behind it) const ImVec2 sz = ui::size_of(c.f.glyph, ipx, icons[i]); const ImVec2 at(std::floor(t.icon_x - sz.x * 0.5f), std::floor(t.icon_y - sz.y * 0.5f)); c.d->AddText(c.f.glyph, ipx, ImVec2(at.x, at.y + ui::lu(c, 3)), ui::rgba(0, 0, 0, (int)(140 * show)), icons[i]); @@ -8068,6 +8128,7 @@ void menu_init() { mic_tell_host(); } if (!has_resolution && old_dynres >= 0) opts.resolution = old_dynres ? 0 : 1; + sens_watch("as the options file has it, at the start"); // ((Triforce, 11-30) the value each change is logged from opts.rumble = rumble_step(opts.rumble); // (a hand-edited 60: 50, on the arrows' steps) opts.vibration = std::min(std::max(opts.vibration, 0), 2); // ((Triforce) 11-24: Auto, Basic or Off) opts.ds_hd_haptics = opts.ds_hd_haptics != 0; @@ -8093,6 +8154,10 @@ void menu_init() { // Frame pacing is on by default: a file from before wrote its old off default whether chosen or not, so every install // turns it on once; one written from 7 on keeps what was chosen) if (version < 7) opts.pace = 1; + // ((Triforce, 11-29, the owner: "Yes default") From options_version 11 Threaded rendering is Auto by default: a file + // from before wrote its old Off default whether chosen or not, so its Off becomes Auto once; On or Auto chosen stays, + // and one written from 11 on keeps what was chosen. vk_main.cpp threaded_choice reads the row after this) + if (version < 11 && opts.threaded_rendering == 0) opts.threaded_rendering = 2; // ((Triforce, 11-16, the owner: "remove monitors shape as a option keep 16:9 16:10 21:9 32:9") Before options_version 6 // the Ultrawide row's 1 was Monitor's shape; now it is 16:10. Such a file's 1 becomes the shape nearest the main // monitor's, as host/hos_main.c read it at this start (ultrawide_rows.h), on every system (main_screen) @@ -8152,6 +8217,12 @@ auto_settings::Hardware auto_hardware() { hw.integrated = p.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; // (the device's mesh shaders; a card the Mesh shaders row runs as compute has them all the same) hw.mesh_native = dev.mesh_shader || opts.mesh_mode == 1; + // ((Triforce, 11-30) the libraries asked first: before their probe dlss_why and fsr4_why answer OK ("not known yet"), and + // Auto chose AMD FSR 4 on RX 580s (#bug-tracker "Rainbow pixellation issue": the 3D covered in rainbow noise after Auto (PC) + // was turned On; the log: "Auto (this PC): new hardware: ... AMD: FSR 4 Balanced" on a Radeon RX 580), and DLSS where it + // can't run. Once each (their own locks); this runs only with Auto (this PC) On, at its choice) + dlss_probe(); + fsr4_probe(); hw.dlss_runs = dlss_why() == DLSS_OK; hw.fsr4_runs = fsr4_why() == FSR_OK; hw.vram_mb = (uint32_t)(device_vram_bytes() >> 20); @@ -9030,8 +9101,14 @@ void menu_option_set(int id, int value) { if (amiibo_said.exchange(value, std::memory_order_relaxed) != value) amiibo_new.store(true, std::memory_order_relaxed), menu_refresh = true; return; } + if (id == HOS_OPT_COMPARE_PLAY) { // ((Triforce, 11-30) the host's word: in play (2), or the game's menus stayed (3) + int asked = 1; + if (value == 2 || value == 3) compare_play.compare_exchange_strong(asked, value, std::memory_order_relaxed); + return; + } if (id != 7) return; opts.mouse_sens = std::min(std::max(value, 10), 500); // (the keys work while the menu is closed: it shows it when opened) + sens_watch("the host: its - or = key, or mouse_sens.txt moved in"); // ((Triforce, 11-30) host/nn_hid.c mouse_sens_keys save(); } @@ -9562,6 +9639,7 @@ void mic_test_tick(bool focused) { // ((Triforce, 11-26) a held Up or Down: its first repeat and each after, the game's own Options screen's (the owner's clip)) constexpr int64_t kNavFirstNs = 330000000LL, kNavStepNs = 135000000LL; void menu_tick() { + sens_watch("another writer, not the row nor the host's keys"); // ((Triforce, 11-30) none known: said if one comes std::lock_guard bridge_lk(menu_mu); // ((Triforce) the control bridge's settings: menu_setting_set) auto_tick(); // ((Triforce) Auto (this PC): a step its tuning asked for if (sim_turf_tick(prof_now())) menu_refresh = true; // ((Triforce, 11-24) the Simulated turf page: its rows' changes, the area) @@ -9877,6 +9955,13 @@ void menu_tick() { } f2_held = f2_down; } + { // ((Triforce, 11-28) Evil HD's texture pack prepared as BC7, once: its progress at the foot of the screen + char t[64]; + if (texpack_prepare_text(t, sizeof t)) { + snprintf(notice_text, sizeof notice_text, "%s", t); + notice_until = prof_now() + 500000000LL; + } + } { // (Triforce) F8, a bug capture. The window's key handler asks the host for it itself (host/display.c); where the host has // no queue of key presses (Linux) the key is read here, and asked for as the rows ask static bool f8_held = false; @@ -10163,13 +10248,27 @@ void menu_tick() { // ((Triforce) 11-24) the ReShade comparison (reshade_menu.h): its bar takes the keys and the mouse alone. Up and down its rows, // left and right its choices, confirm; back, Insert, F1 or the right button close it, the saved preset back. The options shut // another way end it too + // ((Triforce, 11-30) the comparison asked inside the pause menu's Options (compare_leaves_menus): once the host has left the + // game's menus (2: in play) it opens over the game, and its Back closes the options too, as the game's menus are gone; where + // they stayed (3) it opens where it is, as before. The options opened again meanwhile: the ask is dropped + { + int ready = compare_play.load(std::memory_order_relaxed); + if (ready == 1 && open_now.load()) compare_play.compare_exchange_strong(ready, 0, std::memory_order_relaxed); + else if ((ready == 2 || ready == 3) && compare_play.compare_exchange_strong(ready, 0, std::memory_order_relaxed)) { + open_now = true, page = 0, listening = 0, changed = true; + compare_from_game = ready == 2; + reshade_menu::start_comparison(); + logf("vk: ReShade comparison: %s", ready == 2 ? "over the game, its menus left" : "the game's menus stayed: over them"); + } + } if (reshade_menu::comparing()) { - if (!open_now.load()) reshade_menu::end_comparison(); + if (!open_now.load()) reshade_menu::end_comparison(), compare_from_game = false; else { const auto click = mouse && (ptr.pressed & HOS_MOUSE_LEFT) ? hits.at((float)mx, (float)my) : menu_hit::Hit{}; const bool cancel = press[0] || press[6] || press[5] || (mouse && (ptr.pressed & HOS_MOUSE_RIGHT)); changed |= reshade_menu::update_comparison(int(press[4]) - int(press[3]), int(press[2] || tab_right) - int(press[1] || tab_left), press[7], cancel, click); + if (!reshade_menu::comparing() && compare_from_game) compare_from_game = false, open_now = false, page = 0; for (int i = 0; i < K_N; i++) press[i] = false; tab_left = tab_right = false, moved = false; ptr.pressed = 0, ptr.wheel = 0; // (nothing of them for the page under the bar) @@ -10684,6 +10783,11 @@ void menu_tick() { else if (press[7] && is_files_row(r)) files_open(false), press[7] = false, changed = true; else if (press[7] && is_motion_row(r)) cur_tab = TAB_MOTION, tab_selected[TAB_MOTION] = 0, press[7] = false, changed = true; else if (press[7] && r.name == kNfcTag) names_open(kNamesAmiibo), press[7] = false, changed = true; // ((Triforce) 11-24) + else if (press[7] && r.name == kReshadeCompare && compare_leaves_menus()) { // ((Triforce, 11-30) to play first + compare_play.store(1, std::memory_order_relaxed); + open_now = false, page = 0, listening = 0, press[7] = false, changed = true; + logf("vk: ReShade comparison: from the pause menu's Options, its menus left for play first"); + } else if (press[7] && reshade_menu::act(r.name)) press[7] = false, changed = true; // ((Triforce) 11-24: Compare, Rescan) // ((Triforce) 11-24) the Test microphone row: on and off again (mic_test_tick tells the host) else if (press[7] && r.name == kTestMic) { @@ -10713,6 +10817,7 @@ void menu_tick() { changed = true; } } + sens_watch("the options' input at this tick: its row's Left or Right, A, a click on it or its slider"); // ((Triforce, 11-30) { // (Triforce) the options' own sounds, the game's interface sounds: what this tick's input did to the options names one // sound at most (menu_sound_events.h sound_of), which waits for the host's sound thread (menu_take_sound). None is // asked for while the Menu sounds row is at 0. A save row and the Motion row take their press for themselves diff --git a/gpu/vk/vk_menu.h b/gpu/vk/vk_menu.h index 43c188b..a156024 100644 --- a/gpu/vk/vk_menu.h +++ b/gpu/vk/vk_menu.h @@ -15,8 +15,9 @@ struct Options { int tail_early = 1; // (Triforce) Start next frame early (Debug tab, on by default since options_version 6): 1 the game's frame wait ends before its frame's upscaler and interface run on // the GPU (gpu/vk/vk_replay.cpp the early tail, tail_early.h; RX_VK_TAIL_EARLY over it); read at the start // (tail_early=, NX2navi's key) - int threaded_rendering = 0; // ((Triforce) Threaded rendering, Debug tab: 0 Off (the default: as before), 1 On, 2 Auto (by the - // physical cores); threaded_rendering.h, vk_main.cpp threaded_choice; RX_VK_THREADED over it; read at the start + int threaded_rendering = 2; // ((Triforce) Threaded rendering, Debug tab: 0 Off (as before), 1 On, 2 Auto (by the physical + // cores; the default since options_version 11, menu_init); threaded_rendering.h, vk_main.cpp + // threaded_choice; RX_VK_THREADED over it; read at the start int hdr = 0; // (hookshot) HDR10 out (vk_framegen.cpp framegen_hdr): 0 off, 1 the SDR picture expanded, 2 the game's own (native) HDR; when the display has it (the swapchain made again at once) int hdr_white = 200; // HDR paper white, nits (the picture's white) int colour_vision = 0; // ((Triforce) 11-24) Colour vision correction: 0 Off, 1 Protan, 2 Deutan, 3 Tritan; taken at each @@ -158,6 +159,8 @@ struct Options { // (host/oot_autoload.c: read once, when the title's list first shows) int autosave = 1; // (Triforce) Autosave: 1 the game's own; 0 its autosaves of going from one area to another are skipped // (host/oot_autosave.c, nx2/oot_patches.py) + int amiibo_unlimited = 0; // (Triforce) Unlimited amiibo uses: 0 the game's own, a figure gives its reward once a day; 1 its + // once-a-day check always answers "not used today" (host/oot_amiibo_uses.c, nx2/oot_patches.py) int mute_background = 0; // (Triforce) Mute in background: 1 no sound while another window has the focus (host/nn_audio.c master_volume) int mic_gain = 100; // (Triforce) Microphone gain: the ocarina's microphone, percent of what it gives, 25 to 400 (host/nn_audio_in.c, host/mic_gain.h) int invert_cam_x = 0; // right-stick camera horizontal inversion: 0 normal, 1 inverted @@ -257,6 +260,9 @@ bool resolution_full(); /// ((Triforce, 11-26) the Frame pacing row's Steady frame rate now, opts.steady_fps (host/pace_steady.h PACE_STEADY_*): the host /// reads it each frame, HOS_OPT_STEADY_ROW, so the row's Steady changes at once int menu_steady_row(); +/// ((Triforce, 11-30) 1 while the ReShade comparison asked inside the pause menu's Options waits for the game's menus to close, +/// HOS_OPT_COMPARE_PLAY (host/nn_hid.c compare_to_play taps their Back), else 0 +int menu_compare_play(); /// Whether RenoDX's shaders run in this session: the RenoDX HDR row as it was at the start, or RX_VK_RENODX bool renodx_chosen(); /// (Triforce) opts.replay_threads as the file had it at the start, and the threads a value of that row stands for: 0 none, diff --git a/gpu/vk/vk_replay.cpp b/gpu/vk/vk_replay.cpp index 49a28c8..4eeb1ee 100644 --- a/gpu/vk/vk_replay.cpp +++ b/gpu/vk/vk_replay.cpp @@ -146,6 +146,7 @@ CondNote cond_ring[1 << 15]; uint32_t cond_ring_at = 0; void memory_part_submitted(uint64_t seq); // ((Triforce, 11-28) vk_memory.cpp: a part's batch of write-backs by its number uint64_t memory_wb_part_seq(uint64_t guest, uint64_t size, uint64_t value); // (and the part that wrote a range back) +bool memory_part_rb_write(); // ((Triforce, 11-29) and whether this part writes back a page the CPU reads back namespace { // ---- submissions: a timeline semaphore; value n = the n-th submit done ---- @@ -574,11 +575,43 @@ bool vk_timeline_wait_sent(uint64_t v) { } namespace { std::atomic st_lq_waits{0}, st_lq_wait_ns{0}, st_lq_timeouts{0}; +std::atomic st_lq_part{0}, st_lq_part_ns{0}, st_lq_part_unknown{0}; +/// ((Triforce, 11-29, the performance session) RX_VK_LATE_PART (the lab knob latepart): the pending fixes' late pages waited for +/// at the part that wrote them back last (vk_memory.cpp memory_late_fix_part), on the recordings' timeline, not at their value. +/// A recording made in parts signals its value with its last part, and the pages (OoT's exposure meter and its per-frame pool) +/// may be written back parts before it: the value's wait was ~0.8 ms a frame at the owner's settings, the queue's lock held. +/// Their recording was sent whole (the take puts a fix off only then), so no later part of it writes them again, and a part +/// done is everything before it on the queue done. True: that wait made and done; false: the value's, as before (no part +/// known, no recordings' timeline, or not done in 1 s) +bool late_fix_part_wait() { + if (!rec_timeline || !memory_late_part_on()) return false; + const uint64_t seq = memory_late_fix_part(); + if (!seq) { + st_lq_part_unknown.fetch_add(1, std::memory_order_relaxed); + return false; + } + const auto t0 = std::chrono::steady_clock::now(); + bool done = false; + for (int i = 0; i < 4 && !done; i++) { + VkSemaphoreWaitInfo wi{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + wi.semaphoreCount = 1, wi.pSemaphores = &rec_timeline, wi.pValues = &seq; + const VkResult res = vkWaitSemaphores(dev.device, &wi, 250000000ull); + done = res == VK_SUCCESS; + if (res == VK_ERROR_DEVICE_LOST) break; + } + st_lq_part.fetch_add(1, std::memory_order_relaxed); + st_lq_part_ns.fetch_add(std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + return done; +} +} +void vk_late_part_stats(int64_t* waits, int64_t* wait_ns, int64_t* unknown) { + *waits = st_lq_part.exchange(0), *wait_ns = st_lq_part_ns.exchange(0), *unknown = st_lq_part_unknown.exchange(0); } void late_fix_flush_locked() { // (dev.present_mu held) const uint64_t v = memory_late_fix_pending(); if (!v) return; - if (completed() < v) { + if (completed() < v && !late_fix_part_wait()) { // ((Triforce, 11-29) RX_VK_LATE_PART: at the pages' part, above) const auto t0 = std::chrono::steady_clock::now(); if (!vk_timeline_wait_sent(v)) { static std::atomic logged{0}; @@ -3619,10 +3652,10 @@ int64_t part_draws() { // is set: unset, the knob's own number decides in its phases, and the driver's default nowhere) const char* const not_in_force = !pass_end_parts_on() ? "" - : env ? "; not in force outside the knob's phases: a part ends where the game ends its render pass (Threaded rendering, " - "RX_VK_PART_PASS_END)" - : "; not in force: a part ends where the game ends its render pass (Threaded rendering, RX_VK_PART_PASS_END; the " - "knob's phases are counted)"; + : env ? "; not in force outside the knob's phases: a part ends where the game ends its render pass (Threaded rendering " + "or NVIDIA's driver, RX_VK_PART_PASS_END)" + : "; not in force: a part ends where the game ends its render pass (Threaded rendering or NVIDIA's driver, " + "RX_VK_PART_PASS_END; the knob's phases are counted)"; logf("vk: a submission's parts: %lld draws and dispatches each (RX_VK_CHUNK%s%s; 0: whole submissions; this driver's default " "%lld; the lab knob chunk: in its phases when the variable is unset)%s", (long long)barrier_rules::part_draws(env != nullptr, env_value, v), env ? "=" : " unset", env ? env : "", (long long)v, @@ -3643,30 +3676,78 @@ int64_t part_draws() { // +4%, walking +15%, turning +2.5%; walking's 99th percentile 26.8 ms against 36.7, frames over 50 ms 20 against 44), and no // part ended inside a pass but at the ceiling. On with Threaded rendering and RX_VK_CHUNK unset; RX_VK_PART_PASS_END=1 on any // run, =0 off (counted parts of part_draws' size). Not with the lab knob chunk: in its phases (part_draws decides there) +// ((Triforce, 11-29, the performance session) and on NVIDIA's driver with Threaded rendering off too (barrier_rules.h +// part_pass_end_default: the GPU idled while a burst was recorded up to the 240-draw cut; measured in docs/development.md's +// RX_VK_PART_PASS_END row). RX_VK_PART_PASS_END=0 there: counted parts every 240, as before +// ((Triforce, 11-29, the performance session) RX_VK_PART_IDLE= (off unset; the lab's knob partidle:): a part +// after the first ends from too, not RX_VK_PART_MIN, once the GPU has done everything sent (the recordings' timeline +// at rec_seq, looked at every 8th draw past ): the first part's rule wherever the GPU waits for the next cut. part_min_now) struct PassEndParts { bool on = false; - int64_t min = 120, max = 512, first = 32; - int64_t at_pass_end = 0, ceiling = 0; + int64_t min = 120, max = 512, first = 32, idle = 0, rb = 0; + int64_t at_pass_end = 0, ceiling = 0, idle_seen = 0, rb_seen = 0; }; PassEndParts& pass_end_parts() { static PassEndParts p = [] { PassEndParts v; const char* e = getenv("RX_VK_PART_PASS_END"); - v.on = e && *e ? atoi(e) != 0 : threaded_on() && !getenv("RX_VK_CHUNK"); + const bool by_default = threaded_on() || barrier_rules::part_pass_end_default((uint32_t)dev.driver_id); + v.on = e && *e ? atoi(e) != 0 : by_default && !getenv("RX_VK_CHUNK"); const auto num = [](const char* name, int64_t def) { const char* x = getenv(name); return x && *x ? atoll(x) : def; }; v.min = std::max(1, num("RX_VK_PART_MIN", 120)); v.max = std::max(v.min, num("RX_VK_PART_MAX", 512)); v.first = std::clamp(num("RX_VK_PART_FIRST", 32), 0, v.min); + v.idle = std::clamp(num("RX_VK_PART_IDLE", 0), 0, v.min); + // ((Triforce, 11-29, the owner's decision) 32 unset where a readback of a range the CPU only reads waits for the part + // that copied it (RX_VK_RB_REC_END=3, the default with these parts: rb_rec_end_mode; asked of the switch here, as the + // mode's own reader asks these parts), so that its wait is shorter; =0, or another mode set, from RX_VK_PART_MIN + const bool range = ::mkwvk::wb_rec_wait::rec_end_mode(getenv("RX_VK_RB_REC_END"), ::mkwvk::wb_rec_wait::kRecEndRange) == + ::mkwvk::wb_rec_wait::kRecEndRange; + v.rb = std::clamp(num("RX_VK_PART_RB", range ? 32 : 0), 0, v.min); + if (v.on && v.rb) + logf("vk: a submission's parts end from %lld draws and dispatches where the part writes back a page the CPU reads back " + "(RX_VK_PART_RB%s; =0: from RX_VK_PART_MIN)", (long long)v.rb, + getenv("RX_VK_PART_RB") && *getenv("RX_VK_PART_RB") ? "" : ", the default with RX_VK_RB_REC_END=3"); + if (v.on && v.idle) + logf("vk: a submission's parts end from %lld draws and dispatches where the GPU has done everything sent " + "(RX_VK_PART_IDLE; unset: from RX_VK_PART_MIN)", (long long)v.idle); if (v.on) logf("vk: a submission's parts end where the game has ended its render pass, from %lld draws and dispatches (the first " - "part from %lld), at %lld at the latest (Threaded rendering; RX_VK_PART_PASS_END=0: counted parts of RX_VK_CHUNK or " + "part from %lld), at %lld at the latest (%s; RX_VK_PART_PASS_END=0: counted parts of RX_VK_CHUNK or " "the driver's default, RX_VK_CHUNK=120 the size before)", - (long long)v.min, (long long)v.first, (long long)v.max); + (long long)v.min, (long long)v.first, (long long)v.max, + e && *e ? "RX_VK_PART_PASS_END=1" : threaded_on() ? "Threaded rendering" : "NVIDIA's driver's default since 11-29"); return v; }(); return p; } bool pass_end_parts_on() { return pass_end_parts().on; } +// ((Triforce, 11-29) RX_VK_PART_IDLE: the draws a part after the first needs before it may end at a pass end: RX_VK_PART_MIN, or +// the idle size once the GPU has done everything sent (seen once, kept for the part: the GPU does not get busier until the +// replay submits, which ends the part). The replay's thread, as maybe_split. Its branches here, not in maybe_split: the +// renderer's play profile matches maybe_split by a hash of its control flow, and a call in place of pe.min keeps it +bool part_idle_now = false; +int64_t part_min_now(PassEndParts& pe) { + const int64_t n = part_work + 1; // (the count maybe_split compares: ++part_work) + // ((11-29) RX_VK_PART_RB, the knob partrb: a part that writes back a page the CPU reads back ends from that size, so that + // the readback's wait (RX_VK_RB_REC_END=3: for the part that copied its range) is shorter. Seen once a part, as below) + const int64_t rb = lab_ab::value_of("partrb", pe.rb); + if (rb > 0 && n >= rb && n < pe.min && memory_part_rb_write()) { + pe.rb_seen += n == rb; + return rb; + } + const int64_t idle = lab_ab::value_of("partidle", pe.idle); + if (idle <= 0 || n < idle) { + part_idle_now = false; + return pe.min; + } + if (part_idle_now) return idle; + if (n >= pe.min || (n & 7) != 0 || !rec_timeline) return pe.min; + uint64_t done = 0; + part_idle_now = vkGetSemaphoreCounterValue(dev.device, rec_timeline, &done) == VK_SUCCESS && done >= rec_seq; + pe.idle_seen += part_idle_now; + return part_idle_now ? idle : pe.min; +} // ((Triforce, RX_VK_DRY_SHORT) a short command buffer replay_handle records on the replay thread in place of its dry pass and // one segment: one segment's worth, and a segment is not split) @@ -3678,14 +3759,15 @@ void maybe_split(VkCommandBuffer& cmd) { PassEndParts& pe = pass_end_parts(); if (pe.on && !part_end_now && lab_ab::value_of("chunk", -1) < 0) { // ((Triforce) Threaded rendering's parts: above) if (part_end_wanted) return; // (waiting for the next plain draw: RX_VK_SPLIT_BEFORE_DRAW) - const int64_t need = rec_parts == 0 && pe.first ? pe.first : pe.min; + const int64_t need = rec_parts == 0 && pe.first ? pe.first : part_min_now(pe); if (!rec_cur || ++part_work < need || rec_parts + 1 >= kMaxParts || dump_on()) return; const bool ceiling = part_work >= pe.max; if (!ceiling && draw_pass_open()) return; // (the next place the game ends its pass) (ceiling ? pe.ceiling : pe.at_pass_end)++; if ((pe.ceiling + pe.at_pass_end) % 20000 == 0) - logf("vk: a submission's parts ended: %lld where the game had ended its render pass, %lld at %lld draws", - (long long)pe.at_pass_end, (long long)pe.ceiling, (long long)pe.max); + logf("vk: a submission's parts ended: %lld where the game had ended its render pass, %lld at %lld draws; the GPU " + "seen idle in %lld parts (RX_VK_PART_IDLE, partidle), %lld parts writing back a read-back page (RX_VK_PART_RB, partrb)", + (long long)pe.at_pass_end, (long long)pe.ceiling, (long long)pe.max, (long long)pe.idle_seen, (long long)pe.rb_seen); if (split_before_draw_on()) { part_end_wanted = true; return; @@ -6215,28 +6297,39 @@ bool wait_recorded(uint64_t f, uint64_t timeout_ns, int* ok) { } /// ((Triforce, 11-27) RX_VK_RB_REC_END: a readback's wait for its write-back ends at the LAST part of the recording that writes it /// back, not the first (wb_rec_wait.h readback_wait: the exposure meter read as 0 between a recording's parts, the brightness -/// flashes). On unless =0, read once +/// flashes). On unless =0, read once. ((Triforce, 11-29, the owner's decision) Unset, 3 where a submission's parts end at the +/// game's render passes (pass_end_parts: NVIDIA's driver's default, or Threaded rendering): their first part is ~32 draws, and +/// mode 2's wait for it read a later part's result a frame late, the picture's brightness pulsing with the camera moving +/// (docs/development.md's RX_VK_RB_REC_END row); else 2 int rb_rec_end_mode() { static const int v = [] { namespace wr = ::mkwvk::wb_rec_wait; - const int m = wr::rec_end_mode(getenv("RX_VK_RB_REC_END")); - logf("vk: a readback waits for %s (RX_VK_RB_REC_END=%d; =0: the first part, as before; =1: the last part, every readback, " - "as 0.8.5; =2, the default: the last part where the CPU writes the range after reading it)", + const char* e = getenv("RX_VK_RB_REC_END"); + const bool parts = pass_end_parts_on(); + const int m = wr::rec_end_mode(e, parts ? wr::kRecEndRange : wr::kRecEndCpuWritten); + logf("vk: a readback waits for %s (RX_VK_RB_REC_END=%d%s; =0: the first part, as before; =1: the last part, every readback, " + "as 0.8.5; =2, the default with counted parts: the last part where the CPU writes the range after reading it; =3, the " + "default where the parts end at the game's render passes: 2, and a range the CPU only reads at the part that copied it " + "back)", m == wr::kRecEndAll ? "the last part of the recording that writes it back" : m == wr::kRecEndCpuWritten ? "the last part of the recording that writes it back where the CPU writes the range, else the first part" + : m == wr::kRecEndRange ? "the last part of the recording that writes it back where the CPU writes the range, else the part " + "that copied the range back" : "the first part of the recording that writes it back, as before", - m); + m, e && *e ? "" : parts ? ", the default where the parts end at the game's render passes" : ", the default"); return m; }(); return v; } bool rb_rec_end_on() { return rb_rec_end_mode() != ::mkwvk::wb_rec_wait::kRecEndOff; } std::atomic st_rb_cpu_ranges{0}; // ((Triforce, 11-28) readbacks the last-part rule took, the CPU writing their range) -/// ((Triforce, 11-28) whether this readback takes the last-part rule (wb_rec_wait.h rec_end_applies) -bool rb_rec_end_for(uint64_t guest, uint64_t size) { +/// ((Triforce, 11-28) whether this readback takes the last-part rule (wb_rec_wait.h rec_end_applies); ((11-29)) else *range: +/// whether it waits for its range's part (range_applies, RX_VK_RB_REC_END=3), not the first part +bool rb_rec_end_for(uint64_t guest, uint64_t size, bool* range) { namespace wr = ::mkwvk::wb_rec_wait; const int m = rb_rec_end_mode(); - const bool cpu = m == wr::kRecEndCpuWritten && memory_rb_cpu_written(guest, size); + const bool cpu = (m == wr::kRecEndCpuWritten || m == wr::kRecEndRange) && memory_rb_cpu_written(guest, size); + *range = wr::range_applies(m, cpu); if (cpu) { st_rb_cpu_ranges.fetch_add(1, std::memory_order_relaxed); static std::mutex lm; @@ -6249,9 +6342,13 @@ bool rb_rec_end_for(uint64_t guest, uint64_t size) { return wr::rec_end_applies(m, cpu); } std::atomic st_rb_went_on{0}, st_rb_went_on_ns{0}; // ((Triforce, 11-27) readbacks whose writer's recording went on past a part) +// ((Triforce, 11-29) RX_VK_RB_REC_END=3: the read-only readbacks that waited for their range's part, and those whose part came +// after the recording's first part (what the first part's wait read a part early: a frame late)) +std::atomic st_rb_range{0}, st_rb_range_later{0}, st_rb_range_ns{0}; /// ((Triforce, 11-27) A readback's wait for write-back value v on the recordings' timeline, by the rule (rb_rec_end_on): true when -/// the writer's recording is known (the result in *ok, as wait_recorded), false when it is not (the caller's fallback) -bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) { +/// the writer's recording is known (the result in *ok, as wait_recorded), false when it is not (the caller's fallback). +/// ((11-29)) range: a range the CPU only reads, at the part that copied it back (wb_rec_wait.h readback_range_wait, mode 3) +bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok, bool range) { if (!rec_timeline || per_queue_fences_off()) return false; struct Calls { uint64_t v, guest, size; @@ -6299,7 +6396,15 @@ bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) { static const bool rb_log = getenv("RX_VK_LOG_RB_RANGE") != nullptr; const ::mkwvk::wb_rec_wait::Parts::Entry e0 = rb_log ? calls.look() : ::mkwvk::wb_rec_wait::Parts::Entry{}; const uint64_t rs0 = rb_log ? calls.range_seq() : 0; - const ::mkwvk::wb_rec_wait::ReadbackWait r = ::mkwvk::wb_rec_wait::readback_wait(rb_rec_end_on(), calls); + const ::mkwvk::wb_rec_wait::ReadbackWait r = + range ? ::mkwvk::wb_rec_wait::readback_range_wait(calls) : ::mkwvk::wb_rec_wait::readback_wait(rb_rec_end_on(), calls); + if (range && r.known) { + const uint64_t first = calls.first_part(), rs = calls.range_seq(); + st_rb_range.fetch_add(1, std::memory_order_relaxed); + if (rs > first) st_rb_range_later.fetch_add(1, std::memory_order_relaxed); + st_rb_range_ns.fetch_add(std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + } if (rb_log && r.went_on) { static std::atomic told{0}; if (told.fetch_add(1) < 60) { @@ -6326,7 +6431,9 @@ bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) { // note) left both at plain -O2, invalidate's ~460,000 calls a benchmark run among them. A call in place of a call keeps it. /// A readback's wait on the recordings' timeline: by the rule (readback_rec_wait), or the first part as before (wait_recorded) bool readback_recorded_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) { - return rb_rec_end_for(guest, size) ? readback_rec_wait(v, guest, size, ok) : wait_recorded(v, UINT64_MAX, ok); + bool range = false; + if (rb_rec_end_for(guest, size, &range)) return readback_rec_wait(v, guest, size, ok, false); + return range ? readback_rec_wait(v, guest, size, ok, true) : wait_recorded(v, UINT64_MAX, ok); } /// RX_VK_LOG_READBACK_ZERO's line, with the writer's recording now: its first part (the old wait's), its newest part and /// whether that ended it, and the recordings' timeline (a read between the parts waited for the first alone) @@ -6356,6 +6463,12 @@ void readback_went_on_line() { (long long)on, st_rb_went_on_ns.exchange(0) / (double)on / 1e6, (long long)cpu); else if (cpu) logf("vk: readbacks of GPU results: %lld took the last-part rule, the CPU writing their range; none waited past a part", (long long)cpu); + // ((Triforce, 11-29) RX_VK_RB_REC_END=3's read-only ranges) + if (const int64_t n = st_rb_range.exchange(0)) + logf("vk: readbacks of GPU results: %lld read-only ranges waited for the part that copied them back, %.3f ms each; %lld of " + "those parts came after the recording's first part (the first part's wait read them a frame late; RX_VK_RB_REC_END=2: " + "the first part)", + (long long)n, st_rb_range_ns.exchange(0) / (double)n / 1e6, (long long)st_rb_range_later.exchange(0)); } // ((Triforce, 11-22, the performance audit's SYNC-122, after Source B's) A readback whose write-back is not recorded yet // (wait_recorded said so: its writer is still being recorded, or stopped at an event wait). It waited on the submissions' @@ -9249,7 +9362,7 @@ bool present_thread_on() { static const bool on = [] { // ((Triforce, 11-16) Off by default: the lab's Market runs showed no gain (on 91.9 / 92.1 fps, off 89.4 / 93.6), and // the frame trace left only ~0.09 ms of present work on the game's thread. RX_VK_PRESENT_THREAD=1 on) - // ((Triforce) unset: Threaded rendering's present thread (threaded_rendering.h; Off by default, so off as before) + // ((Triforce) unset: Threaded rendering's present thread (threaded_rendering.h; Auto by default, Off as before) const char* e = getenv("RX_VK_PRESENT_THREAD"); const bool v = e && *e ? atoi(e) == 1 : threaded_on(); logf("vk: the game's presents go out %s (RX_VK_PRESENT_THREAD%s)", v ? "from a present thread of their own: the presenting " @@ -10146,8 +10259,8 @@ bool async_on() { // (hookshot: off by default. OoT rewrites double-buffered data right after a submit with no fence, which lands // inside a replay running behind (TotK Recomp's reason to replay on the submitting thread): whole-screen white or // black frames, 28 per 1000 gameplay frames, against 1.3 synchronous, at the same frame rate. RX_VK_ASYNC=1: on) - // ((Triforce) unset: Threaded rendering's render thread (threaded_rendering.h, vk_main.cpp threaded_choice: Off by default, so - // off as before). The host asks the same answer (HOS_OPT_RENDER_THREAD: host/rx_backend.c rx_async_replay)) + // ((Triforce) unset: Threaded rendering's render thread (threaded_rendering.h, vk_main.cpp threaded_choice: Auto by default, + // on from 4 physical cores; Off as before). The host asks the same answer (HOS_OPT_RENDER_THREAD: host/rx_backend.c rx_async_replay)) static const bool on = getenv("RX_VK_ASYNC") ? atoi(getenv("RX_VK_ASYNC")) != 0 : threaded_render_thread(); return on; } @@ -10981,6 +11094,8 @@ void fill_replay_table(MkwVkRenderer& t) { if (id == HOS_OPT_AUDIO_OUTPUT) return opts.audio_output; // ((Triforce) the Audio output row now: its Mono, host/nn_audio.c audio_mono) if (id == HOS_OPT_MUTE_BACKGROUND) return opts.mute_background != 0; // ((Triforce) the Mute in background row, host/nn_audio.c) if (id == HOS_OPT_MIC_GAIN) return std::clamp(opts.mic_gain, 25, 400); // ((Triforce) the Microphone gain row, host/nn_audio_in.c) + if (id == HOS_OPT_AMIIBO_UNLIMITED) return opts.amiibo_unlimited != 0; // ((Triforce) the Unlimited amiibo uses row, host/oot_amiibo_uses.c) + if (id == HOS_OPT_COMPARE_PLAY) return menu_compare_play(); // ((Triforce, 11-30) the ReShade comparison's way to play: host/nn_hid.c if (id == HOS_OPT_STEADY_ROW) return menu_steady_row(); // ((Triforce, 11-26) the Frame pacing row's Steady, now: host/nn_vi.c) // ((Triforce, 11-26) 2 and 3, the Render resolution as applied (vk_menu.h applied_resolution): host/nn_vi.c reads them // each frame, and the game remakes its 3D's targets when the scale changes. The 3D's full size by the applied choice diff --git a/gpu/vk/vk_sim_turf.cpp b/gpu/vk/vk_sim_turf.cpp index d282e38..cfb5fee 100644 --- a/gpu/vk/vk_sim_turf.cpp +++ b/gpu/vk/vk_sim_turf.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include "vk_loader.h" @@ -26,9 +27,15 @@ void seen_now() { seen_global = st::global, seen_multipliers = st::multipliers, } // namespace void sim_turf_init(const std::string& options_ini) { - const size_t slash = options_ini.find_last_of("\\/"); - st::config_file = (slash == std::string::npos ? std::string{} : options_ini.substr(0, slash + 1)) + "sim_turf_settings.ini"; - st::load_config(); + // ((Triforce, 11-30) the page is closed (vk_menu.cpp: no row opens it) and its file, sim_turf_settings.ini, is neither read + // nor written: a player's saved area edits are left on disk but not applied, so every area has the game's own turf and the + // renderer's own turf lists stay off (sim_turf_edited false; the 11-29 GPU hang). RX_VK_SIM_TURF_PAGE=1: as before (lab) + const char* e = getenv("RX_VK_SIM_TURF_PAGE"); + if (e && e[0] == '1') { + const size_t slash = options_ini.find_last_of("\\/"); + st::config_file = (slash == std::string::npos ? std::string{} : options_ini.substr(0, slash + 1)) + "sim_turf_settings.ini"; + st::load_config(); + } seen_now(); } diff --git a/gpu/vk/vk_temporal.cpp b/gpu/vk/vk_temporal.cpp index 749cdee..533d364 100644 --- a/gpu/vk/vk_temporal.cpp +++ b/gpu/vk/vk_temporal.cpp @@ -54,6 +54,7 @@ #include #include #include +#include #include #include "capture_tables.h" // ((Triforce, the upscaler audit's UPS-02) the stored draws' tables, kept from frame to frame) @@ -384,6 +385,8 @@ struct State { bool own = false; bool placed = false; // ((Triforce) a skinned draw's place, read at its draw (note_skinned_place): pair_copies) float place[3]{}; + bool origin_ok = false; // ((Triforce) not skinned: its object's origin as read at the draw, its place if its model has copies) + float origin[3]{}; }; // (the camera read last for a stored draw, most draws of a frame having the same one) uint64_t capture_camera = 0, capture_camera_view = 0; @@ -397,6 +400,10 @@ struct State { const bool capture_tables_kept = capture_tables::kept(getenv("RX_VK_CAPTURE_TABLES")); capture_tables::Nth captured_models{capture_tables_kept}; // (by model: its draws so far this frame, for the key's nth) capture_tables::Before captured_before{capture_tables_kept}; + // ((Triforce) the models drawn 2+ times this frame and the frame before (copies: their object's origin is read at the draw), + // and where in `captured` each model's first draw is (read once its second shows up)) + std::unordered_set multi_now, multi_before; + std::unordered_map capture_first; uint64_t captured_frame = 0; struct CaptureBuffer { VkBuffer buffer = VK_NULL_HANDLE; @@ -756,6 +763,19 @@ bool place_pairing() { return on; } +/// (Triforce) Copies without a place (not skinned: trees, rocks, pieces of ground) of a model drawn more than once get the +/// camera's motion (capture_motion, dlss_actor::unsure_copies): by their n-th draw, one took its neighbour's positions as its +/// own frame before whenever the game drew them in another order, and frame generation drew it part way to the neighbour. +/// RX_VK_DLSS_COPY_ORDER=1: by their n-th draw, as before +bool copy_order() { + static const bool on = [] { + const bool v = env_switch("RX_VK_DLSS_COPY_ORDER") > 0; + if (v) logf("vk: actor motion: copies without a place pair by draw order (RX_VK_DLSS_COPY_ORDER=1)"); + return v; + }(); + return on; +} + /// This upscale's reach (dlss_actor::place_reach), the time since the last one's taken float pairs_reach(State& s) { static const float speed = [] { @@ -777,13 +797,17 @@ float pairs_reach(State& s) { /// Which of the frame before's draws each of this frame's pairs with. keys[i]: this frame's draw's key (dlss_actor::key), /// placed[i] and places[i * 3]: its place when it has one (left out: not of the scene's depth, so not paired); then: the -/// frame before's draws with a place. Out: look[i], the frame before's key to take (has[i] 0: none, the camera's motion) +/// frame before's draws with a place. Out: look[i], the frame before's key to take (has[i] 0: none, the camera's motion). +/// by_origin[i]: its place is its object's origin (not skinned): unsure[i] is then set when its pair is not a sure one +/// (dlss_actor::ambiguous_by_place), or its model had no copy with a place the frame before (nothing to pair by): the camera's +/// motion for it, as for any copy without a place of a model with copies void pair_copies(const std::vector& keys, const std::vector& placed, const std::vector& places, - const std::vector& then, float reach, std::vector& look, - std::vector& has) { + const std::vector& by_origin, const std::vector& then, float reach, + std::vector& look, std::vector& has, std::vector& unsure) { const size_t n = keys.size(); look.assign(keys.begin(), keys.end()); has.assign(n, 1); + unsure.assign(n, 0); if (!place_pairing()) return; struct Copies { std::vector now, then; @@ -796,7 +820,10 @@ void pair_copies(const std::vector& keys, const std::vector& pla c.then.push_back({{p.place[0], p.place[1], p.place[2]}, (int)(p.key & 0xff)}); c.key.push_back(p.key); } - if (models.empty()) return; // (none had a place the frame before: by draw order, as before) + if (models.empty()) { // (none had a place the frame before: by draw order, as before) + for (size_t i = 0; i < n; i++) unsure[i] = placed[i] && by_origin[i]; + return; + } std::vector decided(n, 0); std::vector by_place(n, 0); std::vector paired(n, 0); @@ -804,7 +831,10 @@ void pair_copies(const std::vector& keys, const std::vector& pla for (size_t i = 0; i < n; i++) { if (!placed[i]) continue; const auto m = models.find(keys[i] >> 8); - if (m == models.end()) continue; // (its model had no copy with a place the frame before: by its n-th) + if (m == models.end()) { // (its model had no copy with a place the frame before: by its n-th, a guess for a copy by origin) + unsure[i] = by_origin[i]; + continue; + } m->second.now.push_back({{places[i * 3], places[i * 3 + 1], places[i * 3 + 2]}, (int)(keys[i] & 0xff)}); m->second.draw.push_back(i); decided[i] = 1; @@ -812,6 +842,9 @@ void pair_copies(const std::vector& keys, const std::vector& pla for (const auto& [model, c] : models) { if (c.now.empty()) continue; const std::vector pairs = dlss_actor::pair_by_place(c.now, c.then, reach); + const std::vector doubtful = dlss_actor::ambiguous_by_place(c.now, c.then, pairs); + for (size_t a = 0; a < pairs.size(); a++) + if (by_origin[c.draw[a]] && doubtful[a]) unsure[c.draw[a]] = 1; for (size_t a = 0; a < pairs.size(); a++) if (pairs[a] >= 0) by_place[c.draw[a]] = c.key[pairs[a]], paired[c.draw[a]] = 1, taken[c.key[pairs[a]]] = 1; } @@ -1062,7 +1095,8 @@ int actor_motion(VkCommandBuffer cmd, const Camera& cam, const float* before, co dlss_actor::place_of(k.pose.data(), k.pose.data() + dlss_actor::kPoseHead, k.nbones, &places[i * 3]); placed[i] = 1; } - pair_copies(keys, placed, places, then, pairs_reach(s), look, has); + std::vector no_origin(skins.size(), 0), no_unsure; // (skinned: every place is a pose's, never unsure) + pair_copies(keys, placed, places, no_origin, then, pairs_reach(s), look, has, no_unsure); for (size_t i = 0; i < skins.size(); i++) { const State::Skin& k = skins[i]; if (k.k.depth != cam.depth) { @@ -1163,7 +1197,8 @@ constexpr uint32_t kCaptureMostSlots = 1u << 20; // (a draw's) std::vector take_captures() { State& s = st(); std::vector c = std::move(s.captured); - s.captured.clear(), s.captured_models.clear(); + s.captured.clear(), s.captured_models.clear(), s.capture_first.clear(); + s.multi_before.swap(s.multi_now), s.multi_now.clear(); // ((Triforce, UPS-02) the next frame's list at this frame's size from its start: moved from, it grew from nothing again // every frame, a dozen times over) s.captured.reserve(capture_tables::room(c.size(), s.capture_tables_kept)); @@ -1209,20 +1244,60 @@ int capture_motion(VkCommandBuffer cmd, const Camera& cam, const float* before, if (c.k.depth == cam.depth) s.captured_before.put(c.key, c); // ((Triforce) which of the frame before's each pairs with: copies of a skinned model by place, pair_copies) std::vector keys(caps.size()), look; - std::vector placed(caps.size(), 0), has; + std::vector placed(caps.size(), 0), has, by_origin(caps.size(), 0), origin_unsure; std::vector places(caps.size() * 3, 0.0f); std::vector then; if (old_ok) then = std::move(s.placed_before); s.placed_before.clear(); + // ((Triforce) the copies without a skin, of a model with copies (drawn 2+ times this frame, or its 2nd the frame before), + // whose object's origin was read are placed by it. A model drawn once keeps its own pairing: it may move fast) + const bool by_place = !copy_order(); // (recorded also without history: the next frame pairs by it) + std::vector origin_set(caps.size(), 0); + if (by_place) { + std::vector scene_keys; + std::vector readable; + std::vector scene_at; + for (size_t i = 0; i < caps.size(); i++) + if (caps[i].k.depth == cam.depth && !caps[i].placed) + scene_keys.push_back(caps[i].key), readable.push_back(caps[i].origin_ok), scene_at.push_back(i); + const std::vector w = dlss_actor::place_by_origin( + scene_keys, readable, [&](uint64_t k) { return s.captured_before.before(k) != nullptr; }); + for (size_t j = 0; j < w.size(); j++) origin_set[scene_at[j]] = w[j]; + } for (size_t i = 0; i < caps.size(); i++) { const State::Captured& c = caps[i]; keys[i] = c.key; - if (c.k.depth != cam.depth || !c.placed) continue; - placed[i] = 1; - for (int a = 0; a < 3; a++) places[i * 3 + a] = c.place[a]; - s.placed_before.push_back({c.key, {c.place[0], c.place[1], c.place[2]}}); + if (c.k.depth != cam.depth) continue; + if (c.placed) { + placed[i] = 1; + for (int a = 0; a < 3; a++) places[i * 3 + a] = c.place[a]; + } else if (origin_set[i]) { + placed[i] = by_origin[i] = 1; + for (int a = 0; a < 3; a++) places[i * 3 + a] = c.origin[a]; + } + if (placed[i]) s.placed_before.push_back({c.key, {places[i * 3], places[i * 3 + 1], places[i * 3 + 2]}}); + } + pair_copies(keys, placed, places, by_origin, then, pairs_reach(s), look, has, origin_unsure); + // ((Triforce) a copy without a place of a model drawn more than once: its n-th the frame before is a guess, the camera's + // motion instead. dlss_actor::unsure_copies) + std::vector unsure(caps.size(), 0); + if (old_ok && !copy_order()) { + std::vector scene_keys; + std::vector scene_placed; + std::vector scene_at; + for (size_t i = 0; i < caps.size(); i++) + if (caps[i].k.depth == cam.depth) + scene_keys.push_back(keys[i]), scene_placed.push_back(placed[i]), scene_at.push_back(i); + const std::vector u = dlss_actor::unsure_copies( + scene_keys, scene_placed, [&](uint64_t k) { return s.captured_before.before(k) != nullptr; }); + for (size_t j = 0; j < u.size(); j++) unsure[scene_at[j]] = u[j]; + std::unordered_set then_keys; + for (const auto& p : then) then_keys.insert(p.key); + const std::vector lost = dlss_actor::lost_second_copy( + keys, by_origin, [&](uint64_t k) { return s.captured_before.before(k) != nullptr; }, + [&](uint64_t k) { return then_keys.count(k) != 0; }); + for (size_t i = 0; i < caps.size(); i++) unsure[i] = unsure[i] || origin_unsure[i] || lost[i]; } - pair_copies(keys, placed, places, then, pairs_reach(s), look, has); // (RX_VK_DLSS_TRACE=: on vk_draw.cpp's traced frames, each stored draw left out here and why) static const int trace_every = env_switch("RX_VK_DLSS_TRACE"); const uint64_t now = texture_frame_no(); @@ -1231,6 +1306,37 @@ int capture_motion(VkCommandBuffer cmd, const Camera& cam, const float* before, if (trace) logf("vk: dlss-trace capture left out: prog %016llx vb %llx ib %llx n%d: %s", (unsigned long long)c.k.program, (unsigned long long)c.k.vbuf, (unsigned long long)c.k.ibuf, c.k.count, why); }; + // (RX_VK_DLSS_TRACE: the 8 models with most copies placed by their object's origin: whether that origin is a place. key>>8, + // copies, how many differ, how many are flagged (unsure), the least and greatest distance between two of them) + if (trace && by_place) { + struct Group { + uint64_t model; + std::vector at; + int flagged = 0; + }; + std::unordered_map index; + std::vector groups; + for (size_t i = 0; i < caps.size(); i++) { + if (caps[i].k.depth != cam.depth || caps[i].placed || !caps[i].origin_ok) continue; // (by origin, or over the cap) + const auto it = index.emplace(keys[i] >> 8, groups.size()); + if (it.second) groups.push_back({keys[i] >> 8, {}, 0}); + Group& g = groups[it.first->second]; + g.at.push_back({{caps[i].origin[0], caps[i].origin[1], caps[i].origin[2]}, (int)(keys[i] & 0xff)}); + g.flagged += old_ok && unsure[i]; + } + std::sort(groups.begin(), groups.end(), [](const Group& a, const Group& b) { return a.at.size() > b.at.size(); }); + for (size_t g = 0; g < groups.size() && g < 8; g++) { + const bool over = groups[g].at.size() > dlss_actor::kCopyCap; // (not paired by place: all flagged, nothing measured) + const dlss_actor::Spread sp = over ? dlss_actor::Spread{} : dlss_actor::origin_spread(groups[g].at); + if (over) + logf("vk: dlss-trace f%llu copy origins: model %llx copies %zu over cap (camera motion for all)%s", (unsigned long long)now, + (unsigned long long)groups[g].model, groups[g].at.size(), old_ok ? "" : " (no history)"); + else + logf("vk: dlss-trace f%llu copy origins: model %llx copies %zu distinct %d flagged %d gap min %g max %g%s", + (unsigned long long)now, (unsigned long long)groups[g].model, groups[g].at.size(), sp.distinct, groups[g].flagged, + (double)sp.min_gap, (double)sp.max_gap, old_ok ? "" : " (no history)"); + } + } if (caps.empty() || !make_capture_pipeline()) return 0; struct Redraw { dlss_actor::CapturePush push; @@ -1245,6 +1351,11 @@ int capture_motion(VkCommandBuffer cmd, const Camera& cam, const float* before, left(c, "another depth target than the scene's"); continue; } + if (unsure[i]) { + s.actor_skipped++; + left(c, "a copy of a model drawn more than once, with no place to pair by"); + continue; + } const State::Captured* const was = old_ok && has[i] ? s.captured_before.before(look[i]) : nullptr; if (!was) { s.actor_skipped++; @@ -1450,6 +1561,7 @@ void drop_all() { } s.poses.clear(), s.skins.clear(), s.model_bones.clear(); s.captured.clear(), s.captured_models.clear(), s.captured_before.clear(), s.index_ranges.clear(); + s.capture_first.clear(), s.multi_now.clear(), s.multi_before.clear(); s.capture_used = 0, s.captured_frame = 0; if (!s.depth_views.empty()) { auto old = std::move(s.depth_views); @@ -1827,7 +1939,7 @@ void temporal_capture_draw(const CaptureDraw& k, CaptureSlot* out) { // buffer given out again. Left to pile up, the buffer ran out there, and was made twice as large for nothing) const uint64_t frame = texture_frame_no(); if (frame > s.capture_frame + 1 || s.captured.size() >= 32768) { - s.captured.clear(), s.captured_models.clear(); + s.captured.clear(), s.captured_models.clear(), s.capture_first.clear(), s.multi_now.clear(), s.multi_before.clear(); s.capture_used = 0, s.capture_full = false; } if (s.captured.empty()) s.capture_frame = frame; @@ -1888,6 +2000,34 @@ void temporal_capture_draw(const CaptureDraw& k, CaptureSlot* out) { c.placed = true; for (int a = 0; a < 3; a++) c.place[a] = skin_place.place[a]; } + // ((Triforce) a draw without a skin: its object's place (buffer 4: a 3x4 row-major world matrix, the translation at +0x0c, + // +0x1c, +0x2c; dlss_actor::object_place; the skinned draws' origin at 0x40 is not it), the place of one of the + // copies of its model (capture_motion decides which are). Read only for a model that has copies: its 2nd or later draw, or + // its 1st when it had a 2nd the frame before; its 1st otherwise is read when its 2nd shows up. Read as submitted; not + // readable or not a world matrix: none, and its copies then go by unsure_copies as before) + if (!placed && place_pairing() && !copy_order()) { + const auto read_origin = [](State::Captured& d) { + float m[12], o[3]; + if (d.k.object && d.k.object_size >= 0x30 && memory_read_as_submitted(d.k.object, m, sizeof m) && + dlss_actor::object_place(m, o)) { + d.origin_ok = true; + for (int a = 0; a < 3; a++) d.origin[a] = o[a]; + } + }; + const uint64_t group = c.key >> 8; + if (nth == 0) { + s.capture_first[group] = s.captured.size(); // (c's place in captured, pushed below) + if (s.multi_before.count(group)) read_origin(c); + } else { + s.multi_now.insert(group); + read_origin(c); + const auto first = nth == 1 ? s.capture_first.find(group) : s.capture_first.end(); + if (first != s.capture_first.end() && first->second < s.captured.size()) { + State::Captured& f = s.captured[first->second]; + if (f.key >> 8 == group && !f.placed && !f.origin_ok) read_origin(f); + } + } + } // (the jitter of the camera it is drawn with, as submitted: read again when the address or the captures' view changes) if (k.camera && k.camera_size >= 0xb0) { const uint64_t view = memory_capture_view(); diff --git a/gpu/vk/vk_temporal.h b/gpu/vk/vk_temporal.h index a1d6190..ed466b2 100644 --- a/gpu/vk/vk_temporal.h +++ b/gpu/vk/vk_temporal.h @@ -107,6 +107,7 @@ struct CaptureDraw { int itype = 0, count = 0, base_vertex = 0; uint64_t program = 0; uint64_t camera = 0, camera_size = 0; // (the vertex stage's uniform buffer 3: the camera it is drawn with, its jitter) + uint64_t object = 0, object_size = 0; // ((Triforce) its object buffer, buffer 4: a skinned draw's origin at 0x40, a plain draw's world matrix at 0) VkPrimitiveTopology topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; bool restart = false; // (primitive restart, as the draw has it) uint64_t stream_pos = 0; // (Triforce: its place in the stream, as SkinnedDraw's) diff --git a/gpu/vk/vk_texture.cpp b/gpu/vk/vk_texture.cpp index dfc767a..c8abf23 100644 --- a/gpu/vk/vk_texture.cpp +++ b/gpu/vk/vk_texture.cpp @@ -77,6 +77,7 @@ #include "linux_pressure.h" // ((Triforce, 11-22) the performance audit's MEM-141: the swap hold's valves here (arenas, malloc_trim, budget) #include "tex_detail.h" #include "tex_pack.h" // ((Triforce, 11-24) Evil HD's texture pack: pack_view) +#include "tex_pack_bc7.h" // ((Triforce, 11-28) the pack as BC7, prepared once: texpack) #include "vk_mods.h" // (its files decoded as the Mods page's pictures are) #include #include @@ -5541,18 +5542,17 @@ VkImageView twin3d_view(Texture* tex, VkFormat f, uint32_t level0, uint32_t nlev // ---- ((Triforce, 11-24) Evil HD's texture pack, tex_pack.h) While Evil HD is on, a colour texture the pack has a file for is // sampled from an image of its own, twice each way, made from that file (an AI upscale of the texture, the pack's tool's): the -// game's image and memory are as they were. The file is read and decoded off the replay (a thread of its own, Windows' WIC as -// the Mods page's pictures); once it is there the texture's views go stale (views_gone, destroy_gen) and its next sampled -// view (texture_view) makes the image: RGBA8, its levels made by blits from the file's, in the uploads of that recording, as -// the 3D twin above is. A texture the GPU writes, or one of another shape, is never taken. The pack's images together stay -// under kPackBudget of video memory; past it none is made. RX_VK_TEX_PACK=0: no pack; RX_VK_TEX_PACK_LOG=1: each key looked +// game's image and memory are as they were. ((Triforce, 11-28) The pack's PNGs are prepared once as BC7 files (tex_pack_bc7.h, +// prepare_start: the first time Evil HD is on, on most of the cores, the foot of the screen saying how far), and none is used +// before that is done, so they turn HD together. A texture's file is then read off the replay (kReaders threads); once it is +// there the texture's views go stale (views_gone, destroy_gen) and its next sampled view (texture_view) makes the image: BC7 with +// the file's levels, in the uploads of that recording, as the 3D twin above is. A texture the GPU writes, or one of another +// shape, is never taken; which ones is the tier's, by the card, once a run; images go only past the emergency line +// (texpack_pressure). RX_VK_TEX_PACK=0: no pack; RX_VK_TEX_PACK_LOG=1: each key looked // up, found or not (the lab's, to make a pack for a place). The folder: triforce_texpack in the game folder ---- namespace texpack { -constexpr uint64_t kPackBudget = 3ull << 30; -// ((Triforce, 11-27) the pack's share of the card (texpack_pressure): a fifth of what the driver allows, kPackBudget at most; -// and whether the use is past the line where the pack's images go before any of the game's textures (no new one meanwhile) -uint64_t cap = kPackBudget; +// (whether the use is past the emergency line, texpack_pressure: no new image meanwhile) bool pressed = false; /// A pack file's picture as RGBA8 (false: not a picture this reads) bool decode_png(const std::string& bytes, std::vector& rgba, int* w, int* h) { @@ -5572,22 +5572,22 @@ constexpr char kSep = '\\'; #else constexpr char kSep = '/'; #endif +// ((Triforce, 11-28) a texture's prepared file as read: its size, its levels (each BC7, level 0 first) one after another struct Decoded { int w = 0, h = 0; - std::vector rgba; - // (the pack's own smaller levels, _m1.png on, when it has them: the texture's own level 0 as is, its halves made - // sharp: what is seen from afar stays the game's. Each half the one before, or the list stops there) - std::vector more; + uint32_t levels = 0; + std::vector data; }; // ((Triforce, 11-25) his v0.8.0 stutter: every decoded file stayed in RAM for good (private 15.7 -> 28 GB, the PC 1.6 GB free). -// Now a decoded file is held only until its image is made (take), or kKeepFrames when no look takes it; the decoder waits -// while kRamCap of them are held; the images made in one present stay under kMakeBudget of staging; and the views of the -// textures whose file came go stale together every kFlipEvery presents, not at each file (each flip renews the descriptors)) +// Now a read file is held only until its image is made (take), or kKeepFrames when no look takes it; the readers wait while +// kRamCap of them are held; the images made in one present stay under kMakeBudget of staging; and the views of the textures +// whose file came go stale together every kFlipEvery presents, not at each file (each flip renews the descriptors)) constexpr uint64_t kRamCap = 768ull << 20; -constexpr uint64_t kMakeBudget = 96ull << 20; -constexpr uint64_t kFlipEvery = 8; +constexpr uint64_t kMakeBudget = 192ull << 20; // ((Triforce, 11-28) BC7: four times the textures of the RGBA8 96 MB) +constexpr uint64_t kFlipEvery = 4; constexpr uint64_t kKeepFrames = 240; -constexpr uint64_t kRetryFrames = 600; // (a texture the budget turned away: asked again no sooner) +constexpr uint64_t kRetryFrames = 600; // (a texture the emergency line turned away: asked again no sooner) +constexpr int kReaders = 4; struct Held { std::shared_ptr d; uint64_t bytes = 0, frame = 0; // (its RAM; the present it came at) @@ -5595,14 +5595,160 @@ struct Held { std::mutex mu; std::condition_variable cv; std::deque queue; -std::unordered_set index, asked; // (asked: being decoded or held in done; out of both once taken or let go) +std::unordered_set index, asked; // (asked: being read or held in done; out of both once taken or let go) std::unordered_map done; -std::vector> waiting; // (textures whose file is being decoded: their views go stale when it is) +std::vector> waiting; // (textures whose file is being read: their views go stale when it is) std::vector> retry; // (textures whose image waits for a later present's kMakeBudget) std::atomic done_count{0}, done_bytes{0}, frame_no{0}; uint64_t bytes = 0; // (the pack's images' video memory; the replay thread's) uint64_t made_now = 0; // (the staging of the images made in this present; the replay thread's) std::string folder; +// ((Triforce, 11-28) the prepare: every pack file as BC7 in folder/bc7, once (tex_pack_bc7.h). No pack image is used before it +// is done, so the textures turn HD together. tier: the textures it stands in for, by the card (-1 until the first look) +std::atomic ready{false}, prepare_began{false}; +std::atomic prep_total{0}, prep_done{0}, prep_made{0}, prep_failed{0}; +std::atomic ready_at_ns{0}; +std::atomic tier{-1}; +std::string file_of(uint64_t k, const char* tail) { + char name[40]; + std::snprintf(name, sizeof name, "%016llx%s", (unsigned long long)k, tail); + return folder + kSep + name; +} +std::string bc7_path(uint64_t k) { + char name[40]; + std::snprintf(name, sizeof name, "bc7%c%016llx.bc7", kSep, (unsigned long long)k); + return folder + kSep + name; +} +bool read_all(const std::string& path, std::string& out) { + out.clear(); + FILE* f = fopen(path.c_str(), "rb"); + if (!f) return false; + fseek(f, 0, SEEK_END); + const long size = ftell(f); + fseek(f, 0, SEEK_SET); + if (size > 0) { + out.resize((size_t)size); + if (fread(out.data(), 1, out.size(), f) != out.size()) out.clear(); + } + fclose(f); + return !out.empty(); +} +uint64_t file_size(const std::string& path) { + std::error_code ec; + const auto n = std::filesystem::file_size(path, ec); + return ec ? 0 : (uint64_t)n; +} +/// A pack file's prepared BC7 file is there, whole, and of its PNG as it is now +bool prepared(uint64_t k) { + namespace tb = tex_pack_bc7; + const std::string path = bc7_path(k); + const uint64_t n = file_size(path); + if (n < tb::kHeader) return false; + uint8_t head[tb::kHeader]; + FILE* f = fopen(path.c_str(), "rb"); + if (!f) return false; + const bool got = fread(head, 1, sizeof head, f) == sizeof head; + fclose(f); + if (!got) return false; + uint32_t v[5]; + std::memcpy(v, head, sizeof v); + tb::Header hd; + hd.w = v[2], hd.h = v[3], hd.levels = v[4]; + std::memcpy(&hd.png_size, head + sizeof v, 8); + return v[0] == tb::kMagic && v[1] == tb::kVersion && hd.w && hd.h && hd.levels && + tb::file_bytes(hd.w, hd.h, hd.levels) == n && hd.png_size == file_size(file_of(k, ".png")); +} +/// One pack file made BC7: its PNG, its own smaller levels (_m1.png on: the texture's own level 0 as is, its halves made +/// sharp, while each is half the one before), the rest halved down to 1 x 1, each level encoded; written beside, then renamed +bool prepare_one(uint64_t k) { + namespace tb = tex_pack_bc7; + std::string bytes_in; + std::vector rgba; + int w = 0, h = 0; + if (!read_all(file_of(k, ".png"), bytes_in) || !decode_png(bytes_in, rgba, &w, &h) || w <= 0 || h <= 0) return false; + const uint32_t levels = tb::full_levels((uint32_t)w, (uint32_t)h); + tb::Header hd; + hd.w = (uint32_t)w, hd.h = (uint32_t)h, hd.levels = levels, hd.png_size = (uint64_t)bytes_in.size(); + std::vector out((size_t)tb::file_bytes(hd.w, hd.h, levels)); + tb::write_header(out.data(), hd); + size_t at = tb::kHeader; + std::vector cur(rgba.begin(), rgba.end()); + uint32_t cw = hd.w, ch = hd.h; + bool own = true; + for (uint32_t l = 0; l < levels; l++) { + if (l) { + uint32_t nw = 0, nh = 0; + std::vector m; + int mw = 0, mh = 0; + char tail[16]; + std::snprintf(tail, sizeof tail, "_m%u.png", l); + if (own && read_all(file_of(k, tail), bytes_in) && decode_png(bytes_in, m, &mw, &mh) && + (uint32_t)mw == std::max(1u, cw / 2) && (uint32_t)mh == std::max(1u, ch / 2)) { + cur.assign(m.begin(), m.end()), nw = (uint32_t)mw, nh = (uint32_t)mh; + } else { + own = false; + cur = tb::half(cur, cw, ch, &nw, &nh); + } + cw = nw, ch = nh; + } + tb::encode(cur.data(), cw, ch, out.data() + at); + at += (size_t)tb::level_bytes(cw, ch); + } + const std::string path = bc7_path(k), part = path + ".part"; + FILE* f = fopen(part.c_str(), "wb"); + if (!f) return false; + const bool wrote = fwrite(out.data(), 1, out.size(), f) == out.size(); + fclose(f); + std::error_code ec; + if (wrote) std::filesystem::rename(part, path, ec); + if (!wrote || ec) { + std::filesystem::remove(part, ec); + return false; + } + return true; +} +/// (texpack_tick, the first time Evil HD is on) Every pack file not prepared yet, on every core but four (two at least), below +/// the game's threads; then ready +void prepare_start() { + if (prepare_began.exchange(true)) return; + auto list = std::make_shared>(index.begin(), index.end()); + prep_total = list->size(); + std::error_code ec; + std::filesystem::create_directories(folder + kSep + "bc7", ec); + const unsigned hw = std::max(1u, std::thread::hardware_concurrency()); + const unsigned n = hw > 6 ? hw - 4 : 2u; + auto next = std::make_shared>(0); + auto left = std::make_shared>(n); + const auto t0 = std::chrono::steady_clock::now(); + logf("vk: texture pack: preparing its %zu textures as BC7 (once: %s%cbc7) on %u threads", list->size(), folder.c_str(), kSep, n); + for (unsigned t = 0; t < n; t++) + std::thread([next, left, list, t0, n] { +#ifdef _WIN32 + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); +#endif + for (size_t i; (i = next->fetch_add(1)) < list->size();) { + const uint64_t k = (*list)[i]; + if (!prepared(k)) { + if (prepare_one(k)) prep_made.fetch_add(1); + else { + prep_failed.fetch_add(1); + static std::atomic told{0}; + if (told.fetch_add(1) < 8) + logf("vk: texture pack: %016llx could not be prepared (its PNG unread or not a picture)", (unsigned long long)k); + } + } + prep_done.fetch_add(1); + } + if (left->fetch_sub(1) == 1) { + const double s = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + logf("vk: texture pack: prepared: %llu made now, %llu there already, %llu failed, in %.1f s on %u threads: the pack's " + "textures in use from here", (unsigned long long)prep_made.load(), + (unsigned long long)(prep_total.load() - prep_made.load() - prep_failed.load()), (unsigned long long)prep_failed.load(), s, n); + ready_at_ns = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); + ready = true; + } + }).detach(); +} bool on() { static const bool v = [] { if (const char* e = getenv("RX_VK_TEX_PACK"); e && !strcmp(e, "0")) return false; @@ -5623,64 +5769,36 @@ bool on() { } logf("vk: Evil HD texture pack: %zu textures in %s", index.size(), folder.c_str()); if (index.empty()) return false; - std::thread([] { - for (;;) { - uint64_t k; - { - std::unique_lock lk(mu); - cv.wait(lk, [] { return !queue.empty() && done_bytes.load(std::memory_order_relaxed) < kRamCap; }); - k = queue.front(); - queue.pop_front(); - } - char name[24]; - tex_pack::file_name(k, name); - auto d = std::make_shared(); - std::string bytes_in; - if (FILE* f = fopen((folder + kSep + name).c_str(), "rb")) { - fseek(f, 0, SEEK_END); - const long size = ftell(f); - fseek(f, 0, SEEK_SET); - if (size > 0) { - bytes_in.resize((size_t)size); - if (fread(bytes_in.data(), 1, bytes_in.size(), f) != bytes_in.size()) bytes_in.clear(); + for (int r = 0; r < kReaders; r++) // ((Triforce, 11-28) the prepared files, read as they are asked for) + std::thread([] { + for (;;) { + uint64_t k; + { + std::unique_lock lk(mu); + cv.wait(lk, [] { return !queue.empty() && done_bytes.load(std::memory_order_relaxed) < kRamCap; }); + k = queue.front(); + queue.pop_front(); } - fclose(f); - } - if (bytes_in.empty() || !decode_png(bytes_in, d->rgba, &d->w, &d->h)) d->w = d->h = 0; - for (int m = 1; d->w && m < 16; m++) { - char more[40]; - std::snprintf(more, sizeof more, "%016llx_m%d.png", (unsigned long long)k, m); - std::string b; - if (FILE* f = fopen((folder + kSep + more).c_str(), "rb")) { - fseek(f, 0, SEEK_END); - const long size = ftell(f); - fseek(f, 0, SEEK_SET); - if (size > 0) { - b.resize((size_t)size); - if (fread(b.data(), 1, b.size(), f) != b.size()) b.clear(); - } - fclose(f); + auto d = std::make_shared(); + std::string bytes_in; + tex_pack_bc7::Header hd; + if (read_all(bc7_path(k), bytes_in) && + tex_pack_bc7::read_header((const uint8_t*)bytes_in.data(), bytes_in.size(), &hd)) { + d->w = (int)hd.w, d->h = (int)hd.h, d->levels = hd.levels; + d->data.assign(bytes_in.begin() + tex_pack_bc7::kHeader, bytes_in.end()); } - Decoded l; - const int pw = m == 1 ? d->w : d->more.back().w, ph = m == 1 ? d->h : d->more.back().h; - if (b.empty() || !decode_png(b, l.rgba, &l.w, &l.h) || l.w != std::max(1, pw / 2) || - l.h != std::max(1, ph / 2)) - break; - d->more.push_back(std::move(l)); + const uint64_t held = d->data.size(); + { + std::lock_guard lk(mu); + asked.insert(k); // (held: not asked again; let go after kKeepFrames if no look takes it) + Held& h = done[k]; + done_bytes -= h.bytes; + h = {d, held, frame_no.load(std::memory_order_relaxed)}; + done_bytes += held; + } + done_count.fetch_add(1, std::memory_order_release); } - uint64_t held = d->rgba.size(); - for (const auto& l : d->more) held += l.rgba.size(); - { - std::lock_guard lk(mu); - asked.insert(k); // (held: not asked again; let go after kKeepFrames if no look takes it) - Held& h = done[k]; - done_bytes -= h.bytes; - h = {d, held, frame_no.load(std::memory_order_relaxed)}; - done_bytes += held; - } - done_count.fetch_add(1, std::memory_order_release); - } - }).detach(); + }).detach(); return true; }(); return v; @@ -5785,12 +5903,17 @@ bool srgb(VkFormat f) { /// The pack's view of a texture sampled flat (type 2D, one layer) while Evil HD is on: the game's levels from level0, nlevels /// of them, as the image twice its size has them (its level L is the game's L - 1: one level more on top). VK_NULL_HANDLE: -/// the game's own view (no file for it, not decoded yet, another shape, the GPU writes it, no memory) +/// the game's own view (no file for it, not read yet, another shape, the GPU writes it, not its tier, the pack not prepared yet) +/// ((Triforce, 11-28) BC7 from the prepared file (tex_pack_bc7.h), its levels as the file has them: no blit, no budget share. +/// Which textures is the tier's, decided once by the card; only the emergency line (texpack_pressure) lets images go) VkImageView pack_view(Texture* tex, VkFormat f, uint32_t level0, uint32_t nlevels, const VkComponentMapping& cm, VkFormat* format_out) { - if (tex->pack_state == 1 || !texpack::on()) return VK_NULL_HANDLE; + namespace tb = tex_pack_bc7; + if (tex->pack_state == 1 || !texpack::on() || !texpack::ready.load(std::memory_order_acquire)) return VK_NULL_HANDLE; + const int tier = texpack::tier.load(std::memory_order_relaxed); + if (tier < 0) return VK_NULL_HANDLE; // (the card not known yet) const uint32_t fw = tex->width << tex->skip, fh = tex->height << tex->skip; if (tex->type != VK_IMAGE_TYPE_2D || tex->layers != 1 || tex->cube || tex->sparse || tex->aspect != VK_IMAGE_ASPECT_COLOR_BIT || - tex->samples != VK_SAMPLE_COUNT_1_BIT || !tex_pack::wanted(true, 1, true, fw, fh)) { + tex->samples != VK_SAMPLE_COUNT_1_BIT || !tex_pack::wanted(true, 1, true, fw, fh) || !tb::tier_wants((tb::Tier)tier, fw, fh)) { tex->pack_state = 1; // (never one the pack stands in for) return VK_NULL_HANDLE; } @@ -5813,69 +5936,61 @@ VkImageView pack_view(Texture* tex, VkFormat f, uint32_t level0, uint32_t nlevel } texpack::want(tex); } - // ((Triforce, 11-25) 4: its image did not fit kPackBudget, its file let go: asked again once there is room) - const uint64_t want_need = (uint64_t)fw * tex_pack::kScale * fh * tex_pack::kScale * 4 * 4 / 3; - if (tex->pack_state == 4 && texpack::frame_no.load(std::memory_order_relaxed) >= tex->pack_retry_at && !texpack::pressed && - texpack::bytes + want_need <= texpack::cap) + // (4: let go at the emergency line, its file too: asked again once the use is back under it) + const uint32_t w = fw * tex_pack::kScale, h = fh * tex_pack::kScale; + uint32_t levels = 1; + while (levels < tex->levels + tex->skip + 1 && (std::max(w, h) >> levels)) levels++; + uint64_t need = 0; + for (uint32_t l = 0; l < levels; l++) need += tb::level_bytes(std::max(1u, w >> l), std::max(1u, h >> l)); + if (tex->pack_state == 4 && texpack::frame_no.load(std::memory_order_relaxed) >= tex->pack_retry_at && !texpack::pressed) texpack::want(tex); if (tex->pack_state != 3) return VK_NULL_HANDLE; if (!tex->hd) { - if (texpack::bytes + want_need > texpack::cap || texpack::pressed) { // ((Triforce, 11-27) its share, and not under pressure) - static std::atomic told{0}; - if (told.fetch_add(1) < 4) logf("vk: texture pack: its %llu MB of video memory are used: the game's own textures from here", - (unsigned long long)(texpack::bytes >> 20)); - texpack::let_go(tex->pack_key); // (not held in RAM meanwhile) + if (texpack::pressed) { // (the emergency line: no new image while the use is past it) + texpack::let_go(tex->pack_key); tex->pack_state = 4, tex->pack_retry_at = texpack::frame_no.load(std::memory_order_relaxed) + texpack::kRetryFrames; return VK_NULL_HANDLE; } - if (texpack::made_now && texpack::made_now + want_need > texpack::kMakeBudget) { // (the next presents': no spike) + if (texpack::made_now && texpack::made_now + need > texpack::kMakeBudget) { // (the next presents': no spike) texpack::later(tex); return VK_NULL_HANDLE; } const auto d = texpack::take(tex->pack_key); - if (!d) { // (let go before a look took it: decoded again) + if (!d) { // (let go before a look took it: read again) texpack::want(tex); return VK_NULL_HANDLE; } - if (d->w != (int)(fw * tex_pack::kScale) || d->h != (int)(fh * tex_pack::kScale)) { + if (d->w != (int)w || d->h != (int)h || d->levels < levels) { static std::atomic told{0}; if (told.fetch_add(1) < 16) - logf("vk: texture pack: %016llx is %dx%d, not twice %ux%u: the game's own", (unsigned long long)tex->pack_key, - d->w, d->h, fw, fh); + logf("vk: texture pack: %016llx is %dx%d with %u levels, not twice %ux%u with %u: the game's own (its prepared file " + "missing or another's)", (unsigned long long)tex->pack_key, d->w, d->h, d->levels, fw, fh, levels); tex->pack_state = 1; return VK_NULL_HANDLE; } - const uint32_t w = (uint32_t)d->w, h = (uint32_t)d->h; - uint32_t levels = 1; - while (levels < tex->levels + tex->skip + 1 && (std::max(w, h) >> levels)) levels++; - const uint64_t need = (uint64_t)w * h * 4 * 4 / 3; VkImageCreateInfo ci{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ci.imageType = VK_IMAGE_TYPE_2D, ci.format = VK_FORMAT_R8G8B8A8_UNORM; + ci.imageType = VK_IMAGE_TYPE_2D, ci.format = VK_FORMAT_BC7_UNORM_BLOCK; ci.extent = {w, h, 1}, ci.mipLevels = levels, ci.arrayLayers = 1, ci.samples = VK_SAMPLE_COUNT_1_BIT; ci.tiling = VK_IMAGE_TILING_OPTIMAL; - ci.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + ci.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; ci.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; // (seen as sRGB where the game's view is) - uint64_t staged = (uint64_t)w * h * 4; - uint32_t own = 1; // (levels the pack gives: level 0 and its _m files, as many as the image has) - for (const auto& l : d->more) - if (own < levels) staged += ((uint64_t)l.w * l.h * 4 + 255) & ~255ull, own++; - const Staging s = staging(staged + 256, 256); + const Staging s = staging(need + 256, 256); if (!s.buffer || !create_image(ci, tex->hd, tex->hd_alloc, false, false, false)) { tex->hd = VK_NULL_HANDLE, tex->hd_alloc = nullptr; return VK_NULL_HANDLE; } std::vector regions; + std::memcpy(s.data, d->data.data(), (size_t)need); // (the file's levels one after another, as the copies read them) { uint64_t at = 0; - for (uint32_t l = 0; l < own; l++) { - const texpack::Decoded& src = l == 0 ? *d : d->more[l - 1]; - std::memcpy(s.data + at, src.rgba.data(), (size_t)src.w * src.h * 4); + for (uint32_t l = 0; l < levels; l++) { + const uint32_t lw = std::max(1u, w >> l), lh = std::max(1u, h >> l); VkBufferImageCopy r{}; r.bufferOffset = s.offset + at; r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, l, 0, 1}; - r.imageExtent = {(uint32_t)src.w, (uint32_t)src.h, 1}; + r.imageExtent = {lw, lh, 1}; regions.push_back(r); - at += ((uint64_t)src.w * src.h * 4 + 255) & ~255ull; + at += tb::level_bytes(lw, lh); } flush_mapped_range(s.allocation, s.offset, at); } @@ -5894,30 +6009,21 @@ VkImageView pack_view(Texture* tex, VkFormat f, uint32_t level0, uint32_t nlevel } VkCommandBuffer cmd = upload_cmd(); vkCmdCopyBufferToImage(cmd, s.buffer, tex->hd, VK_IMAGE_LAYOUT_GENERAL, (uint32_t)regions.size(), regions.data()); - for (uint32_t l = own; l < levels; l++) { // (each level the pack does not give, from the one above) - full_barrier(cmd, "barrier (Evil HD's texture pack: a level made)"); - VkImageBlit bl{}; - bl.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, l - 1, 0, 1}; - bl.srcOffsets[1] = {(int32_t)std::max(1u, w >> (l - 1)), (int32_t)std::max(1u, h >> (l - 1)), 1}; - bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, l, 0, 1}; - bl.dstOffsets[1] = {(int32_t)std::max(1u, w >> l), (int32_t)std::max(1u, h >> l), 1}; - vkCmdBlitImage(cmd, tex->hd, VK_IMAGE_LAYOUT_GENERAL, tex->hd, VK_IMAGE_LAYOUT_GENERAL, 1, &bl, VK_FILTER_LINEAR); - } full_barrier(cmd, "barrier (Evil HD's texture pack: made)"); tex->hd_levels = levels, tex->hd_bytes = need; texpack::bytes += need; - texpack::made_now += staged; + texpack::made_now += need; static std::atomic made{0}; const int m = made.fetch_add(1) + 1; if (m <= 8 || !(m & (m - 1))) - logf("vk: texture pack: %d made so far (%016llx, %ux%u from %ux%u; %llu MB in all; decoded files held %llu MB)", m, + logf("vk: texture pack: %d made so far (%016llx, %ux%u BC7 from %ux%u; %llu MB in all; read files held %llu MB)", m, (unsigned long long)tex->pack_key, w, h, fw, fh, (unsigned long long)(texpack::bytes >> 20), (unsigned long long)(texpack::done_bytes.load(std::memory_order_relaxed) >> 20)); } // (the game's level L is the pack's L + 1: the pack's level0 = the game's image level + its skip, one level more on top) const uint32_t l0 = std::min(level0 + tex->skip, tex->hd_levels - 1); const uint32_t nl = std::clamp(nlevels + 1, 1, tex->hd_levels - l0); - const VkFormat hf = texpack::srgb(f) ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; + const VkFormat hf = texpack::srgb(f) ? VK_FORMAT_BC7_SRGB_BLOCK : VK_FORMAT_BC7_UNORM_BLOCK; uint64_t key = mix((uint64_t)hf, (uint64_t)l0 << 32 | nl); key = mix(key, (uint64_t)cm.r << 24 | (uint64_t)cm.g << 16 | (uint64_t)cm.b << 8 | cm.a); if (format_out) *format_out = hf; @@ -5941,19 +6047,32 @@ void texpack_gone(Texture& tex) { texpack::bytes -= std::min(texpack::bytes, (uint64_t)tex.hd_bytes); tex.hd = VK_NULL_HANDLE, tex.hd_alloc = nullptr, tex.hd_views.clear(); } -/// ((Triforce, 11-27) texture_frame's, each look with the driver's count: the pack's share and its yielding. A player's RX 6800 -/// XT (16 GB, ~13.5 GB allowed) ran Castle Town at ~30 fps with "textures 3489 MB (budget 1208 MB)": the pack's images (up to -/// 3 GB) were not textures to the budget, so the live line squeezed the game's own instead, which were made again at every -/// turn (texture lookups 20 ms a frame), each taking its pack image with it to be decoded again; an RTX 3060 Ti (8 GB, 1440p) -/// lost its device at "textures 1041 MB (budget 181 MB)". Now the pack's share is a fifth of what the driver allows (3 GB at -/// most), and past 75% of it (under the textures' own lines: the live one's ~80%, the 90% rule) the pack's images go first, the least recently used, down to 2% under that line, before any of -/// the game's textures: those textures are drawn from the game's own image (pack_state 4, asked again after kRetryFrames once -/// the use is back under the line). No pack image is made while the use is past it -void texpack_pressure(bool known, uint64_t pressure, uint64_t allowed) { +/// ((Triforce, 11-27/28) texture_frame's, each look with the driver's count. 11-27: a player's RX 6800 XT (16 GB) ran Castle Town at +/// ~30 fps with the pack's RGBA8 images (up to 3 GB) outside the textures' budget, and an RTX 3060 Ti (8 GB) lost its device; so +/// the pack had a share and gave way at 75%, then 88%. The owner, 11-28: "A texture pack should just reduce fps and have all the +/// textures showing instead of popping in random textures as hd ... its not even constant". So the pack is BC7 (a quarter of the +/// memory) and which textures it stands in for is decided once a run by what the driver allows (tex_pack_bc7.h tier_for: at +/// Hyrule Field 4.7 GB for all, 2.7 GB without those of 1024 or more), the same textures every time. Its images are let go only +/// at the emergency line, 95% of what the driver allows (RX_VK_TEX_PACK_LINE=, 20 to 98), the least recently used, down to 2% +/// under it, before the device runs short; none is made while the use is past it +void texpack_pressure(bool known, uint64_t pressure, uint64_t allowed, uint64_t /*live_pct*/) { + namespace tb = tex_pack_bc7; if (!texpack::on() || !known || !allowed) return; - texpack::cap = std::min(texpack::kPackBudget, allowed / 5); - // (RX_VK_TEX_PACK_LINE=, 20 to 95: another line, the lab's way to see the yielding on a card with room) - static const uint64_t pct = getenv("RX_VK_TEX_PACK_LINE") ? (uint64_t)std::clamp(atoi(getenv("RX_VK_TEX_PACK_LINE")), 20, 95) : 75; + if (texpack::tier.load(std::memory_order_relaxed) < 0) { // (once: the card's tier, or the lab's) + static const int env = tb::tier_env(getenv("RX_VK_TEX_PACK_TIER")); + VkFormatProperties fp{}; + vkGetPhysicalDeviceFormatProperties(dev.physical, VK_FORMAT_BC7_UNORM_BLOCK, &fp); + const bool bc7 = dev.features.textureCompressionBC && (fp.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT); + uint64_t heap = 0; // (the card's own memory: the same every run) + for (uint32_t h = 0; h < dev.memory.memoryHeapCount; h++) + if (dev.memory.memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) heap = std::max(heap, (uint64_t)dev.memory.memoryHeaps[h].size); + const tb::Tier t = !bc7 ? tb::kNone : env >= 0 ? (tb::Tier)env : tb::tier_for(heap >> 20); + texpack::tier = (int)t; + logf("vk: texture pack: a card of %llu MB (%llu MB allowed now): it stands in for %s%s (RX_VK_TEX_PACK_TIER=0-3)", + (unsigned long long)(heap >> 20), (unsigned long long)(allowed >> 20), tb::tier_name(t), + !bc7 ? "; this GPU samples no BC7" : env >= 0 ? ", by RX_VK_TEX_PACK_TIER" : ""); + } + static const uint64_t pct = getenv("RX_VK_TEX_PACK_LINE") ? (uint64_t)std::clamp(atoi(getenv("RX_VK_TEX_PACK_LINE")), 20, 98) : 95; const uint64_t line = allowed / 100 * pct; texpack::pressed = pressure > line; if (!texpack::pressed || !texpack::bytes) return; @@ -5970,7 +6089,7 @@ void texpack_pressure(bool known, uint64_t pressure, uint64_t allowed) { freed += t->hd_bytes; views_gone.went(t->id); texpack_gone(*t); - texpack::let_go(t->pack_key); // (its decoded file not held in RAM meanwhile) + texpack::let_go(t->pack_key); // (its read file not held in RAM meanwhile) t->pack_state = 4, t->pack_retry_at = now + texpack::kRetryFrames; n++; } @@ -5978,10 +6097,26 @@ void texpack_pressure(bool known, uint64_t pressure, uint64_t allowed) { destroy_gen++; static std::atomic told{0}; if (told.fetch_add(1, std::memory_order_relaxed) < 8) - logf("vk: texture pack: VRAM past %llu%% of what the driver allows (%llu of %llu MB): %d of its images let go first, %llu MB " - "(the least recently used; %llu MB of them now, its share %llu MB)", (unsigned long long)pct, (unsigned long long)(pressure >> 20), - (unsigned long long)(allowed >> 20), n, (unsigned long long)(freed >> 20), (unsigned long long)(texpack::bytes >> 20), - (unsigned long long)(texpack::cap >> 20)); + logf("vk: texture pack: VRAM past %llu%% of what the driver allows (%llu of %llu MB), the emergency line: %d of its images let " + "go, %llu MB (the least recently used; %llu MB of them now)", (unsigned long long)pct, (unsigned long long)(pressure >> 20), + (unsigned long long)(allowed >> 20), n, (unsigned long long)(freed >> 20), (unsigned long long)(texpack::bytes >> 20)); +} +/// ((Triforce, 11-28) the foot-of-screen line while the pack is prepared (vk_menu.cpp shows it): true with the text while the +/// prepare runs with files to make, and for 4 s after it ended +bool texpack_prepare_text(char* out, size_t cap) { + if (!texpack::prepare_began.load(std::memory_order_relaxed)) return false; + const uint64_t total = texpack::prep_total.load(), done_n = texpack::prep_done.load(), made = texpack::prep_made.load(); + if (!texpack::ready.load(std::memory_order_acquire)) { + if (!made && done_n < total / 20) return false; // (still checking the files there: nothing said yet) + std::snprintf(out, cap, "Evil HD: preparing HD textures (once) %llu%%", + (unsigned long long)(total ? done_n * 100 / total : 100)); + return true; + } + if (!made) return false; + const int64_t now = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); + if (now - texpack::ready_at_ns.load() > 4000000000LL) return false; + std::snprintf(out, cap, "Evil HD: HD textures ready"); + return true; } /// (texture_frame) decoded files' textures, and Evil HD turned (F2, the row): the views that had the game's or the pack's /// image go stale, so the next look takes the other @@ -5990,6 +6125,29 @@ void texpack_tick() { texpack::frame(); static int was = -1; const int now = evil_hd_now(); + if (now) texpack::prepare_start(); // ((Triforce, 11-28) once: the pack as BC7 (a few minutes the first time, then none)) + if (now && texpack::ready.load(std::memory_order_acquire) && texpack::frame_no.load(std::memory_order_relaxed) % 1200 == 0) { + // (every 1,200 presents while it is in use, 40 lines: the textures it stands in for and those waiting, by state) + static int told = 0; + if (told < 40) { + int st[5] = {}, hd = 0; + for (auto& kv : textures) + if (kv.second) st[std::min(kv.second->pack_state, 4)]++, hd += kv.second->hd != VK_NULL_HANDLE; + told++; + logf("vk: texture pack: %d textures drawn from it (%llu MB), %d being read, %d read and waiting for their image, %d let " + "go at the emergency line; %d not its, %d not looked at yet", hd, (unsigned long long)(texpack::bytes >> 20), st[2], + st[3] - hd > 0 ? st[3] - hd : 0, st[4], st[1], st[0]); + } + } + { // (prepared: every texture looks again, so the pack's turn HD together) + static bool was_ready = false; + if (!was_ready && texpack::ready.load(std::memory_order_acquire)) { + was_ready = true; + for (auto& kv : textures) + if (kv.second && kv.second->pack_state != 1) views_gone.went(kv.second->id); + destroy_gen++; + } + } if (was >= 0 && now != was) { bool any = false; const uint64_t before = texpack::bytes; @@ -8342,7 +8500,7 @@ void texture_frame(uint64_t completed) { if (textures_pool_usage(&pool_blocks, &pool_free)) reclaim = vram_compact::reclaimable(block_free, pool_free); } const uint64_t pressure = by_blocks ? used : used - std::min(used, reclaim); - texpack_pressure(known, pressure, allowed); // ((Triforce, 11-27) Evil HD's pack yields first: texpack_pressure) + texpack_pressure(known, pressure, allowed, press.live ? press_pct : 0); // ((Triforce, 11-27/28) Evil HD's pack: texpack_pressure) pool_pressed = known && pressure > allowed / 10 * 9; // (the target pool given back meanwhile) pool_tier = target_pool::tier(known, pressure, allowed); // ((Triforce, 11-21, TEX-29) halved above 90%, none above 97%) compact.pressed = known && vram_compact::pressed(used, allowed); // (hookshot, RX_VK_COMPACT: by the driver's own count) diff --git a/gpu/vk/vk_vendor.h b/gpu/vk/vk_vendor.h index 1001dff..40a351a 100644 --- a/gpu/vk/vk_vendor.h +++ b/gpu/vk/vk_vendor.h @@ -40,6 +40,15 @@ struct VendorFixes { // for these drivers (the AMD and Intel ones, and the mobile ones Eden runs on): shadow edges drawn as dashed lines without it. // RX_VK_GATHER_OFFSET bool gather_offset = false; + // ((Triforce, 11-30) Robust buffer access on (vk_main.cpp: robustBufferAccess and robustBufferAccess2), whatever the Debug + // tab's Robust buffers row says, for Intel's Windows driver. With it off (the row's default since 11-17) an Arc B570, an + // Arc Pro B70 and an Arc A770 lost the device at the title's first button press, all three in the frame the file select + // first draws, at the draws of its text (program 0ed5737e4ec64d5d, whose vertex stage reads each glyph's 224 bytes from + // a storage buffer by its instance, unchecked: the game's own global loads) or just before them; an Arc B580 with the row + // On went through the same frame and played on. Out-of-range buffer reads are dropped then, not followed to an unmapped + // address. Not in the translation (but for what fetch_bounds_buffers leaves to it, which the program cache's stamp + // counts, on these GPUs alone). RX_VK_ROBUST (vk_main.cpp's switch, read there before this) forces it either way + bool robust_buffers = false; }; /// Which of the fixes the device needs (before the RX_VK_ switches: vendor_fixes_env) @@ -75,6 +84,7 @@ inline VendorFixes vendor_fixes(const VendorFacts& f) { default: break; } + x.robust_buffers = f.driver_id == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS; return x; } @@ -86,6 +96,7 @@ template void vendor_fixes_env(VendorFixes& x, Get get) { over("RX_VK_FETCH_BOUNDS", x.fetch_bounds); over("RX_VK_NAN_BITS", x.nan_bits); over("RX_VK_GATHER_OFFSET", x.gather_offset); + over("RX_VK_ROBUST", x.robust_buffers); } } // namespace mkwvk diff --git a/gpu/vk/wb_rec_wait.h b/gpu/vk/wb_rec_wait.h index 51371b4..04ef313 100644 --- a/gpu/vk/wb_rec_wait.h +++ b/gpu/vk/wb_rec_wait.h @@ -254,16 +254,28 @@ struct Parts { /// 0.8.5.1 turned it off. Now, by default, a readback waits for the last part where the CPU writes the range after reading it /// (kRecEndCpuWritten: the exposure meter, whose late read lost the CPU's 0 and flashed), and for the first part, as before, /// where it only reads it (a frame late at worst, then the next read has it). vk_memory.cpp memory_rb_cpu_written -enum RecEnd { kRecEndOff = 0, kRecEndAll = 1, kRecEndCpuWritten = 2 }; -/// The mode from the switch's text: unset or empty, 2 (the CPU-written ranges); 0 or a word (atoi, as the renderer's other -/// switches), off: the first part, as before; 1, every readback, as 0.8.5; another number, 2 -inline int rec_end_mode(const char* text) { - if (!text || !*text) return kRecEndCpuWritten; +/// ((Triforce, 11-29) kRecEndRange: mode 2, and a range the CPU only reads waits for the part that copied it back (Parts' range, +/// readback_range_wait below), not the recording's first part. The first part is the first ~32 draws where a submission's parts end +/// at the game's render passes (vk_replay.cpp pass_end_parts, on NVIDIA's driver by default since 11-29): a result written back +/// in a later part was read as it was a frame before, and one of them moves OoT's exposure: with the camera moving the whole +/// picture went ~5 levels brighter for 15 presents and back, three times in 30 s at Kakariko (the performance session's +/// moving-camera picture check), and never with the parts counted (240 draws, the first part 240 too) or with mode 1) +enum RecEnd { kRecEndOff = 0, kRecEndAll = 1, kRecEndCpuWritten = 2, kRecEndRange = 3 }; +/// The mode from the switch's text: unset or empty, `unset` (2, the CPU-written ranges; ((Triforce, 11-29, the owner's +/// decision)) 3 where a submission's parts end at the game's render passes: vk_replay.cpp rb_rec_end_mode); 0 or a word (atoi, +/// as the renderer's other switches), off: the first part, as before; 1, every readback, as 0.8.5; 3, 2 and the read-only +/// ranges at their part; another number, 2 +inline int rec_end_mode(const char* text, int unset = kRecEndCpuWritten) { + if (!text || !*text) return unset; const int v = std::atoi(text); - return v == 0 ? kRecEndOff : v == 1 ? kRecEndAll : kRecEndCpuWritten; + return v == 0 ? kRecEndOff : v == 1 ? kRecEndAll : v == 3 ? kRecEndRange : kRecEndCpuWritten; } -/// Whether a readback takes the last-part rule: by the mode, and in mode 2 whether the CPU writes its range (cpu_written) -inline bool rec_end_applies(int mode, bool cpu_written) { return mode == kRecEndAll || (mode == kRecEndCpuWritten && cpu_written); } +/// Whether a readback takes the last-part rule: by the mode, and in modes 2 and 3 whether the CPU writes its range (cpu_written) +inline bool rec_end_applies(int mode, bool cpu_written) { + return mode == kRecEndAll || ((mode == kRecEndCpuWritten || mode == kRecEndRange) && cpu_written); +} +/// ((Triforce, 11-29) Whether a readback the last-part rule did not take waits for its range's part (mode 3), not the first part +inline bool range_applies(int mode, bool cpu_written) { return mode == kRecEndRange && !cpu_written; } /// The switch on at all (a mode other than 0) inline bool rec_end_on(const char* text) { return rec_end_mode(text) != kRecEndOff; } @@ -329,4 +341,55 @@ ReadbackWait readback_wait(bool rec_end, D& d) { return r; } +/// ((Triforce, 11-29) RX_VK_RB_REC_END=3's wait for a range the CPU only reads: the part whose write-back covered the range (d's +/// range_seq: vk_memory.cpp memory_wb_part_seq, the part's batch noted at its submit), not the recording's first part. While no part +/// of the recording is known to have copied the range back, the newest part submitted is waited for and the recording looked at +/// again between 1 ms slices of the submissions' timeline (as the last-part rule), until the range's part is known (then that part), +/// the recording has ended (then all its parts are done: a range none of them noted, its runs dropped once done, is not waited for +/// again), or the timeline reaches the value. A range one part copied back and a later one copies again is read at the first of +/// them (the result of that part: a frame late at worst, as before, but never at the first part when a later one wrote it). A +/// recording whose parts are not known at all: the first part, as before (the old lookup), else the caller's fallback. +/// d as readback_wait's, with uint64_t range_seq() the part that copied the read's range back, 0 while none is known +template +ReadbackWait readback_range_wait(D& d) { + ReadbackWait r; + Parts::Entry e = d.look(); + if (!e.seq) { + const uint64_t seq = d.first_part(); + if (!seq) return r; + r.known = true; + r.ok = d.rec_wait(seq) == 0; + return r; + } + r.known = true; + for (;;) { + const uint64_t rs = d.range_seq(); + if (rs) { // (the part that copied the range back) + r.ok = d.rec_wait(rs) == 0; + return r; + } + if (d.rec_wait(e.seq) != 0) return r; // (the newest part submitted: never past what the recording has sent) + if (e.ended) { + r.ok = true; + return r; + } + r.went_on = true; // (a part, and the range not copied back by any part submitted yet) + for (;;) { + d.flush(); // (a batched submit's part is noted once the batch goes out: RX_VK_PEND_HELD) + const Parts::Entry n = d.look(); + if (n.ended || n.seq != e.seq || d.range_seq()) { + e = n; + break; + } + const int s = d.slice(); + r.slices++; + if (s == 0) { // (the timeline at the value: every recording up to it done) + r.ok = true; + return r; + } + if (s != 1) return r; + } + } +} + } // namespace mkwvk::wb_rec_wait diff --git a/host/hos_main.c b/host/hos_main.c index 3b25762..16f4e3c 100644 --- a/host/hos_main.c +++ b/host/hos_main.c @@ -883,6 +883,7 @@ static const unsigned char oot_item_kinds[] = {OOT_CHEAT_ITEMS(OOT_NO_SECTION, O static int oot_gamedata_bool(Ctx *c, uint32_t hash, int *value); static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size); static int oot_first_night_fix(Ctx *c, const char *map); /* (below, after the tools it uses) */ +static int oot_adult_map_fix(Ctx *c, const char *map); /* (below too) */ static void oot_inventory_refresh(Ctx *c, int64_t now) { void rx_option_set(int id, int value); @@ -891,9 +892,10 @@ static void oot_inventory_refresh(Ctx *c, int64_t now) { next = now + 500000000LL; /* (a save is loaded once the pouch answers: before that GameData holds a new game's values, shown as unknown) */ const int loaded = oot_pouch_count(c, oot_item_names[0]) >= 0; - { /* (the map Link is in, Sequence_CurrentBanc: the first night's time lock is Hyrule Field's alone) */ + { /* (the map Link is in, Sequence_CurrentBanc: the first night's time lock is repaired by it) */ char map[80] = ""; - if (loaded && oot_gamedata_string(c, 0x1d6189dau, map, sizeof map) && map[0]) oot_first_night_fix(c, map); + if (loaded && oot_gamedata_string(c, 0x1d6189dau, map, sizeof map) && map[0]) + oot_first_night_fix(c, map), oot_adult_map_fix(c, map); /* ((Triforce, 11-30) and the adult's maps, #1576602300313506086) */ /* ((Triforce) the map and Link's age, logged when either changes: the window after a crash says "while you were playing" from these lines (host/hos_crash_dialog.h), and a log's reader sees where a problem happened */ static char logged[100]; @@ -1286,28 +1288,6 @@ static int oot_gamedata_set_bool(Ctx *c, uint32_t hash, int value) { return 0; } -/* The first adult night's time lock: f_8347c020 holds the clock at 20:00 while the saved Bool - HrlField_isFirstNightTime_Adult (0x8592aa82) is 1 and quest 0x4dbca27f is not Ready. The flag belongs to Hyrule - Field's first night only. A save in any other map that still holds it cannot leave night (the Sun's Song and the Debug - tab's time are overwritten, the clock snaps back): clear it there with the game's own Bool, once, and say so, never - while an event (the escape's cutscene) is running. HOS_OOT_FIRST_NIGHT_FIX=0 turns the repair off for a run. Returns 1 - when it cleared the flag. Asked by oot_inventory_refresh, twice a second while a save is loaded. */ -static int oot_first_night_fix(Ctx *c, const char *map) { - static int on = -1; - if (on < 0) { - const char *e = getenv("HOS_OOT_FIRST_NIGHT_FIX"); - on = !(e && *e && atoi(e) == 0); - } - if (!on || !map[0] || !strncmp(map, "HyruleField", 11)) return 0; - const uint64_t events = oot_singleton(c, OOT_EVENTMGR_SLOT); - if (events && recomp_load64(c, events + 104)) return 0; /* (the Main sequence's "Event" test: an event is playing) */ - int set = 0; - if (!oot_gamedata_bool(c, 0x8592aa82u, &set) || !set) return 0; - if (!oot_gamedata_set_bool(c, 0x8592aa82u, 0)) return 0; - hos_log("oot: cleared the first adult night's time lock (the save was in %s, outside Hyrule Field)", map); - return 1; -} - /* ---- (Triforce, 11-13) The inventory in GameData ---- The items are GameData: struct "Pouch" (0x3da094e3) has a struct for each item, whose member "Stock" (0x22344481) is an Int, the item's count; struct 0xade0ef78 has a Bool for each item, "got it once". The names' hashes are MurmurHash3 @@ -1393,6 +1373,78 @@ static int oot_gd_set(Ctx *c, uint64_t mgr, uint32_t hash, uint32_t value, int i return 1; } +/* The first adult night's time lock. f_8347c020, which the clock's update f_803edf70 asks twice a frame, holds the clock + (zeroes its step and puts it back at the hour, before a time request is taken: the Sun's Song's 06:00 lasts one frame) while + quest Meet_DekuTree (0x4dbca27f) is past its step Ready, the game's first quest, so from the opening on, and either the Bool + HyruleField_ArriveEntrance (0x804aec99) is 0, at 06:00 (the child's morning until Goto_HyruleCastle sets it), or + HrlField_HasEnteredFirstTime_Adult (0x8592aa82) is 1, at 20:00 (f_8347c450's hours at 0x83ca34e8). ((Triforce, 11-30) + 0x8592aa82 is HrlField_HasEnteredFirstTime_Adult by its MurmurHash3; this said HrlField_isFirstNightTime_Adult, which is + 0xf1024b60 and no hold reads.) Two event flows in the whole romfs name it: the first time Link becomes an adult Sheik's + cutscene sets it (Dm_TimeTemple_0055, its Event252), and the adult Market's gate into Hyrule Field, whose arrival is + Dm_SY_BancChangeArrive's entry Dm_SY_BancChangeArrive_HyruleField_02 (Banc/Market/Market_Adult_Static), clears it as its + first event (Event257, Event434). So the night is the adult Temple of Time's and Market's until Link first walks out of + the gate, and that is left to the game. What the game never clears is repaired here, once no event plays, through the + game's own Bool setter (oot_gd_set: the live value and the save's copy; the live byte alone, as this wrote it before, + came back as 1 at the next load, and the gate's clear saw 0 and skipped): + - a child holding it (became an adult and went back before the gate: no child's way out clears it, #1064), anywhere; + - an adult holding it in Hyrule Field's map (HyruleField_Adult, with Lon Lon Ranch and Lake Hylia): out without the + gate's arrival, or a save the earlier live-only clear left with 1 saved, which is held at 20:00 for good there. + An adult in any other map (the Market and Temple of Time: the first night itself) keeps it. HOS_OOT_FIRST_NIGHT_FIX=0 + turns the repair off for a run. Returns 1 when it cleared the flag. Asked by oot_inventory_refresh, twice a second while + a save is loaded. */ +static int oot_first_night_fix(Ctx *c, const char *map) { + static int on = -1; + if (on < 0) { + const char *e = getenv("HOS_OOT_FIRST_NIGHT_FIX"); + on = !(e && *e && atoi(e) == 0); + } + if (!on || !map[0]) return 0; + const uint64_t events = oot_singleton(c, OOT_EVENTMGR_SLOT); + if (events && recomp_load64(c, events + 104)) return 0; /* (the Main sequence's "Event" test: an event is playing) */ + int set = 0, child = 0; + if (!oot_gamedata_bool(c, 0x8592aa82u, &set) || !set) return 0; + if (!oot_gamedata_bool(c, 0xcea220d3u, &child)) return 0; /* (Sequence_IsChildhood) */ + const int field = !strncmp(map, "HyruleField", 11); + if (!child && !field) return 0; /* (the adult Market and Temple of Time: the game's first night, its gate clears it) */ + if (!oot_gd_set(c, oot_singleton(c, OOT_GAMEDATA_SLOT), 0x8592aa82u, 0, 1)) return 0; + hos_log("oot: cleared the first adult night's time lock (HrlField_HasEnteredFirstTime_Adult) for %s in %s, where " + "the game's own clear at the Market's gate cannot come", child ? "a child" : "an adult", map); + return 1; +} + +/* ((Triforce, 11-30) #1576602300313506086) The adult's maps. Both of them ask the same thing of an adult: the pause menu's + Map page (f_80b47d70, from UIMapMenuScreen f_834012c0; "Unavailable right now.", MapMessage_01, when it answers no) and + the HUD's minimap (f_805a2cf0) say yes for the child (the player's PlayerGameParam IsChild, kept at +0x5c0 of the player's + info) and, for the adult, only once HavePlayedEvent.Dm_TimeTemple_0065 (Bool 0xc1b29b0a, saved; struct HavePlayedEvent + 0x2b05cbb9, member 0xc367dcdc) is 1. Dm_TimeTemple_0065 is the adult's first step out of the Temple of Time into the + ruined Market (Navi, the Market's name): Market_Adult_Static places a 2 x 2.5 x 3 m Area at the temple's door, there while + the flag is 0, and Market_Adult_Prefab_50e3's logic asks for the event when Link is in it (and challenge AllSage is at its + step Step01). Nothing else in the romfs plays it or sets the flag. An adult who leaves the temple any other way (a teleport + or the age switch of the Debug tab, the no-clip flight) never has it: no map page and no minimap as an adult, in every + area, for good, and a save made from then on keeps it. Repaired here once no event plays, through the game's own Bool + setter (oot_gd_set: the live value and the save's copy), for an adult in any map but the Market (the Temple of Time is in + it: the game's own first walk out, still to come), the Chamber of Sages (where the first adult wakes) and the dream world + (Sequence_IsInDreamWorld hides the maps there by itself). HOS_OOT_ADULT_MAP_FIX=0 turns it off for a run. Returns 1 when + it set the flag. Asked by oot_inventory_refresh, twice a second while a save is loaded. */ +static int oot_adult_map_fix(Ctx *c, const char *map) { + static int on = -1; + if (on < 0) { + const char *e = getenv("HOS_OOT_ADULT_MAP_FIX"); + on = !(e && *e && atoi(e) == 0); + } + if (!on || !map[0]) return 0; + if (!strncmp(map, "Market", 6) || !strncmp(map, "SageRoom", 8) || !strncmp(map, "DreamWorld", 10)) return 0; + const uint64_t events = oot_singleton(c, OOT_EVENTMGR_SLOT); + if (events && recomp_load64(c, events + 104)) return 0; /* (the Main sequence's "Event" test: an event is playing) */ + int child = 1, played = 1; + if (!oot_gamedata_bool(c, 0xcea220d3u, &child) || child) return 0; /* (Sequence_IsChildhood) */ + if (!oot_gamedata_bool(c, 0xc1b29b0au, &played) || played) return 0; /* HavePlayedEvent.Dm_TimeTemple_0065 */ + if (!oot_gd_set(c, oot_singleton(c, OOT_GAMEDATA_SLOT), 0xc1b29b0au, 1, 1)) return 0; + hos_log("oot: the adult's map and minimap: set HavePlayedEvent.Dm_TimeTemple_0065 in %s (the first walk out of the Temple " + "of Time, which opens them, was never made)", map); + return 1; +} + /* A map-hiding area sets the saved flag MapIconDeactivateByAreaActor while Link is in it and shows the minimap again as he walks out. The teleport's map change takes him out without that: the flag stayed set, and no area had a minimap from then on, in that save and every one made from it. oot_teleport clears it once its request is taken; the map he arrives in sets it diff --git a/host/nn_hid.c b/host/nn_hid.c index 3e1175c..05d152f 100644 --- a/host/nn_hid.c +++ b/host/nn_hid.c @@ -79,9 +79,18 @@ static void mouse_sens_save(void) { /* The Insert menu keeps the sensitivity (its Mouse sensitivity row, option 7, in percent), read with each read; - and = change it there. HOS_MOUSE_SENS still wins, and then - and = keep it in /mouse_sens.txt as before. A value in mouse_sens.txt from before is moved into the menu once, while the menu's is still its default; the file is renamed - mouse_sens.txt.moved then, so the menu's value is not replaced by it again at a later start */ + mouse_sens.txt.moved then, so the menu's value is not replaced by it again at a later start. + ((Triforce, 11-30) A key that is a control's (the Controls page's bindings, the walk key) is that control's alone and no + sensitivity key: bound to a control (- or Num - on A, say), every press of it took a fifth off the sensitivity, down to + its 0.1 floor, faster the more the control was pressed (talking to people). #bug-tracker 11-30, v0.8.5.2. Each change is + logged with the key that made it, sens_key_name) */ void rx_option_set(int id, int value); static int sens_from_file; /* (mouse_setup: /mouse_sens.txt was there) */ +static int key_is_a_control(int vk); /* (below, beside bound_down: the binding table's) */ +static int sens_key(int vk) { return !key_is_a_control(vk) && key(vk); } +static const char *sens_key_name(int vk) { + return vk == VK_OEM_MINUS ? "-" : vk == VK_SUBTRACT ? "Num -" : vk == VK_OEM_PLUS ? "=" : vk == VK_ADD ? "Num +" : "?"; +} static void mouse_sens_keys(void) { static int prev_minus, prev_plus, from_env = -1; if (from_env < 0) { @@ -97,11 +106,16 @@ static void mouse_sens_keys(void) { } } if (!from_env) hos_mouse_sens = rx_option(7, 100) / 100.0; - const int minus = key(VK_OEM_MINUS) || key(VK_SUBTRACT), plus = key(VK_OEM_PLUS) || key(VK_ADD); + const int minus_vk = sens_key(VK_OEM_MINUS) ? VK_OEM_MINUS : sens_key(VK_SUBTRACT) ? VK_SUBTRACT : 0; + const int plus_vk = sens_key(VK_OEM_PLUS) ? VK_OEM_PLUS : sens_key(VK_ADD) ? VK_ADD : 0; + const int minus = minus_vk != 0, plus = plus_vk != 0; if ((minus && !prev_minus) || (plus && !prev_plus)) { + const double was = hos_mouse_sens; hos_mouse_sens *= minus && !prev_minus ? 0.8 : 1.25; if (hos_mouse_sens < 0.1) hos_mouse_sens = 0.1; if (hos_mouse_sens > 5) hos_mouse_sens = 5; + hos_log("hid: mouse sensitivity %.2f -> %.2f (the %s key)", was, hos_mouse_sens, + sens_key_name(minus && !prev_minus ? minus_vk : plus_vk)); if (from_env) mouse_sens_save(); else rx_option_set(7, (int)lround(hos_mouse_sens * 100)); } @@ -1270,6 +1284,16 @@ static int bound_down(int i, int mouse) { } return 0; } +/* ((Triforce, 11-30) vk is a key some control has (any row of the binding table: the Switch's buttons, the stick's and the + camera's keys, the note rows, Toggle HUD) or the walk key: then no shortcut of the host's own takes it, mouse_sens_keys) */ +static int key_is_a_control(int vk) { + if (vk <= 0) return 0; + if (vk == walk_vk) return 1; + for (int i = 0; i < HOS_KEY_N; i++) + for (int k = 0; k < 2; k++) + if ((int)key_bind[i][k] == vk) return 1; + return 0; +} /* ((Triforce) The Controls page's Toggle HUD row: a press of its gamepad input or one of its keys hides the HUD in play, the next shows it again (host/hos_wide_ui.c hos_gameplay_hud_toggle: for the session). readable: the player's input counts at @@ -1455,6 +1479,47 @@ static uint64_t oc_pad_word(uint64_t buttons) { return w; } +/* ((Triforce, 11-30) The ReShade comparison asked for inside the pause menu's Options (gpu/vk/vk_menu.cpp, option + HOS_OPT_COMPARE_PLAY 1): the game is paused there and its scene draws nothing, the preset is laid on the gameplay picture + alone, so the comparison over those screens showed the Options and the pause menu and no change ("ReShade Compare not + taking you to gameplay screen", #bug-tracker 11-30). The menus are left as Back leaves them: B tapped on the Options + screen (as for one of our tabs left with Back, above), then B on the pause menu (its Back prompt's, host/oot_menu.c), each + once and once more if its screen still runs 1.5 s later (a press lost in its animation). Neither run for 300 ms: in play, + the renderer told 2 and the comparison opened over the game. Not there 4 s after the ask: 3, the comparison where it is */ +int hos_oot_options_front(void); /* (host/oot_menu.c) */ +int hos_oot_pause_front(void); +static void compare_to_play(int64_t now) { + static int64_t asked_ns, menus_ns, tap_ns[2]; + static int taps[2]; + if (rx_option(HOS_OPT_COMPARE_PLAY, 0) != 1) { + asked_ns = 0; + return; + } + if (!asked_ns) { + asked_ns = menus_ns = now, taps[0] = taps[1] = 0; + hos_log("hid: the ReShade comparison asked from the Options: leaving the game's menus for play"); + } + const int options = hos_oot_options_front(), pause = !options && hos_oot_pause_front(); + if (options || pause) { + const int i = options ? 0 : 1; + menus_ns = now; + if (!taps[i] || (taps[i] < 2 && now - tap_ns[i] >= 1500000000LL)) { + hos_hid_tap("0:B/80"); + hos_log("hid: the ReShade comparison: B on the %s (%d)", i ? "pause menu" : "Options", ++taps[i]); + tap_ns[i] = now; + } + } else if (now - menus_ns >= 300000000LL) { + rx_option_set(HOS_OPT_COMPARE_PLAY, 2); + hos_log("hid: the ReShade comparison: in play after %.1f s", (now - asked_ns) / 1e9); + asked_ns = 0; + return; + } + if (now - asked_ns >= 4000000000LL) { + rx_option_set(HOS_OPT_COMPARE_PLAY, 3); + hos_log("hid: the ReShade comparison: the game's menus still up after 4 s; opened where it is"); + asked_ns = 0; + } +} static void read_input(uint64_t *buttons, int32_t stick[4]) { *buttons = 0; memset(stick, 0, 4 * sizeof *stick); @@ -1544,6 +1609,7 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) { } was_open = open; } + compare_to_play(hos_now_ns()); /* ((Triforce, 11-30) the ReShade comparison asked from the pause menu's Options) */ uint64_t down = 0; /* (the pads' buttons and the bound keys down at this read) */ { /* (hookshot) while the Insert menu is open the pads are its own, as the keyboard is (key()), and after it closed each input it had waits until it is let go (the press that closed it never reaches the game); the diff --git a/host/nn_vi.c b/host/nn_vi.c index ef64d69..c0e4114 100644 --- a/host/nn_vi.c +++ b/host/nn_vi.c @@ -502,15 +502,36 @@ static float text_scale(const char *env, int menu) { volatile uint64_t hos_step_probe = 0; /* (f_80706be0's object, set by the lifted code when the frame-time hook is in this build; its +0xd58 is the game clock in 1/60 s: nx2/oot_patches.py) */ volatile uint32_t hos_frame_seconds_bits = 0; /* (the frame's seconds as a float's bits for that hook, 0: the game's own step) */ +/* ((Triforce, 11-30) The rate the game steps by now (the graphics module's +0x2c8, realtime_step's), for hos_movie_frames below + 60: the rate under 60 (the step 60 / rate), 0 at 60 or when it is not known. Said once in the log when a movie counts by it) */ +static int movie_game_rate(void) { + const uint64_t mod = hos_gfx_module; + if (!mod) return 0; + const int rate = __atomic_load_n((const int *)GP(mod + 0x2c8), __ATOMIC_RELAXED); + if (rate < 15 || rate >= 60) return 0; + static volatile LONG said; + if (!InterlockedExchange(&said, 1)) + hos_log("video: a movie's count of 60ths below 60 fps: %.3f an update at the game's rate %d (HOS_FPS_MOVIE=0: 1, as shipped)", + 60.0 / rate, rate); + return rate; +} /* A movie's frame count while the frames' time is given (a Frame rate cap above 60): how many 60ths of a second this update of that movie player is worth, the rest carried to its next one, so the count the cutscene's cues are placed by keeps the clock - as the movie's picture does (issue 1742: the narration ran ahead above 60 fps). 1, the game's own step, otherwise, and with - HOS_FPS_MOVIE=0 (for comparisons). Called by the lifted f_83b7c710 (nx2/oot_patches.py). */ + as the movie's picture does (issue 1742: the narration ran ahead above 60 fps). 1, the game's own step, at 60 fps, and with + HOS_FPS_MOVIE=0 (for comparisons). Called by the lifted f_83b7c710 (nx2/oot_patches.py), once a frame. + ((Triforce, 11-30) Below 60 fps too, by the game's step (60 / its rate, movie_game_rate): the count grew by 1 a frame, half + the movie's 60ths at 30 fps, while the picture keeps the clock (nn_video.c skips the pictures behind it). The ending's second + staff roll (Dm_StaffCredit_0005, a timeline of 7343 frames on the movie of 7343 pictures) places its UI by that count: "Presented + by Nintendo" in at 3326, out at 3892, the staff roll's end screen opened at 6260. At 30 fps the movie ended with the count near + 3672: the text stayed, the end screen was never opened, and Dm_StaffCredit_0007's EventWaitInputTheEndNext waits for input on + that screen, which it never finds: the game stood on the 3D behind the text for good, the "The End" screen never came (5+ + players, all of them under 60 fps; the lab: at 30 the same, at 60 the end screen and the title). */ uint32_t hos_movie_frames(uint64_t player) { enum { PLACES = 16 }; movie_seen(); /* (Triforce: a movie plays, for the frame pacing: pace_handed) */ const uint32_t bits = __atomic_load_n(&hos_frame_seconds_bits, __ATOMIC_RELAXED); /* (realtime_step writes it at each present) */ - if (!bits) return 1; + const int rate = bits ? 0 : movie_game_rate(); /* ((Triforce) below 60: the game's step) */ + if (!bits && !rate) return 1; static SRWLOCK lock = SRWLOCK_INIT; static int timed = -1; /* (these four under the lock) */ static struct { uint64_t player, used; double part; } carry[PLACES]; @@ -538,7 +559,7 @@ uint32_t hos_movie_frames(uint64_t player) { carry[i].player = player, carry[i].part = x / 4294967296.0; } carry[i].used = ++calls; - carry[i].part += (double)secs * 60.0; + carry[i].part += bits ? (double)secs * 60.0 : 60.0 / rate; n = (uint32_t)carry[i].part; carry[i].part -= n; } diff --git a/host/oot_amiibo_uses.c b/host/oot_amiibo_uses.c new file mode 100644 index 0000000..e45d723 --- /dev/null +++ b/host/oot_amiibo_uses.c @@ -0,0 +1,30 @@ +/* (Triforce) The System tab's Unlimited amiibo uses row (its NFC group): On, a figure can be scanned again at once, any + number of times, and gives its reward each time. + + What limits a figure's use (read in the game's own code, the supported build; host/amiibo.h has what it asks of the + reader): once its amiibo sequence has a figure's TagInfo and ModelInfo, it decides (f_8328bbc0) by asking f_8328cd30 + whether the figure was used today. That function looks the figure up in the save's amiibo history (a list of figures, + each with the date and time of its last use, its serial number's hash and its names: f_8328d110 writes it after each + use) and answers 1 when the figure's last use was on today's date (the PC's, through nn::time). Then the game says so + and gives nothing until the next day. Nothing is written to the figure (the game opens no data of its own on it), and + the runtime counts no uses: a figure chosen again on the Scan amiibo page (host/nn_nfp.c) is another touch. + + The game also refuses a figure while the clock was set by hand, within the day, by more than the time gone by + (f_8328c870, nn::time::CalculateStandardUserSystemClockDifferenceByUser). host/nn_applet.c answers 0, "not set by the + user", so that never refuses here, row or not. + + nx2/oot_patches.py (patch_amiibo_uses) calls hos_oot_amiibo_used_today at the head of f_8328cd30. With the row Off, the + default, it returns 0 before anything is read and the game checks as it always did. With it On it answers 0, "not used + today", and the function returns: the game gives the figure's reward and writes its history as for the day's first use + (so after the row is turned Off again, a figure used today counts as used today). The player's dump is never written. */ +#include "hos.h" +#include "../gpu/vk/vk_api.h" + +int rx_option(int id, int otherwise); + +int hos_oot_amiibo_used_today(Ctx *c) { + if (!rx_option(HOS_OPT_AMIIBO_UNLIMITED, 0)) return 0; /* (the row Off: the game's own check, nothing read) */ + c->x[0] = 0; /* (not used today) */ + hos_log("amiibo: the game's once-a-day check of the figure answered \"not used today\" (Unlimited amiibo uses is On)"); + return 1; +} diff --git a/host/oot_menu.c b/host/oot_menu.c index 4a60719..74c9f92 100644 --- a/host/oot_menu.c +++ b/host/oot_menu.c @@ -330,6 +330,13 @@ int hos_oot_options_front(void) { const LONG64 t = InterlockedCompareExchange64(&options_seen_ns, 0, 0); return t && (LONG64)hos_now_ns() - t < 200000000LL; } +/* ((Triforce, 11-30) the pause menu's screen updated within 200 ms, as hos_oot_options_front for the Options': it stops while + the Options screen is over it (OPTIONS_FROM_PAUSE_NS) and when the pause menu closes. nn_hid.c compare_to_play */ +static volatile LONG64 pause_seen_ns; +int hos_oot_pause_front(void) { + const LONG64 t = InterlockedCompareExchange64(&pause_seen_ns, 0, 0); + return t && (LONG64)hos_now_ns() - t < 200000000LL; +} /* (Triforce) the renderer is told of the Options screen (its tabs over the header): HOS_OPTIONS_TABS=0 keeps it untold */ static int options_tabs_on(void) { static int tabs = -1; @@ -1183,7 +1190,7 @@ void hos_oot_menu_tick(Ctx *c, uint64_t screen) { (kept for the run; a run begins after 200 ms with no Options frame, as hos_oot_options_front's) */ static int64_t pause_ran_ns; /* (under seen_lock) */ static int options_from_pause; - if (peek64(screen) == PAUSE_SCREEN_VTABLE) pause_ran_ns = now; + if (peek64(screen) == PAUSE_SCREEN_VTABLE) pause_ran_ns = now, InterlockedExchange64(&pause_seen_ns, (LONG64)now); if (me->options) { const LONG64 was = InterlockedCompareExchange64(&options_seen_ns, 0, 0); if (!was || now - was >= 200000000LL) options_from_pause = pause_ran_ns && now - pause_ran_ns < OPTIONS_FROM_PAUSE_NS; @@ -1270,6 +1277,7 @@ void hos_oot_menu_tick(Ctx *c, uint64_t screen) { #include #include "../gpu/vk/vk_api.h" /* (HOS_OPT_GAME_OPTIONS) */ static int64_t options_seen_ns; /* (the screens' updates run on several of the game's threads: read and written whole) */ +static int64_t pause_seen_ns; /* ((Triforce, 11-30) the pause menu's last update, hos_oot_pause_front: the same) */ void hos_input_clear_toggles(void); /* ((Triforce) 11-24: host/nn_hid.c, hold-to-toggle's latches) */ /* (the pause page's focus hook runs here too, without the mouse's menu navigation: a latched button is let go for it) */ void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr) { @@ -1300,7 +1308,7 @@ void hos_oot_menu_tick(Ctx *c, uint64_t screen) { static int64_t pause_ran_ns; /* ((Triforce, 11-20) the pause menu's last update: where the Options were chosen from) */ static int options_from_pause; const int64_t now = hos_now_ns(); - if (vt == PAUSE_SCREEN_VTABLE) __atomic_store_n(&pause_ran_ns, now, __ATOMIC_RELAXED); + if (vt == PAUSE_SCREEN_VTABLE) __atomic_store_n(&pause_ran_ns, now, __ATOMIC_RELAXED), __atomic_store_n(&pause_seen_ns, now, __ATOMIC_RELAXED); oot_menu_screen_tick(vt); /* ((Triforce) the screen's class, each frame it runs: oot_title_movie.h) */ if (vt != OPTIONS_SCREEN_VTABLE) return; static int tabs = -1; @@ -1318,6 +1326,10 @@ int hos_oot_options_front(void) { const int64_t t = __atomic_load_n(&options_seen_ns, __ATOMIC_RELAXED); return t && hos_now_ns() - t < 200000000LL; } +int hos_oot_pause_front(void) { /* ((Triforce, 11-30) the Windows half's, nn_hid.c compare_to_play) */ + const int64_t t = __atomic_load_n(&pause_seen_ns, __ATOMIC_RELAXED); + return t && hos_now_ns() - t < 200000000LL; +} /* ((Triforce, 11-18) the Mods entry under the game's lists is the Windows half's (mods_list_tick): here no list's last button has the cursor, so nn_hid.c never keeps a Down from the game. Without it every Linux build of v0.5.0 stopped at the link, "undefined reference to hos_oot_mods_down" (#bug-tracker, 11-18). tests/test_oot_menu_linux_half.py) */ diff --git a/host/rx_backend.c b/host/rx_backend.c index 28bcdb7..d668845 100644 --- a/host/rx_backend.c +++ b/host/rx_backend.c @@ -447,7 +447,7 @@ int rx_async_replay(void) { on = atoi(e) != 0; } else if (vk && vk->option) { /* ((Triforce) unset: the renderer's answer, resolved once (HOS_OPT_RENDER_THREAD: the Debug tab's Threaded rendering - row or RX_VK_THREADED, gpu/vk/threaded_rendering.h; off by default, so 0 as before) */ + row or RX_VK_THREADED, gpu/vk/threaded_rendering.h; Auto by default, Off 0 as before) */ on = vk->option(HOS_OPT_RENDER_THREAD) > 0; } else { /* (asked before the renderer runs: hos_reserved_cpus at its device's pick. RX_VK_THREADED=1 or on says it already; diff --git a/launcher/App/Backend.Character.cs b/launcher/App/Backend.Character.cs new file mode 100644 index 0000000..8d3ba3f --- /dev/null +++ b/launcher/App/Backend.Character.cs @@ -0,0 +1,427 @@ +using System.Text.Json.Nodes; +using Triforce.Core.GameFiles; +using Triforce.Logic; + +namespace Triforce.Launcher; + +/// ((Triforce, 11-29) The Character page (char.js, char3d.js): Link in 3D from the player's own game files +/// (Core LinkScene), young and adult, in his own colours (Logic LinkColors: OOTRR's recolouring, the randomizer's program). +/// The page is sent what it draws through Content's char/ route, made on a worker first (the route runs on the window's +/// thread and only hands over bytes that are ready): +/// char/scene/N.json, N.bin look N's parts and its posed mesh +/// char/tex/NAME.bin a texture (u32 width, u32 height, RGBA8) +/// char/mask/NAME.bin a colour map's calibration mask (where each of its parts lies) +/// char/exact/N/NAME.bin OOTRR's own recoloured colour map, from preview N +/// Picking a colour is live on the page (a tint over the mask) at once, and OOTRR's exact maps follow a moment later. +/// Apply writes the colours into the game as a mod (mods\~Link colors): every save shows them. +public sealed partial class Backend +{ + LinkColors? linkColors; + LinkColors Colors => linkColors ??= new LinkColors(ctx, Rando.Tool, Rando.Manager); + LinkColors.Choice? charChoice; + LinkColors.Choice CharChoice => charChoice ??= Colors.LoadChoice(); + readonly object charGate = new(); + readonly Dictionary charFiles = new(StringComparer.Ordinal); + readonly Dictionary charScenes = new(StringComparer.Ordinal); + IReadOnlyList? charCal; + string? charCalGame, charCalError; + bool charCalBusy, charBusy; + string charLine = ""; + int charN, charApplying; + readonly Dictionary charPreviewCts = new(); + CancellationTokenSource? charApplyCts; + + void RegisterCharacter() + { + TextureRecolor.Astc = (texels, w, h) => AstcEncode.EncodeBlock(texels, w, h); + content.Character = CharContent; + OnAsync("char.open", _ => CharOpen()); + OnAsync("char.look", m => CharLook((string?)m["look"] ?? "child", (m["have"] as JsonArray)?.Select(x => (string?)x).OfType().ToHashSet() ?? new HashSet())); + On("char.loaded", m => { var n = (int?)m["n"] ?? -1; lock (charGate) foreach (var k in charFiles.Keys.Where(k => k.StartsWith("tex/") || k.StartsWith("scene/" + n + ".")).ToList()) charFiles.Remove(k); }); + On("char.set", m => CharSet((string?)m["age"], (string?)m["part"], (string?)m["hex"])); + On("char.many", m => CharMany((string?)m["age"], m["colors"] as JsonObject)); + On("char.revert", _ => { charChoice = Colors.Applied(GameDir ?? "")?.Colors.Copy() ?? new LinkColors.Choice(); Colors.SaveChoice(CharChoice); CharPreviewSoon("child"); CharPreviewSoon("adult"); SendChar(); }); + OnAsync("char.apply", _ => CharApply()); + On("char.install", _ => CharInstallAsk()); + On("char.hero", m => CharHero((string?)m["hero"])); + On("char.linkle", _ => CharLinkleAsk()); + OnAsync("char.linkle.go", m => (string?)m["id"] == "go" ? CharLinkleGet() : Task.CompletedTask); + On("char.stop", _ => { try { charApplyCts?.Cancel(); } catch { } }); + On("char.remove", _ => + { + if (GameDir is not { } g || Colors.Applied(g) == null) return; + Ask("Back to the game's own colors?", "

Link's colors leave the game. Your picks stay here, so you can apply them again.

", + "char.remove.go", new[] { ("no", "Keep them", false), ("go", "Use the game's colors", true) }); + }); + On("char.remove.go", m => + { + if ((string?)m["id"] != "go" || GameDir is not { } g) return; + try { Colors.Remove(g); Toast("Link wears the game's own colors again", "success"); } + catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException) { Toast(H(e.Message), "error"); } + SendChar(); + }); + } + + void CharInstallAsk() + { + if (Colors.Tool.Have || randoToolBusy) return; + Ask("Get the color tool", + "

Link's colors are dyed by OOTRR, the Ocarina of Time Remake Randomizer's own program (free software, GPL-3.0, as Triforce is), " + + "the one the Randomizer page uses. It recolors the game's own textures exactly, block by block, so nothing is redrawn or blurred.

" + + "

" + H(Colors.Tool.File.Name) + ", " + Size(Colors.Tool.File.Size) + ", is downloaded once from its release on GitHub and checked " + + "against the fingerprint Triforce knows for it. It reads your game files on this PC only; nothing is uploaded.

", + "rando.install.go", new[] { ("no", "Not now", false), ("go", "Download", true) }); + } + + // ---------------- the page's files ---------------- + + (byte[], string)? CharContent(string path) + { + // (the name part is unescaped by Content already) + string key; + if (path.StartsWith("scene/", StringComparison.Ordinal) || path.StartsWith("tex/", StringComparison.Ordinal) || path.StartsWith("mask/", StringComparison.Ordinal) + || path.StartsWith("exact/", StringComparison.Ordinal)) key = path; + else return null; + byte[]? data; + lock (charGate) charFiles.TryGetValue(key, out data); + if (data == null) return null; + return (data, key.EndsWith(".json", StringComparison.Ordinal) ? "application/json" : "application/octet-stream"); + } + + static byte[] TexFile(int w, int h, byte[] rgba) + { + var f = new byte[8 + rgba.Length]; + BitConverter.GetBytes(w).CopyTo(f, 0); + BitConverter.GetBytes(h).CopyTo(f, 4); + rgba.CopyTo(f, 8); + return f; + } + + // ---------------- state ---------------- + + async Task CharOpen() + { + var g = GameDir; + if (g != null) try { Colors.LeftOvers(g); } catch (Exception) { } + SendChar(); + // (the exact previews first, then the calibration: once per game, in the background; the page tints live once it is there) + CharPreviewSoon("child", 0); CharPreviewSoon("adult", 0); + if (g != null && Colors.Tool.Have && charCal == null && !charCalBusy) { await Task.Delay(6000); if (charCal == null && !charCalBusy) await CharCalibrate(g); } + else if (charCal != null) SendCal(); + } + + JsonObject WithLinkleProgress(JsonObject o) + { + o["busy"] = charLinkleGetting == 1; o["frac"] = charLinkleFrac; o["line"] = charLinkleLine; + o["name"] = Linkle.Name; o["author"] = Linkle.Author; o["page"] = Linkle.Page; + return o; + } + + void SendChar() + { + var g = GameDir; + var applied = g != null ? Colors.Applied(g) : null; + var choice = CharChoice; + // (who the game shows now: Linkle when her mod is on, whatever the colours' marker says) + var linkleOn = g != null && Linkle.Find(Rando.Manager, g) is { On: true }; + var inGame = applied?.Colors.Copy() ?? new LinkColors.Choice(); + inGame.Hero = linkleOn ? "linkle" : "link"; + var tool = Colors.Tool; + var o = new JsonObject + { + ["game"] = g != null, + ["tool"] = new JsonObject { ["have"] = tool.Have, ["busy"] = randoToolBusy, ["frac"] = randoToolFrac, ["size"] = Size(tool.File.Size), ["version"] = Ootrr.Version }, + ["hero"] = choice.Hero, + ["linkle"] = g == null ? null : WithLinkleProgress(Linkle.Find(Rando.Manager, g) is { } lm ? new JsonObject { ["have"] = true, ["on"] = lm.On } : new JsonObject { ["have"] = false }), + ["parts"] = new JsonArray((choice.Hero == "linkle" ? Linkle.Parts : LinkColors.Parts).Select(p => (JsonNode?)new JsonObject + { + ["id"] = p.Id, ["label"] = p.Label, ["group"] = p.Group, ["ages"] = p.Ages, ["tunic"] = p.Tunic, ["swatch"] = p.Swatch, + }).ToArray()), + ["colors"] = choice.ToJson(), + ["applied"] = applied?.Colors.ToJson(), + ["appliedOn"] = applied?.On ?? false, + ["same"] = inGame.Same(choice) || (applied == null && !linkleOn && choice.Empty), + ["appliedHero"] = inGame.Hero, + ["busy"] = charBusy, ["line"] = charLine, + ["calBusy"] = charCalBusy, ["calError"] = charCalError, + ["others"] = g != null ? new JsonArray(Colors.Others(g).Select(x => (JsonNode?)x).ToArray()) : new JsonArray(), + }; + SendState(new JsonObject { ["char"] = o }); + } + + // ---------------- Link in 3D ---------------- + + async Task CharLook(string look, HashSet have) + { + if (!LinkScene.Looks.Contains(look) || GameDir is not { } g) return; + var n = Interlocked.Increment(ref charN); + try + { + var data = await Task.Run(() => + { + var romfs = Path.Combine(g, "romfs"); + var hero = CharChoice.Hero; + var her = hero == "linkle" ? Linkle.Find(Rando.Manager, g) : null; + if (hero == "linkle" && her == null) throw new IOException("Linkle is not in the mods folder"); + using IGameSource src = her != null ? Linkle.Source(her, g) : new FolderSource(romfs); + var zs = new Zs(src); + LinkScene scene; + lock (charGate) + { + var sk = hero + "/" + look; + if (!charScenes.TryGetValue(sk, out var c) || c.Game != g) charScenes[sk] = c = (LinkScene.Build(src, zs, look, hero, hero == "linkle" ? Linkle.SceneRenames : null), g); + scene = c.Scene; + } + var files = new Dictionary + { + ["scene/" + n + ".json"] = System.Text.Encoding.UTF8.GetBytes(scene.Info.ToJsonString()), + ["scene/" + n + ".bin"] = scene.Mesh, + }; + var names = new HashSet(StringComparer.Ordinal); + foreach (var p in (JsonArray)scene.Info["parts"]!) + foreach (var role in new[] { "alb", "nrm", "nrm2", "ao", "lut", "grey", "emc" }) + if ((string?)p![role] is { } name && !have.Contains(name)) names.Add(name); + Parallel.ForEach(names, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(2, Environment.ProcessorCount / 2) }, name => + { + try + { + var max = name.EndsWith("_Alb", StringComparison.Ordinal) || name.StartsWith("eye:", StringComparison.Ordinal) ? LinkScene.MaxTexture : LinkScene.MaxTexture / 2; + if (LinkScene.Texture(src, zs, hero == "linkle" ? Linkle.Original(name) : name, max) is { } t) + lock (files) files["tex/" + name + ".bin"] = TexFile(t.W, t.H, t.Rgba); + } + catch (Exception e) { Log.Write("character: texture " + name + ": " + e.Message); } + }); + return files; + }); + lock (charGate) foreach (var (k, v) in data) charFiles[k] = v; + Send(new JsonObject { ["t"] = "charLook", ["look"] = look, ["n"] = n, ["hero"] = CharChoice.Hero }); + } + catch (Exception e) when (e is IOException || e is InvalidDataException || e is NotSupportedException || e is DirectoryNotFoundException) + { + Log.Write("character: " + look + ": " + e); + Send(new JsonObject { ["t"] = "charLook", ["look"] = look, ["n"] = n, ["error"] = "Link could not be read from your game: " + e.Message }); + } + } + + // ---------------- colours ---------------- + + void CharSet(string? age, string? part, string? hex) + { + var hero = CharChoice.Hero; + if (age == null || part == null || !LinkColors.Valid(hero, age, part)) return; + var clean = hex == null ? null : LinkColors.CleanHex(hex); + var ages = LinkColors.Shared.Contains(part) ? new[] { "child", "adult" } : new[] { age }; + lock (charGate) + foreach (var a in ages) + if (clean == null) CharChoice.Age(LinkColors.Key(hero, a)).Remove(part); else CharChoice.Age(LinkColors.Key(hero, a))[part] = clean; + Colors.SaveChoice(CharChoice); + foreach (var a in ages) CharPreviewSoon(a); + SendChar(); + } + + /// Several parts at once (a preset, Randomize, Reset): colors {part: hex | null}; parts not named stay. + void CharMany(string? age, JsonObject? colors) + { + if (age is not ("child" or "adult") || colors == null) return; + lock (charGate) + foreach (var (part, v) in colors) + { + if (!LinkColors.Valid(CharChoice.Hero, age, part)) continue; + var hex = v is JsonValue jv && jv.TryGetValue(out var s) ? LinkColors.CleanHex(s) : null; + foreach (var a in LinkColors.Shared.Contains(part) ? new[] { "child", "adult" } : new[] { age }) + if (hex == null) CharChoice.Age(LinkColors.Key(CharChoice.Hero, a)).Remove(part); else CharChoice.Age(LinkColors.Key(CharChoice.Hero, a))[part] = hex; + } + Colors.SaveChoice(CharChoice); + CharPreviewSoon("child"); CharPreviewSoon("adult"); + SendChar(); + } + + JsonArray? charCalMsg; + void SendCal() { if (charCalMsg != null) Send(new JsonObject { ["t"] = "charCal", ["maps"] = charCalMsg.DeepClone() }); } + + async Task CharCalibrate(string g) + { + charCalBusy = true; charCalError = null; SendChar(); + try + { + var stamp = GameStamp(g); + var cal = await Colors.CalibrateAsync(g, stamp, CancellationToken.None); + var arr = new JsonArray(); + lock (charGate) + foreach (var m in cal) + { + charFiles["mask/" + m.Texture + ".bin"] = TexFile(m.Width, m.Height, m.Mask); + arr.Add(new JsonObject + { + ["tex"] = LinkColors.ModelName(m.Texture), ["file"] = m.Texture, + ["parts"] = new JsonArray(m.Parts.Select(p => (JsonNode?)p).ToArray()), + ["ym"] = new JsonArray(m.Ym.Select(y => (JsonNode?)y).ToArray()), ["qm"] = new JsonArray(m.Qm.Select(y => (JsonNode?)y).ToArray()), + ["ty"] = new JsonArray(m.Ty.Select(y => (JsonNode?)y).ToArray()), + ["g"] = new JsonArray(m.G.Select(y => (JsonNode?)y).ToArray()), + }); + } + charCal = cal; charCalGame = g; charCalMsg = arr; + SendCal(); + } + catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException || e is InvalidDataException || e is InvalidOperationException) + { + Log.Write("character: calibration: " + e); + charCalError = e.Message; + } + finally { charCalBusy = false; SendChar(); } + } + + /// A name for this game's files (the folder and Link's model as they are): the calibration is kept under it. + static string GameStamp(string g) + { + var f = new FileInfo(Path.Combine(g, "romfs", "Model", "Player_Child.Player_Child.bfres.zs")); + var key = g.ToLowerInvariant() + "|" + (f.Exists ? f.Length + "-" + f.LastWriteTimeUtc.Ticks : "none") + "|" + Ootrr.Version; + return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(key)))[..16].ToLowerInvariant(); + } + + /// OOTRR's exact maps for one age, a moment after the last change (a newer change cancels a preview that runs). + void CharPreviewSoon(string age, int delayMs = 650) + { + if (GameDir is not { } g || (!Colors.Tool.Have && CharChoice.Hero != "linkle")) return; + CancellationTokenSource cts; + lock (charPreviewCts) + { + if (charPreviewCts.TryGetValue(age, out var old)) { try { old.Cancel(); } catch { } } + charPreviewCts[age] = cts = new CancellationTokenSource(); + } + Dictionary colors; + string hero; + lock (charGate) { hero = CharChoice.Hero; colors = new Dictionary(CharChoice.Of(age)); } + var key = LinkColors.Key(hero, age); + _ = Task.Run(async () => + { + try + { + await Task.Delay(delayMs, cts.Token); + var maps = hero == "linkle" ? await LinklePreview(g, age, colors, cts.Token) : await Colors.PreviewAsync(g, colors, cts.Token); + cts.Token.ThrowIfCancellationRequested(); + var n = Interlocked.Increment(ref charN); + lock (charGate) + { + foreach (var k in charFiles.Keys.Where(k => k.StartsWith("exact/" + key + "/", StringComparison.Ordinal)).ToList()) charFiles.Remove(k); + foreach (var (tex, t) in maps) charFiles["exact/" + key + "/" + n + "/" + tex + ".bin"] = TexFile(t.W, t.H, t.Rgba); + } + Send(new JsonObject + { + ["t"] = "charExact", ["age"] = age, ["hero"] = hero, ["key"] = key, ["n"] = n, + ["colors"] = new JsonObject(colors.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)kv.Value))), + ["tex"] = new JsonArray(maps.Keys.Select(k => (JsonNode?)k).ToArray()), + }); + } + catch (OperationCanceledException) { } + catch (Exception e) when (e is OotrrException || e is IOException || e is InvalidDataException || e is NotSupportedException) + { + Log.Write("character: preview " + age + ": " + e.Message); + } + }); + } + + /// Linkle's dyed textures for one age (the launcher's own dye), and adult hair from the colour tool. + async Task> LinklePreview(string g, string age, Dictionary colors, CancellationToken token) + { + var maps = new Dictionary(StringComparer.Ordinal); + if (colors.Count == 0) return maps; + var mod = Linkle.Find(Rando.Manager, g); + if (mod == null) return maps; + await Task.Run(() => + { + using var her = Linkle.Source(mod, g); + var zs = new Zs(her); + foreach (var (tex, (_, _, prev)) in Linkle.Dye(her, zs, age, colors)) maps[tex] = prev; + }, token); + if (age == "adult" && colors.TryGetValue("hair", out var hair) && Colors.Tool.Have) + foreach (var (tex, m) in await Colors.PreviewAsync(g, new Dictionary { ["hair"] = hair }, token)) + if (tex == "Mt_Hairs_Player_Adult_Alb") maps[tex] = m; + return maps; + } + + void CharHero(string? hero) + { + if (hero is not ("link" or "linkle") || hero == CharChoice.Hero) return; + lock (charGate) CharChoice.Hero = hero; + Colors.SaveChoice(CharChoice); + SendChar(); + if (hero == "link" || (GameDir is { } g && Linkle.Find(Rando.Manager, g) != null)) { CharPreviewSoon("child", 0); CharPreviewSoon("adult", 0); } + } + + int charLinkleGetting; + double charLinkleFrac; + string charLinkleLine = ""; + + void CharLinkleAsk() + { + Ask("Get Linkle", + "

" + H(Linkle.Name) + " by " + H(Linkle.Author) + " replaces Link with Linkle from Hyrule Warriors, young and adult, " + + "with her own voice, gear and fairy, Liri.

It is downloaded from its page on GameBanana (about 320 MB) into your mods folder, " + + "as the Mods page does. It is the author's work: Triforce only installs it and switches it on and off.

", + "char.linkle.go", new[] { ("no", "Not now", false), ("go", "Download", true) }); + } + + async Task CharLinkleGet() + { + if (GameDir is not { } g || Interlocked.CompareExchange(ref charLinkleGetting, 1, 0) != 0) return; + charLinkleFrac = 0; charLinkleLine = "Asking GameBanana"; SendChar(); + try + { + var d = await Gb.DetailsAsync(Linkle.GameBananaId, false); + if (d.Files.Count == 0) throw new ModsException("Its GameBanana page has no file to download."); + var file = d.Files[d.DefaultFile(false)]; + var card = new GbMod(Linkle.GameBananaId, false, Linkle.Name, Linkle.Author, "", Linkle.Page, 0, 0, 0, null); + var last = DateTime.MinValue; + await new GameBananaInstaller(ctx).InstallAsync(gbHttp.Value, card, file, g, p => + { + charLinkleFrac = p.Fraction; charLinkleLine = p.Fraction >= 1 ? "Unpacking" : "Downloading, " + (int)(p.Fraction * 100) + " %"; + if ((DateTime.UtcNow - last).TotalMilliseconds < 500) return; + last = DateTime.UtcNow; SendChar(); + }, CancellationToken.None); + Toast("◆ Linkle is in your mods folder", "success"); + CharHero("linkle"); + } + catch (Exception e) when (e is ModsException || e is HttpRequestException || e is IOException || e is UnauthorizedAccessException || e is TaskCanceledException || e is InvalidOperationException || e is System.Text.Json.JsonException) + { + Log.Write("character: linkle: " + e); + Toast("Linkle could not be downloaded: " + H(e.Message), "error"); + } + finally { charLinkleLine = ""; Interlocked.Exchange(ref charLinkleGetting, 0); SendChar(); } + } + + async Task CharApply() + { + if (GameDir is not { } g) return; + if (!Colors.Tool.Have) { CharInstallAsk(); return; } + if (Interlocked.CompareExchange(ref charApplying, 1, 0) != 0) return; + LinkColors.Choice choice; + lock (charGate) choice = CharChoice.Copy(); + charBusy = true; charLine = "Getting ready"; SendChar(); + var cts = charApplyCts = new CancellationTokenSource(); + try + { + var dest = await Colors.ApplyAsync(g, choice, l => { charLine = l; SendChar(); }, cts.Token); + if (dest == null) Toast("Link wears the game's own colors again", "success"); + else + { + var others = Colors.Others(g); + Toast("◆ Link's colors are in your game · every save, the next time you play" + + (others.Count > 0 ? " · they show over " + H(string.Join(", ", others)) : ""), "success"); + Sfx("success"); + } + } + catch (OperationCanceledException) { Toast("Stopped: your game keeps the colors it had"); } + catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException || e is InvalidDataException || e is ModsException) + { + Log.Write("character: apply: " + e); + Toast("The colors could not be applied: " + H(e.Message), "error"); + } + finally + { + charBusy = false; charLine = ""; charApplyCts = null; + Interlocked.Exchange(ref charApplying, 0); + SendChar(); + } + } +} diff --git a/launcher/App/Backend.Core.cs b/launcher/App/Backend.Core.cs index 9921789..215cacb 100644 --- a/launcher/App/Backend.Core.cs +++ b/launcher/App/Backend.Core.cs @@ -55,6 +55,13 @@ public sealed partial class Backend OnAsync("retry", _ => retry != null ? retry() : Task.CompletedTask); On("workback", _ => { StopWork(); Go(workKind == "update" ? "home" : "reveal"); }); On("play", _ => Play()); + // ((Triforce, 11-30) Play's question when the mods' code patches wait for a build: PlayOne) + On("play.mods", m => + { + var id = (string?)m["id"]; + if (id == "build") StartRebuild(); + else if (id == "anyway") { playModsAnyway = true; Play(); } + }); On("playold", _ => Play()); On("showgame", _ => ShowGame()); OnAsync("update", _ => UpdateNow(start.Args.UpdateFolder)); @@ -86,7 +93,7 @@ public sealed partial class Backend // (only a language the game has: the code goes to the registry or builder.ini, which other programs read) On("lang", m => { if (Languages.Find((string?)m["id"]) is { } l) { ctx.Settings.Language = l.Code; SendReveal(); } }); On("dlssanswer", m => { if ((string?)m["id"] == "yes" && Answered(ref dlssKey, m)) new Dlss(ctx).Accept(); SendReveal(); }); - On("screen", _ => { }); + On("screen", m => { pageScreen = (string?)m["s"]; }); On("open", m => OpenThing((string?)m["arg"] ?? "")); On("report", _ => Copy(Report.ForBuild(ctx, lastResult, runner?.Details ?? "", new Tools(ctx).InstalledVersion, lastFailure))); On("sound", m => @@ -636,6 +643,7 @@ public sealed partial class Backend } // ---------------- Play ---------------- + bool playModsAnyway; // ((Triforce, 11-30) "Play anyway" once this session: Play does not ask about the mods' build again void Play() { // ((Triforce, 11-26) one start at a time: two clicks on Play started two games before the first was seen running) @@ -651,6 +659,18 @@ public sealed partial class Backend if (Volatile.Read(ref workBusy) != 0) { Go("work"); return; } // (a build or an update is writing the game folder) var game = new Game(ctx); if (game.IsRunning(g)) { Go("playing"); ShowGame(); return; } + // ((Triforce, 11-30) #bug-tracker: crashes at the start or the first load (guest 0x1, 0x10 writes) whose logs say "mods: N code + // patches wait for a build": a mod with code patches was added, removed or switched since the game was built, so its game files + // and the code built in no longer match. The Mods page said so; Play did not. Asked once a session: Build now, or Play anyway) + if (!playModsAnyway && SafeNeedsRebuild(g)) + { + Ask("Your mods need a build", + "

A mod with code patches was added, removed or switched on or off since the game was built. Until the game is built " + + "again its code and that mod's files don't match, and the game can crash at the start or when a save loads.

" + + "

Building again takes " + H(RebuildTime()) + ". Your saves and mods stay.

", + "play.mods", new[] { ("anyway", "Play anyway", false), ("build", "Build now", true) }); + return; + } gameProc = game.Play(g); if (gameProc == null) { Toast("The game would not start. Settings, Build the game again, repairs a broken game folder.", "error"); return; } Log.Write("play " + g); @@ -708,6 +728,7 @@ public sealed partial class Backend { "help" => BuildInfo.Home, "changes" => release?.PageUrl ?? BuildInfo.Home, + "linkle" => Linkle.Page, _ => what.StartsWith("https://", StringComparison.Ordinal) ? what : null, }; // (through OpenLink: https only, whatever the release feed or the page says; a test run opens nothing) diff --git a/launcher/App/Backend.Randomizer.cs b/launcher/App/Backend.Randomizer.cs index 7eff6ca..a169acd 100644 --- a/launcher/App/Backend.Randomizer.cs +++ b/launcher/App/Backend.Randomizer.cs @@ -261,6 +261,7 @@ public sealed partial class Backend if ((DateTime.UtcNow - last).TotalMilliseconds < 400) return; last = DateTime.UtcNow; SendRando(); + if (pageScreen == "char") SendChar(); }, CancellationToken.None); randoToolLine = "Reading its settings"; SendRando(); @@ -273,7 +274,12 @@ public sealed partial class Backend Log.Write("randomizer: install: " + e); Toast("The randomizer could not be installed: " + H(e.Message), "error"); } - finally { randoToolBusy = false; randoToolLine = ""; Interlocked.Exchange(ref randoInstalling, 0); SendRando(true); } + finally + { + randoToolBusy = false; randoToolLine = ""; Interlocked.Exchange(ref randoInstalling, 0); SendRando(true); + // ((Triforce, 11-29) the Character page uses the same program for Link's colors) + if (pageScreen == "char") _ = CharOpen(); else SendChar(); + } } // ---------------- the settings ---------------- @@ -427,7 +433,7 @@ public sealed partial class Backend }, cts.Token, preset); var wins = made.Shared.Where(x => x.Wins).ToList(); var msg = "◆ Seed " + H(made.Seed.Seed) + " is on · start a new game in an empty file"; - if (wins.Count > 0) msg += " · " + H(string.Join(", ", wins.Select(x => x.Name))) + " " + (wins.Count == 1 ? "changes" : "change") + " some of the same files and " + (wins.Count == 1 ? "wins" : "win") + " them (Mods page)"; + if (wins.Count > 0) msg += " · " + H(string.Join(", ", wins.Select(x => x.Name))) + " " + (wins.Count == 1 ? "changes" : "change") + " some of the same files and " + (wins.Count == 1 ? "wins" : "win") + " them: the seed may not work (chests that stay shut) while " + (wins.Count == 1 ? "it is" : "they are") + " on (Mods page)"; Toast(msg, "success"); Sfx("success"); // (the next seed gets a new text: the one just used is kept with its seed. One typed while this one was made stays) diff --git a/launcher/App/Backend.cs b/launcher/App/Backend.cs index 8baf9cc..5e50542 100644 --- a/launcher/App/Backend.cs +++ b/launcher/App/Backend.cs @@ -11,7 +11,8 @@ namespace Triforce.Launcher; /// Backend.Saves.cs the Saves page (RegisterSaves) /// Backend.Mods.cs the Mods page (RegisterMods) /// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings) -/// Backend.Randomizer.cs the Randomizer page (OOTRR's seeds) (RegisterRandomizer) +/// Backend.Randomizer.cs the Randomizer page (OOTRR's seeds) (RegisterRandomizer) +/// Backend.Character.cs the Character page (Link in 3D, his colors) (RegisterCharacter) public sealed partial class Backend { readonly IHost host; @@ -20,13 +21,15 @@ public sealed partial class Backend readonly TriforceContext ctx; readonly StartupResult start; readonly Dictionary> cmds = new(); + /// The screen the page shows (its 'screen' message). + string? pageScreen; public Backend(IHost host, Content content, TriforceContext ctx, StartupResult start, string dataDir) { this.host = host; this.content = content; this.ctx = ctx; this.start = start; this.dataDir = dataDir; content.Media = MediaFor; content.SavePicture = SavePicture; - RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack(); RegisterRandomizer(); + RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack(); RegisterRandomizer(); RegisterCharacter(); } partial void RegisterSaves(); diff --git a/launcher/App/Content.cs b/launcher/App/Content.cs index f4cba4c..490f855 100644 --- a/launcher/App/Content.cs +++ b/launcher/App/Content.cs @@ -7,6 +7,7 @@ namespace Triforce.Launcher; /// media/png/NAME a texture from the player's own game (Core/GameFiles), e.g. the title logo /// media/wav/ID music or a sound from the player's own game /// save/N.jpg the picture in save file N (the game's own caption.sav) +/// char/... the Character page's Link: his posed mesh, textures, masks and recoloured maps /// Anything not there answers 404, and the page falls back (no game yet: no game art, no music). public sealed class Content { @@ -16,6 +17,8 @@ public sealed class Content readonly Dictionary names; public MediaSource? Media; public Func? SavePicture; + /// ((Triforce, 11-29) char/...: the Character page's model, textures and colour maps (Backend.Character.cs). + public Func? Character; public Content() { @@ -48,6 +51,8 @@ public sealed class Content var data = Media(parts[1], name); return data == null ? null : (data, parts[1] == "png" ? "image/png" : "audio/wav"); } + if (path.StartsWith("char/", StringComparison.Ordinal) && Character != null) + return Character(path["char/".Length..]); if (path.StartsWith("save/", StringComparison.Ordinal) && SavePicture != null && int.TryParse(Path.GetFileNameWithoutExtension(path)[..Math.Min(2, Path.GetFileNameWithoutExtension(path).Length)], out var n)) { diff --git a/launcher/Core/GameFiles/Astc.cs b/launcher/Core/GameFiles/Astc.cs index 130fd0f..238073c 100644 --- a/launcher/Core/GameFiles/Astc.cs +++ b/launcher/Core/GameFiles/Astc.cs @@ -21,7 +21,7 @@ public static class Astc // ---- bit streams ---- /// Reads bits from the low bit of the first byte upward; past the end it reads zeros. - ref struct InputBitStream + internal ref struct InputBitStream { readonly ReadOnlySpan data; int bitsRead; @@ -91,9 +91,9 @@ public static class Astc // ---- bounded integer sequences ---- - enum IntegerEncoding : byte { JustBits, Quint, Trit } + internal enum IntegerEncoding : byte { JustBits, Quint, Trit } - struct IntegerEncodedValue + internal struct IntegerEncodedValue { public IntegerEncoding Encoding; public int NumBits; @@ -143,7 +143,7 @@ public static class Astc return new IntegerEncodedValue(IntegerEncoding.JustBits, 0); } - static readonly IntegerEncodedValue[] Encodings = MakeEncodedValues(); + internal static readonly IntegerEncodedValue[] Encodings = MakeEncodedValues(); static IntegerEncodedValue[] MakeEncodedValues() { @@ -155,7 +155,7 @@ public static class Astc /// A fixed-capacity list of decoded values (boost::static_vector without throwing: values past the capacity /// are dropped, as there). - sealed class EncodedVector + internal sealed class EncodedVector { public readonly IntegerEncodedValue[] Items = new IntegerEncodedValue[300]; public int Count; @@ -167,7 +167,7 @@ public static class Astc } } - static void DecodeTritBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue) + internal static void DecodeTritBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue) { // (section C.2.12: read the trit-encoded block per table C.2.14) Span m = stackalloc uint[5]; @@ -230,7 +230,7 @@ public static class Astc } } - static void DecodeQuintBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue) + internal static void DecodeQuintBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue) { // (section C.2.12: read the quint-encoded block per table C.2.15) Span m = stackalloc uint[3]; @@ -308,7 +308,7 @@ public static class Astc // ---- block mode ---- - struct TexelWeightParams + internal struct TexelWeightParams { public uint Width, Height; public bool DualPlane; @@ -332,7 +332,7 @@ public static class Astc } } - static TexelWeightParams DecodeBlockInfo(ref InputBitStream strm) + internal static TexelWeightParams DecodeBlockInfo(ref InputBitStream strm) { var p = new TexelWeightParams(); // (the whole block mode at once) @@ -523,7 +523,7 @@ public static class Astc // ---- color endpoints ---- - static void DecodeColorValues(Span output, ReadOnlySpan data, ReadOnlySpan modes, int nPartitions, + internal static void DecodeColorValues(Span output, ReadOnlySpan data, ReadOnlySpan modes, int nPartitions, int nBitsForColorData, EncodedVector decoded) { // (how many color values there are) @@ -668,7 +668,7 @@ public static class Astc } } - static uint UnquantizeTexelWeight(IntegerEncodedValue val) + internal static uint UnquantizeTexelWeight(IntegerEncodedValue val) { var bitval = val.BitValue; var bitlen = val.NumBits; diff --git a/launcher/Core/GameFiles/AstcEncode.cs b/launcher/Core/GameFiles/AstcEncode.cs new file mode 100644 index 0000000..6f6218f --- /dev/null +++ b/launcher/Core/GameFiles/AstcEncode.cs @@ -0,0 +1,1084 @@ +// (Triforce, 11-29) ASTC block encoding (2D, LDR, one partition, one weight plane), for recolouring the game's textures: a +// texture is decoded with Astc.Decompress, recoloured, and the blocks whose texels changed are encoded again here. A block +// gets direct endpoints, CEM 8 (RGB) when every alpha in it is 255 and CEM 12 (RGBA) otherwise; a block of one colour is a +// void extent. The block modes, the trit and quint packing and the unquantised endpoint and weight values are all taken +// from the decoder's own code in Astc.cs (its block mode decoding, its trit/quint decoding enumerated backwards, its +// unquantisation), and the error of a fit is worked out with the decoder's own integer arithmetic, so what is written +// here decodes there as it was fitted. +// +// Per block: the principal axis of the texels gives the starting endpoints. Every legal weight grid and weight range for +// the footprint is scored quickly (grid weights fitted by least squares through the decoder's bilinear infill, endpoints +// rounded to the colour range the remaining bits leave), and the best few are refined over a few rounds: weights by +// projection onto the actual unquantised endpoints, grid weights moved a level at a time while that lowers the error, +// endpoints by least squares on the decoded weights, then moved a level at a time the same way. The best fit wins. +using System.Collections.Concurrent; + +namespace Triforce.Core.GameFiles; + +/// ASTC encoding of RGBA8 blocks and images (2D, LDR, single partition). +public static class AstcEncode +{ + /// How many of the quickly scored block modes are refined fully. + const int Candidates = 8; + + /// Refinement rounds per candidate. + const int Rounds = 4; + + // ---- bits ---- + + /// Writes the low n bits of val at bit pos (bits counted from the low bit of the first byte upward). + static void PutBits(Span buf, int pos, uint val, int n) + { + for (var i = 0; i < n; i++, pos++) + { + var mask = (byte)(1 << (pos & 7)); + if (((val >> i) & 1) != 0) + buf[pos >> 3] |= mask; + else + buf[pos >> 3] &= (byte)~mask; + } + } + + // ---- bounded integer sequences ---- + + /// Five trits (t0 + 3 t1 + 9 t2 + 27 t3 + 81 t4) to the 8 packed bits the decoder reads back as them. + static readonly byte[] TritPack = MakePack(true); + + /// Three quints (q0 + 5 q1 + 25 q2) to the 7 packed bits the decoder reads back as them. + static readonly byte[] QuintPack = MakePack(false); + + /// The packing table, by running the decoder's own trit or quint block decoding over every packed value (with + /// no plain bits, the packed bits are read in order). Where several packed values give the same digits the smallest is + /// kept, which is the one whose top bits are zero when the last digits are zero padding (a short last group drops + /// those bits). + static byte[] MakePack(bool trits) + { + var digits = trits ? 5 : 3; + var count = trits ? 243 : 125; + var pack = new byte[count]; + var seen = new bool[count]; + var vec = new Astc.EncodedVector(); + var one = new byte[1]; + for (var packed = (trits ? 256 : 128) - 1; packed >= 0; packed--) + { + one[0] = (byte)packed; + vec.Clear(); + var s = new Astc.InputBitStream(one); + if (trits) + Astc.DecodeTritBlock(ref s, vec, 0); + else + Astc.DecodeQuintBlock(ref s, vec, 0); + var idx = 0; + for (var i = digits - 1; i >= 0; i--) + idx = idx * (trits ? 3 : 5) + (int)vec.Items[i].QuintOrTritValue; + pack[idx] = (byte)packed; + seen[idx] = true; + } + if (Array.IndexOf(seen, false) >= 0) + throw new InvalidOperationException("ASTC " + (trits ? "trit" : "quint") + " packing does not cover every value"); + return pack; + } + + /// The values (each below the encoding's number of levels) written from bit pos as the decoder's + /// DecodeIntegerSequence reads them; returns the bit after the last one written. + static int WriteIse(Span buf, int pos, ReadOnlySpan values, Astc.IntegerEncodedValue enc) + { + var n = enc.NumBits; + var mask = (1 << n) - 1; + var total = enc.GetBitLength(values.Length); + Span tmp = stackalloc byte[64]; + tmp.Clear(); + Span m = stackalloc int[5]; + Span d = stackalloc int[5]; + var p = 0; + switch (enc.Encoding) + { + case Astc.IntegerEncoding.JustBits: + foreach (var v in values) + { + PutBits(tmp, p, (uint)v, n); + p += n; + } + break; + + case Astc.IntegerEncoding.Trit: + for (var g = 0; g < values.Length; g += 5) + { + for (var i = 0; i < 5; i++) + { + var v = g + i < values.Length ? values[g + i] : 0; + m[i] = v & mask; + d[i] = v >> n; + } + uint T = TritPack[d[0] + 3 * d[1] + 9 * d[2] + 27 * d[3] + 81 * d[4]]; + PutBits(tmp, p, (uint)m[0], n); p += n; + PutBits(tmp, p, T & 3, 2); p += 2; + PutBits(tmp, p, (uint)m[1], n); p += n; + PutBits(tmp, p, (T >> 2) & 3, 2); p += 2; + PutBits(tmp, p, (uint)m[2], n); p += n; + PutBits(tmp, p, (T >> 4) & 1, 1); p += 1; + PutBits(tmp, p, (uint)m[3], n); p += n; + PutBits(tmp, p, (T >> 5) & 3, 2); p += 2; + PutBits(tmp, p, (uint)m[4], n); p += n; + PutBits(tmp, p, (T >> 7) & 1, 1); p += 1; + } + break; + + case Astc.IntegerEncoding.Quint: + for (var g = 0; g < values.Length; g += 3) + { + for (var i = 0; i < 3; i++) + { + var v = g + i < values.Length ? values[g + i] : 0; + m[i] = v & mask; + d[i] = v >> n; + } + uint Q = QuintPack[d[0] + 5 * d[1] + 25 * d[2]]; + PutBits(tmp, p, (uint)m[0], n); p += n; + PutBits(tmp, p, Q & 7, 3); p += 3; + PutBits(tmp, p, (uint)m[1], n); p += n; + PutBits(tmp, p, (Q >> 3) & 3, 2); p += 2; + PutBits(tmp, p, (uint)m[2], n); p += n; + PutBits(tmp, p, (Q >> 5) & 3, 2); p += 2; + } + break; + } + // (a short last group is cut to the sequence's length, as the spec counts it) + for (var i = 0; i < total; i++) + PutBits(buf, pos + i, (uint)(tmp[i >> 3] >> (i & 7)) & 1, 1); + return pos + total; + } + + /// The number of levels an encoding has (2^n, 3 * 2^n or 5 * 2^n). + static int Levels(Astc.IntegerEncodedValue enc) => enc.Encoding switch + { + Astc.IntegerEncoding.Trit => 3 << enc.NumBits, + Astc.IntegerEncoding.Quint => 5 << enc.NumBits, + _ => 1 << enc.NumBits, + }; + + // ---- quantisation ---- + + /// One quantisation range: its codes, what each unquantises to, and the way back. + sealed class Quant + { + public readonly Astc.IntegerEncodedValue Enc; + public readonly int Levels; + /// Code to unquantised value. + public readonly int[] Unq; + /// The codes in order of their unquantised values. + public readonly int[] Sorted; + /// Code to its place in Sorted. + public readonly int[] Rank; + /// A value (0 to the top) to the code that unquantises nearest it. + public readonly int[] Nearest; + + public Quant(Astc.IntegerEncodedValue enc, int[] unq, int top) + { + Enc = enc; + Levels = unq.Length; + Unq = unq; + Sorted = Enumerable.Range(0, Levels).OrderBy(c => unq[c]).ThenBy(c => c).ToArray(); + Rank = new int[Levels]; + for (var i = 0; i < Levels; i++) + Rank[Sorted[i]] = i; + Nearest = new int[top + 1]; + for (var v = 0; v <= top; v++) + { + var best = 0; + for (var c = 1; c < Levels; c++) + if (Math.Abs(unq[c] - v) < Math.Abs(unq[best] - v)) + best = c; + Nearest[v] = best; + } + } + } + + /// The weight ranges a block mode can name (its largest weight), each with the decoder's unquantised weights. + static readonly Dictionary WeightQuants = MakeWeightQuants(); + + static Dictionary MakeWeightQuants() + { + var d = new Dictionary(); + foreach (var max in new uint[] { 1, 2, 3, 4, 5, 7, 9, 11, 15, 19, 23, 31 }) + { + var enc = Astc.Encodings[max]; + if (Levels(enc) != max + 1) + throw new InvalidOperationException("ASTC weight range " + max + " has no exact encoding"); + var unq = new int[max + 1]; + for (var v = 0; v <= max; v++) + unq[v] = (int)Astc.UnquantizeTexelWeight(new Astc.IntegerEncodedValue(enc.Encoding, enc.NumBits) + { + BitValue = (uint)(v & ((1 << enc.NumBits) - 1)), + QuintOrTritValue = (uint)(v >> enc.NumBits), + }); + d[max] = new Quant(enc, unq, 64); + } + return d; + } + + static readonly Dictionary ColourQuants = new(); + + /// The colour range of that many levels, its unquantised values found by encoding each code (all the block's + /// endpoint values set to it) and running the decoder's DecodeColorValues on it, with the bits that chose this range. + static Quant ColourQuant(int levels, uint cem, int nValues, int colourBits) + { + lock (ColourQuants) + { + if (ColourQuants.TryGetValue(levels, out var q)) + return q; + var enc = Astc.Encodings[levels - 1]; + var unq = new int[levels]; + var data = new byte[16]; + var values = new int[nValues]; + var output = new uint[32]; + var vec = new Astc.EncodedVector(); + for (var v = 0; v < levels; v++) + { + Array.Fill(values, v); + Array.Clear(data); + WriteIse(data, 0, values, enc); + Astc.DecodeColorValues(output, data, new[] { cem }, 1, colourBits, vec); + for (var i = 1; i < nValues; i++) + if (output[i] != output[0]) + throw new InvalidOperationException("ASTC colour value packing does not read back"); + unq[v] = (int)output[0]; + } + q = new Quant(enc, unq, 255); + ColourQuants[levels] = q; + return q; + } + } + + /// The number of levels the decoder gives nValues endpoint values in that many bits (DecodeColorValues' search: + /// the largest range that fits), or 0. + static int ColourLevels(int nValues, int bits) + { + var range = 256; + while (--range > 0) + { + var val = Astc.Encodings[range]; + if (val.GetBitLength(nValues) <= bits) + { + while (--range > 0) + { + if (!Astc.Encodings[range].MatchesEncoding(val)) + break; + } + range++; + break; + } + } + if (range <= 0) + return 0; + var levels = Levels(Astc.Encodings[range]); + return levels - 1 == range ? levels : 0; + } + + // ---- footprints ---- + + /// A weight grid on a footprint: the decoder's bilinear infill per texel, and its least squares inverse. + sealed class Grid + { + public int W, H, Count, Index; + /// Per texel, four grid points and their weights out of 16 (a point past the grid has weight 0). + public int[] Idx = Array.Empty(), Fac = Array.Empty(); + /// The grid is the footprint itself, one weight per texel. + public bool Identity; + /// Count x texels: the grid weights whose infill is nearest (least squares) a set of texel weights. + public double[] Fit = Array.Empty(); + /// Per grid point, the texels its weight reaches. + public int[][] Touch = Array.Empty(); + } + + /// One usable block mode: its 11 bits, grid, weight range and the colour range that leaves. + sealed class Mode + { + public uint Bits; + public Grid Grid = null!; + public Quant Weights = null!, Colours = null!; + public int WeightBits; + } + + sealed class Footprint + { + public int Bw, Bh, T; + public Grid[] Grids = Array.Empty(); + public Mode[] Rgb = Array.Empty(), Rgba = Array.Empty(); + } + + static readonly ConcurrentDictionary> Footprints = new(); + + static Footprint GetFootprint(int bw, int bh) => + Footprints.GetOrAdd(bw * 16 + bh, _ => new Lazy(() => MakeFootprint(bw, bh))).Value; + + /// Every block mode the decoder accepts for this footprint that is single plane and within the spec's limits + /// (at most 64 weights, 24 to 96 weight bits, a colour range of at least 6 levels), found by running all 2048 mode values + /// through the decoder's own block mode decoding. + static Footprint MakeFootprint(int bw, int bh) + { + var grids = new Dictionary<(uint, uint), Grid>(); + var seen = new HashSet<(uint, uint, uint)>(); + var rgb = new List(); + var rgba = new List(); + var bits = new byte[16]; + for (var m = 0u; m < 2048; m++) + { + Array.Clear(bits); + bits[0] = (byte)m; + bits[1] = (byte)(m >> 8); + var s = new Astc.InputBitStream(bits); + var p = Astc.DecodeBlockInfo(ref s); + if (p.Error || p.VoidExtentLDR || p.VoidExtentHDR || p.DualPlane || p.Width > bw || p.Height > bh) + continue; + var weightBits = p.GetPackedBitSize(); + if (p.Width * p.Height > 64 || weightBits < 24 || weightBits > 96 || !seen.Add((p.Width, p.Height, p.MaxWeight))) + continue; + if (!grids.TryGetValue((p.Width, p.Height), out var grid)) + { + grid = MakeGrid(bw, bh, (int)p.Width, (int)p.Height); + grid.Index = grids.Count; + grids[(p.Width, p.Height)] = grid; + } + var colourBits = 128 - 17 - weightBits; + foreach (var cem in new uint[] { 8, 12 }) + { + var nValues = cem == 8 ? 6 : 8; + var levels = ColourLevels(nValues, colourBits); + if (levels < 6) + continue; + var mode = new Mode + { + Bits = m, + Grid = grid, + Weights = WeightQuants[p.MaxWeight], + Colours = ColourQuant(levels, cem, nValues, colourBits), + WeightBits = weightBits, + }; + (cem == 8 ? rgb : rgba).Add(mode); + } + } + return new Footprint + { + Bw = bw, + Bh = bh, + T = bw * bh, + Grids = grids.Values.OrderBy(g => g.Index).ToArray(), + Rgb = rgb.ToArray(), + Rgba = rgba.ToArray(), + }; + } + + /// The decoder's weight infill (UnquantizeTexelWeights) for a grid on a footprint, and its inverse. + static Grid MakeGrid(int bw, int bh, int gw, int gh) + { + var T = bw * bh; + var count = gw * gh; + var g = new Grid { W = gw, H = gh, Count = count, Idx = new int[T * 4], Fac = new int[T * 4] }; + var Ds = (uint)((1024 + bw / 2) / (bw - 1)); + var Dt = (uint)((1024 + bh / 2) / (bh - 1)); + for (var t = 0; t < bh; t++) + for (var s = 0; s < bw; s++) + { + var cs = Ds * (uint)s; + var ct = Dt * (uint)t; + var gs = (cs * (uint)(gw - 1) + 32) >> 6; + var gt = (ct * (uint)(gh - 1) + 32) >> 6; + var js = gs >> 4; + var fs = gs & 0xF; + var jt = gt >> 4; + var ft = gt & 0xF; + var w11 = (fs * ft + 8) >> 4; + var w10 = ft - w11; + var w01 = fs - w11; + var w00 = 16 - fs - ft + w11; + var v0 = js + jt * (uint)gw; + var at = (t * bw + s) * 4; + for (var k = 0; k < 4; k++) + { + var i = v0 + (k == 1 || k == 3 ? 1u : 0u) + (k >= 2 ? (uint)gw : 0u); + var f = k switch { 0 => w00, 1 => w01, 2 => w10, _ => w11 }; + // (the decoder reads a point past the grid as 0) + var inside = i < (uint)count; + g.Idx[at + k] = inside ? (int)i : 0; + g.Fac[at + k] = inside ? (int)f : 0; + } + } + + g.Identity = gw == bw && gh == bh; + for (var t = 0; t < T && g.Identity; t++) + if (g.Idx[t * 4] != t || g.Fac[t * 4] != 16) + g.Identity = false; + + var touch = Enumerable.Range(0, count).Select(_ => new List()).ToArray(); + for (var t = 0; t < T; t++) + for (var k = 0; k < 4; k++) + if (g.Fac[t * 4 + k] > 0 && !touch[g.Idx[t * 4 + k]].Contains(t)) + touch[g.Idx[t * 4 + k]].Add(t); + g.Touch = touch.Select(l => l.ToArray()).ToArray(); + + if (!g.Identity) + { + // (A: texels x grid points, the infill as fractions; Fit = (A'A + small)^-1 A') + var a = new double[T * count]; + for (var t = 0; t < T; t++) + for (var k = 0; k < 4; k++) + a[t * count + g.Idx[t * 4 + k]] += g.Fac[t * 4 + k] / 16.0; + var n = count; + var mtm = new double[n * 2 * n]; + for (var i = 0; i < n; i++) + { + for (var j = 0; j < n; j++) + { + double sum = 0; + for (var t = 0; t < T; t++) + sum += a[t * n + i] * a[t * n + j]; + mtm[i * 2 * n + j] = sum + (i == j ? 1e-4 : 0); + } + mtm[i * 2 * n + n + i] = 1; + } + Invert(mtm, n); + g.Fit = new double[n * T]; + for (var i = 0; i < n; i++) + for (var t = 0; t < T; t++) + { + double sum = 0; + for (var j = 0; j < n; j++) + sum += mtm[i * 2 * n + n + j] * a[t * n + j]; + g.Fit[i * T + t] = sum; + } + } + return g; + } + + /// Gauss-Jordan elimination on an n x 2n matrix [M | I], leaving [I | M^-1]. + static void Invert(double[] m, int n) + { + var w = 2 * n; + for (var c = 0; c < n; c++) + { + var piv = c; + for (var r = c + 1; r < n; r++) + if (Math.Abs(m[r * w + c]) > Math.Abs(m[piv * w + c])) + piv = r; + if (piv != c) + for (var k = 0; k < w; k++) + (m[c * w + k], m[piv * w + k]) = (m[piv * w + k], m[c * w + k]); + var d = m[c * w + c]; + for (var k = 0; k < w; k++) + m[c * w + k] /= d; + for (var r = 0; r < n; r++) + { + if (r == c) + continue; + var f = m[r * w + c]; + if (f == 0) + continue; + for (var k = 0; k < w; k++) + m[r * w + k] -= f * m[c * w + k]; + } + } + } + + // ---- the decoder's arithmetic ---- + + /// One channel of a texel from two endpoint bytes and a weight 0..64, exactly as the decoder makes it. + static int Interp(int e0, int e1, int w) + { + var c0 = (uint)e0 * 257u; + var c1 = (uint)e1 * 257u; + var c = (c0 * (uint)(64 - w) + c1 * (uint)w + 32) / 64; + return c == 65535 ? 255 : (int)(255.0 * (c / 65536.0) + 0.5); + } + + /// A texel's weight from the unquantised grid weights, as the decoder infills it. + static int InfillOne(Grid g, int[] gunq, int t) + { + var b = t * 4; + return (gunq[g.Idx[b]] * g.Fac[b] + gunq[g.Idx[b + 1]] * g.Fac[b + 1] + gunq[g.Idx[b + 2]] * g.Fac[b + 2] + + gunq[g.Idx[b + 3]] * g.Fac[b + 3] + 8) >> 4; + } + + // ---- per thread working memory ---- + + sealed class Work + { + public readonly int[] Px = new int[144 * 4]; + public readonly double[] Ideal = new double[144]; + public readonly double[][] GridFits = Enumerable.Range(0, 128).Select(_ => new double[64]).ToArray(); + public readonly bool[] GridDone = new bool[128]; + public readonly double[] GridF = new double[64]; + public readonly int[] GCodes = new int[64], GUnq = new int[64], BestG = new int[64], CandG = new int[64]; + public readonly int[] Tw = new int[144], Terr = new int[144]; + public readonly int[] Lut = new int[4 * 65], LutTry = new int[65]; + public readonly int[] C0 = new int[4], C1 = new int[4], BestC0 = new int[4], BestC1 = new int[4]; + public readonly int[] CandC0 = new int[4], CandC1 = new int[4]; + public readonly double[] E0 = new double[4], E1 = new double[4]; + public long[] Quick = new long[256]; + public int[] Order = new int[256]; + } + + [ThreadStatic] static Work? work; + + // ---- the encoder ---- + + /// texels: blockWidth * blockHeight RGBA8 texels of one block, row-major. Returns 16 bytes: one ASTC block + /// (2D, LDR, single partition). + public static byte[] EncodeBlock(ReadOnlySpan texels, int blockWidth, int blockHeight) + { + var block = new byte[16]; + EncodeBlock(texels, blockWidth, blockHeight, block); + return block; + } + + /// A whole image (width x height RGBA8, row-major) to linear-order ASTC blocks (blocks in rows, 16 bytes each), + /// the edge blocks padded by repeating the last row and column. Rows of blocks are encoded on several threads. + public static byte[] Encode(ReadOnlySpan rgba, int width, int height, int blockWidth, int blockHeight) + { + CheckFootprint(blockWidth, blockHeight); + ImageLimits.Check(width, height); + if (rgba.Length < (long)width * height * 4) + throw new ArgumentException("the image is shorter than " + width + " x " + height + " RGBA8", nameof(rgba)); + var cols = (width + blockWidth - 1) / blockWidth; + var rows = (height + blockHeight - 1) / blockHeight; + var src = rgba[..(width * height * 4)].ToArray(); + var output = new byte[cols * rows * 16]; + GetFootprint(blockWidth, blockHeight); + Parallel.For(0, rows, () => new byte[blockWidth * blockHeight * 4], (by, _, texels) => + { + for (var bx = 0; bx < cols; bx++) + { + for (var y = 0; y < blockHeight; y++) + { + var sy = Math.Min(by * blockHeight + y, height - 1); + for (var x = 0; x < blockWidth; x++) + { + var sx = Math.Min(bx * blockWidth + x, width - 1); + Buffer.BlockCopy(src, (sy * width + sx) * 4, texels, (y * blockWidth + x) * 4, 4); + } + } + EncodeBlock(texels, blockWidth, blockHeight, output.AsSpan((by * cols + bx) * 16, 16)); + } + return texels; + }, _ => { }); + return output; + } + + static void CheckFootprint(int bw, int bh) + { + if (bw < 4 || bw > 12 || bh < 4 || bh > 12) + throw new NotSupportedException("ASTC block " + bw + "x" + bh); + } + + /// One block encoded into dest (16 bytes). + static void EncodeBlock(ReadOnlySpan texels, int bw, int bh, Span dest) + { + CheckFootprint(bw, bh); + var T = bw * bh; + if (texels.Length < T * 4) + throw new ArgumentException("a " + bw + "x" + bh + " block needs " + T * 4 + " bytes of texels", nameof(texels)); + dest[..16].Clear(); + + // (one colour: a void extent block) + var solid = true; + var hasAlpha = false; + for (var t = 0; t < T; t++) + { + if (texels[t * 4 + 3] != 255) + hasAlpha = true; + if (solid && (texels[t * 4] != texels[0] || texels[t * 4 + 1] != texels[1] || texels[t * 4 + 2] != texels[2] + || texels[t * 4 + 3] != texels[3])) + solid = false; + } + if (solid) + { + WriteVoidExtent(dest, texels[0], texels[1], texels[2], texels[3]); + return; + } + + var fp = GetFootprint(bw, bh); + var modes = hasAlpha ? fp.Rgba : fp.Rgb; + var C = hasAlpha ? 4 : 3; + var wk = work ??= new Work(); + var px = wk.Px; + for (var t = 0; t < T; t++) + for (var c = 0; c < 4; c++) + px[t * 4 + c] = texels[t * 4 + c]; + + PrincipalEndpoints(wk, T, C); + Project(wk, wk.E0, wk.E1, T, C); + + // (every mode scored quickly) + if (wk.Quick.Length < modes.Length) + { + wk.Quick = new long[modes.Length]; + wk.Order = new int[modes.Length]; + } + Array.Clear(wk.GridDone); + for (var i = 0; i < modes.Length; i++) + { + wk.Quick[i] = QuickError(wk, modes[i], T, C); + wk.Order[i] = i; + } + Array.Sort(wk.Quick, wk.Order, 0, modes.Length); + + // (the best few refined) + var best = long.MaxValue; + Mode? bestMode = null; + for (var i = 0; i < Math.Min(Candidates, modes.Length); i++) + { + var mode = modes[wk.Order[i]]; + var err = Refine(wk, mode, T, C); + if (err < best) + { + best = err; + bestMode = mode; + Array.Copy(wk.CandC0, wk.BestC0, 4); + Array.Copy(wk.CandC1, wk.BestC1, 4); + Array.Copy(wk.CandG, wk.BestG, mode.Grid.Count); + } + } + WriteBlock(dest, bestMode!, hasAlpha, wk.BestC0, wk.BestC1, wk.BestG); + } + + /// The ends of the texels' principal axis (power iteration on their covariance), clamped to 0..255 and ordered + /// so the second has the larger RGB sum (the decoder swaps and blue-contracts otherwise). + static void PrincipalEndpoints(Work wk, int T, int C) + { + var px = wk.Px; + Span mean = stackalloc double[4]; + mean.Clear(); + for (var t = 0; t < T; t++) + for (var c = 0; c < C; c++) + mean[c] += px[t * 4 + c]; + for (var c = 0; c < C; c++) + mean[c] /= T; + Span cov = stackalloc double[16]; + cov.Clear(); + for (var t = 0; t < T; t++) + for (var i = 0; i < C; i++) + { + var di = px[t * 4 + i] - mean[i]; + for (var j = 0; j < C; j++) + cov[i * 4 + j] += di * (px[t * 4 + j] - mean[j]); + } + + // (start from the column of the channel that varies most) + var top = 0; + for (var c = 1; c < C; c++) + if (cov[c * 4 + c] > cov[top * 4 + top]) + top = c; + Span v = stackalloc double[4]; + Span nv = stackalloc double[4]; + for (var c = 0; c < C; c++) + v[c] = cov[c * 4 + top]; + for (var it = 0; it < 16; it++) + { + double len = 0; + for (var c = 0; c < C; c++) + len += v[c] * v[c]; + len = Math.Sqrt(len); + if (len < 1e-12) + { + v.Clear(); + v[top] = 1; + break; + } + for (var c = 0; c < C; c++) + v[c] /= len; + for (var i = 0; i < C; i++) + { + double sum = 0; + for (var j = 0; j < C; j++) + sum += cov[i * 4 + j] * v[j]; + nv[i] = sum; + } + nv[..C].CopyTo(v); + } + { + double len = 0; + for (var c = 0; c < C; c++) + len += v[c] * v[c]; + len = Math.Sqrt(len); + if (len < 1e-12) + { + v.Clear(); + v[top] = 1; + len = 1; + } + for (var c = 0; c < C; c++) + v[c] /= len; + } + + double tmin = double.MaxValue, tmax = double.MinValue; + for (var t = 0; t < T; t++) + { + double d = 0; + for (var c = 0; c < C; c++) + d += (px[t * 4 + c] - mean[c]) * v[c]; + tmin = Math.Min(tmin, d); + tmax = Math.Max(tmax, d); + } + for (var c = 0; c < 4; c++) + { + wk.E0[c] = c < C ? Math.Clamp(mean[c] + tmin * v[c], 0, 255) : 255; + wk.E1[c] = c < C ? Math.Clamp(mean[c] + tmax * v[c], 0, 255) : 255; + } + if (wk.E1[0] + wk.E1[1] + wk.E1[2] < wk.E0[0] + wk.E0[1] + wk.E0[2]) + for (var c = 0; c < 4; c++) + (wk.E0[c], wk.E1[c]) = (wk.E1[c], wk.E0[c]); + } + + /// Each texel's weight (0..64, fractional) by projection onto the segment from e0 to e1, into wk.Ideal. + static void Project(Work wk, ReadOnlySpan e0, ReadOnlySpan e1, int T, int C) + { + Span d = stackalloc double[4]; + double len2 = 0; + for (var c = 0; c < C; c++) + { + d[c] = e1[c] - e0[c]; + len2 += d[c] * d[c]; + } + for (var t = 0; t < T; t++) + { + if (len2 < 1e-9) + { + wk.Ideal[t] = 0; + continue; + } + double dot = 0; + for (var c = 0; c < C; c++) + dot += (wk.Px[t * 4 + c] - e0[c]) * d[c]; + wk.Ideal[t] = Math.Clamp(dot / len2, 0, 1) * 64; + } + } + + /// Grid weights (0..64, fractional) whose infill is nearest the texel weights in wk.Ideal. + static void FitGrid(Work wk, Grid g, int T, double[] into) + { + if (g.Identity) + { + Array.Copy(wk.Ideal, into, T); + return; + } + var fit = g.Fit; + for (var k = 0; k < g.Count; k++) + { + double sum = 0; + var row = k * T; + for (var t = 0; t < T; t++) + sum += fit[row + t] * wk.Ideal[t]; + into[k] = Math.Clamp(sum, 0, 64); + } + } + + static int RgbSum(Quant q, ReadOnlySpan codes) => q.Unq[codes[0]] + q.Unq[codes[1]] + q.Unq[codes[2]]; + + static int ToByte(double v) => (int)Math.Clamp(Math.Round(v), 0, 255); + + /// The lookup of decoded channel values by weight for the current endpoint codes. + static void FillLut(Work wk, Quant cq, int C) + { + for (var c = 0; c < C; c++) + { + int d0 = cq.Unq[wk.C0[c]], d1 = cq.Unq[wk.C1[c]]; + for (var w = 0; w <= 64; w++) + wk.Lut[c * 65 + w] = Interp(d0, d1, w); + } + } + + static int TexelError(Work wk, int t, int w, int C) + { + var e = 0; + for (var c = 0; c < C; c++) + { + var d = wk.Lut[c * 65 + w] - wk.Px[t * 4 + c]; + e += d * d; + } + return e; + } + + /// A quick score for a mode: the principal-axis endpoints rounded to its colour range, the grid fitted to the + /// projected weights and rounded to its weight range. + static long QuickError(Work wk, Mode mode, int T, int C) + { + var g = mode.Grid; + var cq = mode.Colours; + var wq = mode.Weights; + var gf = wk.GridFits[g.Index]; + if (!wk.GridDone[g.Index]) + { + FitGrid(wk, g, T, gf); + wk.GridDone[g.Index] = true; + } + for (var c = 0; c < C; c++) + { + wk.C0[c] = cq.Nearest[ToByte(wk.E0[c])]; + wk.C1[c] = cq.Nearest[ToByte(wk.E1[c])]; + } + var flip = RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0); + if (flip) + for (var c = 0; c < C; c++) + (wk.C0[c], wk.C1[c]) = (wk.C1[c], wk.C0[c]); + for (var k = 0; k < g.Count; k++) + { + var v = flip ? 64 - gf[k] : gf[k]; + wk.GUnq[k] = wq.Unq[wq.Nearest[(int)Math.Round(v)]]; + } + FillLut(wk, cq, C); + long err = 0; + for (var t = 0; t < T; t++) + err += TexelError(wk, t, InfillOne(g, wk.GUnq, t), C); + return err; + } + + /// A mode fitted fully; the best endpoint and grid codes found are left in wk.CandC0/CandC1/CandG. + static long Refine(Work wk, Mode mode, int T, int C) + { + var g = mode.Grid; + var cq = mode.Colours; + var wq = mode.Weights; + for (var c = 0; c < 4; c++) + { + wk.C0[c] = c < C ? cq.Nearest[ToByte(wk.E0[c])] : 0; + wk.C1[c] = c < C ? cq.Nearest[ToByte(wk.E1[c])] : 0; + } + if (RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0)) + for (var c = 0; c < C; c++) + (wk.C0[c], wk.C1[c]) = (wk.C1[c], wk.C0[c]); + + var best = long.MaxValue; + Span d0 = stackalloc double[4]; + Span d1 = stackalloc double[4]; + for (var round = 0; round < Rounds; round++) + { + // (weights: projection onto the actual endpoints, fitted to the grid and rounded) + for (var c = 0; c < C; c++) + { + d0[c] = cq.Unq[wk.C0[c]]; + d1[c] = cq.Unq[wk.C1[c]]; + } + Project(wk, d0, d1, T, C); + FitGrid(wk, g, T, wk.GridF); + for (var k = 0; k < g.Count; k++) + { + wk.GCodes[k] = wq.Nearest[(int)Math.Round(wk.GridF[k])]; + wk.GUnq[k] = wq.Unq[wk.GCodes[k]]; + } + FillLut(wk, cq, C); + long err = 0; + for (var t = 0; t < T; t++) + { + wk.Tw[t] = InfillOne(g, wk.GUnq, t); + wk.Terr[t] = TexelError(wk, t, wk.Tw[t], C); + err += wk.Terr[t]; + } + err = DescendGrid(wk, g, wq, err, C); + if (err < best) + best = Keep(wk, g, err); + if (err == 0) + break; + + // (endpoints: least squares on the decoded weights, rounded, then nudged) + if (!LeastSquaresEndpoints(wk, cq, T, C)) + continue; + FillLut(wk, cq, C); + err = DescendEndpoints(wk, cq, T, C); + if (err < best) + best = Keep(wk, g, err); + } + return best; + } + + static long Keep(Work wk, Grid g, long err) + { + Array.Copy(wk.C0, wk.CandC0, 4); + Array.Copy(wk.C1, wk.CandC1, 4); + Array.Copy(wk.GCodes, wk.CandG, g.Count); + return err; + } + + /// Each grid weight moved a level up or down while that lowers the decoded error; returns the new error. + static long DescendGrid(Work wk, Grid g, Quant wq, long err, int C) + { + for (var pass = 0; pass < 3; pass++) + { + var changed = false; + for (var k = 0; k < g.Count; k++) + { + var rank = wq.Rank[wk.GCodes[k]]; + var old = wk.GUnq[k]; + for (var dir = -1; dir <= 1; dir += 2) + { + var r2 = rank + dir; + if (r2 < 0 || r2 >= wq.Levels) + continue; + var code = wq.Sorted[r2]; + wk.GUnq[k] = wq.Unq[code]; + long delta = 0; + foreach (var t in g.Touch[k]) + delta += TexelError(wk, t, InfillOne(g, wk.GUnq, t), C) - wk.Terr[t]; + if (delta < 0) + { + wk.GCodes[k] = code; + foreach (var t in g.Touch[k]) + { + wk.Tw[t] = InfillOne(g, wk.GUnq, t); + wk.Terr[t] = TexelError(wk, t, wk.Tw[t], C); + } + err += delta; + changed = true; + old = wk.GUnq[k]; + break; + } + wk.GUnq[k] = old; + } + } + if (!changed) + break; + } + return err; + } + + /// Endpoints by least squares on the decoded texel weights, rounded to the colour range. False when the + /// result's order is the wrong way round (it is swapped for the next round's weights to follow). + static bool LeastSquaresEndpoints(Work wk, Quant cq, int T, int C) + { + for (var c = 0; c < C; c++) + { + double saa = 0, sab = 0, sbb = 0, sap = 0, sbp = 0, sp = 0; + for (var t = 0; t < T; t++) + { + var b = wk.Tw[t] / 64.0; + var a = 1 - b; + var p = wk.Px[t * 4 + c]; + saa += a * a; + sab += a * b; + sbb += b * b; + sap += a * p; + sbp += b * p; + sp += p; + } + var det = saa * sbb - sab * sab; + double x0, x1; + if (Math.Abs(det) < 1e-9) + x0 = x1 = sp / T; + else + { + x0 = (sbb * sap - sab * sbp) / det; + x1 = (saa * sbp - sab * sap) / det; + } + wk.C0[c] = cq.Nearest[ToByte(x0)]; + wk.C1[c] = cq.Nearest[ToByte(x1)]; + } + if (RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0)) + { + for (var c = 0; c < C; c++) + (wk.C0[c], wk.C1[c]) = (wk.C1[c], wk.C0[c]); + return false; + } + return true; + } + + /// Each endpoint value moved a level up or down while that lowers the decoded error (keeping the endpoints' + /// order); returns the error. + static long DescendEndpoints(Work wk, Quant cq, int T, int C) + { + Span chan = stackalloc long[4]; + for (var c = 0; c < C; c++) + { + long e = 0; + for (var t = 0; t < T; t++) + { + var d = wk.Lut[c * 65 + wk.Tw[t]] - wk.Px[t * 4 + c]; + e += d * d; + } + chan[c] = e; + } + for (var pass = 0; pass < 3; pass++) + { + var changed = false; + for (var c = 0; c < C; c++) + for (var end = 0; end < 2; end++) + { + var codes = end == 0 ? wk.C0 : wk.C1; + var rank = cq.Rank[codes[c]]; + for (var dir = -1; dir <= 1; dir += 2) + { + var r2 = rank + dir; + if (r2 < 0 || r2 >= cq.Levels) + continue; + var code = cq.Sorted[r2]; + var old = codes[c]; + codes[c] = code; + if (c < 3 && RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0)) + { + codes[c] = old; + continue; + } + int v0 = cq.Unq[wk.C0[c]], v1 = cq.Unq[wk.C1[c]]; + for (var w = 0; w <= 64; w++) + wk.LutTry[w] = Interp(v0, v1, w); + long e = 0; + for (var t = 0; t < T; t++) + { + var d = wk.LutTry[wk.Tw[t]] - wk.Px[t * 4 + c]; + e += d * d; + } + if (e < chan[c]) + { + chan[c] = e; + Array.Copy(wk.LutTry, 0, wk.Lut, c * 65, 65); + changed = true; + break; + } + codes[c] = old; + } + } + if (!changed) + break; + } + long total = 0; + for (var c = 0; c < C; c++) + total += chan[c]; + return total; + } + + // ---- writing ---- + + /// The block's bits: mode, one partition, the CEM, the endpoint values from bit 17, the weights from bit 127 down. + static void WriteBlock(Span dest, Mode mode, bool hasAlpha, int[] c0, int[] c1, int[] gcodes) + { + PutBits(dest, 0, mode.Bits, 11); + PutBits(dest, 11, 0, 2); + PutBits(dest, 13, hasAlpha ? 12u : 8u, 4); + Span values = stackalloc int[8]; + var n = hasAlpha ? 8 : 6; + for (var c = 0; c < n / 2; c++) + { + values[2 * c] = c0[c]; + values[2 * c + 1] = c1[c]; + } + WriteIse(dest, 17, values[..n], mode.Colours.Enc); + Span w = stackalloc byte[16]; + w.Clear(); + WriteIse(w, 0, gcodes.AsSpan(0, mode.Grid.Count), mode.Weights.Enc); + for (var i = 0; i < mode.WeightBits; i++) + if (((w[i >> 3] >> (i & 7)) & 1) != 0) + dest[(127 - i) >> 3] |= (byte)(1 << ((127 - i) & 7)); + } + + /// A void extent block (LDR, no extent given): the whole block is one colour, stored as UNORM16. + static void WriteVoidExtent(Span dest, byte r, byte g, byte b, byte a) + { + PutBits(dest, 0, 0x1FC, 9); + PutBits(dest, 9, 0, 1); + PutBits(dest, 10, 3, 2); + for (var i = 0; i < 4; i++) + PutBits(dest, 12 + 13 * i, 0x1FFF, 13); + PutBits(dest, 64, r * 257u, 16); + PutBits(dest, 80, g * 257u, 16); + PutBits(dest, 96, b * 257u, 16); + PutBits(dest, 112, a * 257u, 16); + } +} diff --git a/launcher/Core/GameFiles/Bc7.cs b/launcher/Core/GameFiles/Bc7.cs new file mode 100644 index 0000000..de1db5d --- /dev/null +++ b/launcher/Core/GameFiles/Bc7.cs @@ -0,0 +1,220 @@ +// (Triforce, 11-29) BC7 (BPTC unorm) decoding to RGBA8, for the Character page's textures (Link's face and adult hair are BC7). +// Written from the format's specification (the D3D11 functional spec / KHR_texture_compression_bptc): 8 modes, 1-3 subsets, +// partition tables, P-bits, index rotation and the separate alpha indexes of modes 4 and 5. +namespace Triforce.Core.GameFiles; + +public static class Bc7 +{ + struct Mode + { + public int Subsets, PartBits, RotBits, IdxSelBits, ColorBits, AlphaBits, EndPBits, SharedPBits, IdxBits, Idx2Bits; + public Mode(int ns, int pb, int rb, int isb, int cb, int ab, int epb, int spb, int ib, int ib2) + { Subsets = ns; PartBits = pb; RotBits = rb; IdxSelBits = isb; ColorBits = cb; AlphaBits = ab; EndPBits = epb; SharedPBits = spb; IdxBits = ib; Idx2Bits = ib2; } + } + + static readonly Mode[] Modes = + { + new(3, 4, 0, 0, 4, 0, 1, 0, 3, 0), + new(2, 6, 0, 0, 6, 0, 0, 1, 3, 0), + new(3, 6, 0, 0, 5, 0, 0, 0, 2, 0), + new(2, 6, 0, 0, 7, 0, 1, 0, 2, 0), + new(1, 0, 2, 1, 5, 6, 0, 0, 2, 3), + new(1, 0, 2, 0, 7, 8, 0, 0, 2, 2), + new(1, 0, 0, 0, 7, 7, 1, 0, 4, 0), + new(2, 6, 0, 0, 5, 5, 1, 0, 2, 0), + }; + + static readonly byte[] W2 = { 0, 21, 43, 64 }; + static readonly byte[] W3 = { 0, 9, 18, 27, 37, 46, 55, 64 }; + static readonly byte[] W4 = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 }; + + static readonly uint[] P2 = + { + 0xCCCC, 0x8888, 0xEEEE, 0xECC8, 0xC880, 0xFEEC, 0xFEC8, 0xEC80, 0xC800, 0xFFEC, 0xFE80, 0xE800, 0xFFE8, 0xFF00, 0xFFF0, 0xF000, + 0xF710, 0x008E, 0x7100, 0x08CE, 0x008C, 0x7310, 0x3100, 0x8CCE, 0x088C, 0x3110, 0x6666, 0x366C, 0x17E8, 0x0FF0, 0x718E, 0x399C, + 0xAAAA, 0xF0F0, 0x5A5A, 0x33CC, 0x3C3C, 0x55AA, 0x9696, 0xA55A, 0x73CE, 0x13C8, 0x324C, 0x3BDC, 0x6996, 0xC33C, 0x9966, 0x0660, + 0x0272, 0x04E4, 0x4E40, 0x2720, 0xC936, 0x936C, 0x39C6, 0x639C, 0x9336, 0x9CC6, 0x817E, 0xE718, 0xCCF0, 0x0FCC, 0x7744, 0xEE22, + }; + + static readonly string P3 = + "0011001102212222" + "0001001122112221" + "0000200122112211" + "0222002200110111" + "0000000011221122" + "0011001100220022" + "0022002211111111" + "0011001122112211" + + "0000000011112222" + "0000111111112222" + "0000111122222222" + "0012001200120012" + "0112011201120112" + "0122012201220122" + "0011011211221222" + "0011200122002220" + + "0001001101121122" + "0111001120012200" + "0000112211221122" + "0022002200221111" + "0111011102220222" + "0001000122212221" + "0000001101220122" + "0000110022102210" + + "0122012200110000" + "0012001211222222" + "0110122112210110" + "0000011012211221" + "0022110211020022" + "0110011020022222" + "0011012201220011" + "0000200022112221" + + "0000000211221222" + "0222002200120011" + "0011001200220222" + "0120012001200120" + "0000111122220000" + "0120120120120120" + "0120201212010120" + "0011220011220011" + + "0011112222000011" + "0101010122222222" + "0000000021212121" + "0022112200221122" + "0022001100220011" + "0220122102201221" + "0101222222220101" + "0000212121212121" + + "0101010101012222" + "0222011102220111" + "0002111200021112" + "0000211221122112" + "0222011101110222" + "0002111211120002" + "0110011001102222" + "0000000021122112" + + "0110011022222222" + "0022001100110022" + "0022112211220022" + "0000000000002112" + "0002000100020001" + "0222122202221222" + "0101222222222222" + "0111201122012220"; + + static readonly byte[] A2 = + { + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, + 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, + }; + static readonly byte[] A3a = + { + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, + 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, + }; + static readonly byte[] A3b = + { + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, + 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, + }; + + ref struct Bits + { + readonly ReadOnlySpan b; + int pos; + public Bits(ReadOnlySpan block) { b = block; pos = 0; } + public int Read(int n) + { + var v = 0; + for (var i = 0; i < n; i++, pos++) v |= ((b[pos >> 3] >> (pos & 7)) & 1) << i; + return v; + } + } + + /// BC7 blocks (16 bytes each, rows of blocks) decoded to RGBA8. + public static byte[] Decode(ReadOnlySpan blocks, int width, int height) + { + ImageLimits.Check(width, height); + int wb = (width + 3) / 4, hb = (height + 3) / 4; + var output = new byte[width * height * 4]; + Span texels = stackalloc byte[64]; + for (var by = 0; by < hb; by++) + for (var bx = 0; bx < wb; bx++) + { + DecodeBlock(blocks.Slice((by * wb + bx) * 16, 16), texels); + for (var y = 0; y < 4 && by * 4 + y < height; y++) + { + var count = Math.Min(4, width - bx * 4); + texels.Slice(y * 16, count * 4).CopyTo(output.AsSpan(((by * 4 + y) * width + bx * 4) * 4)); + } + } + return output; + } + + static int Subset(int subsets, int partition, int i) => subsets switch + { + 2 => (int)((P2[partition] >> i) & 1), + 3 => P3[partition * 16 + i] - '0', + _ => 0, + }; + + static bool IsAnchor(int subsets, int partition, int i) => + i == 0 || (subsets == 2 && i == A2[partition]) || (subsets == 3 && (i == A3a[partition] || i == A3b[partition])); + + static int Interp(int a, int b, int index, int bits) + { + var w = bits == 2 ? W2[index] : bits == 3 ? W3[index] : W4[index]; + return ((64 - w) * a + w * b + 32) >> 6; + } + + static void DecodeBlock(ReadOnlySpan block, Span texels) + { + var mode = 0; + while (mode < 8 && ((block[0] >> mode) & 1) == 0) mode++; + if (mode == 8) { texels.Clear(); return; } + var m = Modes[mode]; + var bits = new Bits(block); + bits.Read(mode + 1); + var partition = bits.Read(m.PartBits); + var rotation = bits.Read(m.RotBits); + var idxSel = bits.Read(m.IdxSelBits); + + // endpoints: [subset*2 + end][channel] + Span ep = stackalloc int[6 * 4]; + var ns = m.Subsets; + for (var c = 0; c < 3; c++) + for (var e = 0; e < ns * 2; e++) + ep[e * 4 + c] = bits.Read(m.ColorBits); + for (var e = 0; e < ns * 2; e++) + ep[e * 4 + 3] = m.AlphaBits > 0 ? bits.Read(m.AlphaBits) : 255; + + var colorBits = m.ColorBits; + var alphaBits = m.AlphaBits; + if (m.EndPBits > 0) + { + for (var e = 0; e < ns * 2; e++) + { + var p = bits.Read(1); + for (var c = 0; c < 3; c++) ep[e * 4 + c] = (ep[e * 4 + c] << 1) | p; + if (alphaBits > 0) ep[e * 4 + 3] = (ep[e * 4 + 3] << 1) | p; + } + colorBits++; + if (alphaBits > 0) alphaBits++; + } + else if (m.SharedPBits > 0) + { + for (var s = 0; s < ns; s++) + { + var p = bits.Read(1); + for (var e = s * 2; e < s * 2 + 2; e++) + for (var c = 0; c < 3; c++) ep[e * 4 + c] = (ep[e * 4 + c] << 1) | p; + } + colorBits++; + } + // expand to 8 bits + for (var e = 0; e < ns * 2; e++) + { + for (var c = 0; c < 3; c++) ep[e * 4 + c] = Expand(ep[e * 4 + c], colorBits); + if (m.AlphaBits > 0) ep[e * 4 + 3] = Expand(ep[e * 4 + 3], alphaBits); + } + + Span idx1 = stackalloc int[16]; + Span idx2 = stackalloc int[16]; + for (var i = 0; i < 16; i++) + { + var anchor = IsAnchor(ns, partition, i) && (ns == 1 ? i == 0 : true) && IsAnchorFor(ns, partition, i); + idx1[i] = bits.Read(anchor ? m.IdxBits - 1 : m.IdxBits); + } + if (m.Idx2Bits > 0) + for (var i = 0; i < 16; i++) + idx2[i] = bits.Read(i == 0 ? m.Idx2Bits - 1 : m.Idx2Bits); + + for (var i = 0; i < 16; i++) + { + var s = Subset(ns, partition, i); + int e0 = s * 2 * 4, e1 = (s * 2 + 1) * 4; + int r, g, b, a; + if (m.Idx2Bits > 0) + { + int cIdx = idxSel == 0 ? idx1[i] : idx2[i], aIdx = idxSel == 0 ? idx2[i] : idx1[i]; + int cBits = idxSel == 0 ? m.IdxBits : m.Idx2Bits, aBits = idxSel == 0 ? m.Idx2Bits : m.IdxBits; + r = Interp(ep[e0], ep[e1], cIdx, cBits); + g = Interp(ep[e0 + 1], ep[e1 + 1], cIdx, cBits); + b = Interp(ep[e0 + 2], ep[e1 + 2], cIdx, cBits); + a = Interp(ep[e0 + 3], ep[e1 + 3], aIdx, aBits); + } + else + { + r = Interp(ep[e0], ep[e1], idx1[i], m.IdxBits); + g = Interp(ep[e0 + 1], ep[e1 + 1], idx1[i], m.IdxBits); + b = Interp(ep[e0 + 2], ep[e1 + 2], idx1[i], m.IdxBits); + a = m.AlphaBits > 0 ? Interp(ep[e0 + 3], ep[e1 + 3], idx1[i], m.IdxBits) : 255; + } + switch (rotation) + { + case 1: (a, r) = (r, a); break; + case 2: (a, g) = (g, a); break; + case 3: (a, b) = (b, a); break; + } + texels[i * 4] = (byte)r; + texels[i * 4 + 1] = (byte)g; + texels[i * 4 + 2] = (byte)b; + texels[i * 4 + 3] = (byte)a; + } + } + + /// Whether texel i is the anchor of its own subset (its index has one bit less). + static bool IsAnchorFor(int ns, int partition, int i) + { + if (i == 0) return true; + if (ns == 2) return i == A2[partition]; + if (ns == 3) return i == A3a[partition] || i == A3b[partition]; + return false; + } + + static int Expand(int v, int bits) => bits >= 8 ? v : (v << (8 - bits)) | (v >> (2 * bits - 8)); +} diff --git a/launcher/Core/GameFiles/Bfres.cs b/launcher/Core/GameFiles/Bfres.cs new file mode 100644 index 0000000..3c1236b --- /dev/null +++ b/launcher/Core/GameFiles/Bfres.cs @@ -0,0 +1,298 @@ +// (Triforce, 11-29) BFRES v10: the game's model files (romfs/Model/*.bfres.zs), read far enough to draw a character in the +// launcher's Character page: the first model's skeleton, its shapes' level-of-detail 0 vertices and triangles, and each +// material's name and texture names. Offsets as the lab's offline renders read them (export.py, 11-17), little-endian: +// +// FRES 0x28 u64 the model array (FMDL, the first one is used), 0x170 u64 where the vertex and index data starts +// FMDL 0x18 skeleton, 0x20 vertex buffers, 0x28 shapes (0x60 each), 0x38 materials (0xb0 each); 0x68/0x6a/0x6c counts +// FSKL 0x10 bones (0x58 each), 0x18 matrix-to-bone list (u16), 0x20 inverse bind matrices (3x4 f32); +// 0x38 bone count, 0x3a smooth matrices, 0x3c rigid matrices +// bone 0x00 name, 0x22 parent (s16), 0x2c flags (0x1000 = the rotation is Euler XYZ, else a quaternion), +// 0x30 scale (3 f32), 0x3c rotation (4 f32), 0x4c translation (3 f32) +// FVTX 0x08 attributes (0x10 each: name, 0x08 format, 0x0c offset, 0x0e buffer), 0x30 buffer sizes, 0x38 strides +// (0x10 each), 0x48 u32 the buffers' offset in the data, 0x4c attribute count, 0x4d buffer count, 0x50 vertex count, +// 0x54 skin count (0: rigid on the shape's bone, 1: rigid on one matrix with bone-local positions, 2+: smooth) +// FSHP 0x08 name, 0x10 vertex buffer, 0x18 meshes (the first is level of detail 0), 0x52 material, 0x58 bone +// mesh 0x20 index offset, 0x24 primitive (3 = triangles), 0x28 index format (0 u8, 1 u16, 2 u32), 0x2c count, 0x30 first +// FMAT 0x08 name, 0x20 texture names, 0xa3 texture count +// Names are inline (u16 length, then the text). Nothing is written back: the Character page only reads. +using System.Buffers.Binary; +using System.Numerics; +using System.Text; + +namespace Triforce.Core.GameFiles; + +public sealed record BfresBone(string Name, int Parent, Vector3 Scale, Vector4 Rotation, bool Euler, Vector3 Translation); + +public sealed record BfresMaterial(string Name, IReadOnlyList Textures); + +/// One shape at level of detail 0, in the model's bind pose: positions, normals, tangents (w = handedness), the +/// first UV set, its bone influences (skeleton bone indices) and triangles. +public sealed class BfresShape +{ + public string Name = ""; + public int Material; + public int SkinCount; + public Vector3[] Positions = Array.Empty(); + public Vector3[] Normals = Array.Empty(); + public Vector4[] Tangents = Array.Empty(); + public Vector2[] Uvs = Array.Empty(); + /// The second UV set (zero when the shape has none). + public Vector2[] Uvs1 = Array.Empty(); + /// The vertex colour (_c0), white when the shape has none. + public Vector4[] Colors = Array.Empty(); + /// Up to 8 influences a vertex: (bone, weight); a rigid vertex has one of weight 1. + public (int Bone, float Weight)[][] Influences = Array.Empty<(int, float)[]>(); + public int[] Indices = Array.Empty(); +} + +public sealed class Bfres +{ + readonly byte[] b; + public IReadOnlyList Bones { get; } + public IReadOnlyList Materials { get; } + public IReadOnlyList Shapes { get; } + /// Each bone's bind pose in model space (parents applied). + public Matrix4x4[] BindWorld { get; } + + public Bfres(byte[] data) + { + b = data; + if (b.Length < 0x180 || Encoding.ASCII.GetString(b, 0, 4) != "FRES") throw new InvalidDataException("not a BFRES file"); + var dataStart = (long)U64(0x170); + var fmdl = (long)U64(0x28); + Need(fmdl, 0x70); + if (Encoding.ASCII.GetString(b, (int)fmdl, 4) != "FMDL") throw new InvalidDataException("BFRES: no model"); + long skl = (long)U64(fmdl + 0x18), shapesAt = (long)U64(fmdl + 0x28), matsAt = (long)U64(fmdl + 0x38); + int nShapes = U16(fmdl + 0x6a), nMats = U16(fmdl + 0x6c); + if (nShapes > 512 || nMats > 512) throw new InvalidDataException("BFRES: too many shapes or materials"); + + // skeleton + Need(skl, 0x40); + int nBones = U16(skl + 0x38), nSmooth = U16(skl + 0x3a), nRigid = U16(skl + 0x3c); + if (nBones > 4096 || nSmooth + nRigid > 8192) throw new InvalidDataException("BFRES: too many bones"); + long bonesAt = (long)U64(skl + 0x10), m2bAt = (long)U64(skl + 0x18); + var bones = new List(); + for (var i = 0; i < nBones; i++) + { + var o = bonesAt + 0x58 * i; + Need(o, 0x58); + var flags = U32(o + 0x2c); + bones.Add(new BfresBone(Str((long)U64(o)), (short)U16(o + 0x22), V3(o + 0x30), new Vector4(F(o + 0x3c), F(o + 0x40), F(o + 0x44), F(o + 0x48)), + (flags & 0x1000) != 0, V3(o + 0x4c))); + } + Bones = bones; + BindWorld = new Matrix4x4[nBones]; + for (var i = 0; i < nBones; i++) + { + var local = Local(bones[i]); + var p = bones[i].Parent; + BindWorld[i] = p >= 0 && p < i ? local * BindWorld[p] : local; + } + var m2b = new int[nSmooth + nRigid]; + for (var i = 0; i < m2b.Length; i++) m2b[i] = Math.Min(U16(m2bAt + 2 * i), nBones - 1); + + // materials + var mats = new List(); + for (var i = 0; i < nMats; i++) + { + var f = matsAt + 0xb0 * i; + Need(f, 0xb0); + var tp = (long)U64(f + 0x20); + var n = b[f + 0xa3]; + var tex = new List(); + for (var k = 0; k < n; k++) tex.Add(Str((long)U64(tp + 8 * k))); + mats.Add(new BfresMaterial(Str((long)U64(f + 8)), tex)); + } + Materials = mats; + + // shapes + var shapes = new List(); + for (var i = 0; i < nShapes; i++) + { + var sh = shapesAt + 0x60 * i; + Need(sh, 0x60); + var vb = (long)U64(sh + 0x10); + Need(vb, 0x58); + int nAttr = b[vb + 0x4c], nBuf = b[vb + 0x4d], skin = b[vb + 0x54]; + var vc = (int)U32(vb + 0x50); + if (vc > 2_000_000 || nBuf > 16) throw new InvalidDataException("BFRES: a shape too large"); + var bufStart = new long[nBuf]; + var strides = new int[nBuf]; + var at = dataStart + U32(vb + 0x48); + for (var k = 0; k < nBuf; k++) + { + bufStart[k] = at; + var size = U32((long)U64(vb + 0x30) + 0x10 * k); + strides[k] = (int)U32((long)U64(vb + 0x38) + 0x10 * k); + at += (size + 7) & ~7u; + } + var attrs = new Dictionary(); + for (var k = 0; k < nAttr; k++) + { + var a = (long)U64(vb + 8) + 0x10 * k; + var name = Str((long)U64(a)); + var fmt = U32(a + 8); + int off = U16(a + 0xc), bi = U16(a + 0xe); + if (bi >= nBuf) continue; + Need(bufStart[bi], (long)vc * strides[bi]); + var vals = new Vector4[vc]; + var ok = true; + for (var v = 0; v < vc && ok; v++) ok = Attr(fmt, bufStart[bi] + (long)v * strides[bi] + off, out vals[v]); + if (ok) attrs[name] = vals; + } + if (!attrs.TryGetValue("_p0", out var p0)) continue; + attrs.TryGetValue("_n0", out var n0); + attrs.TryGetValue("_t0", out var t0); + attrs.TryGetValue("_u0", out var u0); + attrs.TryGetValue("_u1", out var u1); + attrs.TryGetValue("_c0", out var c0); + attrs.TryGetValue("_i0", out var i0); + attrs.TryGetValue("_i1", out var i1); + attrs.TryGetValue("_w0", out var w0); + attrs.TryGetValue("_w1", out var w1); + int shapeBone = Math.Min(U16(sh + 0x58), nBones - 1); + + var s = new BfresShape { Name = Str((long)U64(sh + 8)), Material = U16(sh + 0x52), SkinCount = skin }; + s.Positions = new Vector3[vc]; s.Normals = new Vector3[vc]; s.Tangents = new Vector4[vc]; s.Uvs = new Vector2[vc]; + s.Influences = new (int, float)[vc][]; + s.Uvs1 = new Vector2[vc]; s.Colors = new Vector4[vc]; + for (var v = 0; v < vc; v++) + { + var p = new Vector3(p0[v].X, p0[v].Y, p0[v].Z); + var n = n0 != null ? new Vector3(n0[v].X, n0[v].Y, n0[v].Z) : Vector3.UnitY; + var t = t0 != null ? new Vector3(t0[v].X, t0[v].Y, t0[v].Z) : Vector3.UnitX; + (int, float)[] inf; + if (skin <= 1) + { + // (rigid: skin 0 on the shape's own bone, skin 1 on one matrix; both store bone-local positions) + var bone = skin == 0 || i0 == null ? shapeBone : m2b[Math.Clamp((int)i0[v].X, 0, m2b.Length - 1)]; + var w = BindWorld[bone]; + p = Vector3.Transform(p, w); n = Vector3.TransformNormal(n, w); t = Vector3.TransformNormal(t, w); + inf = new[] { (bone, 1f) }; + } + else + { + var l = new List<(int, float)>(8); + float[] ia = i0 != null ? new[] { i0[v].X, i0[v].Y, i0[v].Z, i0[v].W } : new float[4]; + float[] wa = w0 != null ? new[] { w0[v].X, w0[v].Y, w0[v].Z, w0[v].W } : new[] { 1f, 0, 0, 0 }; + for (var k = 0; k < Math.Min(4, skin); k++) l.Add((m2b[Math.Clamp((int)ia[k], 0, m2b.Length - 1)], wa[k])); + if (skin > 4 && i1 != null && w1 != null) + { + float[] ib = { i1[v].X, i1[v].Y, i1[v].Z, i1[v].W }, wb = { w1[v].X, w1[v].Y, w1[v].Z, w1[v].W }; + for (var k = 0; k < Math.Min(4, skin - 4); k++) l.Add((m2b[Math.Clamp((int)ib[k], 0, m2b.Length - 1)], wb[k])); + } + inf = l.ToArray(); + } + s.Positions[v] = p; + s.Normals[v] = n.LengthSquared() > 1e-12f ? Vector3.Normalize(n) : Vector3.UnitY; + s.Tangents[v] = new Vector4(t.LengthSquared() > 1e-12f ? Vector3.Normalize(t) : Vector3.UnitX, t0 != null && t0[v].W < 0 ? -1 : 1); + s.Uvs[v] = u0 != null ? new Vector2(u0[v].X, u0[v].Y) : Vector2.Zero; + s.Uvs1[v] = u1 != null ? new Vector2(u1[v].X, u1[v].Y) : Vector2.Zero; + s.Colors[v] = c0 != null ? c0[v] : Vector4.One; + s.Influences[v] = inf; + } + // level of detail 0 + var mesh = (long)U64(sh + 0x18); + Need(mesh, 0x34); + long faceOff = U32(mesh + 0x20); + uint prim = U32(mesh + 0x24), ifmt = U32(mesh + 0x28); + var count = (int)U32(mesh + 0x2c); + var first = (int)U32(mesh + 0x30); + if (prim != 3 || ifmt > 2 || count > 12_000_000) continue; + var isz = ifmt == 0 ? 1 : ifmt == 1 ? 2 : 4; + Need(dataStart + faceOff, (long)count * isz); + var idx = new int[count]; + for (var k = 0; k < count; k++) + { + var o = dataStart + faceOff + (long)k * isz; + var x = (ifmt == 0 ? b[o] : ifmt == 1 ? U16(o) : (int)U32(o)) + first; + idx[k] = x < vc ? x : 0; + } + s.Indices = idx; + shapes.Add(s); + } + Shapes = shapes; + } + + /// A bone's local transform (scale, then rotation, then translation; row vectors as System.Numerics has them). + public static Matrix4x4 Local(BfresBone bone, Quaternion? rotation = null) + { + var q = rotation ?? Rotation(bone); + return Matrix4x4.CreateScale(bone.Scale) * Matrix4x4.CreateFromQuaternion(q) * Matrix4x4.CreateTranslation(bone.Translation); + } + + /// A bone's rotation as a quaternion (Euler XYZ: X first, then Y, then Z). + public static Quaternion Rotation(BfresBone bone) + { + if (!bone.Euler) return Quaternion.Normalize(new Quaternion(bone.Rotation.X, bone.Rotation.Y, bone.Rotation.Z, bone.Rotation.W)); + var r = bone.Rotation; + return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, r.Z) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, r.Y) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, r.X)); + } + + // ---------------- reading ---------------- + void Need(long at, long n) + { + if (at < 0 || n < 0 || at + n > b.Length) throw new InvalidDataException("BFRES: a part lies outside the file"); + } + ushort U16(long at) { Need(at, 2); return BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan((int)at)); } + uint U32(long at) { Need(at, 4); return BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan((int)at)); } + ulong U64(long at) { Need(at, 8); return BinaryPrimitives.ReadUInt64LittleEndian(b.AsSpan((int)at)); } + float F(long at) { Need(at, 4); return BinaryPrimitives.ReadSingleLittleEndian(b.AsSpan((int)at)); } + Vector3 V3(long at) => new(F(at), F(at + 4), F(at + 8)); + + string Str(long at) + { + if (at <= 0 || at + 2 > b.Length) return ""; + var n = U16(at); + if (at + 2 + n > b.Length) return ""; + return Encoding.UTF8.GetString(b, (int)at + 2, n); + } + + /// One vertex attribute decoded to floats (unused components 0). False for a format this reader does not know. + bool Attr(uint fmt, long o, out Vector4 v) + { + v = default; + switch (fmt) + { + case 0x1805: v = new Vector4(F(o), F(o + 4), F(o + 8), 0); return true; + case 0x1905: v = new Vector4(F(o), F(o + 4), F(o + 8), F(o + 12)); return true; + case 0x1705: v = new Vector4(F(o), F(o + 4), 0, 0); return true; + case 0x1205: Need(o, 4); v = new Vector4((float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o)), (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 2)), 0, 0); return true; + case 0x1505: + Need(o, 8); + v = new Vector4((float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o)), (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 2)), + (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 4)), (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 6))); + return true; + case 0x1202: v = new Vector4(Math.Max((short)U16(o) / 32767f, -1), Math.Max((short)U16(o + 2) / 32767f, -1), 0, 0); return true; + case 0x1201: v = new Vector4(U16(o) / 65535f, U16(o + 2) / 65535f, 0, 0); return true; + case 0x0e02: + { + var x = U32(o); + float C(int c) { var q = (int)((x >> (10 * c)) & 0x3ff); if (q >= 512) q -= 1024; return Math.Max(q / 511f, -1); } + var w = (int)((x >> 30) & 3); if (w >= 2) w -= 4; + v = new Vector4(C(0), C(1), C(2), w); + return true; + } + case 0x0201: Need(o, 1); v = new Vector4(b[o] / 255f, 0, 0, 0); return true; + case 0x0203: Need(o, 1); v = new Vector4(b[o], 0, 0, 0); return true; + case 0x0901: Need(o, 2); v = new Vector4(b[o] / 255f, b[o + 1] / 255f, 0, 0); return true; + case 0x0903: Need(o, 2); v = new Vector4(b[o], b[o + 1], 0, 0); return true; + case 0x0b01: Need(o, 4); v = new Vector4(b[o] / 255f, b[o + 1] / 255f, b[o + 2] / 255f, b[o + 3] / 255f); return true; + case 0x0b03: Need(o, 4); v = new Vector4(b[o], b[o + 1], b[o + 2], b[o + 3]); return true; + case 0x0a01: v = new Vector4(U16(o) / 65535f, 0, 0, 0); return true; + case 0x0a03: v = new Vector4(U16(o), 0, 0, 0); return true; + case 0x1001: v = new Vector4(U16(o) / 65535f, U16(o + 2) / 65535f, 0, 0); return true; + case 0x1003: v = new Vector4(U16(o), U16(o + 2), 0, 0); return true; + case 0x1501 or 0x1503: + { + var k = fmt == 0x1501 ? 1 / 65535f : 1f; + v = new Vector4(U16(o) * k, U16(o + 2) * k, U16(o + 4) * k, U16(o + 6) * k); + return true; + } + default: return false; + } + } + + /// The attribute formats a file uses that this reader skips (for diagnostics). + public static string FormatName(uint fmt) => "0x" + fmt.ToString("x4"); +} diff --git a/launcher/Core/GameFiles/BlockLinear.cs b/launcher/Core/GameFiles/BlockLinear.cs index b6d67b8..b028add 100644 --- a/launcher/Core/GameFiles/BlockLinear.cs +++ b/launcher/Core/GameFiles/BlockLinear.cs @@ -69,4 +69,41 @@ public static class BlockLinear } return output; } + + /// ((Triforce, 11-29) The other way: a linear image written into block-linear order, into output (at least + /// Size bytes; bytes the image does not cover are left as they are). For the Character page's recoloured textures. + public static void Swizzle(ReadOnlySpan linear, Span output, int width, int height, int bytesPerElement, int blockHeightLog2) + { + if (bytesPerElement is not (1 or 2 or 4 or 8 or 16)) + throw new NotSupportedException(bytesPerElement + " bytes per element"); + if (Size(width, height, bytesPerElement, blockHeightLog2) > output.Length) + throw new InvalidDataException("the texture's data is shorter than its size calls for"); + var pitch = width * bytesPerElement; + var gobsInX = (pitch + 63) >> GobSizeXShift; + var blockSize = gobsInX << (GobSizeShift + blockHeightLog2); + var blockHeightMask = (1 << blockHeightLog2) - 1; + var xShift = GobSizeShift + blockHeightLog2; + for (var y = 0; y < height; y++) + { + var swizzledY = SwizzleY(y); + var blockY = y >> GobSizeYShift; + var offsetY = (blockY >> blockHeightLog2) * blockSize + ((blockY & blockHeightMask) << GobSizeShift); + var row = linear.Slice(y * pitch, pitch); + for (var x = 0; x < pitch; x += bytesPerElement) + { + var offsetX = (x >> GobSizeXShift) << xShift; + var at = offsetY + offsetX + (SwizzleX(x & 63) | swizzledY); + row.Slice(x, bytesPerElement).CopyTo(output.Slice(at, bytesPerElement)); + } + } + } + + /// The block height (log2, in GOBs) a smaller mip level uses: the texture's, halved while half of it still + /// covers the level's height (the GPU's rule). + public static int MipBlockHeight(int heightInElements, int blockHeightLog2) + { + var bh = blockHeightLog2; + while (bh > 0 && (8 << (bh - 1)) >= heightInElements) bh--; + return bh; + } } diff --git a/launcher/Core/GameFiles/Bntx.cs b/launcher/Core/GameFiles/Bntx.cs index 83d5c37..3f6215e 100644 --- a/launcher/Core/GameFiles/Bntx.cs +++ b/launcher/Core/GameFiles/Bntx.cs @@ -18,6 +18,9 @@ namespace Triforce.Core.GameFiles; public sealed record BntxTexture(string Name, int Width, int Height, uint Format, int MipCount, int TileMode, int BlockHeightLog2, long DataOffset, long ImageSize, byte[] ChannelSources) { + /// ((Triforce, 11-29) Where each mip level's data starts in the file (level 0 is DataOffset). + public long[] MipOffsets { get; init; } = Array.Empty(); + /// The format's kind (high byte), e.g. 0x2d for ASTC 4x4. public int Kind => (int)(Format >> 8); @@ -58,8 +61,11 @@ public sealed class Bntx if (nameLength > 1024 || nameAt + 2 + nameLength > data.Length) throw new InvalidDataException("BNTX texture " + i + "'s name is too long"); var name = Encoding.UTF8.GetString(data, (int)nameAt + 2, nameLength); var mips = (long)U64(p + 0x70); + int mipCount = Math.Clamp((int)U16(p + 0x16), 1, 16); + var offs = new long[mipCount]; + for (var k = 0; k < mipCount; k++) offs[k] = mips + 8L * k + 8 <= data.Length ? (long)U64(mips + 8L * k) : 0; var tex = new BntxTexture(name, (int)U32(p + 0x24), (int)U32(p + 0x28), U32(p + 0x1C), U16(p + 0x16), U16(p + 0x12), - (int)(U32(p + 0x34) & 7), (long)U64(mips), U32(p + 0x50), data[(int)(p + 0x58)..(int)(p + 0x5C)]); + (int)(U32(p + 0x34) & 7), (long)U64(mips), U32(p + 0x50), data[(int)(p + 0x58)..(int)(p + 0x5C)]) { MipOffsets = offs }; list.Add(tex); byName.TryAdd(name, tex); } @@ -96,6 +102,7 @@ public sealed class Bntx 0x1c => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC3), 0x1d => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC4), 0x1e => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC5), + 0x20 => Bc7.Decode(linear, t.Width, t.Height), 0x0b => linear, 0x0c => Swap(linear, 2, 1, 0, 3), 0x02 => Expand(linear, 1), @@ -108,13 +115,13 @@ public sealed class Bntx } /// The block size and bytes per block of a format (1x1 for an uncompressed one). - static (int W, int H, int Bytes) BlockInfo(uint format) => (format >> 8) switch + public static (int W, int H, int Bytes) BlockInfo(uint format) => (format >> 8) switch { 0x02 => (1, 1, 1), 0x09 => (1, 1, 2), 0x0b or 0x0c => (1, 1, 4), 0x1a or 0x1d => (4, 4, 8), - 0x1b or 0x1c or 0x1e => (4, 4, 16), + 0x1b or 0x1c or 0x1e or 0x20 => (4, 4, 16), var k and >= 0x2d and <= 0x3a => (AstcBlocks[k - 0x2d].W, AstcBlocks[k - 0x2d].H, 16), _ => throw new NotSupportedException("texture format " + FormatName(format) + " is not supported"), }; diff --git a/launcher/Core/GameFiles/Fska.cs b/launcher/Core/GameFiles/Fska.cs new file mode 100644 index 0000000..e6b245b --- /dev/null +++ b/launcher/Core/GameFiles/Fska.cs @@ -0,0 +1,107 @@ +// (Triforce, 11-29) FSKA, a skeletal animation inside a BFRES v10 animation file (romfs/Model/*_Animation.anim.bfres.zs), +// read far enough to pose a model at one frame: each bone track's base values (frame 0) and its curves sampled at the frame. +// Layout as the lab's offline renders read it (export.py anim_base, 11-17), little-endian: +// FSKA 0x04 flags (0x1000: rotations are Euler XYZ), 0x08 name, 0x28 bone tracks (0x38 each), 0x4c track count +// track 0x00 bone name, 0x08 curves (0x30 each), 0x10 base data, 0x28 flags (0x08 scale, 0x10 rotation, 0x20 translation +// in the base data), 0x2e curve count +// base scale (3 f32), rotation (4 f32: Euler XYZ and a pad, or a quaternion), translation (3 f32), each when flagged +// curve 0x00 frames, 0x08 keys, 0x10 flags (bits 0-1 frame type: 0 f32, 1 s16/32, 2 u8; bits 2-3 key type: 0 f32, +// 1 u16, 2 u8), 0x12 key count, 0x14 target offset (0x04.. scale, 0x10.. translation, 0x20.. rotation), +// 0x18 start, 0x1c end, 0x24 scale, 0x28 offset (a key is offset + value * scale); keys are sampled with a +// Catmull-Rom spline through them +using System.Buffers.Binary; +using System.Numerics; +using System.Text; + +namespace Triforce.Core.GameFiles; + +public sealed record FskaPose(Vector3? Scale, Vector4? Rotation, Vector3? Translation, bool Euler); + +public static class Fska +{ + /// The bone poses of animation in this file at (null when the file + /// has no such animation). + public static Dictionary? Pose(byte[] a, string name, float frame) + { + ushort U16(long o) => o >= 0 && o + 2 <= a.Length ? BinaryPrimitives.ReadUInt16LittleEndian(a.AsSpan((int)o)) : (ushort)0; + uint U32(long o) => o >= 0 && o + 4 <= a.Length ? BinaryPrimitives.ReadUInt32LittleEndian(a.AsSpan((int)o)) : 0; + long U64(long o) => o >= 0 && o + 8 <= a.Length ? (long)BinaryPrimitives.ReadUInt64LittleEndian(a.AsSpan((int)o)) : -1; + float F(long o) => o >= 0 && o + 4 <= a.Length ? BinaryPrimitives.ReadSingleLittleEndian(a.AsSpan((int)o)) : 0; + string S(long o) + { + if (o <= 0 || o + 2 > a.Length) return ""; + var n = U16(o); + return o + 2 + n <= a.Length ? Encoding.UTF8.GetString(a, (int)o + 2, n) : ""; + } + var magic = "FSKA"u8; + for (var f = a.AsSpan().IndexOf(magic); f >= 0;) + { + if (S(U64(f + 8)) == name) + { + var euler = (U32(f + 4) & 0x1000) != 0; + long tracks = U64(f + 0x28); + int n = U16(f + 0x4c); + var poses = new Dictionary(StringComparer.Ordinal); + for (var i = 0; i < n && i < 4096; i++) + { + var o = tracks + 0x38L * i; + var bone = S(U64(o)); + long k = U64(o + 0x10); + var fl = U32(o + 0x28); + float[]? sc = null, rot = null, tr = null; + if ((fl & 0x08) != 0) { sc = new[] { F(k), F(k + 4), F(k + 8) }; k += 12; } + if ((fl & 0x10) != 0) { rot = new[] { F(k), F(k + 4), F(k + 8), F(k + 12) }; k += 16; } + // (a file may mix them: an Euler track keeps 1 in its fourth value, a quaternion track does not unless it is + // the identity, which reads the same either way) + var trackEuler = rot == null ? euler : euler || MathF.Abs(rot[3] - 1) < 1e-6f; + if ((fl & 0x20) != 0) { tr = new[] { F(k), F(k + 4), F(k + 8) }; k += 12; } + int nc = o + 0x2e < a.Length ? a[o + 0x2e] : 0; + long cv = U64(o + 8); + for (var c = 0; c < nc; c++) + { + var co = cv + 0x30L * c; + long frames = U64(co), keys = U64(co + 8); + int cfl = U16(co + 0x10), nk = U16(co + 0x12); + var target = U32(co + 0x14); + float scale = F(co + 0x24), offset = F(co + 0x28); + if (nk <= 0 || nk > 100000) continue; + int ft = cfl & 3, kt = (cfl >> 2) & 3; + var fr = new float[nk]; + var val = new float[nk]; + for (var j = 0; j < nk; j++) + { + fr[j] = ft == 2 ? (frames + j < a.Length ? a[frames + j] : 0) : ft == 1 ? (short)U16(frames + 2 * j) / 32f : F(frames + 4 * j); + var kp = keys + 8; + val[j] = kt == 2 ? offset + (kp + 2 * j < a.Length ? a[kp + 2 * j] : 0) * scale + : kt == 1 ? offset + U16(kp + 4 * j) * scale + : F(kp + 8 * j); + } + var v = Sample(fr, val, frame); + if (target >= 0x04 && target <= 0x0c && sc != null) sc[(target - 0x04) / 4] = v; + else if (target >= 0x10 && target <= 0x18 && tr != null) tr[(target - 0x10) / 4] = v; + else if (target >= 0x20 && target <= 0x2c && rot != null) rot[(target - 0x20) / 4] = v; + } + poses[bone] = new FskaPose(sc == null ? null : new Vector3(sc[0], sc[1], sc[2]), + rot == null ? null : new Vector4(rot[0], rot[1], rot[2], rot[3]), tr == null ? null : new Vector3(tr[0], tr[1], tr[2]), trackEuler); + } + return poses; + } + var next = a.AsSpan(f + 4).IndexOf(magic); + f = next < 0 ? -1 : f + 4 + next; + } + return null; + } + + /// A Catmull-Rom spline through the keys, at frame t (held at the ends). + static float Sample(float[] fr, float[] v, float t) + { + var n = fr.Length; + if (n == 1) return v[0]; + t = Math.Clamp(t, fr[0], fr[n - 1]); + var i = 0; + while (i < n - 2 && fr[i + 1] < t) i++; + float f0 = fr[i], f1 = fr[i + 1], u = f1 == f0 ? 0 : (t - f0) / (f1 - f0); + float p0 = i > 0 ? v[i - 1] : v[i], p1 = v[i], p2 = v[i + 1], p3 = i + 2 < n ? v[i + 2] : v[i + 1]; + return 0.5f * (2 * p1 + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u * u + (-p0 + 3 * p1 - 3 * p2 + p3) * u * u * u); + } +} diff --git a/launcher/Core/GameFiles/LinkScene.cs b/launcher/Core/GameFiles/LinkScene.cs new file mode 100644 index 0000000..dd0b5fd --- /dev/null +++ b/launcher/Core/GameFiles/LinkScene.cs @@ -0,0 +1,418 @@ +// (Triforce, 11-29) Link as the launcher's Character page draws him, from the player's own game files: young Link +// (Player_Child) or adult Link (Player_Adult) in the Kokiri, Goron or Zora tunic (Armor_Adult_Goron / _Zora drawn over +// Player_Adult with the shapes they replace hidden), posed from the models' A-pose to a relaxed stand (arms lowered) by +// skinning on the CPU. The result is one binary of interleaved vertices and triangles plus a JSON description of each part +// (its material, its textures and how it is drawn). Textures are decoded here too (Texture), at most MaxTexture wide. +// Nothing of the game is kept by the launcher beyond its own cache; nothing is written into the game. +using System.Buffers.Binary; +using System.Numerics; +using System.Text.Json.Nodes; + +namespace Triforce.Core.GameFiles; + +public sealed class LinkScene +{ + /// The looks the page offers: young Link and adult Link in each tunic. + public static readonly string[] Looks = { "child", "adult", "adult-goron", "adult-zora" }; + + /// The widest a texture is sent to the page: the preview is never larger on screen. + public const int MaxTexture = 2048; + + public byte[] Mesh { get; private init; } = Array.Empty(); + public JsonObject Info { get; private init; } = new(); + + /// Materials whose shapes an armour model replaces on Player_Adult (the armour brings its own). + static readonly HashSet ArmourHides = new(StringComparer.Ordinal) + { + "Mt_Angin", "Mt_Angin_Acs", "Mt_Angin_Acs_AlphaMask", "Mt_Vest", "Mt_Inner", "Mt_Leater_Upper", "Mt_Leather_Upper_Metal", + }; + + /// The relaxed stand: (bone, axis in model space, degrees), applied from the root out. The models' A-pose holds the + /// arms 45 degrees out; these bring them down beside the body with a slight bend at the elbow. + static readonly (string Bone, Vector3 Axis, float Deg)[] Stand = + { + ("Arm_1_L", Vector3.UnitZ, -36), ("Arm_1_R", Vector3.UnitZ, 36), + ("Arm_1_L", Vector3.UnitX, -8), ("Arm_1_R", Vector3.UnitX, -8), + ("Arm_2_L", Vector3.UnitX, -14), ("Arm_2_R", Vector3.UnitX, -14), + ("Arm_2_L", Vector3.UnitY, 10), ("Arm_2_R", Vector3.UnitY, -10), + ("Wrist_L", Vector3.UnitZ, 10), ("Wrist_R", Vector3.UnitZ, -10), + }; + + /// Linkle (the Playable Linkle mod, read through an OverlaySource of its romfs over the game's): her models, by + /// the names the mod's packs give them. Her Goron and Zora outfits are whole bodies of their own. + public const string LinkleChild = "Model/Npc_Kokiri_WC_002.Player_Linkle_Child.bfres.zs"; + const string LinkleChildAnim = "Model/Linkl__Child_04_Animation.anim.bfres.zs"; + const string LinkleZora = "Model/Npc_Hylia_WU_Zelda_Adult.Player_Zelda_Adult_Zora.bfres.zs"; + const string LinkleFairy = "Model/Npc_Navi.Dm_Npc_Liri.bfres.zs"; + + /// Per model file, texture names to show under another name (Linkle's copies: her model will point + /// at them once dyed, so the preview's dyed maps reach only the outfit that wears them). + public static LinkScene Build(IGameSource src, Zs zs, string look, string hero = "link", IReadOnlyDictionary>? renames = null) + { + Renames = renames; + if (!Looks.Contains(look)) throw new ArgumentException("no such look: " + look); + if (hero == "linkle") return BuildLinkle(src, zs, look); + return Build2(src, zs, look, "link", look == "child" ? "Model/Player_Child.Player_Child.bfres.zs" : "Model/Player_Adult.Player_Adult.bfres.zs", + look == "child" ? "Model/Player_Child_04_Animation.anim.bfres.zs" : "Model/Player_Adult_04_Animation.anim.bfres.zs"); + } + + static LinkScene Build2(IGameSource src, Zs zs, string look, string hero, string bodyFile, string animFile) + { + var child = look == "child"; + var body = new Bfres(zs.Unpack(bodyFile)); + IReadOnlyDictionary? rename = null; + Renames?.TryGetValue(bodyFile, out rename); + Bfres? armour = hero == "linkle" ? null : look switch + { + "adult-goron" => new Bfres(zs.Unpack("Model/Armor_Adult_Goron.Armor_Adult_Goron.bfres.zs")), + "adult-zora" => new Bfres(zs.Unpack("Model/Armor_Adult_Zora.Armor_Adult_Zora.bfres.zs")), + _ => null, + }; + + // the pose: the game's own standing animation ("Wait") at its first frame, on the body's skeleton; an armour's bones + // follow the body's bone of the same name. A game without it: the bind pose with the arms lowered by hand + Dictionary? wait = null; + try { if (src.Exists(animFile)) wait = Fska.Pose(zs.Unpack(animFile), "Wait", 0); } + catch (Exception e) when (e is IOException || e is InvalidDataException || e is FileNotFoundException) { } + var posed = Pose(body, wait); + var byName = new Dictionary(StringComparer.Ordinal); + for (var i = 0; i < body.Bones.Count; i++) byName.TryAdd(body.Bones[i].Name, i); + Matrix4x4[] SkinOf(Bfres m, Matrix4x4[]? own) + { + var s = new Matrix4x4[m.Bones.Count]; + for (var i = 0; i < s.Length; i++) + { + Matrix4x4.Invert(m.BindWorld[i], out var inv); + if (own != null) s[i] = inv * own[i]; + else if (byName.TryGetValue(m.Bones[i].Name, out var j)) + { + // (the armour's bind may differ from the body's by a little: carry its bone as the body's moves) + Matrix4x4.Invert(body.BindWorld[j], out var invBody); + s[i] = invBody * posed[j]; + } + else s[i] = Matrix4x4.Identity; + } + return s; + } + var bodySkin = SkinOf(body, posed); + + var parts = new JsonArray(); + using var bin = new MemoryStream(); + var min = new Vector3(float.MaxValue); + var max = new Vector3(float.MinValue); + var vbuf = new byte[64]; + var ibuf = new byte[4]; + void Add(Bfres m, Matrix4x4[] skin, string source, Func keep) + { + foreach (var s in m.Shapes) + { + if (!keep(s)) continue; + var mat = m.Materials[Math.Clamp(s.Material, 0, m.Materials.Count - 1)]; + var kind = Kind(mat.Name, s.Name); + if (kind == "skip") continue; + if (source == "navi" && kind is "cloth" or "hair" or "skin") kind = "fairy"; // (Linkle's Liri: a little lit figure) + var n = s.Positions.Length; + var voff = bin.Position; + var v = vbuf; + for (var i = 0; i < n; i++) + { + var p = Vector3.Zero; var nr = Vector3.Zero; var t = Vector3.Zero; + var total = 0f; + foreach (var (bone, w) in s.Influences[i]) + { + if (w <= 0) continue; + var k = skin[Math.Clamp(bone, 0, skin.Length - 1)]; + p += w * Vector3.Transform(s.Positions[i], k); + nr += w * Vector3.TransformNormal(s.Normals[i], k); + t += w * Vector3.TransformNormal(new Vector3(s.Tangents[i].X, s.Tangents[i].Y, s.Tangents[i].Z), k); + total += w; + } + if (total <= 0) { p = s.Positions[i]; nr = s.Normals[i]; t = new Vector3(s.Tangents[i].X, s.Tangents[i].Y, s.Tangents[i].Z); } + else if (MathF.Abs(total - 1) > 1e-3f) p /= total; + nr = nr.LengthSquared() > 1e-12f ? Vector3.Normalize(nr) : Vector3.UnitY; + t = t.LengthSquared() > 1e-12f ? Vector3.Normalize(t) : Vector3.UnitX; + min = Vector3.Min(min, p); max = Vector3.Max(max, p); + W(v, 0, p.X); W(v, 4, p.Y); W(v, 8, p.Z); + W(v, 12, nr.X); W(v, 16, nr.Y); W(v, 20, nr.Z); + W(v, 24, t.X); W(v, 28, t.Y); W(v, 32, t.Z); W(v, 36, s.Tangents[i].W); + W(v, 40, s.Uvs[i].X); W(v, 44, s.Uvs[i].Y); + var c = s.Colors.Length > i ? s.Colors[i] : Vector4.One; + W(v, 48, c.X); W(v, 52, c.Y); W(v, 56, c.Z); W(v, 60, c.W); + bin.Write(v); + } + var ioff = bin.Position; + var ix = ibuf; + foreach (var x in s.Indices) { BinaryPrimitives.WriteInt32LittleEndian(ix, x); bin.Write(ix); } + var tex = Textures(mat, kind, name => src.Exists("Tex/" + name + ".bntx.zs")); + if (source == "body" && rename != null) + foreach (var k in tex.Keys.ToList()) + if ((string?)tex[k] is { } nm && rename.TryGetValue(nm, out var to)) tex[k] = to; + var part = new JsonObject + { + ["name"] = s.Name, ["mat"] = mat.Name, ["src"] = source, ["kind"] = kind, + ["voff"] = voff, ["vcount"] = n, ["ioff"] = ioff, ["icount"] = s.Indices.Length, + }; + foreach (var kv in tex) part[kv.Key] = kv.Value; + parts.Add(part); + } + } + Add(body, bodySkin, "body", s => + { + if (armour == null) return true; + var mat = body.Materials[Math.Clamp(s.Material, 0, body.Materials.Count - 1)].Name; + if (ArmourHides.Contains(mat)) return false; + // (the Zora tunic brings its own feather) + return !(look == "adult-zora" && mat == "Mt_Feather"); + }); + if (armour != null) Add(armour, SkinOf(armour, null), look[6..], _ => true); + + // Navi, at his shoulder (her own bind pose, a little larger than life so she reads beside him) + JsonArray? naviAt = null; + var fairyFile = FairyOf(src, hero); + if (fairyFile != null) + { + try + { + var navi = new Bfres(zs.Unpack(fairyFile)); + var h = max.Y - min.Y; + var at = new Vector3((min.X + max.X) / 2 + h * 0.3f, min.Y + h * 0.86f, (min.Z + max.Z) / 2 + h * 0.1f); + var place = Matrix4x4.CreateScale(1.5f) * Matrix4x4.CreateRotationY(-0.5f) * Matrix4x4.CreateTranslation(at); + var ns = new Matrix4x4[navi.Bones.Count]; + for (var i = 0; i < ns.Length; i++) { Matrix4x4.Invert(navi.BindWorld[i], out var inv); ns[i] = inv * navi.BindWorld[i] * place; } + var mn = min; var mx = max; + Add(navi, ns, "navi", _ => true); + min = mn; max = mx; // (Link's bounds frame the view, not hers) + naviAt = new JsonArray(at.X, at.Y, at.Z); + } + catch (Exception e) when (e is IOException || e is InvalidDataException) { } + } + + // (the animation may stand him a little off the origin: his feet on the floor, centred on it) + var mesh = bin.ToArray(); + var shift = new Vector3(-(min.X + max.X) / 2, -min.Y, -(min.Z + max.Z) / 2); + foreach (var p in parts) + { + long vo = (long)p!["voff"]!; int vc = (int)p["vcount"]!; + for (var i = 0; i < vc; i++) + { + var at = (int)(vo + 64L * i); + for (var c = 0; c < 3; c++) + { + var s = mesh.AsSpan(at + 4 * c); + BinaryPrimitives.WriteSingleLittleEndian(s, BinaryPrimitives.ReadSingleLittleEndian(s) + (c == 0 ? shift.X : c == 1 ? shift.Y : shift.Z)); + } + } + } + min += shift; max += shift; + if (naviAt != null) naviAt = new JsonArray((float)naviAt[0]! + shift.X, (float)naviAt[1]! + shift.Y, (float)naviAt[2]! + shift.Z); + + return new LinkScene + { + Mesh = mesh, + Info = new JsonObject + { + ["look"] = look, ["parts"] = parts, ["stride"] = 64, + ["min"] = new JsonArray(min.X, min.Y, min.Z), ["max"] = new JsonArray(max.X, max.Y, max.Z), ["navi"] = naviAt, + }, + }; + } + + [ThreadStatic] static IReadOnlyDictionary>? Renames; + + static string? FairyOf(IGameSource src, string hero) => + hero == "linkle" && src.Exists(LinkleFairy) ? LinkleFairy : src.Exists("Model/Npc_Navi.Npc_Navi.bfres.zs") ? "Model/Npc_Navi.Npc_Navi.bfres.zs" : null; + + /// Linkle: young (her own model, posed by her own Wait), adult (the mod's Player_Adult), or her Goron / Zora + /// outfit (whole bodies, posed by adult Link's Wait where their bones carry his names). + static LinkScene BuildLinkle(IGameSource src, Zs zs, string look) => Build2(src, zs, look, "linkle", + look switch + { + "child" => LinkleChild, + "adult-goron" => "Model/Armor_Adult_Goron.Armor_Adult_Goron.bfres.zs", + "adult-zora" => LinkleZora, + _ => "Model/Player_Adult.Player_Adult.bfres.zs", + }, + look == "child" ? LinkleChildAnim : "Model/Player_Adult_04_Animation.anim.bfres.zs"); + + static void W(Span v, int at, float f) => BinaryPrimitives.WriteSingleLittleEndian(v[at..], f); + + /// The posed model-space matrix of each bone: the bind pose with Stand's rotations about the joints. + static Matrix4x4[] Pose(Bfres m, Dictionary? anim) + { + var n = m.Bones.Count; + var posed = new Matrix4x4[n]; + for (var i = 0; i < n; i++) + { + var parent = m.Bones[i].Parent; + var b = m.Bones[i]; + Matrix4x4 local; + if (anim != null && anim.TryGetValue(b.Name, out var a)) + { + var r = a.Rotation is { } q + ? (a.Euler ? Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, q.Z) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, q.Y) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, q.X)) + : Quaternion.Normalize(new Quaternion(q.X, q.Y, q.Z, q.W))) + : Bfres.Rotation(b); + local = Matrix4x4.CreateScale(a.Scale ?? b.Scale) * Matrix4x4.CreateFromQuaternion(r) * Matrix4x4.CreateTranslation(a.Translation ?? b.Translation); + } + else if (parent >= 0 && parent < i) + { + Matrix4x4.Invert(m.BindWorld[parent], out var invParent); + local = m.BindWorld[i] * invParent; + } + else local = m.BindWorld[i]; + posed[i] = parent >= 0 && parent < i ? local * posed[parent] : local; + if (anim != null) continue; + foreach (var (bone, axis, deg) in Stand) + { + if (m.Bones[i].Name != bone) continue; + var o = posed[i].Translation; + posed[i] = posed[i] * Matrix4x4.CreateTranslation(-o) * Matrix4x4.CreateFromAxisAngle(axis, deg * MathF.PI / 180) * Matrix4x4.CreateTranslation(o); + } + } + return posed; + } + + /// How a material is drawn: cloth (the default), skin, hair, eye, metal, lash (soft-edged cards), fur, or skip. + static string Kind(string mat, string shape) + { + if (mat == "Mt_Wings") return "wing"; + if (mat.StartsWith("Mt_Body", StringComparison.Ordinal) && shape.Contains("Fur", StringComparison.Ordinal)) return "navifur"; + if (mat == "Mt_Body") return "navi"; + if (mat.Contains("Eye_Outer", StringComparison.Ordinal)) return "glint"; // (the wet film over the eye: its highlights) + if (mat.Contains("Eye_Inner", StringComparison.Ordinal)) return "eye"; + if (mat.Contains("EyeShadow", StringComparison.OrdinalIgnoreCase)) return "shade"; // (a soft shadow over the eye: its map is a mask) + if (mat.Contains("Eyelash", StringComparison.Ordinal) || mat.Contains("Eyebrow", StringComparison.Ordinal)) return "lash"; + if (mat.Contains("Hair", StringComparison.Ordinal)) return "hair"; + if (mat is "Mt_Skin" or "Mt_Face" or "Mt_Hand" or "Mt_Face_Eyelid" or "Mt_Face_SoftEdge" || mat.StartsWith("Mt_Skin", StringComparison.Ordinal)) return "skin"; + if (mat.Contains("Teeth", StringComparison.Ordinal)) return "skin"; + if (mat.Contains("Fur", StringComparison.Ordinal) || mat.Contains("Far", StringComparison.Ordinal)) return "fur"; + if (mat.Contains("Metal", StringComparison.Ordinal)) return "metal"; + return "cloth"; + } + + /// A part's textures by role: alb (colour), nrm (normal map), ao, mask (alpha cut), lut (a colour ramp read + /// by a grey map: young Link's hair has no colour map of its own), eye (iris|sclera|mask composited here). + const string AdultHair = "Mt_Hairs_Player_Adult"; + + static Dictionary Textures(BfresMaterial mat, string kind, Func exists) + { + var t = mat.Textures.Where(exists).ToList(); + // (a name may carry a variant number after its kind: "..._Alb.01") + static bool Is(string x, string suffix) => x.EndsWith(suffix, StringComparison.Ordinal) + || (x.Length > suffix.Length + 3 && x[^3] == '.' && char.IsAsciiDigit(x[^2]) && char.IsAsciiDigit(x[^1]) && x[..^3].EndsWith(suffix, StringComparison.Ordinal)); + string? First(string suffix, Func? not = null) => t.FirstOrDefault(x => Is(x, suffix) && (not == null || !not(x))); + var o = new Dictionary(); + if (kind == "eye") + { + var iris = t.FirstOrDefault(x => x.Contains("Iris", StringComparison.Ordinal) && x.EndsWith("_Alb", StringComparison.Ordinal)); + var sclera = t.FirstOrDefault(x => x.Contains("Sclera", StringComparison.Ordinal) && x.EndsWith("_Alb", StringComparison.Ordinal)); + var mask = t.FirstOrDefault(x => x.Contains("Mask", StringComparison.Ordinal) && x.EndsWith("_Gn3", StringComparison.Ordinal)); + if (iris != null && sclera != null && mask != null) o["alb"] = "eye:" + iris + "|" + sclera + "|" + mask; + else if (t.FirstOrDefault(x => x.Contains("_Alb", StringComparison.Ordinal)) is { } own) o["alb"] = own; // (Linkle's eyes: a picture of their own) + return o; + } + if (kind == "glint") { if (First("_Emc") is { } emc) o["alb"] = emc; return o; } + if (kind is "navi" or "navifur" or "wing") + { + if (t.FirstOrDefault(x => x.Contains("_Alb", StringComparison.Ordinal)) is { } na) o["alb"] = na; + if (t.FirstOrDefault(x => x.Contains("_Emc", StringComparison.Ordinal)) is { } ne) o["emc"] = ne; + if (First("_Nrm") is { } nn) o["nrm"] = nn; + return o; + } + var alb = First("_Alb"); + if (alb == null && kind == "hair" && exists(AdultHair + "_Alb")) + { + // (young Link's hair maps are not in the game: his hair cards are laid out on the same strand sheet as adult + // Link's, whose maps give them their strands) + o["alb"] = AdultHair + "_Alb"; + if (exists(AdultHair + "_Nrm")) o["nrm"] = AdultHair + "_Nrm"; + if (exists(AdultHair + "_AO")) o["ao"] = AdultHair + "_AO"; + return o; + } + if (alb != null) o["alb"] = alb; + else if (kind == "hair" && First("_Gn0") is { } lut && First("_Gn3") is { } grey) { o["lut"] = lut; o["grey"] = grey; } + else if (kind == "shade" && First("_Gn3") is { } g3) o["alb"] = g3; + var nrm = First("_Nrm", x => x.StartsWith("Skin_Detail", StringComparison.Ordinal) || x.Contains("Flatten", StringComparison.Ordinal)); + if (nrm != null) o["nrm"] = nrm; + // (Mt_Cloth's tile normal is the first; the garment's own shape normal is the second _Nrm) + var nrms = t.Where(x => x.EndsWith("_Nrm", StringComparison.Ordinal) && !x.StartsWith("Skin_Detail", StringComparison.Ordinal)).ToList(); + if (nrms.Count > 1 && nrms[0].StartsWith("Angin_Tile", StringComparison.Ordinal)) { o["nrm"] = nrms[1]; o["nrm2"] = nrms[0]; } + var aos = t.Where(x => x.EndsWith("_AO", StringComparison.Ordinal)).ToList(); + if (aos.Count > 0) o["ao"] = aos[^1]; + return o; + } + + // ---------------- textures ---------------- + + /// A texture for the page: (width, height, RGBA8), its channel sources applied, box-shrunk to at most max wide. + /// "eye:iris|sclera|mask" composites an eye; any other name is Tex/<name>.bntx.zs. Null when the game has no such file. + public static (int W, int H, byte[] Rgba)? Texture(IGameSource src, Zs zs, string name, int max = MaxTexture) + { + if (name.StartsWith("eye:", StringComparison.Ordinal)) + { + var p = name[4..].Split('|'); + if (p.Length != 3) return null; + var iris = Texture(src, zs, p[0], 512); var sclera = Texture(src, zs, p[1], 512); var mask = Texture(src, zs, p[2], 512); + if (iris == null || sclera == null || mask == null) return null; + return Eye(iris.Value, sclera.Value, mask.Value); + } + var path = "Tex/" + name + ".bntx.zs"; + if (!src.Exists(path)) return null; + var b = new Bntx(zs.Unpack(path)); + var t = b.Find(name) ?? b.Textures.FirstOrDefault(); + if (t == null) return null; + var rgba = b.DecodeRgba(t, true); + int w = t.Width, h = t.Height; + while (w > max || h > max) + { + (rgba, w, h) = Half(rgba, w, h); + } + return (w, h, rgba); + } + + /// An image at half the size (2x2 boxes). + public static (byte[] Rgba, int W, int H) Half(byte[] src, int w, int h) + { + int nw = Math.Max(1, w / 2), nh = Math.Max(1, h / 2); + var o = new byte[nw * nh * 4]; + for (var y = 0; y < nh; y++) + for (var x = 0; x < nw; x++) + for (var c = 0; c < 4; c++) + { + int x0 = Math.Min(2 * x, w - 1), x1 = Math.Min(2 * x + 1, w - 1), y0 = Math.Min(2 * y, h - 1), y1 = Math.Min(2 * y + 1, h - 1); + o[(y * nw + x) * 4 + c] = (byte)((src[(y0 * w + x0) * 4 + c] + src[(y0 * w + x1) * 4 + c] + src[(y1 * w + x0) * 4 + c] + src[(y1 * w + x1) * 4 + c] + 2) >> 2); + } + return (o, nw, nh); + } + + /// The eye as one picture: the sclera, with the iris inside the mask's circle (the iris map spans the circle at + /// IrisScale of its own width). + static (int, int, byte[]) Eye((int W, int H, byte[] Rgba) iris, (int W, int H, byte[] Rgba) sclera, (int W, int H, byte[] Rgba) mask) + { + const float IrisScale = 2.85f; + int w = sclera.W, h = sclera.H; + var o = new byte[w * h * 4]; + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) + { + float u = (x + .5f) / w, v = (y + .5f) / h; + var m = Sample(mask, u, v, 0) / 255f; + float iu = .5f + (u - .5f) * IrisScale, iv = .5f + (v - .5f) * IrisScale; + for (var c = 0; c < 3; c++) + { + var s = Sample(sclera, u, v, c); + var i = Sample(iris, iu, iv, c); + o[(y * w + x) * 4 + c] = (byte)Math.Clamp(s + (i - s) * m + .5f, 0, 255); + } + o[(y * w + x) * 4 + 3] = 255; + } + return (w, h, o); + } + + static float Sample((int W, int H, byte[] Rgba) t, float u, float v, int c) + { + var x = Math.Clamp((int)(u * t.W), 0, t.W - 1); + var y = Math.Clamp((int)(v * t.H), 0, t.H - 1); + return t.Rgba[(y * t.W + x) * 4 + c]; + } +} diff --git a/launcher/Core/GameFiles/OverlaySource.cs b/launcher/Core/GameFiles/OverlaySource.cs new file mode 100644 index 0000000..4aa8080 --- /dev/null +++ b/launcher/Core/GameFiles/OverlaySource.cs @@ -0,0 +1,36 @@ +// (Triforce, 11-29) A mod's romfs over the game's, as the game sees them both (host/mods.c: a mod's file wins over the game's): +// the Character page reads Linkle (a mod: Model/, Tex/, Pack/ ...) this way, so her models and textures come from the mod and +// everything she shares with the game from the game. Read-only, like every source. +namespace Triforce.Core.GameFiles; + +public sealed class OverlaySource : IGameSource +{ + readonly IGameSource top, bottom; + readonly bool ownsTop; + + /// The mod's romfs (its files win). + /// The game's romfs. + /// Dispose top with this source (bottom is the caller's). + public OverlaySource(IGameSource top, IGameSource bottom, bool ownsTop = true) + { + this.top = top; this.bottom = bottom; this.ownsTop = ownsTop; + } + + public string Describe => top.Describe + " over " + bottom.Describe; + + /// Whether the mod (not the game) has this file. + public bool InTop(string romfsPath) => top.Exists(romfsPath); + + public bool Exists(string romfsPath) => top.Exists(romfsPath) || bottom.Exists(romfsPath); + + public byte[] Read(string romfsPath) => top.Exists(romfsPath) ? top.Read(romfsPath) : bottom.Read(romfsPath); + + public IEnumerable List(string dir) => top.List(dir).Union(bottom.List(dir), StringComparer.Ordinal); + + public string? Stamp(string romfsPath) => top.Exists(romfsPath) ? "mod:" + top.Stamp(romfsPath) : bottom.Stamp(romfsPath); + + public void Dispose() + { + if (ownsTop) top.Dispose(); + } +} diff --git a/launcher/Core/GameFiles/TextureRecolor.cs b/launcher/Core/GameFiles/TextureRecolor.cs new file mode 100644 index 0000000..d6b5413 --- /dev/null +++ b/launcher/Core/GameFiles/TextureRecolor.cs @@ -0,0 +1,357 @@ +// (Triforce, 11-29) Recolouring a texture of a BNTX file in place, for the Character page's Linkle: her outfit textures are ones +// the randomizer's colour tool cannot read (uncompressed, or BC1 / BC3 it does not edit), so the launcher dyes them itself, the +// way that tool does: the texels of a part are found by their colour band (a hue range, enough saturation), keep their shading +// (luminance relative to the band's median, brightness compressed toward the new colour as the tool's dye comes out), and +// take the new colour. Every mip level is dyed from its own texels with the same rule; a block none of whose texels changed +// keeps its bytes; the others are encoded again in the texture's own format (RGBA8, BC1, BC3's colour half, ASTC), so the file +// keeps its size and layout and only its pixels change. BC7 is refused (the caller leaves such a texture as it is). +// A texture may also be given a new name of the same length (a copy only one model points at). +using System.Buffers.Binary; +using System.Text; + +namespace Triforce.Core.GameFiles; + +/// A part's colour band: hues from HueLo to HueHi degrees (wrapping past 360 when HueLo > HueHi), saturation +/// from MinSat and value from MinVal (all 0-1), feathered at the edges so the dye has no hard border. +public sealed record ColorBand(float HueLo, float HueHi, float MinSat = 0.12f, float MinVal = 0.04f, float MaxVal = 1.01f) +{ + /// Where on the texture the part lies (rectangles in 0-1 texture space: x0, y0, x1, y1), when the texture is a + /// sheet of several things that share colours (a face and a red tunic): null is anywhere. + public float[][]? Rects { get; init; } + + /// Any colour at all (a texture that is all one part). + public static readonly ColorBand All = new(0, 360, 0, 0); +} + +public static class TextureRecolor +{ + /// Encodes one ASTC block (texels RGBA8, block width, height) to 16 bytes: AstcEncode.EncodeBlock, set by the + /// caller. Without it an ASTC texture is refused. + public delegate byte[] BlockEncoder(ReadOnlySpan texels, int blockWidth, int blockHeight); + public static BlockEncoder? Astc; + + /// The texture recoloured: (the new BNTX bytes, the recoloured level 0 as RGBA8 for a preview, how many level-0 + /// texels changed). parts: each band and its colour (#rrggbb); a texel in two bands takes the first. newName: a name of the + /// same length for a copy (null keeps the name). + public static (byte[] Bntx, (int W, int H, byte[] Rgba) Preview, int Changed) Recolor(byte[] bntx, string texName, + IReadOnlyList<(ColorBand Band, string Hex)> parts, string? newName = null) + { + var b = new Bntx(bntx); + var t = b.Find(texName) ?? b.Textures[0]; + if (t.TileMode != 0) throw new NotSupportedException(texName + ": a linear texture"); + var kind = t.Format >> 8; + if (!(kind is 0x0b or 0x1a or 0x1c || (kind is >= 0x2d and <= 0x3a && Astc != null))) + throw new NotSupportedException(texName + ": " + Bntx.FormatName(t.Format) + " cannot be dyed here"); + var (bw, bh, bpb) = Bntx.BlockInfo(t.Format); + var output = (byte[])bntx.Clone(); + + // the band's reference brightness, from level 0 + var level0 = DecodeLevel(bntx, t, 0, out _); + var targets = parts.Select(p => (p.Band, Lin: Lin3(p.Hex))).ToArray(); + var ym = new float[targets.Length]; + for (var k = 0; k < targets.Length; k++) + { + var ys = new List(); + for (var i = 0; i < level0.Rgba.Length; i += 4) + if (Weight(targets[k].Band, level0.Rgba, i, level0.W, level0.H) > 0.5f) ys.Add(Y(level0.Rgba, i)); + ys.Sort(); + ym[k] = ys.Count > 0 ? Math.Max(ys[ys.Count / 2], 1e-4f) : 0.1f; + } + + (int, int, byte[]) preview = default; + var changedTexels = 0; + for (var level = 0; level < t.MipOffsets.Length; level++) + { + int w = Math.Max(1, t.Width >> level), h = Math.Max(1, t.Height >> level); + var orig = level == 0 ? level0 : DecodeLevel(bntx, t, level, out _); + var dyed = (byte[])orig.Rgba.Clone(); + var changed = new bool[w * h]; + for (var p = 0; p < w * h; p++) + { + var i = p * 4; + for (var k = 0; k < targets.Length; k++) + { + var wt = Weight(targets[k].Band, orig.Rgba, i, w, h); + if (wt <= 0) continue; + Dye(orig.Rgba, dyed, i, targets[k].Lin, ym[k], wt); + changed[p] = dyed[i] != orig.Rgba[i] || dyed[i + 1] != orig.Rgba[i + 1] || dyed[i + 2] != orig.Rgba[i + 2]; + break; + } + } + if (level == 0) { preview = (w, h, dyed); changedTexels = changed.Count(c => c); } + if (!changed.Any(c => c)) continue; + + // encode the changed blocks, keep the others' bytes + int wB = (w + bw - 1) / bw, hB = (h + bh - 1) / bh; + var bhl = BlockLinear.MipBlockHeight(hB, t.BlockHeightLog2); + var at = (int)t.MipOffsets[level]; + var size = (int)BlockLinear.Size(wB, hB, bpb, bhl); + if (at <= 0 || at + size > output.Length) throw new InvalidDataException(texName + ": mip " + level + " lies outside the file"); + var linear = BlockLinear.Deswizzle(output.AsSpan(at, size), wB, hB, bpb, bhl); + Parallel.For(0, hB, by => + { + Span block = stackalloc byte[12 * 12 * 4]; + for (var bx = 0; bx < wB; bx++) + { + var any = false; + for (var y = 0; y < bh && !any; y++) + for (var x = 0; x < bw && !any; x++) + { + int px = Math.Min(bx * bw + x, w - 1), py = Math.Min(by * bh + y, h - 1); + any = changed[py * w + px]; + } + if (!any) continue; + for (var y = 0; y < bh; y++) + for (var x = 0; x < bw; x++) + { + int px = Math.Min(bx * bw + x, w - 1), py = Math.Min(by * bh + y, h - 1); + dyed.AsSpan((py * w + px) * 4, 4).CopyTo(block.Slice((y * bw + x) * 4, 4)); + } + var dst = linear.AsSpan((by * wB + bx) * bpb, bpb); + var px16 = block[..(bw * bh * 4)]; + switch (kind) + { + case 0x0b: px16[..4].CopyTo(dst); break; + case 0x1a: Bc1(px16, dst, true); break; + case 0x1c: Bc1(px16, dst[8..], false); break; // (BC3: the alpha half stays: the dye leaves alpha alone) + default: Astc!(px16, bw, bh).CopyTo(dst); break; + } + } + }); + BlockLinear.Swizzle(linear, output.AsSpan(at, size), wB, hB, bpb, bhl); + } + + if (newName != null && newName != t.Name) + { + if (newName.Length != t.Name.Length) throw new ArgumentException("a new name must keep the length"); + ReplaceAll(output, t.Name, newName); + } + return (output, preview, changedTexels); + } + + /// Every place a name is written, changed to another of the same length. + public static int ReplaceAll(byte[] data, string from, string to) + { + byte[] f = Encoding.ASCII.GetBytes(from), n = Encoding.ASCII.GetBytes(to); + var count = 0; + for (var i = data.AsSpan().IndexOf(f); i >= 0;) + { + n.CopyTo(data, i); count++; + var next = data.AsSpan(i + f.Length).IndexOf(f); + i = next < 0 ? -1 : i + f.Length + next; + } + return count; + } + + /// One mip level decoded to RGBA8 (as stored: no channel sources applied). + public static (int W, int H, byte[] Rgba) DecodeLevel(byte[] bntx, BntxTexture t, int level, out byte[] linearBlocks) + { + var (bw, bh, bpb) = Bntx.BlockInfo(t.Format); + int w = Math.Max(1, t.Width >> level), h = Math.Max(1, t.Height >> level); + int wB = (w + bw - 1) / bw, hB = (h + bh - 1) / bh; + var bhl = BlockLinear.MipBlockHeight(hB, t.BlockHeightLog2); + var at = (int)t.MipOffsets[level]; + var size = (int)BlockLinear.Size(wB, hB, bpb, bhl); + if (at <= 0 || at + size > bntx.Length) throw new InvalidDataException(t.Name + ": mip " + level + " lies outside the file"); + linearBlocks = BlockLinear.Deswizzle(bntx.AsSpan(at, size), wB, hB, bpb, bhl); + var rgba = (t.Format >> 8) switch + { + >= 0x2d and <= 0x3a => GameFiles.Astc.Decompress(linearBlocks, w, h, bw, bh), + 0x1a => BlockCompression.Decode(linearBlocks, w, h, BlockCompression.Kind.BC1), + 0x1c => BlockCompression.Decode(linearBlocks, w, h, BlockCompression.Kind.BC3), + 0x0b => linearBlocks, + _ => throw new NotSupportedException(t.Name + ": " + Bntx.FormatName(t.Format)), + }; + return (w, h, rgba); + } + + // ---------------- the dye ---------------- + + static readonly float[] ToLin = Enumerable.Range(0, 256).Select(i => { var x = i / 255f; return x <= 0.04045f ? x / 12.92f : MathF.Pow((x + 0.055f) / 1.055f, 2.4f); }).ToArray(); + static byte ToSrgb(float x) + { + x = Math.Clamp(x, 0, 1); + var s = x <= 0.0031308f ? x * 12.92f : 1.055f * MathF.Pow(x, 1 / 2.4f) - 0.055f; + return (byte)Math.Clamp((int)(s * 255 + 0.5f), 0, 255); + } + static float Y(byte[] p, int i) => 0.2126f * ToLin[p[i]] + 0.7152f * ToLin[p[i + 1]] + 0.0722f * ToLin[p[i + 2]]; + static float[] Lin3(string hex) + { + var c = Convert.FromHexString(hex.TrimStart('#')); + return new[] { ToLin[c[0]], ToLin[c[1]], ToLin[c[2]] }; + } + + /// How much a texel belongs to a band (0-1). + static float Weight(ColorBand band, byte[] p, int i, int texW, int texH) + { + if (band.Rects is { } rects) + { + var px = i / 4; + float u = (px % texW + 0.5f) / texW, v = (px / texW + 0.5f) / texH; + if (!rects.Any(r => u >= r[0] && u < r[2] && v >= r[1] && v < r[3])) return 0; + } + if (band.HueLo == 0 && band.HueHi >= 360 && band.MinSat <= 0 && band.MinVal <= 0) return 1; + float r = p[i] / 255f, g = p[i + 1] / 255f, bl = p[i + 2] / 255f; + float mx = Math.Max(r, Math.Max(g, bl)), mn = Math.Min(r, Math.Min(g, bl)), d = mx - mn; + if (mx <= 0) return 0; + float s = d / mx; + float h = d <= 0 ? 0 : mx == r ? 60 * (((g - bl) / d + 6) % 6) : mx == g ? 60 * ((bl - r) / d + 2) : 60 * ((r - g) / d + 4); + // hue inside the range, feathered 10 degrees outside it + float lo = band.HueLo, hi = band.HueHi; + float inside; + if (hi - lo >= 360) inside = 1; + else + { + float span = (hi - lo + 360) % 360, off = (h - lo + 360) % 360; + float dist = off <= span ? 0 : Math.Min(off - span, 360 - off); + inside = Math.Clamp(1 - dist / 10f, 0, 1); + } + float sat = band.MinSat <= 0 ? 1 : Math.Clamp((s - band.MinSat) / 0.06f + 0.5f, 0, 1); // (no saturation floor: whites too) + float val = Math.Clamp((mx - band.MinVal) / 0.04f + 0.5f, 0, 1) * Math.Clamp((band.MaxVal - mx) / 0.04f + 0.5f, 0, 1); + return inside * sat * val; + } + + /// A texel dyed: its luminance relative to the band's median (the shading) carried onto the colour, whose median + /// brightness lands between the band's and the colour's (Ym^0.38 * Ty^0.62, as the colour tool's dye comes out). + static void Dye(byte[] src, byte[] dst, int i, float[] target, float ym, float wt) + { + float ty = Math.Max(0.2126f * target[0] + 0.7152f * target[1] + 0.0722f * target[2], 1e-4f); + float y = Y(src, i); + float q = ym * MathF.Pow(ty / ym, 0.62f); + float k = q / ty * (y / ym); + for (var c = 0; c < 3; c++) + { + var o = ToLin[src[i + c]]; + dst[i + c] = ToSrgb(o + (target[c] * k - o) * wt); + } + } + + // ---------------- BC1 ---------------- + + /// A BC1 colour block for 16 texels (RGBA8): endpoints along the colours' principal axis, refined once by least + /// squares. punchThrough: texels with alpha under 128 take the transparent index (BC1's three-colour mode). + static void Bc1(ReadOnlySpan px, Span dst, bool punchThrough) + { + Span c = stackalloc float[48]; + Span clear = stackalloc bool[16]; + var anyClear = false; + var n = 0; + var mean = new float[3]; + for (var i = 0; i < 16; i++) + { + clear[i] = punchThrough && px[i * 4 + 3] < 128; + anyClear |= clear[i]; + for (var k = 0; k < 3; k++) c[i * 3 + k] = px[i * 4 + k]; + if (clear[i]) continue; + for (var k = 0; k < 3; k++) mean[k] += c[i * 3 + k]; + n++; + } + if (n == 0) { dst.Clear(); BinaryPrimitives.WriteUInt32LittleEndian(dst[4..], 0xFFFFFFFF); return; } + for (var k = 0; k < 3; k++) mean[k] /= n; + // principal axis (power iteration on the covariance) + float cxx = 0, cxy = 0, cxz = 0, cyy = 0, cyz = 0, czz = 0; + for (var i = 0; i < 16; i++) + { + if (clear[i]) continue; + float x = c[i * 3] - mean[0], y = c[i * 3 + 1] - mean[1], z = c[i * 3 + 2] - mean[2]; + cxx += x * x; cxy += x * y; cxz += x * z; cyy += y * y; cyz += y * z; czz += z * z; + } + float ax = 1, ay = 1, az = 1; + for (var it = 0; it < 8; it++) + { + float nx = cxx * ax + cxy * ay + cxz * az, ny = cxy * ax + cyy * ay + cyz * az, nz = cxz * ax + cyz * ay + czz * az; + var len = MathF.Sqrt(nx * nx + ny * ny + nz * nz); + if (len < 1e-6f) { ax = 0.577f; ay = 0.577f; az = 0.577f; break; } + ax = nx / len; ay = ny / len; az = nz / len; + } + float lo = float.MaxValue, hi = float.MinValue; + for (var i = 0; i < 16; i++) + { + if (clear[i]) continue; + var d = (c[i * 3] - mean[0]) * ax + (c[i * 3 + 1] - mean[1]) * ay + (c[i * 3 + 2] - mean[2]) * az; + lo = Math.Min(lo, d); hi = Math.Max(hi, d); + } + Span e0 = stackalloc float[3], e1 = stackalloc float[3]; + for (var k = 0; k < 3; k++) { var a = k == 0 ? ax : k == 1 ? ay : az; e0[k] = mean[k] + a * hi; e1[k] = mean[k] + a * lo; } + var three = anyClear; + Span idx = stackalloc int[16]; + for (var pass = 0; pass < 2; pass++) + { + // (keep e0 the one that quantises larger, so the indices below refer to e0 / e1 as Encode orders them) + if (!three && To565(e0) < To565(e1)) for (var k = 0; k < 3; k++) (e0[k], e1[k]) = (e1[k], e0[k]); + Encode(e0, e1, three, c, clear, idx, out var q0, out var q1); + if (pass == 1 || three) { Write(dst, q0, q1, idx); return; } + // least squares refit of the endpoints for these indices (four-colour mode: weights 0, 1/3, 2/3, 1) + float aa = 0, ab = 0, bb = 0; + Span ax2 = stackalloc float[3], bx2 = stackalloc float[3]; + ax2.Clear(); bx2.Clear(); + for (var i = 0; i < 16; i++) + { + var wgt = idx[i] switch { 0 => 0f, 1 => 1f, 2 => 1 / 3f, _ => 2 / 3f }; // (index 1 = e1, 2 = 2/3 e0 + 1/3 e1, 3 = 1/3 e0 + 2/3 e1) + float a = 1 - wgt, bq = wgt; + aa += a * a; ab += a * bq; bb += bq * bq; + for (var k = 0; k < 3; k++) { ax2[k] += a * c[i * 3 + k]; bx2[k] += bq * c[i * 3 + k]; } + } + var det = aa * bb - ab * ab; + if (MathF.Abs(det) < 1e-6f) { Write(dst, q0, q1, idx); return; } + for (var k = 0; k < 3; k++) + { + e0[k] = Math.Clamp((bb * ax2[k] - ab * bx2[k]) / det, 0, 255); + e1[k] = Math.Clamp((aa * bx2[k] - ab * ax2[k]) / det, 0, 255); + } + } + } + + static ushort To565(ReadOnlySpan c) => + (ushort)((Math.Clamp((int)(c[0] * 31 / 255 + 0.5f), 0, 31) << 11) | (Math.Clamp((int)(c[1] * 63 / 255 + 0.5f), 0, 63) << 5) | Math.Clamp((int)(c[2] * 31 / 255 + 0.5f), 0, 31)); + static void From565(ushort v, Span o) + { + int r = (v >> 11) & 31, g = (v >> 5) & 63, b = v & 31; + o[0] = (r << 3) | (r >> 2); o[1] = (g << 2) | (g >> 4); o[2] = (b << 3) | (b >> 2); + } + + /// Endpoints quantised and ordered for the mode (four colours: c0 > c1; three plus transparent: c0 <= c1), + /// and each texel's nearest palette entry. + static void Encode(ReadOnlySpan e0, ReadOnlySpan e1, bool three, ReadOnlySpan c, ReadOnlySpan clear, Span idx, out ushort q0, out ushort q1) + { + q0 = To565(e0); q1 = To565(e1); + if (!three && q0 < q1) (q0, q1) = (q1, q0); + if (three && q0 > q1) (q0, q1) = (q1, q0); + if (!three && q0 == q1) + { + // (one colour: four-colour mode needs c0 > c1) + if (q0 > 0) q1 = (ushort)(q0 - 1); else q0 = 1; + } + Span a = stackalloc int[3], b = stackalloc int[3]; + From565(q0, a); From565(q1, b); + Span pal = stackalloc int[12]; + for (var k = 0; k < 3; k++) + { + pal[k] = a[k]; pal[3 + k] = b[k]; + if (three) { pal[6 + k] = (a[k] + b[k] + 1) / 2; pal[9 + k] = 0; } + else { pal[6 + k] = (2 * a[k] + b[k] + 1) / 3; pal[9 + k] = (a[k] + 2 * b[k] + 1) / 3; } + } + var count = three ? 3 : 4; + for (var i = 0; i < 16; i++) + { + if (clear[i]) { idx[i] = 3; continue; } + var best = 0; var bd = int.MaxValue; + for (var j = 0; j < count; j++) + { + int dr = pal[j * 3] - (int)c[i * 3], dg = pal[j * 3 + 1] - (int)c[i * 3 + 1], db = pal[j * 3 + 2] - (int)c[i * 3 + 2]; + var dd = dr * dr * 3 + dg * dg * 4 + db * db * 2; + if (dd < bd) { bd = dd; best = j; } + } + idx[i] = best; + } + } + + static void Write(Span dst, ushort q0, ushort q1, ReadOnlySpan idx) + { + BinaryPrimitives.WriteUInt16LittleEndian(dst, q0); + BinaryPrimitives.WriteUInt16LittleEndian(dst[2..], q1); + uint bits = 0; + for (var i = 0; i < 16; i++) bits |= (uint)(idx[i] & 3) << (2 * i); + BinaryPrimitives.WriteUInt32LittleEndian(dst[4..], bits); + } +} diff --git a/launcher/Logic/Character/LinkColors.cs b/launcher/Logic/Character/LinkColors.cs new file mode 100644 index 0000000..cf42491 --- /dev/null +++ b/launcher/Logic/Character/LinkColors.cs @@ -0,0 +1,652 @@ +// (Triforce, 11-29) The Character page's colours: young Link's and adult Link's tunics, gear and hair, each in its own colours. +// The recolouring is OOTRR's (the randomizer's program, already used by the Randomizer page: Ootrr.cs): its colors-preview +// gives the recoloured colour maps as pictures in seconds (the page's exact preview), and its build writes the game files +// (block-exact edits of the compressed textures, so nothing is re-encoded). A build recolours a part for every age at once, +// so young and adult Link each get a build of their own and the files are taken from each: young Link's from the first, +// adult Link's from the second. The one texture both ages share (OOTRR's own copy of the cloth tile, Angin_Tile_L_Alb) is +// renamed once more for young Link (Angin_Tile_Y_Alb, the same length) and his models point at it: the same one-letter edit +// OOTRR makes to point Link away from the tile the Kokiri share. +// +// The result is a mod of its own, \mods\~Link colors (its name sorts after every other mod's, so its files win over a +// randomizer seed's colours), with triforce_mod.json (its name on the Mods page) and link_colors.json (the colours, which the +// page reads back). It changes the game's files, not a save: every save, old or new, shows the colours. +// +// \character\choices.json the colours being picked (not applied yet) +// \character\\cal\ the calibration: where each part lies on each colour map (masks) and its brightness +// \character\work\\ a build or preview while it runs (taken away after) +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using Triforce.Core.GameFiles; +using ZstdSharp; + +namespace Triforce.Logic; + +/// A part of Link the page can colour: OOTRR's id, its name on the page, its group, the ages and tunics it shows on, +/// and roughly the game's own colour (for the swatch while it is unchanged). +public sealed record LinkPart(string Id, string Label, string Group, string Ages, string Tunic, string Swatch); + +public sealed class LinkColors +{ + public const string ModFolder = "~Link colors"; + public const string Marker = "link_colors.json"; + public const string WorkFolder = "character"; + + /// Ages: "child" (young Link) and "adult". Tunic: "" any, else kokiri / goron / zora (the adult's tunic it shows on). + public static readonly LinkPart[] Parts = + { + new("kokiri", "Tunic and cap", "Tunic", "child,adult", "kokiri", "#2f8f3a"), + new("kokiri_pants", "Leggings", "Tunic", "child", "", "#3d7a33"), + new("kokiri_shirt", "Undershirt and leggings", "Tunic", "adult", "kokiri", "#d8d1bd"), + new("feathers", "Cap feather", "Tunic", "child,adult", "kokiri", "#e6dfcf"), + new("goron", "Goron Tunic", "Tunic", "adult", "goron", "#b3262c"), + new("goron_trim", "Goron trim", "Tunic", "adult", "goron", "#d4a634"), + new("goron_belt", "Goron belt", "Tunic", "adult", "goron", "#6b4a2b"), + new("goron_beads", "Goron beads", "Tunic", "adult", "goron", "#c9b07a"), + new("zora", "Zora Tunic", "Tunic", "adult", "zora", "#2a4fb0"), + new("zora_shirt", "Zora undershirt", "Tunic", "adult", "zora", "#d4d8de"), + new("zora_belt", "Zora belt", "Tunic", "adult", "zora", "#8a3c8e"), + new("zora_scales", "Zora scales", "Tunic", "adult", "zora", "#3d8fb8"), + new("kokiri_belt", "Belts and straps", "Leather", "child,adult", "kokiri", "#6b4a2b"), + new("leather_trim", "Leather trim", "Leather", "child,adult", "", "#9c2f25"), + new("boots", "Boots", "Leather", "adult", "", "#5b3f26"), + new("gloves", "Gloves", "Leather", "adult", "", "#7a5534"), + new("hair", "Hair", "Hair", "child,adult", "", "#e0b84a"), + new("navi", "Navi", "Navi", "child,adult", "", "#dff3ff"), + }; + + public static IEnumerable PartsOf(string age) => Parts.Where(p => p.Ages.Split(',').Contains(age)); + public static bool Valid(string age, string part) => PartsOf(age).Any(p => p.Id == part); + /// (11-29) The heroes: Link, and Linkle (a mod: Linkle.cs). A colour key is the age, "linkle:" in front for her. + public static readonly string[] Heroes = { "link", "linkle" }; + public static string Key(string hero, string age) => hero == "linkle" ? "linkle:" + age : age; + public static (string Hero, string Age) FromKey(string key) => key.StartsWith("linkle:", StringComparison.Ordinal) ? ("linkle", key[7..]) : ("link", key); + public static IEnumerable PartsOf(string hero, string age) => (hero == "linkle" ? Linkle.Parts : Parts).Where(p => p.Ages.Split(',').Contains(age)); + public static bool Valid(string hero, string age, string part) => PartsOf(hero, age).Any(p => p.Id == part); + static readonly string[] Keys = { "child", "adult", "linkle:child", "linkle:adult" }; + /// Parts the game has once for both ages (Navi is one fairy): set for one age, set for both. + public static readonly string[] Shared = { "navi" }; + static readonly Regex Hex = new("^#[0-9a-f]{6}$", RegexOptions.CultureInvariant); + public static string? CleanHex(string? hex) + { + hex = (hex ?? "").Trim().ToLowerInvariant(); + if (hex.Length == 6) hex = "#" + hex; + return Hex.IsMatch(hex) ? hex : null; + } + + readonly TriforceContext ctx; + public Ootrr Tool { get; } + public ModManager Mods { get; } + public LinkColors(TriforceContext ctx, Ootrr tool, ModManager mods) { this.ctx = ctx; Tool = tool; Mods = mods; } + + string Home => Path.Combine(ctx.Home, WorkFolder); + + // ---------------- the colours being picked ---------------- + + /// age -> part -> #rrggbb. A part not in it keeps the game's colour. + public sealed class Choice + { + public Dictionary> Colors { get; } = new() { ["child"] = new(), ["adult"] = new() }; + /// Who the player plays: "link" or "linkle". + public string Hero { get; set; } = "link"; + /// The colours of the hero being played, by age. + public Dictionary Of(string age) => Age(Key(Hero, age)); + public Dictionary Age(string age) => Colors.TryGetValue(age, out var d) ? d : Colors[age] = new(); + public Choice Copy() + { + var c = new Choice { Hero = Hero }; + foreach (var (age, d) in Colors) c.Colors[age] = new Dictionary(d); + return c; + } + /// The same hero, and the same colours for that hero (the other hero's picks are not in the game). + public bool Same(Choice o) => Hero == o.Hero && new[] { Key(Hero, "child"), Key(Hero, "adult") }.All(a => + { + var x = Colors.TryGetValue(a, out var p) ? p : new(); var y = o.Colors.TryGetValue(a, out var q) ? q : new(); + return x.Count == y.Count && x.All(kv => y.TryGetValue(kv.Key, out var v) && v == kv.Value); + }); + /// Nothing to write: Link in the game's own colours. + public bool Empty => Hero == "link" && Of("child").Count == 0 && Of("adult").Count == 0; + public JsonObject ToJson() + { + var o = new JsonObject(Colors.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)new JsonObject(kv.Value.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value)))))); + o["hero"] = Hero; + return o; + } + public static Choice FromJson(JsonNode? n) + { + var c = new Choice(); + if (n is not JsonObject o) return c; + if (o["hero"] is JsonValue h && h.TryGetValue(out var hero) && Heroes.Contains(hero)) c.Hero = hero; + foreach (var key in Keys) + { + var (kh, age) = FromKey(key); + if (o[key] is JsonObject a) + foreach (var (part, v) in a) + if (Valid(kh, age, part) && CleanHex(v is JsonValue jv && jv.TryGetValue(out var s) ? s : null) is { } hex) c.Age(key)[part] = hex; + } + return c; + } + } + + string ChoicesFile => Path.Combine(Home, "choices.json"); + + public Choice LoadChoice() + { + try { return File.Exists(ChoicesFile) ? Choice.FromJson(JsonNode.Parse(File.ReadAllText(ChoicesFile))) : new Choice(); } + catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException) { return new Choice(); } + } + + public void SaveChoice(Choice c) + { + if (!ctx.Allowed(Home)) return; + try + { + Directory.CreateDirectory(Home); + var tmp = ChoicesFile + ".tmp"; + File.WriteAllText(tmp, new JsonObject { ["colors"] = c.ToJson() }["colors"]!.ToJsonString()); + File.Move(tmp, ChoicesFile, true); + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { ctx.Log.Write("character: colours not kept: " + e.Message); } + } + + // ---------------- what the game has now ---------------- + + public static string ModPath(string game) => Path.Combine(Triforce.Logic.Mods.FolderOf(game), ModFolder); + + /// The colours the game has now (the mod's marker), or null when the mod is not there. On is false when the + /// player switched it off on the Mods page. + public (Choice Colors, bool On, string Path)? Applied(string game) + { + var mods = Triforce.Logic.Mods.FolderOf(game); + foreach (var path in new[] { Path.Combine(mods, ModFolder), Path.Combine(mods, "-" + ModFolder), Path.Combine(mods, "_" + ModFolder) }) + { + var marker = Path.Combine(path, Marker); + if (!File.Exists(marker)) continue; + try { return (Choice.FromJson(JsonNode.Parse(File.ReadAllText(marker))?["colors"]), !System.IO.Path.GetFileName(path).StartsWith('-') && !System.IO.Path.GetFileName(path).StartsWith('_'), path); } + catch (Exception e) when (e is IOException || e is JsonException) { return (new Choice(), true, path); } + } + return null; + } + + /// Other mods that are on and carry Link's model or one of the colour maps: the page says which wins. + public IReadOnlyList Others(string game) + { + try + { + return Mods.ListGame(game, false).Where(m => m.On && !m.Path.EndsWith(ModFolder, StringComparison.OrdinalIgnoreCase) + && m.Files.Any(f => f.StartsWith("model/player_child", StringComparison.Ordinal) || f.StartsWith("model/player_adult", StringComparison.Ordinal))) + .Select(m => m.Info?.Name is { Length: > 0 } n ? n : m.Name).ToList(); + } + catch (Exception) { return Array.Empty(); } + } + + // ---------------- calibration: where each part lies on each colour map ---------------- + + /// One colour map's parts: up to two (slot 0 in the mask's red, slot 1 in its green), each with the median + /// linear luminance of its texels before (Ym) and after (Qm) the calibration colour of luminance Ty. OOTRR keeps the + /// shading and compresses brightness: a colour of luminance Y comes out near Qm * (Y / Ty)^0.62 at the median texel. + /// ((11-30) G: the contrast OOTRR gives its texels, after_Y ~ before_Y^G over the part's texels (0.98 to 1.6 on Link's maps: + /// the live tint follows it, or the tint and OOTRR's exact map differed enough that a pick seemed to "switch back") + public sealed record CalMap(string Texture, string[] Parts, float[] Ym, float[] Qm, float[] Ty, float[] G, int Width, int Height, byte[] Mask); + + static readonly string[] Trims = { "leather_trim", "goron_trim" }; + const string Primary = "#ff00ff", Trim = "#00ffff"; + + public string CalFolder(string stamp) => Path.Combine(Home, stamp, "cal5"); // ((11-30) cal5: with G and the mask by strength, made again once + static JsonArray Floats(float[] v) => new(v.Select(x => (JsonNode?)x).ToArray()); + + /// The calibration, read from the cache or made (one colors-preview of every part: about 15 s, once per game). + public async Task> CalibrateAsync(string game, string stamp, CancellationToken token) + { + var dir = CalFolder(stamp); + var index = Path.Combine(dir, "cal.json"); + if (File.Exists(index)) + try { return ReadCal(dir, index); } catch (Exception e) when (e is IOException || e is JsonException || e is InvalidDataException) { ctx.Log.Write("character: calibration unreadable, made again: " + e.Message); } + ctx.Require(Home); + var work = Path.Combine(Home, "work", "cal-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(work); + try + { + var args = new List { "colors-preview", Romfs(game), work, "custom", "triforce" }; + args.AddRange(Parts.Select(p => p.Id + "=" + (Trims.Contains(p.Id) ? Trim : Primary))); + var run = await Tool.RunAsync(args, null, token).ConfigureAwait(false); + var maps = new List(); + foreach (var (tex, parts) in PreviewLines(run.Out)) + { + var before = Path.Combine(work, tex + "_before.png"); + var after = Path.Combine(work, tex + "_after.png"); + if (!File.Exists(before) || !File.Exists(after) || parts.Count == 0) continue; + var (w, h, b) = Png.Decode(File.ReadAllBytes(before)); + var (w2, h2, a) = Png.Decode(File.ReadAllBytes(after)); + if (w != w2 || h != h2) continue; + var slots = parts.Take(2).ToArray(); + var mask = new byte[w * h * 4]; + var yb = slots.Select(_ => new List()).ToArray(); + var ya = slots.Select(_ => new List()).ToArray(); + for (var i = 0; i < w * h; i++) + { + int dr = a[4 * i] - b[4 * i], dg = a[4 * i + 1] - b[4 * i + 1], db = a[4 * i + 2] - b[4 * i + 2]; + // ((11-30) by how far OOTRR moved it: the leather 100 and more (of 765), metal, buckles and charms under 60 + // and nearly grey; the tint fades in from 20 to 100, so it no longer paints the buckle and ring) + var moved = Math.Abs(dr) + Math.Abs(dg) + Math.Abs(db); + if (moved < 20) continue; + // (which part moved it: the trim parts were set to cyan, the others to magenta) + var slot = 0; + if (slots.Length > 1) + { + var cyan = a[4 * i + 1] - a[4 * i]; // (cyan: green over red; magenta: red over green) + var trimSlot = Array.FindIndex(slots, s => Trims.Contains(s)); + slot = trimSlot >= 0 ? (cyan > 0 ? trimSlot : 1 - trimSlot) : 0; + } + mask[4 * i + slot] = (byte)Math.Clamp((moved - 20) * 255 / 80, 0, 255); + mask[4 * i + 3] = 255; + if (moved < 60) continue; // (the part's own texels alone in its medians and contrast) + yb[slot].Add(Lum(b, 4 * i)); + ya[slot].Add(Lum(a, 4 * i)); + } + var ym = new float[slots.Length]; var qm = new float[slots.Length]; var ty = new float[slots.Length]; var g = new float[slots.Length]; + for (var s = 0; s < slots.Length; s++) + { + ty[s] = LumOf(Trims.Contains(slots[s]) ? Trim : Primary); + g[s] = Contrast(yb[s], ya[s]); + ym[s] = yb[s].Count > 0 ? Math.Max(Median(yb[s]), 1e-4f) : 0.05f; + qm[s] = ya[s].Count > 0 ? Math.Max(Median(ya[s]), 1e-4f) : 0.1f; + } + maps.Add(new CalMap(tex, slots, ym, qm, ty, g, w, h, Blur(mask, w, h))); + } + Directory.CreateDirectory(dir); + var j = new JsonArray(); + foreach (var m in maps) + { + await File.WriteAllBytesAsync(Path.Combine(dir, m.Texture + ".mask"), m.Mask, token).ConfigureAwait(false); + j.Add(new JsonObject + { + ["tex"] = m.Texture, ["parts"] = new JsonArray(m.Parts.Select(p => (JsonNode?)p).ToArray()), ["w"] = m.Width, ["h"] = m.Height, + ["ym"] = Floats(m.Ym), ["qm"] = Floats(m.Qm), ["ty"] = Floats(m.Ty), ["g"] = Floats(m.G), + }); + } + await File.WriteAllTextAsync(index, j.ToJsonString(), token).ConfigureAwait(false); + ctx.Log.Write("character: calibration made, " + maps.Count + " colour maps"); + return maps; + } + finally { try { Directory.Delete(work, true); } catch (Exception) { } } + } + + static IReadOnlyList ReadCal(string dir, string index) + { + var list = new List(); + foreach (var n in JsonNode.Parse(File.ReadAllText(index)) as JsonArray ?? new JsonArray()) + { + var tex = (string)n!["tex"]!; + if (tex.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) continue; + int w = (int)n["w"]!, h = (int)n["h"]!; + var mask = File.ReadAllBytes(Path.Combine(dir, tex + ".mask")); + if (mask.Length != w * h * 4) throw new InvalidDataException("a mask of the wrong size"); + float[] F(string k) => ((JsonArray)n[k]!).Select(x => (float)x!).ToArray(); + if (n["g"] is not JsonArray) throw new InvalidDataException("a calibration without the contrast (g)"); + list.Add(new CalMap(tex, ((JsonArray)n["parts"]!).Select(x => (string)x!).ToArray(), F("ym"), F("qm"), F("ty"), F("g"), w, h, mask)); + } + return list; + } + + /// A mask softened by one texel, so the live tint has no hard stairs at its edges. + static byte[] Blur(byte[] m, int w, int h) + { + var o = new byte[m.Length]; + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) + for (var c = 0; c < 4; c++) + { + int s = 0, n = 0; + for (var dy = -1; dy <= 1; dy++) + for (var dx = -1; dx <= 1; dx++) + { + int xx = x + dx, yy = y + dy; + if (xx < 0 || yy < 0 || xx >= w || yy >= h) continue; + s += m[(yy * w + xx) * 4 + c]; n++; + } + o[(y * w + x) * 4 + c] = (byte)(s / n); + } + return o; + } + + static float Lin(byte v) { var x = v / 255f; return x <= 0.04045f ? x / 12.92f : MathF.Pow((x + 0.055f) / 1.055f, 2.4f); } + static float Lum(byte[] p, int i) => 0.2126f * Lin(p[i]) + 0.7152f * Lin(p[i + 1]) + 0.0722f * Lin(p[i + 2]); + public static float LumOf(string hex) + { + var c = Convert.FromHexString(hex[1..]); + return 0.2126f * Lin(c[0]) + 0.7152f * Lin(c[1]) + 0.0722f * Lin(c[2]); + } + static float Median(List v) { v.Sort(); return v[v.Count / 2]; } + + /// ((11-30)) The slope of log(after) on log(before) over a part's texels (least squares), in [0.7, 1.8]; 1 when too few + /// texels or no spread. Measured on young Link's belt: 1.15 for red, 0.98 for blue; his vest: 1.6. + internal static float Contrast(List before, List after) + { + double sx = 0, sy = 0, sxx = 0, sxy = 0; var n = 0; + for (var i = 0; i < before.Count && i < after.Count; i++) + { + if (before[i] < 1e-4f || after[i] < 1e-4f) continue; + double x = Math.Log(before[i]), y = Math.Log(after[i]); + sx += x; sy += y; sxx += x * x; sxy += x * y; n++; + } + if (n < 64) return 1f; + var vx = sxx - sx * sx / n; + if (vx < 1e-6) return 1f; + return (float)Math.Clamp((sxy - sx * sy / n) / vx, 0.7, 1.8); + } + + /// colors-preview's lines: "Tex_Name: part #RRGGBB, part2 #RRGGBB, n of m blocks changed ...". + static IEnumerable<(string Tex, List Parts)> PreviewLines(string output) + { + foreach (var raw in output.Split('\n')) + { + var l = raw.Trim(); + var colon = l.IndexOf(": ", StringComparison.Ordinal); + if (colon <= 0) continue; + var tex = l[..colon]; + if (tex.Contains(' ') || tex.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) continue; + var parts = Regex.Matches(l[(colon + 2)..], @"([a-z_]+) #[0-9A-Fa-f]{6}").Select(m => m.Groups[1].Value).Where(p => Parts.Any(x => x.Id == p)).ToList(); + if (parts.Count > 0) yield return (tex, parts); + } + } + + // ---------------- the exact preview ---------------- + + /// OOTRR's own recoloured colour maps for one age's colours (pictures of the colour maps it would write, at the + /// size colors-preview gives them). Keys are the texture names as the model names them (OOTRR's renamed copy of the cloth + /// tile is given under the tile's own name). + public async Task> PreviewAsync(string game, IReadOnlyDictionary colors, CancellationToken token) + { + var maps = new Dictionary(StringComparer.Ordinal); + if (colors.Count == 0) return maps; + ctx.Require(Home); + var work = Path.Combine(Home, "work", "pv-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(work); + try + { + var args = new List { "colors-preview", Romfs(game), work, "custom", "triforce" }; + args.AddRange(colors.Select(kv => kv.Key + "=" + kv.Value)); + var run = await Tool.RunAsync(args, null, token).ConfigureAwait(false); + using var src = new FolderSource(Romfs(game)); + var zs = new Zs(src); + foreach (var (tex, _) in PreviewLines(run.Out)) + { + var after = Path.Combine(work, tex + "_after.png"); + var before = Path.Combine(work, tex + "_before.png"); + if (!File.Exists(after) || !File.Exists(before)) continue; + var a = Png.Decode(await File.ReadAllBytesAsync(after, token).ConfigureAwait(false)); + var b = Png.Decode(await File.ReadAllBytesAsync(before, token).ConfigureAwait(false)); + var name = ModelName(tex); + // (colors-preview's pictures are small: the change they show is carried onto the game's own full-size map) + var full = LinkScene.Texture(src, zs, name); + maps[name] = full is { } f && a.Width == b.Width && a.Height == b.Height ? Carry(f, b, a) : a; + token.ThrowIfCancellationRequested(); + } + return maps; + } + finally { try { Directory.Delete(work, true); } catch (Exception) { } } + } + + static readonly float[] ToLin = Enumerable.Range(0, 256).Select(i => Lin((byte)i)).ToArray(); + static readonly byte[] ToSrgb = Enumerable.Range(0, 4096).Select(i => + { + var x = i / 4095f; + var s = x <= 0.0031308f ? x * 12.92f : 1.055f * MathF.Pow(x, 1 / 2.4f) - 0.055f; + return (byte)Math.Clamp(MathF.Round(s * 255), 0, 255); + }).ToArray(); + + /// The full-size map with the change from before to after (two small pictures of it) carried over: each texel is + /// scaled, channel by channel in linear light, as the small pictures change at its place. + static (int, int, byte[]) Carry((int W, int H, byte[] Rgba) full, (int Width, int Height, byte[] Rgba) before, (int Width, int Height, byte[] Rgba) after) + { + // ((11-30) E 0.012 -> 0.002: measured on young Link's belt at #FF0000, 0.012 made the red 11% darker than OOTRR's own + // picture (0.220 against 0.246 linear at the median), 0.002 within 1%; the factor is held to 16 where a texel was near black) + const float E = 0.002f, MaxGain = 16f; + int w = full.W, h = full.H, sw = before.Width, sh = before.Height; + var o = new byte[w * h * 4]; + Parallel.For(0, h, y => + { + var fy = Math.Clamp((y + .5f) * sh / h - .5f, 0, sh - 1); + int y0 = (int)fy, y1 = Math.Min(y0 + 1, sh - 1); var ty = fy - y0; + for (var x = 0; x < w; x++) + { + var fx = Math.Clamp((x + .5f) * sw / w - .5f, 0, sw - 1); + int x0 = (int)fx, x1 = Math.Min(x0 + 1, sw - 1); var tx = fx - x0; + var i = (y * w + x) * 4; + for (var c = 0; c < 3; c++) + { + float S(byte[] p, int xx, int yy) => ToLin[p[(yy * sw + xx) * 4 + c]]; + float Bi(byte[] p) => (S(p, x0, y0) * (1 - tx) + S(p, x1, y0) * tx) * (1 - ty) + (S(p, x0, y1) * (1 - tx) + S(p, x1, y1) * tx) * ty; + var v = ToLin[full.Rgba[i + c]] * Math.Min((Bi(after.Rgba) + E) / (Bi(before.Rgba) + E), MaxGain); + o[i + c] = ToSrgb[Math.Clamp((int)(v * 4095 + .5f), 0, 4095)]; + } + o[i + 3] = full.Rgba[i + 3]; + } + }); + return (w, h, o); + } + + /// OOTRR's renamed copies under the name the game's models give them. + public static string ModelName(string tex) => tex switch + { + "Angin_Tile_L_Alb" => "Angin_Tile_A_Alb", + _ => tex, + }; + + // ---------------- apply: the mod ---------------- + + static readonly string[] RomfsNeeds = { "Model", "Tex", "Pack" }; + static string Romfs(string game) + { + var romfs = Path.Combine(game, "romfs"); + if (!RomfsNeeds.All(d => Directory.Exists(Path.Combine(romfs, d)))) + throw new OotrrException("The game folder has no complete romfs folder. Build the game again first."); + return romfs; + } + + /// The seed every colour build uses: the randomizer's defaults, made once (only the colours are taken from the + /// build; the seed's own files are thrown away). + async Task SeedAsync(CancellationToken token) + { + var seed = Path.Combine(Home, "colors-" + Ootrr.Version + ".ootrr"); + if (File.Exists(seed)) return seed; + var settings = Path.Combine(Home, "colors-settings.json"); + await File.WriteAllTextAsync(settings, "{}", token).ConfigureAwait(false); + await Tool.RunAsync(new[] { "generate", settings, "TRIFORCECOLORS", seed }, null, token).ConfigureAwait(false); + if (!File.Exists(seed)) throw new OotrrException("The randomizer made no seed for the colours."); + return seed; + } + + const string ChildTile = "Angin_Tile_L_Alb", ChildTileMine = "Angin_Tile_Y_Alb"; + + /// Writes the mod for these colours (or takes it away when there are none) and returns the folder. progress: a + /// line for the page. + public async Task ApplyAsync(string game, Choice choice, Action? progress, CancellationToken token) + { + var mods = Triforce.Logic.Mods.FolderOf(game); + ctx.Require(mods); + if (Mods.GameRuns(game)) throw new OotrrException("Close the game first: it reads its files when it starts."); + var linkleMod = Linkle.Find(Mods, game); + var linkle = choice.Hero == "linkle"; + if (linkle && linkleMod == null) throw new OotrrException("Get Linkle first: she is a mod from GameBanana, downloaded on the Character page."); + if (choice.Empty) { Remove(game); SetLinkle(game, linkleMod, false); return null; } + // (what the colour tool dyes: all of Link's colours; for Linkle only adult hair, the game's own texture she wears) + var ootrr = new[] { "child", "adult" }.ToDictionary(a => a, a => linkle + ? (a == "adult" && choice.Of(a).TryGetValue("hair", out var hh) ? new Dictionary { ["hair"] = hh } : new Dictionary()) + : new Dictionary(choice.Of(a))); + if (ootrr.Values.Any(d => d.Count > 0) && !Tool.Have) throw new OotrrException("The colour tool is not installed yet."); + var romfs = Romfs(game); + Directory.CreateDirectory(Home); + var seed = ootrr.Values.Any(d => d.Count > 0) ? await SeedAsync(token).ConfigureAwait(false) : ""; + var work = Path.Combine(Home, "work", "apply-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(work); + var staging = Path.Combine(mods, ".colors-" + Guid.NewGuid().ToString("N")[..8]); + try + { + progress?.Invoke("Dyeing the cloth"); + var ages = new[] { "child", "adult" }.Where(a => ootrr[a].Count > 0).ToList(); + await Task.WhenAll(ages.Select(age => + { + var args = new List { "build", seed, romfs, work, age, "--host", "nx2navi", "--colors", "custom", "--no-title-logo" }; + foreach (var (part, hex) in ootrr[age]) { args.Add("--color-part"); args.Add(part + "=" + hex); } + return Tool.RunAsync(args, null, token); + })).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + + progress?.Invoke("Putting the colours in place"); + var into = Path.Combine(staging, "romfs"); + Directory.CreateDirectory(Path.Combine(into, "Model")); + Directory.CreateDirectory(Path.Combine(into, "Tex")); + var src = new FolderSource(romfs); + var zs = new Zs(src); + foreach (var age in ages) + { + var built = Path.Combine(work, age, "romfs"); + var child = age == "child"; + foreach (var f in Directory.EnumerateFiles(Path.Combine(built, "Tex"), "*.bntx.zs")) + { + var name = Path.GetFileName(f)[..^".bntx.zs".Length]; + if (linkle) { if (name == "Mt_Hairs_Player_Adult_Alb") File.Copy(f, Path.Combine(into, "Tex", Path.GetFileName(f)), true); continue; } + var mine = name.Contains("_Adult", StringComparison.Ordinal) ? !child : name.Contains("_Child", StringComparison.Ordinal) ? child + : (child ? !src.Exists("Tex/" + name + ".bntx.zs") || name.Contains("_Dark_", StringComparison.Ordinal) || name.StartsWith("Npc_Navi", StringComparison.Ordinal) : true); + if (!mine) continue; + if (child && name == ChildTile) + { + // (young Link's own copy of the tile, under a name adult Link's models do not use) + var data = Rename(zs, "Tex/" + name + ".bntx.zs", await File.ReadAllBytesAsync(f, token).ConfigureAwait(false), ChildTile, ChildTileMine); + await File.WriteAllBytesAsync(Path.Combine(into, "Tex", ChildTileMine + ".bntx.zs"), data, token).ConfigureAwait(false); + continue; + } + var to = Path.Combine(into, "Tex", Path.GetFileName(f)); + if (child && File.Exists(to)) continue; // (a map both ages write in place: adult Link's wins) + File.Copy(f, to, true); + } + var modelDir = Path.Combine(built, "Model"); + if (linkle || !Directory.Exists(modelDir)) continue; + foreach (var f in Directory.EnumerateFiles(modelDir, "*.bfres.zs")) + { + var name = Path.GetFileName(f); + var isChild = name.Contains("_Child", StringComparison.Ordinal); + var both = name.StartsWith("Npc_Navi", StringComparison.Ordinal); // (Navi: either build's, adult Link's last) + if (isChild != child && !both) continue; + var data = await File.ReadAllBytesAsync(f, token).ConfigureAwait(false); + if (child) data = Rename(zs, "Model/" + name, data, ChildTile, ChildTileMine); + await File.WriteAllBytesAsync(Path.Combine(into, "Model", name), data, token).ConfigureAwait(false); + } + } + if (linkle) + { + progress?.Invoke("Dyeing Linkle's clothes"); + using var her = Linkle.Source(linkleMod!, game); + var hzs = new Zs(her); + var written = new List(); + foreach (var age in new[] { "child", "adult" }) + { + var dyed = Linkle.Dye(her, hzs, age, choice.Of(age)); + foreach (var (tex, (writeName, bntx, _)) in dyed) + { + await File.WriteAllBytesAsync(Path.Combine(into, "Tex", writeName + ".bntx.zs"), Linkle.Pack(hzs, "Tex/" + writeName + ".bntx.zs", bntx), token).ConfigureAwait(false); + written.AddRange(Linkle.Pieces.Where(kv => kv.Key.Age == age).SelectMany(kv => kv.Value).Where(p => (p.Copy ?? p.Texture) == tex)); + } + token.ThrowIfCancellationRequested(); + } + foreach (var (model, data) in Linkle.PatchModels(her, hzs, written)) + await File.WriteAllBytesAsync(Path.Combine(into, model.Replace('/', Path.DirectorySeparatorChar)), data, token).ConfigureAwait(false); + } + if (!Directory.EnumerateFiles(into, "*", SearchOption.AllDirectories).Any()) + { + // (Linkle in her own colours: nothing to write, she only goes on) + Remove(game); + SetLinkle(game, linkleMod, linkle); + return null; + } + var opts = new JsonSerializerOptions { WriteIndented = true }; + await File.WriteAllTextAsync(Path.Combine(staging, "triforce_mod.json"), new JsonObject + { + ["name"] = "Link's colors", ["author"] = "Triforce · Character page", + }.ToJsonString(opts), token).ConfigureAwait(false); + await File.WriteAllTextAsync(Path.Combine(staging, Marker), new JsonObject + { + ["colors"] = choice.ToJson(), ["ootrr"] = Ootrr.Version, ["made"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture), + }.ToJsonString(opts), token).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + + // (in place: the old one goes aside first, the new one moves in, the old one goes; a switched-off one stays off) + var old = Applied(game); + var dest = old is { On: false } o ? o.Path : Path.Combine(mods, ModFolder); + string? aside = null; + if (old != null) + { + aside = Path.Combine(mods, ".colors-old-" + Guid.NewGuid().ToString("N")[..8]); + Directory.Move(old.Value.Path, aside); + } + try { Directory.Move(staging, dest); } + catch + { + if (aside != null) try { Directory.Move(aside, old!.Value.Path); aside = null; } catch (Exception) { } + throw; + } + if (aside != null) try { Directory.Delete(aside, true); } catch (Exception e) { ctx.Log.Write("character: the old colours' folder stays: " + e.Message); } + ctx.Log.Write("character: colours applied in " + dest); + SetLinkle(game, linkleMod, linkle); + return dest; + } + finally + { + try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch (Exception) { } + try { Directory.Delete(work, true); } catch (Exception) { } + } + } + + /// Linkle's mod on (she is played) or off (Link is). + void SetLinkle(string game, Mod? mod, bool on) + { + if (mod == null || mod.On == on) return; + Mods.SetOn(Triforce.Logic.Mods.FolderOf(game), mod, on); + ctx.Log.Write("character: Linkle " + (on ? "on" : "off")); + } + + /// Takes the colours' mod away: the game has its own colours again. + public void Remove(string game) + { + if (Mods.GameRuns(game)) throw new OotrrException("Close the game first: it reads its files when it starts."); + var old = Applied(game); + if (old == null) return; + ctx.Require(old.Value.Path); + Directory.Delete(old.Value.Path, true); + ctx.Log.Write("character: colours taken away (" + old.Value.Path + ")"); + } + + /// Takes away what a stopped apply left in the mods folder (.colors-*: never a folder the game reads). + public void LeftOvers(string game) + { + var mods = Triforce.Logic.Mods.FolderOf(game); + if (!ctx.Allowed(mods) || !Directory.Exists(mods)) return; + foreach (var d in Directory.GetDirectories(mods, ".colors-*")) + try { Directory.Delete(d, true); } catch (Exception) { } + } + + /// A .zs file with one name changed to another of the same length (every place it is written), packed again with + /// the game's dictionary for that file. + static byte[] Rename(Zs zs, string romfsPath, byte[] packed, string from, string to) + { + if (from.Length != to.Length) throw new ArgumentException("names of different lengths"); + var data = zs.Unpack(romfsPath, packed); + byte[] f = Encoding.ASCII.GetBytes(from), t = Encoding.ASCII.GetBytes(to); + var n = 0; + for (var i = data.AsSpan().IndexOf(f); i >= 0;) + { + t.CopyTo(data, i); n++; + var next = data.AsSpan(i + f.Length).IndexOf(f); + i = next < 0 ? -1 : i + f.Length + next; + } + if (n == 0) return packed; + zs.Dictionaries.TryGetValue(Zs.DictionaryFor(romfsPath), out var dict); + using var c = new Compressor(9); + if (dict != null) c.LoadDictionary(dict); + return c.Wrap(data).ToArray(); + } +} diff --git a/launcher/Logic/Character/Linkle.cs b/launcher/Logic/Character/Linkle.cs new file mode 100644 index 0000000..7861656 --- /dev/null +++ b/launcher/Logic/Character/Linkle.cs @@ -0,0 +1,167 @@ +// (Triforce, 11-29) Linkle on the Character page: "Playable Linkle - Total Conversion" by ThatGuyOnCops +// (https://gamebanana.com/mods/746375), a mod the launcher downloads from its GameBanana page on the player's word and +// installs into the mods folder like any other (its license allows downloading and installing it; nothing of it ships with +// Triforce). Choosing Link or Linkle switches that mod off or on. +// +// Her colours: the randomizer's colour tool cannot read her textures (some are uncompressed, the rest it does not edit), so +// the launcher dyes them itself (Core TextureRecolor: the same colour-band rule). Each part names the textures it dyes and the +// band of each; a texture she shares with the game's other characters is dyed as a copy of her own (a name of the same length, +// her model pointed at it). Adult hair is the game's own BC7 texture, which the colour tool does dye (LinkColors). +using System.Text; +using Triforce.Core.GameFiles; +using ZstdSharp; + +namespace Triforce.Logic; + +/// A texture a part dyes: its name, the band of the part on it, and the name of her own copy when the texture is shared +/// (the copy is written under that name and Model is pointed at it). +public sealed record LinklePiece(string Texture, ColorBand Band, string? Copy = null, string? Model = null); + +public static class Linkle +{ + public const int GameBananaId = 746375; + public const string Name = "Playable Linkle - Total Conversion"; + public const string Author = "ThatGuyOnCops"; + public const string Page = "https://gamebanana.com/mods/746375"; + /// A file only this mod has (young Linkle's model), as the Mods list keeps file names. + public const string Signature = "model/npc_kokiri_wc_002.player_linkle_child.bfres.zs"; + + const string ChildModel = "Model/Npc_Kokiri_WC_002.Player_Linkle_Child.bfres.zs"; + const string AdultModel = "Model/Player_Adult.Player_Adult.bfres.zs"; + + /// Her parts (ids as Link's where they mean the same, so a look can dress either). + public static readonly LinkPart[] Parts = + { + new("kokiri", "Outfit", "Outfit", "child", "", "#4f7d2f"), + new("kokiri", "Tunic and hood", "Outfit", "adult", "kokiri", "#3f8a2c"), + new("skirt", "Skirt (every outfit)", "Outfit", "adult", "", "#c8641e"), + new("kokiri_shirt", "Shirt and sleeves", "Outfit", "adult", "kokiri", "#d8d1bd"), + new("goron", "Goron Tunic", "Outfit", "adult", "goron", "#b3262c"), + new("zora", "Zora Tunic", "Outfit", "adult", "zora", "#2a4fb0"), + new("flowers", "Flowers", "Outfit", "child", "", "#e0b84a"), + new("shoes", "Shoes", "Leather", "child", "", "#8a7a3a"), + new("kokiri_belt", "Belts and straps", "Leather", "adult", "", "#5b3f26"), + new("boots", "Boots", "Leather", "adult", "", "#5b3f26"), + new("gloves", "Gloves", "Leather", "adult", "", "#7a5534"), + new("hair", "Hair", "Hair", "child,adult", "", "#e0b84a"), + new("navi", "Liri", "Navi", "child,adult", "", "#d8e070"), + }; + + static readonly ColorBand Green = new(70, 130, 0.15f); + /// Her adult outfit sheets (Kokiri, Goron and Zora tunics share one layout): face and hair at the top left, the + /// cape at the top right, the vest in the middle left, the shirt in the middle, the hood at the bottom left, the skirt panel + /// below the shirt. The tunic is the vest, cape and hood; the skirt its panel. + static readonly float[][] TunicRects = { new[] { 0f, .24f, .47f, .55f }, new[] { .62f, 0f, .97f, .25f }, new[] { 0f, .55f, .29f, .88f }, new[] { .29f, .55f, .50f, .80f } }; + static readonly float[][] SkirtRects = { new[] { .48f, .55f, .85f, .68f } }; + static readonly float[][] ShirtRects = { new[] { .46f, .25f, .68f, .55f }, new[] { .68f, .35f, .85f, .55f } }; + static readonly ColorBand Brown = new(8, 42, 0.18f, 0.04f, 0.6f); + + /// (age, part) to the textures it dyes. + public static readonly Dictionary<(string Age, string Part), LinklePiece[]> Pieces = new() + { + [("child", "kokiri")] = new[] { new LinklePiece("CmnTex_Chara_Mt_Cloth_Npc_Kokiri_WC_001_Alb.01", Green, "CmnTex_Chara_Mt_Cloth_Npc_Kokiri_WC_001_Alb.09", ChildModel) }, + [("child", "flowers")] = new[] { new LinklePiece("Mt_PantsParts_Player_Child_Alb", new ColorBand(28, 62, 0.25f)) }, + [("child", "shoes")] = new[] { new LinklePiece("CmnTex_Chara_Mt_Shoes_Npc_Kokiri_WC_001_Alb.03", ColorBand.All, "CmnTex_Chara_Mt_Shoes_Npc_Kokiri_WC_001_Alb.08", ChildModel) }, + [("child", "hair")] = new[] { new LinklePiece("Mt_Cloth_Parts_Player_Child_Alb", new ColorBand(30, 62, 0.15f)) }, + [("adult", "kokiri")] = new[] + { + new LinklePiece("Mt_Vest_Player_Adult_Alb", Green with { Rects = TunicRects }), + new LinklePiece("Angin_Tile_A_Alb", ColorBand.All, "Angin_Tile_K_Alb", AdultModel), + }, + // (the skirt panel in every outfit's sheet: she wears it with each tunic) + [("adult", "skirt")] = new[] + { + new LinklePiece("Mt_Vest_Player_Adult_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }), + new LinklePiece("Mt_Vest_Armor_Adult_Goron_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }), + new LinklePiece("Mt_Angin_Armor_Adult_Zora_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }), + }, + // (her shirt and sleeves: the white panel of the Kokiri outfit's own sheet; the game's Mt_Inner she wears is not it) + [("adult", "kokiri_shirt")] = new[] { new LinklePiece("Mt_Vest_Player_Adult_Alb", new ColorBand(0, 360, 0, 0.1f) { Rects = ShirtRects }) }, + [("adult", "goron")] = new[] { new LinklePiece("Mt_Vest_Armor_Adult_Goron_Alb", new ColorBand(335, 22, 0.3f) { Rects = TunicRects }) }, + [("adult", "zora")] = new[] { new LinklePiece("Mt_Angin_Armor_Adult_Zora_Alb", new ColorBand(185, 250, 0.15f) { Rects = TunicRects }) }, + [("adult", "kokiri_belt")] = new[] { new LinklePiece("Mt_Leater_Upper_Player_Adult_Alb", new ColorBand(20, 50, 0.2f, 0.04f, 0.45f)) }, + [("adult", "boots")] = new[] { new LinklePiece("Mt_Boots_Player_Adult_Alb", Brown) }, + [("adult", "gloves")] = new[] { new LinklePiece("Mt_Glove_Player_Adult_Alb", Brown) }, + [("child", "navi")] = new[] { new LinklePiece("Npc_Liri_Wings_Alb.00", new ColorBand(48, 88, 0.12f)) }, + [("adult", "navi")] = new[] { new LinklePiece("Npc_Liri_Wings_Alb.00", new ColorBand(48, 88, 0.12f)) }, + // (adult hair: the game's own Mt_Hairs_Player_Adult_Alb, dyed by the colour tool: LinkColors) + }; + + /// Her copies: the copy's name to (the model that points at it, the texture it is a copy of). + public static readonly Dictionary Copies = Pieces.Values.SelectMany(v => v) + .Where(p => p.Copy != null && p.Model != null).DistinctBy(p => p.Copy).ToDictionary(p => p.Copy!, p => (p.Model!, p.Texture), StringComparer.Ordinal); + + /// For the preview's scene: per model, the texture names her models will point at once dyed (original to copy). + public static IReadOnlyDictionary> SceneRenames { get; } = Copies + .GroupBy(kv => kv.Value.Model).ToDictionary(g => g.Key, g => (IReadOnlyDictionary)g.ToDictionary(kv => kv.Value.Original, kv => kv.Key, StringComparer.Ordinal), StringComparer.Ordinal); + + /// The texture to read for a name (a copy reads its original). + public static string Original(string name) => Copies.TryGetValue(name, out var c) ? c.Original : name; + + /// The Linkle mod in this game's mods folder (on or off), or null. + public static Mod? Find(ModManager mods, string game) + { + try + { + return mods.ListGame(game, true).FirstOrDefault(m => m.Info?.GameBananaId == GameBananaId || m.Files.Contains(Signature)); + } + catch (Exception) { return null; } + } + + /// Her files over the game's: what the game shows when the mod is on. + public static OverlaySource Source(Mod mod, string game) => + new(new FolderSource(Path.Combine(mod.Path, "romfs")), new FolderSource(Path.Combine(game, "romfs"))); + + /// Her textures dyed for one age's colours: texture name (as her models name it) to (the name it is written under, + /// the dyed BNTX, its level 0 for the preview). A texture none of the colours touch is left out. + public static Dictionary Dye(IGameSource src, Zs zs, string age, IReadOnlyDictionary colors) + { + var byTex = new Dictionary Bands)>(StringComparer.Ordinal); + foreach (var (part, hex) in colors) + { + if (!Pieces.TryGetValue((age, part), out var pieces)) continue; + foreach (var p in pieces) + { + if (!byTex.TryGetValue(p.Texture, out var e)) byTex[p.Texture] = e = (p, new List<(ColorBand, string)>()); + e.Bands.Add((p.Band, hex)); + } + } + var outp = new Dictionary(StringComparer.Ordinal); + foreach (var (tex, (piece, bands)) in byTex) + { + var path = "Tex/" + tex + ".bntx.zs"; + if (!src.Exists(path)) continue; + try + { + var (bntx, prev, _) = TextureRecolor.Recolor(zs.Unpack(path), tex, bands, piece.Copy); + outp[piece.Copy ?? tex] = (piece.Copy ?? tex, bntx, prev); + } + catch (NotSupportedException) { } + } + return outp; + } + + /// Her models pointed at her copies (only for the copies written): model path to its new packed bytes. + public static Dictionary PatchModels(IGameSource src, Zs zs, IEnumerable written) + { + var outp = new Dictionary(StringComparer.Ordinal); + foreach (var g in written.Where(p => p.Copy != null && p.Model != null).GroupBy(p => p.Model!)) + { + if (!src.Exists(g.Key)) continue; + var data = zs.Unpack(g.Key); + var n = 0; + foreach (var p in g.DistinctBy(p => p.Texture)) n += TextureRecolor.ReplaceAll(data, p.Texture, p.Copy!); + if (n > 0) outp[g.Key] = Pack(zs, g.Key, data); + } + return outp; + } + + /// A romfs file packed again with the game's dictionary for it. + public static byte[] Pack(Zs zs, string romfsPath, byte[] data) + { + zs.Dictionaries.TryGetValue(Zs.DictionaryFor(romfsPath), out var dict); + using var c = new Compressor(9); + if (dict != null) c.LoadDictionary(dict); + return c.Wrap(data).ToArray(); + } +} diff --git a/launcher/Logic/GameOptions/GameOptionsSchema.cs b/launcher/Logic/GameOptions/GameOptionsSchema.cs index 91fd659..d0fd651 100644 --- a/launcher/Logic/GameOptions/GameOptionsSchema.cs +++ b/launcher/Logic/GameOptions/GameOptionsSchema.cs @@ -776,6 +776,8 @@ public static class GameOptionsSchema PadSound("Fishing"), PadSound("Bottles"), Row(GameOptionTab.System, "Saves & reports", "Autosave", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true, "Whether the game saves by itself as you go from one area to another. Off skips those saves; saving from the pause menu still works."), + Row(GameOptionTab.System, "NFC", "Unlimited amiibo uses", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true, + "Off: each figure gives its reward once a day, as in the game. On: a figure can be scanned again at once, any number of times, and gives its reward each time (choose it again under NFC tag for each scan). Your dumps are not changed."), Row(GameOptionTab.System, "Online", "Discord status", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true, "Shows \"Playing Triforce\" and the time played in your Discord status, while Discord runs on this PC."), Row(GameOptionTab.Controls, "Controller", "Controller in background", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, false, diff --git a/launcher/Logic/Mods/ModManager.cs b/launcher/Logic/Mods/ModManager.cs index a383ad8..e40c11c 100644 --- a/launcher/Logic/Mods/ModManager.cs +++ b/launcher/Logic/Mods/ModManager.cs @@ -229,8 +229,10 @@ public sealed class ModManager // ---- on and off ---- - /// Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns its folder now. - public string SetOn(string mods, Mod mod, bool on) + /// Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns its folder now. + /// onName: switched on, the folder takes this name in place of its own without the switch (the Randomizer's seeds, which + /// must sort after the other mods: Randomizer.OnName). + public string SetOn(string mods, Mod mod, bool on, string? onName = null) { Refuse(mods); if (!Directory.Exists(mod.Path)) throw new ModsException(mod.Name + " is no longer in the mods folder."); @@ -238,7 +240,9 @@ public sealed class ModManager if (on && mod.OffAbove != null) throw new ModsException(mod.Name + " is inside the folder " + mod.OffAbove + ", whose name switches off everything in it. Take the - or _ off that folder's name."); if (on == !off) return mod.Path; - var name = on ? mod.Folder.TrimStart('-', '_') : "-" + mod.Folder; + // (an onName that would be off, or is no plain folder name, is not taken) + var own = onName is { Length: > 0 } n && n[0] != '-' && n[0] != '_' && n.IndexOfAny(new[] { '/', '\\' }) < 0 ? n : null; + var name = on ? own ?? mod.Folder.TrimStart('-', '_') : "-" + mod.Folder; if (name.Length == 0 || name[0] == '.') throw new ModsException("Without the " + mod.Folder[0] + " in front, the folder " + mod.Folder + " has no name the game looks at. Rename it by hand."); var target = Path.Combine(Path.GetDirectoryName(mod.Path)!, name); if (Directory.Exists(target) || File.Exists(target)) diff --git a/launcher/Logic/Randomizer/Randomizer.cs b/launcher/Logic/Randomizer/Randomizer.cs index b85b175..ab6fa22 100644 --- a/launcher/Logic/Randomizer/Randomizer.cs +++ b/launcher/Logic/Randomizer/Randomizer.cs @@ -4,6 +4,11 @@ // \mods\Randomizer \ootrr\seed.ootrr the seed file (its settings string inside), spoiler.txt, settings.json // \mods\Randomizer \triforce_rando.json what the page lists it by: seed, settings string, OOTRR's version // \mods\Randomizer \triforce_mod.json its name, author and page on the Mods page +// ((Triforce, 11-30) The folder is "~Randomizer ": the ~ sorts the seed after every other mod (host/mods.c: of two mods +// that carry a file, the one whose name sorts last wins it). A seed's event tables (RSDB EventSetting, GameAnalyzedEventInfo) +// register the events its chests, boss keys and Epona run; a mod that carried its own copies and sorted after "Randomizer" took +// them over, and the seed's chests did not open and its boss warp did nothing (ticket 1576351134820470917, "Song of Time Age +// Swap"). A seed made before is "Randomizer ": Use gives it the ~ when it switches it on.) // The game reads only romfs (and exefs, cheats) under a mod, so the other files lie there unread. One seed is on at a time: making // or choosing one switches the others off (ModManager's rename, "-" in front). Nothing is made while the game runs. using System.Security.Cryptography; @@ -45,6 +50,9 @@ public sealed class Randomizer public const string Marker = "triforce_rando.json"; public const string FilesFolder = "ootrr"; public const string Prefix = "Randomizer "; + /// In front of a seed's folder: it sorts after every other mod's (~ comes after the letters and digits, as the game + /// compares names). + public const string Last = "~"; readonly TriforceContext ctx; public Ootrr Tool { get; } @@ -189,10 +197,19 @@ public sealed class Randomizer var clean = string.Join(" ", new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries)).Trim('-', ' '); while (clean.Contains("--")) clean = clean.Replace("--", "-"); if (clean.Length == 0) clean = "seed"; - var name = Prefix + clean; + var name = Last + Prefix + clean; return name.Length <= 60 ? name : name.Substring(0, 60).TrimEnd(' ', '-'); } + /// The name a seed's folder takes when it is switched on: a seed made before 11-30 ("Randomizer <seed>", which + /// another mod could sort after) gets the ~ in front; null for one that keeps its name (one that has it, or one numbered on + /// the Mods page: that order is the player's). + public static string? OnName(string folder) + { + var (_, number, name) = Mods.Parse(folder); + return number == null && name.StartsWith(Prefix, StringComparison.Ordinal) ? Last + name : null; + } + /// A folder name for a new seed that no folder of the mods folder has yet, on or off (" 2", " 3" ... after it). internal static string FreeName(string mods, string name) { @@ -367,7 +384,7 @@ public sealed class Randomizer foreach (var other in Seeds(game).Where(x => x.Mod.On && x.Mod.Rel != seed.Mod.Rel)) Manager.SetOn(mods, other.Mod, false); // (switching the others off renames only their folders: this one is where it was) var now = Seeds(game).FirstOrDefault(x => x.Mod.Rel == seed.Mod.Rel) ?? seed; - return now.Mod.On ? now.Mod.Path : Manager.SetOn(mods, now.Mod, true); + return now.Mod.On ? now.Mod.Path : Manager.SetOn(mods, now.Mod, true, OnName(now.Mod.Folder)); } /// Switches every seed off: the game is the plain game again. diff --git a/launcher/Logic/Triforce.Logic.csproj b/launcher/Logic/Triforce.Logic.csproj index 256cefa..814c781 100644 --- a/launcher/Logic/Triforce.Logic.csproj +++ b/launcher/Logic/Triforce.Logic.csproj @@ -21,6 +21,11 @@ + + + + + diff --git a/launcher/LogicTests/Tests.GameOptions.cs b/launcher/LogicTests/Tests.GameOptions.cs index f4a75ce..a766419 100644 --- a/launcher/LogicTests/Tests.GameOptions.cs +++ b/launcher/LogicTests/Tests.GameOptions.cs @@ -256,7 +256,8 @@ static partial class Tests Equal("Evil HD,This PC,Upscaling,Anti-aliasing,N64 Classic,Frame generation,Frame rate & latency,Textures,Post-processing,Detail,Advanced", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Graphics)), "Graphics' sections"); Equal("Controller,Mouse & keyboard,Rumble,Gameplay,Motion,Hold to toggle,Controls", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Controls)), "Controls' sections"); Equal("Sound,Microphone,Controller speaker", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Audio)), "Audio's sections"); - Equal("Achievements,Game,Saves & reports,Online", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.System)), "System's sections (with rows)"); + // ((Triforce) NFC: its Unlimited amiibo uses row; the NFC tag row before it opens a page, not a value) + Equal("Achievements,Game,Saves & reports,NFC,Online", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.System)), "System's sections (with rows)"); string L(string key, int v) => GameOptionsSchema.Get(key).Label(v); string Cs(string key) => string.Join("|", GameOptionsSchema.Get(key).Choices.Select(c => c.Value + "=" + c.Label)); diff --git a/launcher/LogicTests/Tests.Randomizer.cs b/launcher/LogicTests/Tests.Randomizer.cs index 309f3e8..ff0d618 100644 --- a/launcher/LogicTests/Tests.Randomizer.cs +++ b/launcher/LogicTests/Tests.Randomizer.cs @@ -195,10 +195,10 @@ static partial class Tests static void RandoNames() { - Equal("Randomizer K7QW2MPA", Randomizer.FolderName("K7QW2MPA"), "a plain seed"); - Equal("Randomizer my seed for Saturday", Randomizer.FolderName(" my_seed.for Saturday "), "space, _ and . become spaces"); - Equal("Randomizer a-b-c", Randomizer.FolderName("a/b\\c"), "path characters cannot leave the folder"); - Equal("Randomizer seed", Randomizer.FolderName("::"), "nothing left: seed"); + Equal("~Randomizer K7QW2MPA", Randomizer.FolderName("K7QW2MPA"), "a plain seed"); + Equal("~Randomizer my seed for Saturday", Randomizer.FolderName(" my_seed.for Saturday "), "space, _ and . become spaces"); + Equal("~Randomizer a-b-c", Randomizer.FolderName("a/b\\c"), "path characters cannot leave the folder"); + Equal("~Randomizer seed", Randomizer.FolderName("::"), "nothing left: seed"); Check(Randomizer.FolderName(new string('x', 300)).Length <= 60, "a long seed is cut"); Check(Randomizer.FolderName("../../x").IndexOf("..", StringComparison.Ordinal) < 0, "no .. in a name"); var root = NewRoot("rando-names"); @@ -310,7 +310,7 @@ static partial class Tests var made = await r.MakeAsync(game, s, values, "Saturday race!", new RandoCosmetics("grouped", "off", "random", false), lines.Add, CancellationToken.None, "Easy"); Check(!Directory.EnumerateDirectories(Path.Combine(game, "mods"), Randomizer.Making + "*").Any(), "no build folder left, the old one taken away"); Equal("Easy", made.Seed.Preset, "the preset it went by, kept"); - var folder = Path.Combine(game, "mods", "Randomizer Saturday race!"); + var folder = Path.Combine(game, "mods", "~Randomizer Saturday race!"); Equal(folder, made.Seed.Mod.Path, "the seed's folder"); Check(made.Seed.Mod.On, "on"); Equal("flow of Saturday race!", File.ReadAllText(Path.Combine(folder, "romfs", "Event", "EventFlow", "Dm_Kokiri_0000.bfevfl.zs")), "the seed's game files"); @@ -333,27 +333,56 @@ static partial class Tests // (a second seed: on, the first off; the same seed again gets a folder of its own) var second = await r.MakeAsync(game, s, s.Defaults(), "Saturday race!", new RandoCosmetics(), null, CancellationToken.None); - Equal("Randomizer Saturday race! 2", second.Seed.Mod.Name, "the same seed's second folder"); + Equal("~Randomizer Saturday race! 2", second.Seed.Mod.Name, "the same seed's second folder"); var seeds = r.Seeds(game); Equal(2, seeds.Count, "two seeds"); Equal(1, seeds.Count(x => x.Mod.On), "one on"); - Check(seeds.Single(x => x.Mod.On).Mod.Name == "Randomizer Saturday race! 2", "the new one"); - Check(Directory.Exists(Path.Combine(game, "mods", "-Randomizer Saturday race!")), "the first switched off by its folder's name"); + Check(seeds.Single(x => x.Mod.On).Mod.Name == "~Randomizer Saturday race! 2", "the new one"); + Check(Directory.Exists(Path.Combine(game, "mods", "-~Randomizer Saturday race!")), "the first switched off by its folder's name"); r.Use(game, seeds.Single(x => !x.Mod.On)); - Equal("Randomizer Saturday race!", r.Seeds(game).Single(x => x.Mod.On).Mod.Name, "Use: that one on, the other off"); + Equal("~Randomizer Saturday race!", r.Seeds(game).Single(x => x.Mod.On).Mod.Name, "Use: that one on, the other off"); r.Off(game); Check(r.Seeds(game).All(x => !x.Mod.On), "Off: every seed off"); - r.Remove(game, r.Seeds(game).First(x => x.Mod.Name == "Randomizer Saturday race! 2")); + r.Remove(game, r.Seeds(game).First(x => x.Mod.Name == "~Randomizer Saturday race! 2")); Equal(1, r.Seeds(game).Count, "removed"); Check(Directory.EnumerateDirectories(Path.Combine(game, "mods", Mods.Removed)).Any(), "into mods\\.removed"); - // (another mod that is on and carries one of the seed's files, sorting after it, wins it: said) + // (another mod that is on and carries one of the seed's files: the seed sorts after it and wins, unnumbered names after + // "Randomizer" included (11-30, ticket 1576351134820470917: "Song of Time Age Swap" took the seed's event tables, its + // chests stayed shut) r.Use(game, r.Seeds(game).Single()); - var other = Path.Combine(game, "mods", "Tall grass", "romfs", "Event", "EventFlow"); + var other = Path.Combine(game, "mods", "Song of Time Age Swap", "romfs", "RSDB"); Directory.CreateDirectory(other); - File.WriteAllText(Path.Combine(other, "Dm_Kokiri_0000.bfevfl.zs"), "other"); + File.WriteAllText(Path.Combine(other, "EventSetting.Product.111.rstbl.byml.zs"), "other"); + var seedRsdb = Path.Combine(r.Seeds(game).Single().Mod.Path, "romfs", "RSDB"); + Directory.CreateDirectory(seedRsdb); + File.WriteAllText(Path.Combine(seedRsdb, "EventSetting.Product.111.rstbl.byml.zs"), "seed's"); var shared = r.Shared(game, r.Seeds(game).Single().Mod.Rel); - Check(shared.Count == 1 && shared[0].Name == "Tall grass" && shared[0].Wins, "the other mod that wins a file"); + Check(shared.Count == 1 && shared[0].Name == "Song of Time Age Swap" && !shared[0].Wins, "the seed wins its event table: " + string.Join(";", shared)); + Equal("seed's", File.ReadAllText(r.Manager.RomfsFile(game, "RSDB/EventSetting.Product.111.rstbl.byml.zs")!), "the file the game takes is the seed's"); + // (a mod whose name sorts after ~ still can: that is said) + var after = Path.Combine(game, "mods", "Über grass", "romfs", "Event", "EventFlow"); + Directory.CreateDirectory(after); + File.WriteAllText(Path.Combine(after, "Dm_Kokiri_0000.bfevfl.zs"), "other"); + shared = r.Shared(game, r.Seeds(game).Single().Mod.Rel); + Check(shared.Any(x => x.Name == "Über grass" && x.Wins), "the other mod that wins a file"); + Directory.Delete(Path.Combine(game, "mods", "Über grass"), true); + Directory.Delete(Path.Combine(game, "mods", "Song of Time Age Swap"), true); + + // (a seed made before 11-30, "Randomizer ": switched on, it gets the ~; one numbered on the Mods page keeps its place) + Equal("~Randomizer Old", Randomizer.OnName("-Randomizer Old"), "an old seed's folder"); + Equal(null, Randomizer.OnName("-~Randomizer New"), "a new one keeps its name"); + Equal(null, Randomizer.OnName("-04-Randomizer Ordered"), "a numbered one keeps its name"); + Equal(null, Randomizer.OnName("-Tall grass"), "not a seed's name"); + var oldSeed = Path.Combine(game, "mods", "-Randomizer Old"); + Directory.CreateDirectory(Path.Combine(oldSeed, "romfs", "Event")); + File.WriteAllText(Path.Combine(oldSeed, "romfs", "Event", "x.zs"), "old"); + File.WriteAllText(Path.Combine(oldSeed, Randomizer.Marker), "{\"seed\":\"Old\"}"); + var onOld = r.Use(game, r.Seeds(game).Single(x => x.Seed == "Old")); + Equal(Path.Combine(game, "mods", "~Randomizer Old"), onOld, "the old seed switched on under the ~ name"); + Check(r.Seeds(game).Single(x => x.Mod.On).Seed == "Old", "and it is the one on"); + r.Use(game, r.Seeds(game).Single(x => x.Seed != "Old")); + r.Remove(game, r.Seeds(game).Single(x => x.Seed == "Old")); // (a seed whose other seed cannot be switched off: it is made, and stays off; never two seeds on) var onNow = r.Seeds(game).Single(x => x.Mod.On); @@ -361,7 +390,7 @@ static partial class Tests var stuck = await ThrowsAsync(() => r.MakeAsync(game, s, s.Defaults(), "Sunday", new RandoCosmetics(), null, CancellationToken.None), "the other seed cannot be switched off"); Check(stuck.Message.StartsWith("Seed Sunday is made, but it stays off: ", StringComparison.Ordinal), "said: " + stuck.Message); Equal(1, r.Seeds(game).Count(x => x.Mod.On), "still one seed on"); - Check(r.Seeds(game).Single(x => x.Seed == "Sunday") is { Mod.On: false } sunday && sunday.Mod.Folder == "-Randomizer Sunday", "the new one is there, off"); + Check(r.Seeds(game).Single(x => x.Seed == "Sunday") is { Mod.On: false } sunday && sunday.Mod.Folder == "-~Randomizer Sunday", "the new one is there, off"); Directory.Delete(Path.Combine(game, "mods", "-" + onNow.Mod.Folder)); r.Use(game, r.Seeds(game).Single(x => x.Seed == "Sunday")); Check(r.Seeds(game).Single(x => x.Mod.On).Seed == "Sunday", "and can be switched on once that is fixed"); @@ -399,12 +428,12 @@ static partial class Tests var s = await r.SchemaAsync(CancellationToken.None); var e = await ThrowsAsync(() => r.MakeAsync(game, s, s.Defaults(), "fail", new RandoCosmetics(), null, CancellationToken.None), "generate fails"); Equal("The randomizer stopped: no placement could be found", e.Message, "OOTRR's own error"); - Check(!Directory.Exists(Path.Combine(game, "mods", "Randomizer fail")), "no folder left"); + Check(!Directory.Exists(Path.Combine(game, "mods", Randomizer.FolderName("fail"))), "no folder left"); // (stopped while the build writes, a file of its own held open: the program is gone before its folder is taken away) using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60))) await ThrowsAsync(() => r.MakeAsync(game, s, s.Defaults(), "slow", new RandoCosmetics(), l => { if (l == "Writing flows") cts.Cancel(); }, cts.Token), "stopped part way"); - Check(!Directory.Exists(Path.Combine(game, "mods", "Randomizer slow")) && !Directory.Exists(Path.Combine(game, "mods", "-Randomizer slow")), "a stopped build leaves no half-made seed"); + Check(!Directory.Exists(Path.Combine(game, "mods", Randomizer.FolderName("slow"))) && !Directory.Exists(Path.Combine(game, "mods", "-" + Randomizer.FolderName("slow"))), "a stopped build leaves no half-made seed"); Check(!Directory.EnumerateDirectories(Path.Combine(game, "mods"), Randomizer.Making + "*").Any(), "nor its build folder (the file it held let go)"); await ThrowsAsync(() => r.MakeAsync(game, s, s.Defaults(), "two\nlines", new RandoCosmetics(), null, CancellationToken.None), "a line break in a seed"); await ThrowsAsync(() => r.MakeAsync(game, s, s.Defaults(), new string('x', Randomizer.MaxSeed + 1), new RandoCosmetics(), null, CancellationToken.None), "a seed too long"); @@ -412,7 +441,7 @@ static partial class Tests full.FreeBytes = _ => 10L << 20; var cramped = new Randomizer(full, null, new ModManager(full) { GameRuns = _ => false }); var room = await ThrowsAsync(() => cramped.MakeAsync(game, s, s.Defaults(), "room", new RandoCosmetics(), null, CancellationToken.None), "a disk without room"); - Check(room.Message.Length > 0 && !Directory.Exists(Path.Combine(game, "mods", "Randomizer room")), "refused before anything is written: " + room.Message); + Check(room.Message.Length > 0 && !Directory.Exists(Path.Combine(game, "mods", Randomizer.FolderName("room"))), "refused before anything is written: " + room.Message); // (the check before a seed: what OOTRR refuses, in the settings' words; nothing written in the mods folder) var refused = s.Defaults(); diff --git a/launcher/ui/app.js b/launcher/ui/app.js index 9f07a40..14de04f 100644 --- a/launcher/ui/app.js +++ b/launcher/ui/app.js @@ -235,9 +235,9 @@ document.addEventListener('pointerdown', e => { }); /* ---------------- screens ---------------- */ -const MAIN = ['home', 'mods', 'rando', 'saves', 'settings']; +const MAIN = ['home', 'mods', 'rando', 'char', 'saves', 'settings']; const FIRST_RUN = ['welcome', 'reveal', 'done']; -const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', rando: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null }; +const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', rando: 'fairy', char: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null }; let screen = null; function go(name) { if (name === screen || !$('#s-' + name)) return; @@ -256,6 +256,7 @@ function go(name) { if (name === 'mods' && !S.mods.loaded) cmd('mods.list', { tab: S.mods.tab, q: '' }); if (name === 'saves') cmd('saves.list'); if (name === 'rando') cmd('rando.open'); + if (typeof charShown === 'function') charShown(name); // (the Character page: char.js) cmd('screen', { s: name }); } function afterOneShot(name) { if (name === 'itemget' && (MUSIC[screen] === 'fairy' || screen === 'done')) music('fairy'); } @@ -884,6 +885,7 @@ onHost(m => { if (m.rando && m.rando.schema) S.randoSchema = m.rando.schema; // (OOTRR's settings come once; the rows every time) if (m.randoMade) S.rtab = 'seeds'; if ((m.rando || m.randoMade) && typeof drawRando === 'function') drawRando(); + if (m.char && typeof drawChar === 'function') drawChar(); if (m.done) { $('#doneEb').textContent = S.done.eb || ''; $('#doneLead').textContent = S.done.lead || ''; } break; } @@ -896,6 +898,7 @@ onHost(m => { case 'choice': openChoice(m); break; case 'ask': openAsk(m); break; case 'bench': onBench(m); break; + case 'charLook': case 'charExact': case 'charCal': if (typeof charMessage === 'function') charMessage(m); break; case 'copy': navigator.clipboard && navigator.clipboard.writeText(m.text).then(() => toast('Copied'), () => toast('Could not copy')); break; } }); @@ -906,7 +909,7 @@ document.addEventListener('keydown', e => { if (document.activeElement && document.activeElement.tagName === 'INPUT' && !['Escape', 'Enter', 'ArrowDown', 'ArrowUp', 'Tab'].includes(e.key)) return; const k = e.key; let used = true; const ca = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] }[k]; - if (ca && colorNudge(ca[0], ca[1])) { } // (the colour picker's square and hue take the arrows first) + if (ca && (colorNudge(ca[0], ca[1]) || (typeof charNudge === 'function' && charNudge(ca[0], ca[1])))) { } // (the colour picker's square and hue take the arrows first) else if (focused && focused.dataset.vol && (k === 'ArrowLeft' || k === 'ArrowRight')) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + (k === 'ArrowLeft' ? -.05 : .05)); sfx('cursor'); } else if (focused && (focused.dataset.gkey || focused.dataset.rkey) && (k === 'ArrowLeft' || k === 'ArrowRight')) gNudge(k === 'ArrowLeft' ? -1 : 1); else if (k === 'ArrowLeft') move(-1, 0); else if (k === 'ArrowRight') move(1, 0); @@ -927,10 +930,11 @@ function pad(t) { const gp = [...(navigator.getGamepads ? navigator.getGamepads() : [])].find(g => g && g.connected); if (!gp) return; const B = i => gp.buttons[i] && gp.buttons[i].pressed; const edge = (i, fn) => { const p = B(i); if (p && !held[i]) { document.body.classList.add('kb'); unlocked = true; fn(); } held[i] = p; }; - const slide = d => { if (colorNudge(d, 0)) return true; if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); }; + const slide = d => { if (colorNudge(d, 0) || (typeof charNudge === 'function' && charNudge(d, 0))) return true; if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); }; edge(0, () => activate(focused)); edge(1, back); edge(4, () => tab(-1)); edge(5, () => tab(1)); edge(3, toggleMute); edge(9, () => { if (MAIN.includes(screen)) go('settings'); }); - edge(12, () => colorNudge(0, 1) || move(0, -1)); edge(13, () => colorNudge(0, -1) || move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0)); + const cn = (dx, dy) => colorNudge(dx, dy) || (typeof charNudge === 'function' && charNudge(dx, dy)); + edge(12, () => cn(0, 1) || move(0, -1)); edge(13, () => cn(0, -1) || move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0)); const x = gp.axes[0] || 0, y = gp.axes[1] || 0, dir = Math.abs(x) > .55 ? (x > 0 ? 'r' : 'l') : Math.abs(y) > .55 ? (y > 0 ? 'd' : 'u') : ''; if (dir && (dir !== stickDir || t - stickAt > 220)) { document.body.classList.add('kb'); stickAt = t + (dir !== stickDir ? 160 : 0); diff --git a/launcher/ui/char.css b/launcher/ui/char.css new file mode 100644 index 0000000..0e48d2e --- /dev/null +++ b/launcher/ui/char.css @@ -0,0 +1,101 @@ +/* ((Triforce, 11-29) The Character page: Link on a lit stage at the left, his colors in a panel at the right. On top of + ui.css, theme.css, v3.css, proto.css and app.css (the picker reuses app.css's .cp-sv / .cp-hue / .cp-f). */ +#s-char { background: + radial-gradient(520px 600px at 360px 520px, rgba(var(--gold-warm-rgb), .16) 0%, rgba(var(--gold-warm-rgb), .05) 38%, rgba(0, 0, 0, 0) 70%), + radial-gradient(900px 760px at 360px 420px, #1d1710 0%, #110e0a 52%, var(--ink) 82%); } +/* the stage: Link's canvas, under the title; a soft light from above behind him */ +.chstage { position: absolute; left: 170px; top: 44px; width: 590px; height: 756px; } +.chstage canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; + -webkit-mask: linear-gradient(90deg, transparent 0, #000 9%, #000 91%, transparent 100%); mask: linear-gradient(90deg, transparent 0, #000 9%, #000 91%, transparent 100%); } +.chstage canvas.grab { cursor: grabbing; } +.chglow { position: absolute; left: 125px; top: 0; width: 340px; height: 520px; pointer-events: none; + background: radial-gradient(closest-side, rgba(var(--gold-lit-rgb), .07), rgba(var(--gold-lit-rgb), 0)); mix-blend-mode: screen; } + +.chhead { position: absolute; left: 64px; top: 96px; z-index: 2; pointer-events: none; } +.chhead > * { pointer-events: auto; } +.chhead .cont h1 { text-shadow: 0 2px 18px rgba(0, 0, 0, .75); } +/* young / adult: two halves of one gold-edged bar */ +.chseg { display: inline-flex; margin-top: 18px; border: 1px solid rgba(var(--gold-rgb), .45); background: rgba(10, 9, 8, .55); } +.chseg span { padding: 9px 20px; font-size: 15px; font-weight: 600; color: var(--text2); cursor: pointer; transition: background .15s, color .15s; } +.chseg span + span { border-left: 1px solid rgba(var(--gold-rgb), .3); } +.chseg span.on { color: var(--gold-ink2); background: linear-gradient(180deg, rgb(var(--gold-bar-hi-rgb)), rgb(var(--gold-bar-rgb)) 55%, rgb(var(--gold-bar-low-rgb))); } +.chseg span:not(.on):hover { color: var(--gold-hi); } +/* the adult's tunic: three small diamonds-and-words under it */ +.chtunic { display: flex; gap: 20px; margin-top: 14px; font-size: 14px; color: var(--text3); } +.chtunic span { position: relative; padding: 4px 0 6px 18px; cursor: pointer; } +.chtunic span::before { content: ''; position: absolute; left: 1px; top: 10px; width: 8px; height: 8px; transform: rotate(45deg); border: 1px solid rgba(var(--gold-rgb), .55); } +.chtunic span:nth-child(1)::before { background: #2f8f3a; } .chtunic span:nth-child(2)::before { background: #b3262c; } .chtunic span:nth-child(3)::before { background: #2a4fb0; } +.chtunic span.on { color: var(--gold-hi); font-weight: 600; box-shadow: inset 0 -2px 0 var(--gold); } +.chtunic span:not(.on):hover { color: var(--text); } + +/* under the stage: turn him, look at his face */ +.chview { position: absolute; left: 64px; bottom: 30px; display: flex; align-items: center; gap: 18px; font-size: 14px; z-index: 2; } +.chview .lnk { color: var(--gold); font-weight: 600; cursor: pointer; padding: 4px 2px; } +.chview #chTurnL, .chview #chTurnR { font-size: 12px; } +.chview em { font-style: normal; color: var(--text3); font-size: 13px; margin-left: 6px; } +.chwait { position: absolute; left: 170px; top: 330px; width: 590px; display: none; flex-direction: column; align-items: center; gap: 16px; color: var(--text2); font-size: 15px; pointer-events: none; } +.chwait.on { display: flex; } +.chwait.err .chspin { display: none; } +.chwait.err span { max-width: 420px; text-align: center; color: var(--text3); } +.chspin { width: 30px; height: 30px; transform: rotate(45deg); border: 2px solid rgba(var(--gold-rgb), .25); border-top-color: var(--gold-hi); animation: chspin 1.1s linear infinite; } +.chspin.sm { display: inline-block; width: 11px; height: 11px; margin: 0 10px -1px 0; border-width: 1.5px; vertical-align: 0; } +@keyframes chspin { to { transform: rotate(405deg); } } + +/* the panel */ +.chpanel { position: absolute; right: 48px; top: 96px; bottom: 26px; width: 468px; display: flex; flex-direction: column; padding: 22px 26px 20px; } +.chtop { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; } +.chtop h3 { font-family: 'Cormorant Garamond', Georgia, serif; font-weight: 700; font-size: 27px; color: var(--text); } +.chstate { font-size: 13px; color: var(--text3); white-space: nowrap; } +.chlooks { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0 6px; } +.chlooks span { padding: 5px 12px; font-size: 13px; font-weight: 600; color: var(--text2); border: 1px solid rgba(var(--gold-rgb), .28); background: rgba(243, 234, 213, .04); cursor: pointer; transition: border-color .15s, color .15s; } +.chlooks span:hover { border-color: rgba(var(--gold-rgb), .7); color: var(--text); } +.chlooks span.on { border-color: var(--gold-hi); color: var(--gold-hi); background: rgba(var(--gold-rgb), .1); } +.chlist { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; margin: 6px -12px 0 0; padding: 0 12px 8px 0; scrollbar-width: thin; scrollbar-color: rgba(var(--gold-rgb), .45) transparent; } +.chlist::-webkit-scrollbar { width: 6px; } .chlist::-webkit-scrollbar-track { background: transparent; } +.chlist::-webkit-scrollbar-thumb { background: rgba(var(--gold-rgb), .38); } .chlist::-webkit-scrollbar-thumb:hover { background: rgba(var(--gold-rgb), .6); } +.chlist h4 { margin: 14px 0 2px; font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-weight: 600; font-size: 17px; color: var(--gold-hi); } +.chrow { display: grid; grid-template-columns: 30px 1fr auto 56px; align-items: center; gap: 12px; padding: 11px 2px; border-bottom: 1px solid var(--line-soft); font-size: 15px; cursor: pointer; } +.chrow b { font-weight: 600; } .chrow > span { color: var(--text2); font-size: 13.5px; font-variant-numeric: tabular-nums; letter-spacing: .02em; } +.chrow > span u { display: inline-block; width: 6px; height: 6px; margin-left: 8px; transform: rotate(45deg) translateY(-2px); background: var(--gold-hi); text-decoration: none; } +.chrow em { font-style: normal; color: var(--gold); font-weight: 600; font-size: 14px; text-align: right; } +.chrow.open { border-bottom-color: transparent; } .chrow.open em { color: var(--gold-hi); } +.chrow:hover b { color: var(--gold-hi); } +.chsw { width: 18px; height: 18px; margin-left: 5px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 1px rgba(243, 234, 213, .35), 0 0 0 3px rgba(10, 9, 8, .9); } +.chsw.orig { box-shadow: 0 0 0 1px rgba(243, 234, 213, .18), 0 0 0 3px rgba(10, 9, 8, .9); opacity: .78; } +.chnote { margin-top: 14px !important; } + +/* the picker under the open row */ +.chpick { display: grid; grid-template-columns: 188px 1fr; gap: 22px; min-width: 0; padding: 8px 2px 18px; border-bottom: 1px solid var(--line-soft); animation: chopen .2s ease; } +@keyframes chopen { from { opacity: 0; transform: translateY(-4px); } } +.chsv { height: 118px; } +.chhue { margin-top: 24px; } +.chpk-r { min-width: 0; } +.chpick label { display: block; font-family: Commissioner, sans-serif; font-style: normal; font-weight: 600; font-size: 13px; color: var(--text3); } +.chpk-r .cp-f input#chHex { width: 112px; font-family: Commissioner, sans-serif; font-style: normal; letter-spacing: .03em; text-transform: uppercase; display: block; height: 36px; margin-top: 5px; padding: 0 12px; font: inherit; font-size: 14.5px; color: var(--text); + background: rgba(243, 234, 213, .05); border: 1px solid rgba(var(--gold-rgb), .35); outline: none; } +.chpk-r .cp-f input#chHex:focus { border-color: var(--gold-hi); } .chpk-r .cp-f input#chHex.bad { border-color: #ff8a92; color: #ffd6d9; } +.chpre { display: grid; grid-template-columns: repeat(8, 14px); gap: 12px 10px; margin: 16px 0 0 4px; } +.chpre span { width: 13px; height: 13px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 1px rgba(243, 234, 213, .25), 0 0 0 3px rgba(10, 9, 8, .9); cursor: pointer; } +.chpre span.on { box-shadow: 0 0 0 2px var(--text), 0 0 0 4px rgba(10, 9, 8, .9); } +.chpk-r .cp-foot { margin-top: 14px; gap: 10px; } .chpk-r .cp-foot .lnk { white-space: nowrap; } + +/* the foot: where the picks stand, and Apply */ +.chfoot { padding-top: 14px; border-top: 1px solid rgba(var(--gold-rgb), .25); } +.chmsg { font-size: 13.5px; color: var(--text2); line-height: 1.45; } +.chmsg.pend { color: var(--gold-hi); } +.chmsg.warn { color: var(--text3); font-size: 12.5px; margin-top: 4px; } +.chbtns { display: flex; align-items: center; justify-content: flex-end; gap: 22px; margin-top: 12px; } +.chbtns .lnk { color: var(--gold); font-weight: 600; font-size: 14px; cursor: pointer; } +.chbtns .play.sm { width: 230px; height: 50px; font-size: 21px; margin: 0; } +.chbtns .play.off { filter: saturate(.25) brightness(.6); cursor: default; } +.chbar { height: 3px; margin-top: 10px; background: rgba(var(--gold-rgb), .15); } .chbar i { display: block; height: 100%; background: var(--gold-hi); } +.chdye { display: none; color: var(--gold-hi); font-size: 13px; font-weight: 600; margin-left: 8px; } .chdye.on { display: inline-flex; align-items: center; } +/* Link or Linkle: above the ages, the same bar a little smaller */ +.chhero { display: flex; width: max-content; margin-top: 16px; } .chhero span { padding: 7px 18px; font-size: 14px; } +.chhero + .chseg { margin-top: 10px; } +/* Linkle not downloaded yet: her card on the stage */ +.chget { position: absolute; left: 230px; top: 300px; width: 470px; padding: 24px 28px; display: none; z-index: 3; } +.chget.on { display: block; } +.chget h3 { font-family: 'Cormorant Garamond', Georgia, serif; font-weight: 700; font-size: 27px; } +.chget p { margin-top: 8px; font-size: 14px; line-height: 1.5; color: var(--text2); } +.chget .chbtns { margin-top: 16px; } diff --git a/launcher/ui/char.js b/launcher/ui/char.js new file mode 100644 index 0000000..8775f3b --- /dev/null +++ b/launcher/ui/char.js @@ -0,0 +1,353 @@ +/* ((Triforce, 11-29) The Character page: Link in 3D (char3d.js) from the player's own game, young or adult (Kokiri, Goron or + Zora tunic), and his colors (launcher/App/Backend.Character.cs, launcher/Logic/Character/LinkColors.cs). The launcher sends + state.char: game, tool {have, busy, frac, size}, parts [{id, label, group, ages, tunic, swatch}], colors {child, adult} + (the picks), applied {child, adult} | null (what the game has), appliedOn, same, busy, line, calBusy, others; and the + messages charLook {look, n, error?} (the look's files are ready), charCal {maps [{tex, file, parts, yref}]} (where each + part lies on each colour map) and charExact {age, n, colors, tex} (OOTRR's own recoloured maps for those colours). + A pick shows at once as a tint over the calibration mask, then OOTRR's exact map takes its place. Uses app.js's $, $$, S, + ACTIONS, cmd, sfx, esc, toast and its colour helpers. */ +'use strict'; +const CH = { + age: 'child', tunic: 'kokiri', open: null, h: 0, s: 0, v: 0, + viewer: null, look: null, want: null, n: 0, have: new Set(), sceneTex: new Set(), loading: false, error: '', + cal: null, masks: new Set(), exact: { child: null, adult: null }, cmKey: new Map(), + colors: { child: {}, adult: {}, 'linkle:child': {}, 'linkle:adult': {} }, touchedAt: 0, sendT: 0, face: false, hero: 'link', +}; +/* swatches in the picker: the game's tunics first, then a spread */ +const CH_SWATCH = [['#2f8f3a', 'Kokiri green'], ['#b3262c', 'Goron red'], ['#2a4fb0', 'Zora blue'], ['#1f5e2e', 'Deep forest'], ['#7d1622', 'Crimson'], + ['#1c2a52', 'Midnight'], ['#4b2a84', 'Royal purple'], ['#2a8f8a', 'Lake teal'], ['#d4a634', 'Triforce gold'], ['#c8641e', 'Ember'], + ['#d86a9a', 'Fairy pink'], ['#ebe7de', 'Snow'], ['#a7abb3', 'Silver'], ['#6b4a2b', 'Leather'], ['#2b2b2e', 'Charcoal'], ['#121214', 'Shadow']]; +/* whole looks: each names what it changes; Original takes every part back to the game's colour */ +const CH_LOOKS = [ + { id: 'original', name: 'Original', c: {} }, + { id: 'midnight', name: 'Midnight', c: { kokiri: '#1f2b4d', kokiri_pants: '#2b3352', kokiri_shirt: '#cfc8b8', kokiri_belt: '#3b2a1f', leather_trim: '#8a1f2b', boots: '#2a1d15', gloves: '#2a1d15', feathers: '#e9e5dc', goron: '#33204a', goron_trim: '#c9a24a', zora: '#1c2448', zora_shirt: '#cfd3da' } }, + { id: 'crimson', name: 'Crimson', c: { kokiri: '#8e1b22', kokiri_pants: '#5a1a1a', kokiri_shirt: '#e6dcc8', kokiri_belt: '#3b2416', leather_trim: '#d4a634', boots: '#3b2416', gloves: '#3b2416', feathers: '#f2ead8', zora: '#7a1a2a' } }, + { id: 'royal', name: 'Royal', c: { kokiri: '#3b2a7a', kokiri_pants: '#2e2458', kokiri_shirt: '#ece3cf', kokiri_belt: '#4a2f1d', leather_trim: '#d4a634', feathers: '#f5e6b0', goron: '#4b2a84', goron_trim: '#e0b84a', zora: '#3b2a7a' } }, + { id: 'snow', name: 'Snow', c: { kokiri: '#e8e6df', kokiri_pants: '#cfcac0', kokiri_shirt: '#f4f1ea', kokiri_belt: '#8a6a4a', leather_trim: '#b8963e', boots: '#e0dbd0', gloves: '#e0dbd0', feathers: '#ffffff', goron: '#e8e6df', zora: '#e8eef4' } }, + { id: 'shadow', name: 'Shadow', c: { kokiri: '#1b1b1e', kokiri_pants: '#222226', kokiri_shirt: '#3a3a3e', kokiri_belt: '#141414', leather_trim: '#6a0f18', boots: '#111113', gloves: '#111113', feathers: '#2a2a2e', hair: '#e8e8ea', goron: '#1b1b1e', zora: '#1b1b1e' } }, + { id: 'random', name: 'Random', c: null }, +]; + +function chS() { return S.char || {}; } +function chLook() { return CH.age === 'child' ? 'child' : CH.tunic === 'kokiri' ? 'adult' : 'adult-' + CH.tunic; } +/* a colour set's key: the age, "linkle:" in front for her */ +function chKey(age) { return (CH.hero === 'linkle' ? 'linkle:' : '') + (age || CH.age); } +function chCur() { return CH.colors[chKey()] || (CH.colors[chKey()] = {}); } +function chLinkle() { return chS().linkle || {}; } +function chHeroName() { return CH.hero === 'linkle' ? 'Linkle' : 'Link'; } +function chParts() { + return (chS().parts || []).filter(p => p.ages.split(',').includes(CH.age) && (CH.age === 'child' || !p.tunic || p.tunic === CH.tunic)); +} +function chLin(hex) { return hexRgb(hex).map(x => { x /= 255; return x <= .04045 ? x / 12.92 : ((x + .055) / 1.055) ** 2.4; }); } + +/* ---------------- the stage ---------------- */ +function chViewer() { + if (CH.viewer) return CH.viewer; + const c = $('#chCanvas'); + try { CH.viewer = window.Char3D && Char3D.create(c); } catch (e) { CH.viewer = null; console.error(e); } + if (!CH.viewer) { CH.error = 'This PC\'s browser engine has no WebGL 2, so Link cannot be drawn here. Colors still apply.'; drawChar(); } + new ResizeObserver(() => CH.viewer && CH.viewer.resize()).observe(c); + return CH.viewer; +} +function chLoad() { + const look = CH.hero + '/' + chLook(); + if (CH.look === look || CH.want === look || !chS().game || !chViewer()) return; + if (CH.hero === 'linkle' && !chLinkle().have) return; + CH.want = look; CH.loading = true; CH.error = ''; drawChar(); + cmd('char.look', { look: chLook(), have: [...CH.have] }); +} +async function chFetchTex(name) { + const r = await fetch('/char/tex/' + encodeURIComponent(name) + '.bin'); + if (!r.ok) return null; + const b = await r.arrayBuffer(), d = new DataView(b); + CH.have.add(name); + return { w: d.getUint32(0, true), h: d.getUint32(4, true), data: new Uint8Array(b, 8) }; +} +async function chFetchBin(url) { + const r = await fetch(url); if (!r.ok) return null; + const b = await r.arrayBuffer(), d = new DataView(b); + return { w: d.getUint32(0, true), h: d.getUint32(4, true), data: new Uint8Array(b, 8) }; +} +async function chOnLook(m) { + const want = (m.hero || 'link') + '/' + m.look; + if (want !== CH.want) return; + if (m.error) { CH.want = null; CH.loading = false; CH.error = m.error; drawChar(); return; } + try { + const info = await (await fetch('/char/scene/' + m.n + '.json')).json(); + const mesh = await (await fetch('/char/scene/' + m.n + '.bin')).arrayBuffer(); + if (want !== CH.want) return; + await CH.viewer.load(info, mesh, chFetchTex); + cmd('char.loaded', { n: m.n }); + CH.look = want; CH.want = null; CH.loading = false; + CH.sceneTex = new Set(info.parts.map(p => p.alb).filter(Boolean)); + CH.cmKey.clear(); CH.viewer.clearColorMaps(); + chTint(); + } catch (e) { CH.want = null; CH.loading = false; CH.error = 'Link could not be drawn: ' + e.message; } + drawChar(); +} + +/* ---------------- colours on the model: OOTRR's exact map when it matches the picks, else the live tint ---------------- */ +function chTint() { + const v = CH.viewer; if (!v || !CH.look) return; + const cur = chCur(), ex = CH.exact[chKey()]; + v.setNaviColor(cur.navi || (CH.hero === 'linkle' ? '#e8f070' : null)); + const same = (parts, colors) => parts.every(p => (cur[p] || null) === ((colors || {})[p] || null)); + const done = new Set(); + for (const [tex, c] of (CH.hero === 'link' && CH.cal || new Map())) { + if (!CH.sceneTex.has(tex)) continue; + done.add(tex); + if (ex && same(c.parts, ex.colors)) { v.setTint(tex, null); chUseExact(tex, ex); continue; } + chUseExact(tex, null); + const slots = c.parts.map((p, i) => cur[p] ? chTintSlot(cur[p], c.ym[i], c.qm[i], c.ty[i], c.g ? c.g[i] : 1) : null); + if (slots.some(Boolean) && chMask(tex, c.file)) v.setTint(tex, slots); else v.setTint(tex, null); + } + /* (no calibration yet: the exact maps alone, when they match every pick of this age) */ + if (ex) for (const tex of ex.tex) if (!done.has(tex) && CH.sceneTex.has(tex)) chUseExact(tex, Object.keys(cur).length === Object.keys(ex.colors).length && Object.keys(cur).every(k => cur[k] === ex.colors[k]) ? ex : null); +} +/* a part's live tint, as OOTRR's dye comes out: [r, g, b] the colour at the part's median texel (linear), ym that texel's + luminance, and the contrast g. OOTRR compresses brightness, so the median texel comes out near qm * (Y / ty)^0.62, mixes + the colour toward its own grey (measured 11-30 at the median texel, linear: 26% for #FF0000, 36% for #2050C0 on young + Link's belt; 30% here), and scales the shading by (y / ym)^g, flattened at the top (char3d.js). 11-30: the tint was + brighter than OOTRR's map, and painted the buckle and ring, so a pick seemed to switch when the exact map came */ +function chTintSlot(hex, ym, qm, ty, g) { + const c = chLin(hex), y = Math.max(1e-4, .2126 * c[0] + .7152 * c[1] + .0722 * c[2]); + const out = qm * Math.pow(y / ty, .62), k = out / y; + return c.map(x => (x * .7 + y * .3) * k).concat(Math.max(1e-4, ym), g || 1); +} +function chUseExact(tex, ex) { + const key = ex && ex.tex.includes(tex) ? chKey() + '/' + ex.n : ''; + if ((CH.cmKey.get(tex) || '') === key) return; + CH.cmKey.set(tex, key); + if (!key) { CH.viewer.setColorMap(tex, null); return; } + chFetchBin('/char/exact/' + chKey() + '/' + ex.n + '/' + encodeURIComponent(tex) + '.bin').then(t => { + if (CH.cmKey.get(tex) === key && t) CH.viewer.setColorMap(tex, t); + }); +} +function chMask(tex, file) { + if (CH.masks.has(tex)) return true; + CH.masks.add(tex); + chFetchBin('/char/mask/' + encodeURIComponent(file) + '.bin').then(t => { if (t) { CH.viewer.setMask(tex, t); chTint(); } else CH.masks.delete(tex); }); + return false; +} + +/* ---------------- picks ---------------- */ +function chNaviBoth() { const h = chCur().navi, o = CH.colors[chKey(CH.age === 'child' ? 'adult' : 'child')] || (CH.colors[chKey(CH.age === 'child' ? 'adult' : 'child')] = {}); if (h) o.navi = h; else delete o.navi; } +function chSet(part, hex, final) { + const c = chCur(); + if (hex) c[part] = hex; else delete c[part]; + if (part === 'navi') chNaviBoth(); + CH.touchedAt = performance.now(); + chTint(); + if (final) drawChar(); else chPatchRow(part); + chDyeing(); + clearTimeout(CH.sendT); + const go = () => cmd('char.set', { age: CH.age, part, hex: hex || null }); + if (final) go(); else CH.sendT = setTimeout(go, 220); +} +function chMany(colors) { + const c = chCur(); + for (const k in colors) { if (colors[k]) c[k] = colors[k]; else delete c[k]; } + if ('navi' in colors) chNaviBoth(); + CH.touchedAt = performance.now(); + chTint(); drawChar(); + cmd('char.many', { age: CH.age, colors }); +} +function chRandom() { + const out = {}, base = Math.random() * 360; + chParts().forEach((p, i) => { + const h = (base + (p.group === 'Tunic' ? 0 : p.group === 'Leather' ? 25 + Math.random() * 30 : Math.random() * 360) + (i % 3) * 8) % 360; + const s = p.group === 'Leather' ? .35 + Math.random() * .3 : .45 + Math.random() * .45; + const v = p.group === 'Leather' ? .22 + Math.random() * .25 : .35 + Math.random() * .5; + out[p.id] = rgbHex(hsvRgb(h, s, v)); + }); + return out; +} + +/* ---------------- drawing the page ---------------- */ +function drawChar() { + if (!$('#s-char')) return; + const st = chS(); + // (the launcher's picks are taken unless one was made here a moment ago and is still on its way) + if (st.colors && performance.now() - CH.touchedAt > 1500) { + CH.colors = {}; + for (const k of ['child', 'adult', 'linkle:child', 'linkle:adult']) CH.colors[k] = Object.assign({}, st.colors[k] || {}); + } + if (st.hero && st.hero !== CH.hero) chHeroSwitch(st.hero); + $$('#chHeroes span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chhero:' + CH.hero)); + $$('#chAges span').forEach(s => { s.textContent = (s.dataset.act === 'chage:child' ? 'Young ' : 'Adult ') + chHeroName(); }); + $$('#chAges span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chage:' + CH.age)); + $('#chTunics').style.visibility = CH.age === 'adult' ? 'visible' : 'hidden'; + $$('#chTunics span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chtunic:' + CH.tunic)); + $('#chTitle').textContent = (CH.age === 'child' ? 'Young ' : 'Adult ') + chHeroName() + '’s colors'; + $('#chFace').textContent = CH.face ? 'Full body' : 'Face'; + const wait = $('#chWait'); + const lk = chLinkle(); + const noLinkle = CH.hero === 'linkle' && st.game && !lk.have; + const waitText = !st.game ? 'Build the game first: Link is read from it' : noLinkle ? '' : CH.error || (CH.loading ? 'Reading ' + chHeroName() + ' from your files' : ''); + wait.classList.toggle('on', !!waitText); wait.classList.toggle('err', !!(CH.error || !st.game)); + $('#chWaitT').textContent = waitText; + const get = $('#chGet'); + get.classList.toggle('on', !!noLinkle); + if (noLinkle) get.innerHTML = `

Play as Linkle

${esc(lk.name || 'Playable Linkle')} by ${esc(lk.author || '')}: Linkle from Hyrule Warriors, young and adult, with her own voice, gear and fairy, Liri. A mod from GameBanana, about 320 MB.

` + + (lk.busy ? `

${esc(lk.line || 'Downloading')}

` + : `
Get Linkle
Her page
`); + if (CH.viewer) { if (noLinkle) CH.viewer.stop(); else if (screen === 'char') CH.viewer.start(); } + $('#chCanvas').style.visibility = noLinkle ? 'hidden' : ''; + const changed = Object.keys(chCur()).length; + chDyeing(); + $('#chState').textContent = changed ? changed + (changed === 1 ? ' part changed' : ' parts changed') : 'The game’s own colors'; + $('#chLooks').innerHTML = CH_LOOKS.map((l, i) => `${esc(l.name)}`).join(''); + chDrawRows(); + chDrawFoot(); + if (screen === 'char') chLoad(); +} +/* "Dyeing" under the stage while OOTRR's exact maps for the picks are on their way and no live tint stands in for them */ +function chDyeing() { + const cur = chCur(), ex = CH.exact[chKey()]; + const match = ex && Object.keys(cur).length === Object.keys(ex.colors).length && Object.keys(cur).every(k => cur[k] === ex.colors[k]); + const el = $('#chDye'); if (el) el.classList.toggle('on', (CH.hero === 'linkle' || !!(chS().tool || {}).have) && !match && (CH.hero === 'linkle' || !CH.cal) && !!CH.look); +} +function chLookOn(l) { + if (!l.c) return false; + const cur = chCur() || {}, ids = chParts().map(p => p.id); + return ids.every(id => (cur[id] || null) === (l.c[id] || null)) && (l.id === 'original' || ids.some(id => l.c[id])); +} +function chDrawRows() { + const list = $('#chList'); if (!list) return; + const parts = chParts(), cur = chCur() || {}, applied = (chS().applied || {})[chKey()] || {}; + const keep = focused && list.contains(focused) ? focused.id : null; + let html = '', group = ''; + for (const p of parts) { + if (p.group !== group) { group = p.group; html += `

${esc(group === 'Leather' ? 'Leather and gear' : group === 'Navi' ? 'Your fairy' : group)}

`; } + const hex = cur[p.id], shown = hex || p.swatch, open = CH.open === p.id, pend = (hex || null) !== (applied[p.id] || null); + html += `
` + + `${esc(p.label)}${hex ? hex.toUpperCase() : 'Game’s color'}${pend ? '' : ''}${open ? 'Done' : 'Change'}
`; + if (open) html += chPicker(p, shown, !!hex); + } + html += CH.hero === 'linkle' ? `

Liri is one fairy for both ages. Linkle is ${esc(chLinkle().name || 'a mod')} by ${esc(chLinkle().author || '')}.

` + : '

Navi is one fairy for both ages: her color goes with young and adult Link.

'; + // (the list is drawn again only when what it shows changed: a pick while dragging moves the marks, not the whole list) + if (list.dataset.html !== html) { + const top = list.scrollTop; list.innerHTML = html; list.dataset.html = html; list.scrollTop = top; + if (keep && $('#' + keep)) { focused = null; setFocus($('#' + keep)); } + } + chDrawPicker(); +} +function chPicker(p, hex, set) { + return `
` + + `
` + + `
${CH_SWATCH.map(([c, n], i) => ``).join('')}
` + + `
${set ? `Game’s color` : ''}
`; +} +/* while a colour is dragged: only the row's mark and value move (the list is not drawn again under the pointer) */ +function chPatchRow(part) { + const row = $('#chp-' + part); if (!row) return; + const hex = chCur()[part], p = chParts().find(x => x.id === part) || {}; + const sw = row.querySelector('.chsw'); sw.style.setProperty('--c', hex || p.swatch); sw.classList.toggle('orig', !hex); + row.querySelector('span').firstChild.textContent = hex ? hex.toUpperCase() : 'Game’s color'; +} +function chDrawPicker() { + const sv = $('#chSv'), hu = $('#chHue'); if (!sv || !CH.open) return; + const hex = chCur()[CH.open] || (chParts().find(p => p.id === CH.open) || {}).swatch || '#808080'; + if (rgbHex(hsvRgb(CH.h, CH.s, CH.v)) !== hex) { const [r, g, b] = hexRgb(hex), mx = Math.max(r, g, b), d = mx - Math.min(r, g, b); CH.s = mx ? d / mx : 0; CH.v = mx / 255; if (d) CH.h = rgbHsl([r, g, b])[0]; } + sv.style.setProperty('--cp-h', CH.h); sv.style.setProperty('--cp-c', hex); + sv.querySelector('u').style.left = CH.s * 100 + '%'; sv.querySelector('u').style.top = (1 - CH.v) * 100 + '%'; + hu.style.setProperty('--cp-c', `hsl(${CH.h}, 100%, 50%)`); hu.querySelector('u').style.left = CH.h / 360 * 100 + '%'; + const f = $('#chHex'); if (f && document.activeElement !== f) { f.value = hex.toUpperCase(); f.classList.remove('bad'); } + const n = CH_SWATCH.find(x => x[0] === hex); $('#chSwName').textContent = n ? n[1] : ''; + $$('.chpre span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chsw:' + hex)); +} +function chDrawFoot() { + const st = chS(), t = st.tool || {}, f = $('#chFoot'); + const changed = !st.same, hasApplied = !!st.applied; + let html; + if (!st.game) html = '

Build the game first: the colors go into its files.

'; + else if (!t.have) html = t.busy ? `

Getting the color tool… ${Math.round((t.frac || 0) * 100)} %

` + : `

Picks show here now. To put them in your game, Triforce uses the randomizer’s color tool (OOTRR, ${esc(t.size || '5 MB')}, once).

Get the color tool
`; + else if (st.busy) html = `

${esc(st.line || 'Working')}… about half a minute

Stop
`; + else { + const msg = changed ? (hasApplied ? 'Changed since you applied: not in your game yet' : 'Not in your game yet') + : hasApplied ? (st.appliedOn ? '◆ In your game · every save, new or old' : 'In your game, but switched off on the Mods page') : 'Your game has its own colors'; + const others = (st.others || []).length ? `

Over ${esc(st.others.join(', '))}, which changes Link too.

` : ''; + html = `

${msg}

${others}
` + + (changed && st.appliedHero && st.appliedHero !== CH.hero ? `Your game plays ${st.appliedHero === 'linkle' ? 'Linkle' : 'Link'} now` : '') + + (changed && hasApplied ? 'Undo changes' : '') + + (!changed && hasApplied ? 'Use the game’s colors' : '') + + `
${changed && !Object.values(CH.colors).some(c => Object.keys(c).length) ? 'Apply the game’s colors' : 'Apply to my game'}
`; + } + if (f.dataset.html !== html) { const keep = focused && f.contains(focused) ? focused.id : null; f.innerHTML = html; f.dataset.html = html; if (keep && $('#' + keep)) { focused = null; setFocus($('#' + keep)); } } +} + +/* ---------------- actions ---------------- */ +function chHeroSwitch(hero) { + if (hero === CH.hero) return; + CH.hero = hero; CH.open = null; CH.look = null; CH.want = null; CH.have.clear(); CH.cmKey.clear(); CH.masks.clear(); + if (CH.viewer) CH.viewer.clearTextures(); + if (hero === 'linkle' && CH.tunic !== 'kokiri' && false) CH.tunic = 'kokiri'; +} +ACTIONS.chhero = (h) => { if (h === CH.hero) return; chHeroSwitch(h); cmd('char.hero', { hero: h }); drawChar(); chLoad(); }; +ACTIONS.chlinkle = () => cmd('char.linkle'); +ACTIONS.chpage = () => cmd('open', { arg: 'linkle' }); +ACTIONS.chage = (a) => { if (CH.age === a) return; CH.age = a; CH.open = null; drawChar(); chLoad(); }; +ACTIONS.chtunic = (t) => { if (CH.tunic === t) return; CH.tunic = t; CH.open = null; drawChar(); chLoad(); }; +ACTIONS.chturn = (d) => CH.viewer && CH.viewer.turn(+d * 0.7); +ACTIONS.chface = () => { CH.face = !CH.face; if (CH.viewer) CH.viewer.look(CH.face ? 'face' : 'body'); drawChar(); }; +ACTIONS.chpick = (id) => { CH.open = CH.open === id ? null : id; chDrawRows(); if (CH.open) setTimeout(() => { const p = $('#chPick'), l = $('#chList'); if (p && l) { const over = p.offsetTop + p.offsetHeight - l.scrollTop - l.clientHeight; if (over > 0) l.scrollTop += over + 8; } }, 30); }; +ACTIONS.chsw = (hex) => { chSet(CH.open, hex, true); chDrawPicker(); }; +ACTIONS.chorig = (id) => { chSet(id, null, true); CH.open = null; chDrawRows(); }; +ACTIONS.chlook = (id) => { + const l = CH_LOOKS.find(x => x.id === id); if (!l) return; + const src = l.c || chRandom(), out = {}; + for (const p of chParts()) out[p.id] = src[p.id] || null; + chMany(out); +}; +ACTIONS.chapply = () => cmd('char.apply'); +ACTIONS.chinstall = () => cmd('char.install'); +ACTIONS.chstop = () => cmd('char.stop'); +ACTIONS.chrevert = () => { CH.touchedAt = 0; cmd('char.revert'); }; +ACTIONS.chremove = () => cmd('char.remove'); + +/* the picker: drag in the square / on the hue, or type the hex */ +document.addEventListener('pointerdown', e => { + const el = e.target.closest('#chSv, #chHue'); if (!el || !CH.open) return; + e.preventDefault(); setFocus(el, true); + const id = el.id; + const mv = ev => { + const n = $('#' + id); if (!n) return; + const b = n.getBoundingClientRect(), x = clamp01((ev.clientX - b.left) / b.width), y = clamp01((ev.clientY - b.top) / b.height); + if (id === 'chHue') CH.h = Math.round(x * 359); else { CH.s = x; CH.v = 1 - y; } + chSet(CH.open, rgbHex(hsvRgb(CH.h, CH.s, CH.v)), false); chDrawPicker(); + }; + mv(e); + const up = () => { removeEventListener('pointermove', mv); removeEventListener('pointerup', up); clearTimeout(CH.sendT); if (CH.open) chSet(CH.open, chCur()[CH.open] || null, true); sfx('cursor'); }; + addEventListener('pointermove', mv); addEventListener('pointerup', up); +}); +document.addEventListener('input', e => { + if (e.target.id !== 'chHex') return; + const v = e.target.value.trim().replace(/^#/, ''); + e.target.classList.toggle('bad', /[^0-9a-f]/i.test(v) || v.length > 6); + if (/^[0-9a-f]{6}$/i.test(v) && CH.open) { chSet(CH.open, '#' + v.toLowerCase(), true); chDrawPicker(); } +}); +/* arrows on the square and the hue (app.js asks this first) */ +function charNudge(dx, dy) { + if (!focused || !CH.open) return false; + if (focused.id === 'chHue' && dx) CH.h = Math.max(0, Math.min(359, CH.h + dx * 5)); + else if (focused.id === 'chSv' && (dx || dy)) { CH.s = clamp01(CH.s + dx * .04); CH.v = clamp01(CH.v + dy * .04); } + else return false; + chSet(CH.open, rgbHex(hsvRgb(CH.h, CH.s, CH.v)), false); chDrawPicker(); sfx('cursor'); + return true; +} + +/* ---------------- from the launcher ---------------- */ +function charMessage(m) { + if (m.t === 'charLook') chOnLook(m); + else if (m.t === 'charCal') { CH.cal = new Map(m.maps.map(x => [x.tex, x])); chTint(); } + else if (m.t === 'charExact') { const k = m.key || m.age; CH.exact[k] = { n: m.n, colors: m.colors || {}, tex: m.tex || [] }; if (k === chKey()) chTint(); chDyeing(); } +} +function charShown(name) { + if (name !== 'char') { if (CH.viewer) CH.viewer.stop(); return; } + cmd('char.open'); + const v = chViewer(); + if (v) { v.start(); v.resize(); } + drawChar(); chLoad(); +} diff --git a/launcher/ui/char3d.js b/launcher/ui/char3d.js new file mode 100644 index 0000000..5c28ff5 --- /dev/null +++ b/launcher/ui/char3d.js @@ -0,0 +1,441 @@ +/* ((Triforce, 11-29) The Character page's stage: Link in 3D, drawn with WebGL2 from the player's own game files (the launcher + sends the posed mesh and the textures: launcher/Core/GameFiles/LinkScene.cs). Studio light: a warm key with a soft shadow + map, a cool fill, a gold rim and a sky/ground ambient; normal maps and AO; ACES tone mapping. The model turns, the lights + stay. Drag turns him, the wheel zooms, a double click looks at the face and back. + Colours: each colour map can carry a "tint" (a mask of where a part is, two parts a map at most, and the part's colour): + that is the live preview while a colour is picked; the launcher then sends OOTRR's own recoloured map (exact) in its place. + Char3D.create(canvas) -> { load(info, meshBuffer, fetchTex), setTint(texName, slots), setColorMap(texName, tex), clearColorMaps(), + look(where), resize(), stop() } with tex = {w, h, data: Uint8Array RGBA}. */ +'use strict'; +(function () { + const VS = `#version 300 es + layout(location=0) in vec3 aPos; layout(location=1) in vec3 aNrm; layout(location=2) in vec4 aTan; layout(location=3) in vec2 aUv; layout(location=4) in vec4 aCol; + uniform mat4 uModel, uVP, uLightVP; + out vec3 vPos; out vec3 vNrm; out vec4 vTan; out vec2 vUv; out vec4 vLight; out vec4 vCol; + void main() { + vec4 w = uModel * vec4(aPos, 1.0); + vPos = w.xyz; vNrm = mat3(uModel) * aNrm; vTan = vec4(mat3(uModel) * aTan.xyz, aTan.w); vUv = aUv; + vLight = uLightVP * w; vCol = aCol; + gl_Position = uVP * w; + }`; + const FS = `#version 300 es + precision highp float; + in vec3 vPos; in vec3 vNrm; in vec4 vTan; in vec2 vUv; in vec4 vLight; in vec4 vCol; + uniform int uDebug, uStrands; + uniform sampler2D uAlb, uNrm, uAo, uLut, uGrey, uMask, uShadow, uNrm2, uEmc; + uniform int uHasEmc; + uniform int uHasAlb, uHasNrm, uHasAo, uHasLut, uHasNrm2, uKind, uAlphaMode, uTint; + uniform vec4 uTintA, uTintB; /* rgb: the part's colour at its median texel (linear), a: that texel's luminance (0: not tinted) */ + uniform vec2 uTintG; /* (11-30) each part's contrast: its texels scale as (y / a)^g, at most 3.6x the median (OOTRR flattens its top: 99% ~3.8x) */ + uniform vec3 uEye; uniform float uExposure, uTile; + out vec4 frag; + float lum(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); } + vec3 aces(vec3 x) { const float a = 2.51, b = 0.03, c = 2.43, d = 0.59, e = 0.14; return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0); } + float shadowAt(vec3 n, vec3 l) { + vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5; + if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z > 1.0) return 1.0; + float bias = 0.0012 + 0.0025 * (1.0 - max(dot(n, l), 0.0)); + vec2 texel = 1.0 / vec2(textureSize(uShadow, 0)); + float s = 0.0; + for (int y = -2; y <= 2; y++) for (int x = -2; x <= 2; x++) + s += (p.z - bias <= texture(uShadow, p.xy + vec2(x, y) * texel * 1.2).r) ? 1.0 : 0.0; + return s / 25.0; + } + void main() { + vec4 alb = uHasAlb == 1 ? texture(uAlb, vUv) : vec4(0.6, 0.6, 0.6, 1.0); + if (uHasLut == 1) { + /* young Link's hair has no colour map: the game's own hair ramp (its warm half), varied a strand at a time by the + vertex colour, darker where the strand mask says the strand turns under */ + float g = texture(uGrey, vUv).r; + vec3 c = texture(uLut, vec2(0.58 + 0.38 * clamp(vCol.r, 0.0, 1.0), 0.5)).rgb; + c = mix(vec3(lum(c)), c, 0.78) * (0.72 + 0.28 * g) * mix(0.82, 1.0, clamp(vCol.g, 0.0, 1.0)); + /* strands: fine stripes across the card (its u), each strand its own shade */ + float su = vUv.x * float(uStrands); + float id = floor(su), fr = fract(su); + float h1 = fract(sin(id * 12.9898 + floor(vUv.y * 3.0) * 4.1) * 43758.5); + float edge = smoothstep(0.0, 0.25, fr) * smoothstep(1.0, 0.75, fr); + c *= mix(0.62, 1.08, h1) * mix(0.78, 1.0, edge); + alb = vec4(c, 1.0); + } + if (uAlphaMode == 1 && alb.a < 0.45) discard; + if (uAlphaMode == 3) { frag = vec4(0.06, 0.025, 0.02, alb.r * 0.5); return; } + if (uKind == 5) { /* Navi's body: her light */ + vec3 c = alb.rgb; float f = pow(1.0 - abs(dot(normalize(vNrm), normalize(uEye - vPos))), 2.0); + frag = vec4(pow(aces(c * (1.6 + 2.2 * f)), vec3(1.0 / 2.2)), 1.0); return; + } + if (uKind == 6) { /* her wings: thin and lit, their own glow added */ + vec3 e = uHasEmc == 1 ? texture(uEmc, vUv).rgb : vec3(0.0); + vec3 c = alb.rgb * 0.55 + e * 1.8; + frag = vec4(pow(aces(c), vec3(1.0 / 2.2)), clamp(alb.a * 0.7 + lum(e), 0.0, 1.0)); return; + } + if (uKind == 8) { vec3 c = alb.rgb; if (uAlphaMode == 1 && alb.a < 0.45) discard; frag = vec4(pow(aces(c * 1.4 + c * c * 0.8), vec3(1.0 / 2.2)), 1.0); return; } + if (uKind == 7) { if (alb.a < 0.3) discard; frag = vec4(pow(aces(alb.rgb * 2.0), vec3(1.0 / 2.2)), 0.55); return; } + if (uAlphaMode == 4) { frag = vec4(pow(clamp(alb.rgb * 1.4, 0.0, 1.0), vec3(1.0 / 2.2)), 0.0); return; } /* the eye's highlights: added */ + vec3 base = alb.rgb; + if (uTint == 1) { + vec2 m = texture(uMask, vUv).rg; + float y = lum(base); + if (uTintA.a > 0.0 && m.r > 0.0) base = mix(base, uTintA.rgb * min(pow(clamp(y / uTintA.a, 0.0, 4.0), uTintG.x), 3.6), m.r); + if (uTintB.a > 0.0 && m.g > 0.0) base = mix(base, uTintB.rgb * min(pow(clamp(y / uTintB.a, 0.0, 4.0), uTintG.y), 3.6), m.g); + } + if (uKind == 1) base *= vec3(1.0, 0.9, 0.82); /* skin: the game's skin shading warms it */ + if (uKind == 3) base = mix(base, base * 1.35, 0.6); /* eyes: the game lights them from inside */ + vec3 n = normalize(vNrm); + if (!gl_FrontFacing) n = -n; + if (uHasNrm == 1) { + vec3 t = normalize(vTan.xyz - n * dot(n, vTan.xyz)); + vec3 b = cross(n, t) * (vTan.w < 0.0 ? -1.0 : 1.0); + vec2 xy = texture(uNrm, vUv).rg * 2.0 - 1.0; + if (uHasNrm2 == 1) xy += (texture(uNrm2, vUv * uTile).rg * 2.0 - 1.0) * 0.6; + vec3 tn = vec3(xy, sqrt(max(1.0 - dot(xy, xy), 0.0))); + n = normalize(mat3(t, b, n) * tn); + } + float ao = uHasAo == 1 ? mix(1.0, texture(uAo, vUv).r, 0.85) : 1.0; + vec3 v = normalize(uEye - vPos); + /* lights: key (warm, upper left front, shadowed), fill (cool, right), rim (gold, behind) */ + vec3 lk = normalize(vec3(-0.55, 0.72, 0.62)), lf = normalize(vec3(0.85, 0.25, 0.45)), lr = normalize(vec3(0.35, 0.55, -0.9)); + vec3 ck = vec3(1.0, 0.9, 0.76) * 3.1, cf = vec3(0.46, 0.56, 0.8) * 0.8, cr = vec3(1.0, 0.78, 0.42) * 2.4; + float rough = uKind == 1 ? 0.5 : uKind == 2 ? 0.42 : uKind == 3 ? 0.12 : uKind == 4 ? 0.3 : 0.82; + float spec = uKind == 1 ? 0.35 : uKind == 2 ? 0.5 : uKind == 3 ? 1.0 : uKind == 4 ? 0.9 : 0.18; + float sh = shadowAt(n, lk); + float wrap = uKind == 1 ? 0.35 : 0.08; + float dk = max((dot(n, lk) + wrap) / (1.0 + wrap), 0.0) * sh; + float df = max((dot(n, lf) + wrap) / (1.0 + wrap), 0.0); + float fres = pow(1.0 - max(dot(n, v), 0.0), 3.0); + float dr = max(dot(n, lr), 0.0) * (0.35 + 0.65 * fres); + float sp = pow(2.0, 12.0 * (1.0 - rough)); + vec3 hk = normalize(lk + v), hr = normalize(lr + v); + float sk = pow(max(dot(n, hk), 0.0), sp) * (sp + 8.0) / 25.0 * sh; + float sr = pow(max(dot(n, hr), 0.0), sp) * (sp + 8.0) / 25.0; + vec3 specCol = uKind == 4 ? base * 1.6 + 0.04 : vec3(0.04 + 0.08 * fres); + vec3 sky = vec3(0.34, 0.36, 0.42), ground = vec3(0.22, 0.16, 0.1); + vec3 amb = mix(ground, sky, n.y * 0.5 + 0.5) * 0.55; + vec3 col = base * (amb * ao + ck * dk * ao + cf * df * ao + cr * dr * 0.55) + + specCol * spec * (ck * sk + cr * sr * 0.6) * ao; + if (uKind == 1) col += base * vec3(0.9, 0.25, 0.15) * 0.09 * (1.0 - dk); + if (uKind == 3) col += base * 0.55; /* eyes: lit from within, never black in shadow */ + if (uKind == 2) { + vec3 tt = normalize(vTan.xyz); + float th = dot(tt, hk), kk = sqrt(max(1.0 - th * th, 0.0)); + float s1 = pow(kk, 90.0), s2 = pow(sqrt(max(1.0 - pow(dot(tt, normalize(hk + n * 0.12)), 2.0), 0.0)), 24.0); + col += (ck * 0.05 * s1 + base * ck * 0.06 * s2) * sh * ao; + } /* skin: a little warmth where the light turns */ + col = aces(col * uExposure); + frag = vec4(pow(col, vec3(1.0 / 2.2)), uAlphaMode == 2 ? alb.a : 1.0); + }`; + const SVS = `#version 300 es + layout(location=0) in vec3 aPos; layout(location=3) in vec2 aUv; + uniform mat4 uModel, uLightVP; out vec2 vUv; + void main() { vUv = aUv; gl_Position = uLightVP * uModel * vec4(aPos, 1.0); }`; + const SFS = `#version 300 es + precision mediump float; in vec2 vUv; uniform sampler2D uAlb; uniform int uCut; out vec4 o; + void main() { if (uCut == 1 && texture(uAlb, vUv).a < 0.45) discard; o = vec4(1.0); }`; + /* the floor: a dark disc lit from above, with his shadow and a gold ring at its edge */ + const GVS = `#version 300 es + layout(location=0) in vec2 aXZ; uniform mat4 uVP, uLightVP; uniform float uR; out vec2 vXZ; out vec4 vLight; + void main() { vXZ = aXZ; vec4 w = vec4(aXZ.x * uR, 0.0, aXZ.y * uR, 1.0); vLight = uLightVP * w; gl_Position = uVP * w; }`; + const GFS = `#version 300 es + precision highp float; in vec2 vXZ; in vec4 vLight; uniform sampler2D uShadow; out vec4 o; + void main() { + float r = length(vXZ); + if (r > 1.0) discard; + vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5; float s = 0.0; + vec2 texel = 1.0 / vec2(textureSize(uShadow, 0)); + for (int y = -3; y <= 3; y++) for (int x = -3; x <= 3; x++) s += (p.z - 0.003 <= texture(uShadow, p.xy + vec2(x, y) * texel * 2.0).r) ? 1.0 : 0.0; + s /= 49.0; + float pool = smoothstep(1.0, 0.0, r); + vec3 c = mix(vec3(0.02, 0.018, 0.014), vec3(0.2, 0.15, 0.08), pool * pool) * (0.35 + 0.65 * s); + float ring = smoothstep(0.03, 0.0, abs(r - 0.93)) * 0.9 + smoothstep(0.012, 0.0, abs(r - 0.86)) * 0.4; + c += vec3(0.88, 0.66, 0.24) * ring * 0.45; + float a = smoothstep(1.0, 0.82, r) * (0.75 + 0.25 * pool); + o = vec4(pow(c, vec3(1.0 / 2.2)) * a, a); + }`; + /* Navi's glow: a soft disc that faces the camera, added over everything */ + const HVS = `#version 300 es + layout(location=0) in vec2 aXZ; uniform mat4 uVP; uniform vec3 uAt, uRight, uUp; uniform float uR; out vec2 vQ; + void main() { vQ = aXZ; gl_Position = uVP * vec4(uAt + (uRight * aXZ.x + uUp * aXZ.y) * uR, 1.0); }`; + const HFS = `#version 300 es + precision mediump float; in vec2 vQ; uniform vec3 uCol; out vec4 o; + void main() { float r = length(vQ); if (r > 1.0) discard; float a = exp(-r * r * 5.0) * 0.85 + exp(-r * r * 40.0) * 0.6; o = vec4(uCol * a, 0.0); }`; + const KIND = { cloth: 0, skin: 1, hair: 2, eye: 3, metal: 4, lash: 0, fur: 0, shade: 0, glint: 0, navi: 5, wing: 6, navifur: 7, fairy: 8 }; + const SOFT = { lash: 1, shade: 1, glint: 1, wing: 1, navifur: 1 }; + + function compile(gl, vs, fs) { + const p = gl.createProgram(); + for (const [t, s] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) { + const sh = gl.createShader(t); gl.shaderSource(sh, s); gl.compileShader(sh); + if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh)); + gl.attachShader(p, sh); + } + gl.linkProgram(p); + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p)); + const u = {}; const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < n; i++) { const a = gl.getActiveUniform(p, i); u[a.name] = gl.getUniformLocation(p, a.name); } + return { p, u }; + } + /* column-major 4x4 helpers */ + function mul(a, b) { const o = new Float32Array(16); for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) { let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k]; o[c * 4 + r] = s; } return o; } + function persp(fov, asp, n, f) { const t = 1 / Math.tan(fov / 2), o = new Float32Array(16); o[0] = t / asp; o[5] = t; o[10] = (f + n) / (n - f); o[11] = -1; o[14] = 2 * f * n / (n - f); return o; } + function ortho(l, r, b, t, n, f) { const o = new Float32Array(16); o[0] = 2 / (r - l); o[5] = 2 / (t - b); o[10] = -2 / (f - n); o[12] = -(r + l) / (r - l); o[13] = -(t + b) / (t - b); o[14] = -(f + n) / (f - n); o[15] = 1; return o; } + function lookAt(e, c, up) { + const z = norm([e[0] - c[0], e[1] - c[1], e[2] - c[2]]), x = norm(cross(up, z)), y = cross(z, x); + return new Float32Array([x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, e), -dot(y, e), -dot(z, e), 1]); + } + function rotY(a) { const c = Math.cos(a), s = Math.sin(a); return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); } + function norm(v) { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; } + function cross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; } + function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } + + function create(canvas) { + const gl = canvas.getContext('webgl2', { antialias: true, alpha: true, premultipliedAlpha: true, preserveDrawingBuffer: false }); + if (!gl) return null; + const aniso = gl.getExtension('EXT_texture_filter_anisotropic'); + const main = compile(gl, VS, FS), shadow = compile(gl, SVS, SFS), floor = compile(gl, GVS, GFS), halo = compile(gl, HVS, HFS); + const SHADOW = 2048; + const shadowTex = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, shadowTex); + gl.texStorage2D(gl.TEXTURE_2D, 1, gl.DEPTH_COMPONENT24, SHADOW, SHADOW); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + const shadowFb = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowTex, 0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + const floorBuf = gl.createBuffer(), floorVao = gl.createVertexArray(); + gl.bindVertexArray(floorVao); gl.bindBuffer(gl.ARRAY_BUFFER, floorBuf); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); + gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + gl.bindVertexArray(null); + const white = tex1([255, 255, 255, 255]), flat = tex1([128, 128, 255, 255]); + function tex1(c) { const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(c)); return t; } + + const S = { parts: [], vao: null, buf: [], tex: new Map(), color: new Map(), tints: new Map(), masks: new Map(), info: null, + yaw: 0.35, yawTo: 0.35, pitch: 0.04, pitchTo: 0.04, dist: 0, distTo: 0, tgt: [0, 1, 0], tgtTo: [0, 1, 0], face: false, + spin: false, idleAt: 0, dirty: true, raf: 0, gen: 0, ready: false, naviCol: [0.75, 0.88, 1.0] }; // ((11-30, the owner) no idle turn: Link turns only when dragged or with the arrows + + function upload(t, srgb, clamp) { + const g = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, g); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + gl.texImage2D(gl.TEXTURE_2D, 0, srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8, t.w, t.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, t.data); + gl.generateMipmap(gl.TEXTURE_2D); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + const wrap = clamp ? gl.CLAMP_TO_EDGE : gl.REPEAT; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap); + if (aniso) gl.texParameterf(gl.TEXTURE_2D, aniso.TEXTURE_MAX_ANISOTROPY_EXT, 8); + return g; + } + + /* info: LinkScene's JSON; mesh: ArrayBuffer; fetchTex(name) -> Promise<{w,h,data}|null>. Resolves once every texture is in. */ + async function load(info, mesh, fetchTex) { + const gen = ++S.gen; + S.ready = false; + const vao = gl.createVertexArray(), vb = gl.createBuffer(), ib = gl.createBuffer(); + gl.bindVertexArray(vao); + gl.bindBuffer(gl.ARRAY_BUFFER, vb); gl.bufferData(gl.ARRAY_BUFFER, mesh, gl.STATIC_DRAW); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh, gl.STATIC_DRAW); + gl.bindVertexArray(null); + const want = new Set(); + for (const p of info.parts) for (const k of ['alb', 'nrm', 'nrm2', 'ao', 'lut', 'grey', 'emc']) if (p[k] && !S.tex.has(p[k])) want.add(p[k]); + await Promise.all([...want].map(async n => { + const t = await fetchTex(n).catch(() => null); + if (gen !== S.gen) return; + const srgb = info.parts.some(p => p.alb === n || p.lut === n || p.emc === n); + S.tex.set(n, t ? upload(t, srgb, n.startsWith('eye:') || info.parts.some(p => p.lut === n)) : null); + })); + if (gen !== S.gen) { gl.deleteVertexArray(vao); gl.deleteBuffer(vb); gl.deleteBuffer(ib); return; } + if (S.vao) { gl.deleteVertexArray(S.vao); S.buf.forEach(b => gl.deleteBuffer(b)); } + S.vao = vao; S.buf = [vb, ib]; S.info = info; + S.parts = info.parts.filter(p => !(SOFT[p.kind] && !p.alb) && !(p.alb && !S.tex.get(p.alb) && !p.lut)); + const h = info.max[1] - info.min[1]; + S.height = h; + const fit = body(); + S.tgtTo = fit.tgt.slice(); S.distTo = fit.dist; + if (!S.dist) { S.tgt = fit.tgt.slice(); S.dist = fit.dist * 1.25; } + S.face = false; + S.ready = true; S.dirty = true; + if (!S.raf) S.raf = requestAnimationFrame(frame); + } + function body() { const h = S.height || 1.2; return { tgt: [0, h * 0.47, 0], dist: h * 2.75 }; } + function headView() { const h = S.height || 1.2; return { tgt: [0, h * 0.84, 0], dist: h * 1.2 }; } + function look(where) { + const v = where === 'face' ? headView() : body(); + S.face = where === 'face'; S.tgtTo = v.tgt; S.distTo = v.dist; S.dirty = true; + if (S.face) { S.yawTo = Math.round(S.yawTo / (2 * Math.PI)) * 2 * Math.PI + 0.25; S.pitchTo = 0.02; } + } + + function draw(proj, view, eye, light) { + const W = canvas.width, H = canvas.height; + const model = rotY(S.yaw); + /* shadow pass */ + gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb); + gl.viewport(0, 0, SHADOW, SHADOW); + gl.clear(gl.DEPTH_BUFFER_BIT); + gl.enable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); gl.colorMask(false, false, false, false); + gl.useProgram(shadow.p); + gl.uniformMatrix4fv(shadow.u.uModel, false, model); gl.uniformMatrix4fv(shadow.u.uLightVP, false, light); + gl.bindVertexArray(S.vao); + bindAttrs(); + gl.activeTexture(gl.TEXTURE0); gl.uniform1i(shadow.u.uAlb, 0); + for (const p of S.parts) { + if (SOFT[p.kind] || p.kind === 'eye' || p.kind === 'navi') continue; + const cut = cutOf(p); + gl.uniform1i(shadow.u.uCut, cut === 1 ? 1 : 0); + ptrs(p); + gl.bindTexture(gl.TEXTURE_2D, (p.alb && S.tex.get(p.alb)) || white); + gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff); + } + gl.colorMask(true, true, true, true); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.viewport(0, 0, W, H); + gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + const vp = mul(proj, view); + /* floor */ + gl.useProgram(floor.p); + gl.uniformMatrix4fv(floor.u.uVP, false, vp); gl.uniformMatrix4fv(floor.u.uLightVP, false, light); gl.uniform1f(floor.u.uR, S.height * 0.46); + gl.activeTexture(gl.TEXTURE7); gl.bindTexture(gl.TEXTURE_2D, shadowTex); gl.uniform1i(floor.u.uShadow, 7); + gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); + gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + gl.depthMask(true); gl.disable(gl.BLEND); + /* Link */ + gl.useProgram(main.p); + gl.uniformMatrix4fv(main.u.uModel, false, model); gl.uniformMatrix4fv(main.u.uVP, false, vp); gl.uniformMatrix4fv(main.u.uLightVP, false, light); + gl.uniform3fv(main.u.uEye, eye); gl.uniform1f(main.u.uExposure, 0.86); + gl.uniform1i(main.u.uAlb, 0); gl.uniform1i(main.u.uNrm, 1); gl.uniform1i(main.u.uAo, 2); gl.uniform1i(main.u.uLut, 3); gl.uniform1i(main.u.uGrey, 4); + gl.uniform1i(main.u.uMask, 5); gl.uniform1i(main.u.uNrm2, 6); gl.uniform1i(main.u.uShadow, 7); gl.uniform1i(main.u.uEmc, 8); + gl.bindVertexArray(S.vao); + const opaque = S.parts.filter(p => !SOFT[p.kind]), soft = S.parts.filter(p => SOFT[p.kind]); + for (const p of opaque) drawPart(p); + gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); + for (const p of soft) { + if (p.kind === 'glint') gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ZERO, gl.ONE); + drawPart(p); + if (p.kind === 'glint') gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + } + gl.depthMask(true); gl.disable(gl.BLEND); + /* Navi's glow */ + const at = S.info && S.info.navi; + if (at) { + const c = Math.cos(S.yaw), s = Math.sin(S.yaw); + const w = [c * at[0] + s * at[2], at[1], -s * at[0] + c * at[2]]; + const right = [view[0], view[4], view[8]], upv = [view[1], view[5], view[9]]; + gl.useProgram(halo.p); + gl.uniformMatrix4fv(halo.u.uVP, false, vp); gl.uniform3fv(halo.u.uAt, w); gl.uniform3fv(halo.u.uRight, right); gl.uniform3fv(halo.u.uUp, upv); + gl.uniform1f(halo.u.uR, S.height * 0.16); gl.uniform3fv(halo.u.uCol, S.naviCol); + /* (depth-tested: when she flies behind him, his head hides her glow) */ + gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); gl.depthMask(false); + gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + gl.depthMask(true); gl.disable(gl.BLEND); + } + } + function cutOf(p) { return p.kind === 'fairy' ? 1 : p.kind === 'glint' ? 4 : p.kind === 'shade' ? 3 : p.kind === 'lash' ? 2 : (p.kind === 'hair' || p.kind === 'fur' || /Alpha|Mask|Feather|Band/.test(p.mat)) ? 1 : 0; } + function bindAttrs() { + gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]); + for (let i = 0; i < 5; i++) gl.enableVertexAttribArray(i); + } + function ptrs(p) { + const stride = 64; + gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]); + gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, p.voff); + gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, p.voff + 12); + gl.vertexAttribPointer(2, 4, gl.FLOAT, false, stride, p.voff + 24); + gl.vertexAttribPointer(3, 2, gl.FLOAT, false, stride, p.voff + 40); + gl.vertexAttribPointer(4, 4, gl.FLOAT, false, stride, p.voff + 48); + } + function drawPart(p) { + ptrs(p); + const albName = p.alb; + const colorMap = albName && S.color.get(albName); + const t = (n) => (n && S.tex.get(n)) || null; + const alb = colorMap || t(albName); + bindTex(0, alb || white); gl.uniform1i(main.u.uHasAlb, alb ? 1 : 0); + bindTex(1, t(p.nrm) || flat); gl.uniform1i(main.u.uHasNrm, t(p.nrm) ? 1 : 0); + bindTex(2, t(p.ao) || white); gl.uniform1i(main.u.uHasAo, t(p.ao) ? 1 : 0); + const lut = !alb && t(p.lut) && t(p.grey); + bindTex(3, lut ? t(p.lut) : white); bindTex(4, lut ? t(p.grey) : white); gl.uniform1i(main.u.uHasLut, lut ? 1 : 0); + bindTex(8, t(p.emc) || white); gl.uniform1i(main.u.uHasEmc, t(p.emc) ? 1 : 0); + bindTex(6, t(p.nrm2) || flat); gl.uniform1i(main.u.uHasNrm2, t(p.nrm2) ? 1 : 0); gl.uniform1f(main.u.uTile, 1.0); + const tint = albName && S.tints.get(albName); + if (tint && S.masks.get(albName)) { + bindTex(5, S.masks.get(albName)); + gl.uniform1i(main.u.uTint, 1); + gl.uniform4fv(main.u.uTintA, tint[0] ? tint[0].slice(0, 4) : [0, 0, 0, 0]); gl.uniform4fv(main.u.uTintB, tint[1] ? tint[1].slice(0, 4) : [0, 0, 0, 0]); + gl.uniform2f(main.u.uTintG, tint[0] && tint[0][4] || 1, tint[1] && tint[1][4] || 1); // ((11-30) each slot's contrast + } else { bindTex(5, white); gl.uniform1i(main.u.uTint, 0); } + gl.uniform1i(main.u.uKind, KIND[p.kind] || 0); gl.uniform1i(main.u.uDebug, window.charDebug || 0); gl.uniform1i(main.u.uStrands, window.charStrands || 80); + gl.uniform1i(main.u.uAlphaMode, cutOf(p)); + if (p.kind === 'hair') gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff); + if (p.kind === 'hair') gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function bindTex(unit, t) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, t); } + + let last = 0; + function frame(now) { + S.raf = requestAnimationFrame(frame); + const dt = Math.min(0.05, (now - (last || now)) / 1000); last = now; + if (!S.ready) return; + if (S.spin && !S.drag && !S.face && now - S.idleAt > 2500) { S.yawTo += dt * 0.32; } + const k = 1 - Math.pow(0.0008, dt); + const moved = Math.abs(S.yawTo - S.yaw) + Math.abs(S.pitchTo - S.pitch) + Math.abs(S.distTo - S.dist) + Math.abs(S.tgtTo[1] - S.tgt[1]); + if (moved < 1e-5 && !S.dirty) return; + S.yaw += (S.yawTo - S.yaw) * k; S.pitch += (S.pitchTo - S.pitch) * k; S.dist += (S.distTo - S.dist) * k; + for (let i = 0; i < 3; i++) S.tgt[i] += (S.tgtTo[i] - S.tgt[i]) * k; + S.dirty = false; + const W = canvas.width, H = canvas.height; + const eye = [S.tgt[0], S.tgt[1] + Math.sin(S.pitch) * S.dist, S.tgt[2] + Math.cos(S.pitch) * S.dist]; + const proj = persp(26 * Math.PI / 180, W / H, 0.05, 20); + const view = lookAt(eye, S.tgt, [0, 1, 0]); + const h = S.height; + const lightDir = norm([-0.55, 0.72, 0.62]); + const lc = [lightDir[0] * 4, h * 0.5 + lightDir[1] * 4, lightDir[2] * 4]; + const light = mul(ortho(-h * 0.75, h * 0.75, -h * 0.75, h * 0.75, 0.5, 9), lookAt(lc, [0, h * 0.5, 0], [0, 1, 0])); + draw(proj, view, eye, light); + } + + /* input: drag turns him (and tilts the view a little), the wheel zooms, a double click looks at his face and back */ + canvas.addEventListener('pointerdown', e => { S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); canvas.setPointerCapture(e.pointerId); canvas.classList.add('grab'); }); + canvas.addEventListener('pointermove', e => { + if (!S.drag) return; + S.yawTo += (e.clientX - S.drag.x) * 0.011; S.pitchTo = Math.max(-0.25, Math.min(0.55, S.pitchTo + (e.clientY - S.drag.y) * 0.004)); + S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); S.dirty = true; + }); + const up = () => { S.drag = null; S.idleAt = performance.now(); canvas.classList.remove('grab'); }; + canvas.addEventListener('pointerup', up); canvas.addEventListener('pointercancel', up); + canvas.addEventListener('wheel', e => { + e.preventDefault(); + const b = body(), f = headView(); + S.distTo = Math.max(f.dist * 0.8, Math.min(b.dist * 1.3, S.distTo * (e.deltaY > 0 ? 1.12 : 0.89))); + /* (closer: the view slides up toward the face) */ + const t = Math.max(0, Math.min(1, (b.dist - S.distTo) / (b.dist - f.dist))); + S.tgtTo = [0, b.tgt[1] + (f.tgt[1] - b.tgt[1]) * t, 0]; S.face = t > 0.6; S.idleAt = performance.now(); S.dirty = true; + }, { passive: false }); + canvas.addEventListener('dblclick', () => look(S.face ? 'body' : 'face')); + + function resize() { + const r = canvas.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1); + const w = Math.max(1, Math.round(r.width * d)), h = Math.max(1, Math.round(r.height * d)); + if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; S.dirty = true; } + } + resize(); + return { + load, look, resize, + turn(by) { S.yawTo += by; S.idleAt = performance.now(); S.dirty = true; }, + spin(on) { S.spin = on; }, + /* a part's live colour: slots [[r,g,b,yref,contrast] | null, ...] in linear light, or null to stop */ + /* Navi's glow colour (#rrggbb), null for her own */ + setNaviColor(hex) { const c = hex ? [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255) : [0.75, 0.88, 1.0]; S.naviCol = c.map(x => Math.max(0.12, x)); S.dirty = true; }, + setTint(name, slots) { if (slots) S.tints.set(name, slots); else S.tints.delete(name); S.dirty = true; }, + setMask(name, t) { const old = S.masks.get(name); if (old) gl.deleteTexture(old); if (t) S.masks.set(name, upload(t, false, false)); else S.masks.delete(name); S.dirty = true; }, + setColorMap(name, t) { const old = S.color.get(name); if (old) gl.deleteTexture(old); if (t) S.color.set(name, upload(t, true, false)); else S.color.delete(name); S.dirty = true; }, + /* every texture let go (another hero's files carry the same names) */ + clearTextures() { for (const g of S.tex.values()) if (g) gl.deleteTexture(g); S.tex.clear(); for (const g of S.color.values()) gl.deleteTexture(g); S.color.clear(); for (const g of S.masks.values()) gl.deleteTexture(g); S.masks.clear(); S.tints.clear(); S.ready = false; S.dirty = true; }, + clearColorMaps() { for (const t of S.color.values()) gl.deleteTexture(t); S.color.clear(); S.tints.clear(); S.dirty = true; }, + get ready() { return S.ready; }, + stop() { cancelAnimationFrame(S.raf); S.raf = 0; }, + start() { if (!S.raf) { S.dirty = true; S.raf = requestAnimationFrame(frame); } }, + }; + } + window.Char3D = { create }; +})(); diff --git a/launcher/ui/index.html b/launcher/ui/index.html index bda7ed3..cc0456a 100644 --- a/launcher/ui/index.html +++ b/launcher/ui/index.html @@ -1,6 +1,6 @@ Triforce - +
@@ -76,7 +76,7 @@ -
+

Your files

@@ -105,8 +105,24 @@
+ +
+
+
Your hero, in your colors

Character

+
LinkLinkle
+
Young LinkAdult Link
+
Kokiri TunicGoron TunicZora Tunic
+
◀Face▶Drag to turn · scroll to zoomDyeing
+
+
Reading Link from your game
+

Young Link's colors

+
+
+
+
+ -
+
The launcher and your game

Settings

@@ -125,7 +141,7 @@
-
+

Your best settings

@@ -138,7 +154,7 @@ @@ -158,4 +174,6 @@ + + diff --git a/nx2/oot_patches.py b/nx2/oot_patches.py index 1d0ed1a..3a32bff 100644 --- a/nx2/oot_patches.py +++ b/nx2/oot_patches.py @@ -1734,6 +1734,36 @@ def patch_autosave(s): return s, 1 +# ((Triforce) Unlimited amiibo uses (host/oot_amiibo_uses.c; the System tab's NFC group), the supported build's function: +# f_8328cd30 answers whether the figure the game has just read was used today (x0 the figure's ids and serial number's hash; +# its answer in x0, bit 0 "used today"), by the save's amiibo history and today's date. At its head the host is asked first: +# with the row On it answers 1, x0 is 0 ("not used today") and the function returns; with it Off it answers 0 and the +# function runs as it is. The function is taken as this one only when its body makes the two calls read here: today's date +# (f_83290a50) and the history's test of one of its figures (f_8328ee40) +AMIIBO_DAY_HEAD = "void f_8328cd30(Ctx *__restrict A64_NOESC c) {\n" +AMIIBO_DAY_HOOK = " if (hos_oot_amiibo_used_today(c)) return; /* (nx2/oot_patches.py: the Unlimited amiibo uses row) */\n" +AMIIBO_DAY_DECL = "extern int hos_oot_amiibo_used_today(Ctx *c);\n" +AMIIBO_DAY_CALLS = (" f_83290a50(c);\n", " f_8328ee40(c);\n") + + +def patch_amiibo_uses(s): + """The Unlimited amiibo uses row's call: (s, 1) when f_8328cd30 is in s, the function read here, with the call at its head + (made now or before), else (s, 0)""" + if s.count(AMIIBO_DAY_HEAD) != 1: + return s, 0 + start, end = _function(s, AMIIBO_DAY_HEAD) + if not all(call in s[start:end] for call in AMIIBO_DAY_CALLS): # (another build's function at that address) + return s, 0 + if AMIIBO_DAY_HEAD + AMIIBO_DAY_HOOK in s: + return s, 1 + if AMIIBO_DAY_HOOK in s: + return s, 0 + s = s.replace(AMIIBO_DAY_HEAD, AMIIBO_DAY_HEAD + AMIIBO_DAY_HOOK, 1) + if AMIIBO_DAY_DECL not in s: + s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + AMIIBO_DAY_DECL, 1) + return s, 1 + + # Movement speed (the Debug tab's tool, host/hos_main.c hos_oot_cct_speed): a character controller's forward speed (s0), on its # way to *(controller+40)+472, which the physics step moves the body by with its collisions. The host scales it for Link's # controller while the tool is above 1x. Four places set it: f_809552f0, the move Link's own walk, run and swim go through (a @@ -2115,6 +2145,7 @@ def apply(gen, *, protect_hearts=False, required=False): damage_sites = 0 # ((Triforce) patch_damage: the Damage taken row's one call) opening_sites = 0 # ((Triforce) patch_opening: the Skip opening row's three calls) autosave_sites = 0 # ((Triforce) patch_autosave: the Autosave row's one call) + amiibo_sites = 0 # ((Triforce) patch_amiibo_uses: the Unlimited amiibo uses row's one call) speed_sites = 0 # ((Triforce) patch_cct_speed: the Movement speed tool's four calls) barrier_sites = 0 # ((Triforce) 11-24: patch_barrier_wait: the three job functions, the supported build's alone) for path in sorted(glob.glob(os.path.join(glob.escape(gen), "code_*.c"))): @@ -2384,6 +2415,11 @@ def apply(gen, *, protect_hearts=False, required=False): if autosaved != out: print("oot_patches: the Autosave row's call in", os.path.basename(path)) out = autosaved + unlimited, found = patch_amiibo_uses(out) + amiibo_sites += found + if unlimited != out: + print("oot_patches: the Unlimited amiibo uses row's call in", os.path.basename(path)) + out = unlimited sped, found = patch_cct_speed(out) speed_sites += found if sped != out: @@ -2460,6 +2496,8 @@ def apply(gen, *, protect_hearts=False, required=False): print("oot_patches: WARNING: the Skip opening row's functions were found at %d of %d places" % (opening_sites, len(OPENING_SITES))) if protect_hearts and autosave_sites != 1: # (without it the Autosave row does nothing: host/oot_autosave.c) print("oot_patches: WARNING: the save request for the Autosave row was found at %d of 1 place" % autosave_sites) + if protect_hearts and amiibo_sites != 1: # (without it the Unlimited amiibo uses row does nothing: host/oot_amiibo_uses.c) + print("oot_patches: WARNING: the amiibo's once-a-day check for the Unlimited amiibo uses row was found at %d of 1 place" % amiibo_sites) if protect_hearts and speed_sites != len(SPEED_PLACES): # (without them the Debug tab's Movement speed does nothing, or part) print("oot_patches: WARNING: the Movement speed tool's places were found %d times, not %d" % (speed_sites, len(SPEED_PLACES))) if protect_hearts and tex_ask_sites != 1: # (without it the compaction may be asked for every frame: host/oot_tex_compact.c) diff --git a/readme.md b/readme.md index 20b0626..ebce271 100644 --- a/readme.md +++ b/readme.md @@ -196,7 +196,8 @@ the game asks. They're saved in `triforce_options.ini` beside the game. | Export save for a bug report | The same zip with the logs and settings a problem report needs | | Import a save | A save export of Triforce or NX2navi becomes your save at the next start | | Bug capture (F8) | One folder with what a problem report needs (System tab; see *Bug capture* below) | -| Scan amiibo | A dump of one of your own figures from a folder `amiibo` beside the game (`.bin`, as the figure's tag has it: 532, 540 or 572 bytes, or a Flipper Zero `.nfc` file of it), put on the reader when the game looks for a figure. Only the figure's serial number and which figure it is are read from the file: no key is needed. Your dump is never written: data a game keeps on a figure goes to `amiibo/areas`. On the Debug tab (with Debug tools On) | +| Scan amiibo | A dump of one of your own figures from a folder `amiibo` beside the game (`.bin`, as the figure's tag has it: 532, 540 or 572 bytes, or a Flipper Zero `.nfc` file of it), put on the reader when the game looks for a figure. Only the figure's serial number and which figure it is are read from the file: no key is needed. Your dump is never written: data a game keeps on a figure goes to `amiibo/areas`. Under NFC tag on the System tab, and on the Debug tab (with Debug tools On) | +| Unlimited amiibo uses | Off, On: Off keeps the game's own rule, each figure gives its reward once a day. On lets a figure be scanned again at once, any number of times, and it gives its reward each time: choose it again under NFC tag for each scan. Your dumps are not changed; the game still notes each use in your save, so a figure used today with the row On counts as used today once it is Off (System tab, NFC) | | Movement speed | 1x, 1.25x, 1.5x, 2x, 3x: how fast Link walks, runs and swims, a testing tool (Debug tab, with Debug tools on) | | Game flags | The game's story and world flags by name, read from your game files: see which are set in your save, and set or clear one (Debug tab) | | Cutscenes | The game's events by name, read from your game files: start one (Debug tab) | diff --git a/scripts/linux/appimage.sh b/scripts/linux/appimage.sh index a4f8c8d..7d8f1db 100755 --- a/scripts/linux/appimage.sh +++ b/scripts/linux/appimage.sh @@ -74,9 +74,15 @@ cp -a gpu/vk gpu/compat gpu/third_party "$T/gpu/" cp -a third_party/imgui third_party/fonts "$T/third_party/" # ((Triforce) the ReShade presets' FX compiler and PNG decoder, compiled into the renderer: nx2/reshade_fx.py) cp -a third_party/reshade_fx third_party/stb_image "$T/third_party/" -# ((Triforce, 11-24) RenHDrum' C header, host/rumble_renhdrum.c includes it (the library itself is the player's own renhdrum.dll / .so)) +# ((Triforce, 11-24) RenHDrum' C header, host/rumble_renhdrum.c includes it) mkdir -p "$T/third_party/renhdrum" cp -a third_party/renhdrum/include third_party/renhdrum/LICENSE-MIT third_party/renhdrum/LICENSE-APACHE third_party/renhdrum/NOTICE third_party/renhdrum/PROVENANCE.md "$T/third_party/renhdrum/" +# ((Triforce, 11-29) and the library, renhdrum.so, built here from that source with the pinned Rust (scripts/renhdrum.py, +# linked by this system's cc against the C library the image is for): nx2/build.py copies it beside the player's game. +# Up to v0.8.5.2 no image carried it and no Linux player had RenHDrum's haptics. RENHDRUM=0 builds the image without it) +if [ "${RENHDRUM:-1}" != "0" ]; then + "$PY" -I scripts/renhdrum.py build --target linux --cache "$B/renhdrum-rust" --out "$T/third_party/renhdrum/renhdrum.so" +fi mkdir -p "$T/third_party/zbic" "$T/third_party/a64-kit" cp -a third_party/zbic/zbic.so third_party/zbic/LICENSE third_party/zbic/PROVENANCE.md "$T/third_party/zbic/" cp -a third_party/a64-kit/* "$T/third_party/a64-kit/" diff --git a/scripts/renhdrum.py b/scripts/renhdrum.py index 96d5178..ce6cdff 100644 --- a/scripts/renhdrum.py +++ b/scripts/renhdrum.py @@ -17,7 +17,8 @@ third_party/renhdrum leaves out), with the same C compiler that links it: No time stamp and no path of this machine go in: the same source gives the same bytes. Its output (--out, default third_party/renhdrum/renhdrum.dll or .so, which .gitignore leaves out) is checked as `check` checks it. -(Triforce) Built by hand: Triforce's release scripts do not run it yet. When the file is in third_party/renhdrum/, +(Triforce) The releases build it (11-29): setup/pack_tools.ps1 puts renhdrum.dll in the tools zip's +third_party/renhdrum/, scripts/linux/appimage.sh renhdrum.so in the AppImage's. When the file is in third_party/renhdrum/, nx2/build.py copies it beside the game. A build without it plays every controller's motors or its own HD rumble, as before. diff --git a/setup/pack_tools.ps1 b/setup/pack_tools.ps1 index 544b3f3..8a56f05 100644 --- a/setup/pack_tools.ps1 +++ b/setup/pack_tools.ps1 @@ -5,12 +5,15 @@ # From this checkout: nx2, host, gpu, scripts, third_party (tracked files, as they are on disk), the speed profile in work\. # From -Deps (not in git, too big or binary): python\ (with lz4 numpy capstone unicorn zstandard), cpm\ (Vulkan headers, FFmpeg), # wgpu-native\, llvm-mingw\ (the compiler; without it a player's PC would need Visual Studio), third_party\ (SDL2.dll, zbic.dll/.lib). +# Built here: RenHDrum's renhdrum.dll (scripts/renhdrum.py build, from third_party/renhdrum with -Deps' llvm-mingw; its pinned +# Rust kept in -Deps\renhdrum-rust), into tools\third_party\renhdrum\, where nx2/build.py copies it beside the player's game. param( [Parameter(Mandatory = $true)][string]$Tag, [string]$Deps = 'D:\src\release\triforce-deps', [string]$Out = (Join-Path $PSScriptRoot 'out\release'), [switch]$AllowNoCompiler, - [switch]$AllowNoStateList + [switch]$AllowNoStateList, + [switch]$AllowNoRenhdrum ) $ErrorActionPreference = 'Stop' $repo = Split-Path $PSScriptRoot @@ -47,6 +50,22 @@ foreach ($f in $files) { } "sources: $($files.Count) files" +# 1b. ((Triforce, 11-29) RenHDrum: renhdrum.dll, the library host/rumble_renhdrum.c plays a DualSense's voice coils and the +# HD rumble of Switch and Xbox controllers with (Controls > Vibration). Ignored by git, so step 1 never packed it: every +# release from v0.8.0 to v0.8.5.2 had the code and not the library, and every controller fell back to its motors or its own +# HD rumble. Built from the tracked source each pack (the same source gives the same bytes) and checked by the build) +$rhOut = Join-Path $tools 'third_party\renhdrum\renhdrum.dll' +$rhMingw = Join-Path $Deps 'llvm-mingw' +if (Test-Path (Join-Path $rhMingw 'bin\x86_64-w64-mingw32-clang.exe')) { + & (Join-Path $Deps 'python\python.exe') -I (Join-Path $repo 'scripts\renhdrum.py') build --target windows --llvm-mingw $rhMingw --cache (Join-Path $Deps 'renhdrum-rust') --out $rhOut + if ($LASTEXITCODE -ne 0 -or -not (Test-Path $rhOut)) { + if (-not $AllowNoRenhdrum) { throw "RenHDrum was not built (scripts\renhdrum.py build): players' controllers would get no HD haptics. (-AllowNoRenhdrum packs anyway)" } + "renhdrum: not built (-AllowNoRenhdrum)" + } else { "renhdrum: {0:N0} bytes, sha256 {1}" -f (Get-Item $rhOut).Length, (Get-FileHash $rhOut -Algorithm SHA256).Hash } +} elseif (-not $AllowNoRenhdrum) { + throw "no llvm-mingw in $Deps to build RenHDrum with (-AllowNoRenhdrum packs without it)" +} else { "renhdrum: not built (no llvm-mingw, -AllowNoRenhdrum)" } + # 2. the dependencies foreach ($d in 'python', 'cpm', 'wgpu-native', 'llvm-mingw', 'third_party') { $src = Join-Path $Deps $d diff --git a/tests/amiibo_test.c b/tests/amiibo_test.c index bcab858..78e0644 100644 --- a/tests/amiibo_test.c +++ b/tests/amiibo_test.c @@ -262,6 +262,28 @@ static void test_game(void) { } } +/* ((Triforce) the Unlimited amiibo uses row: the same figure scanned again and again, each choice right after the game read + the last (the Scan amiibo page sends a figure the game has read again, gpu/vk/vk_menu.cpp names_confirm). The reader side + keeps no count: every touch is read as the first, with the same serial number (the game's own once-a-day check is + host/oot_amiibo_uses.c's) */ +static void test_scans_in_a_row(void) { + uint8_t tag[NFP_TAG_INFO_SIZE], model[NFP_MODEL_INFO_SIZE]; + const AmiiboTag t = figure(); + Nfp n; + nfp_reset(&n); + int64_t now = 1000; + for (int scan = 0; scan < 50; scan++) { + CHECK(nfp_choose(&n, &t) == (scan == 0), "scan %d: the readers are said to change again", scan); + memset(tag, 0, sizeof tag), memset(model, 0, sizeof model); + int calls = 0; + const int64_t from = now; + CHECK(game_task(&n, scan & 1, &now, 500, &calls, tag, model) == 1, "scan %d: the game's task does not read the figure", scan); + CHECK(!memcmp(tag, kUid, 7) && !memcmp(model, kModel, 3), "scan %d: the game is handed another figure", scan); + CHECK(now - from < NFP_HOLD_NS + 100000000, "scan %d: the figure is held longer than the first time", scan); + CHECK(n.said == NFP_SAID_READ && n.holder < 0 && !n.waiting, "scan %d: the figure is not lifted off", scan); + } +} + /* ((Triforce) a Flipper Zero NFC file of the tag: its pages as text; the same figure as the tag's bytes */ static size_t flipper_text(char *out, size_t cap, int pages, int unread_page) { uint8_t d[540]; @@ -344,6 +366,7 @@ int main(void) { test_names(); test_readers(); test_game(); + test_scans_in_a_row(); if (failures) return printf("%d failures\n", failures), 1; printf("ok\n"); return 0; diff --git a/tests/test_amiibo.py b/tests/test_amiibo.py index b3457f6..73c75f5 100644 --- a/tests/test_amiibo.py +++ b/tests/test_amiibo.py @@ -20,6 +20,14 @@ written) for a handle that is not a listed reader's; the file is opened by a che its read is bounded; the only file written is the area's, under the amiibo folder's "areas", by the serial number; nothing names or opens a key; the choice is taken at the pad read; the option ids. +And (Triforce) the System tab's Unlimited amiibo uses row (host/oot_amiibo_uses.c): the same figure read fifty times in a +row through the game's task, each choice right after the last read (the reader side keeps no count); nx2/oot_patches.py's +call at the head of the game's once-a-day check, on a lift of its own making (once, again a no-op, only that function and +only with the calls read there); the host's answer compiled from its source with stubs (Off: 0, nothing of the game read +or written; On: "not used today"); the row Off by default, its option, the renderer's answer and the launcher's copy; the +page sending a figure the game has read again; and the clock's answer that keeps the game's other check (a clock set by +hand) from refusing a figure. + python -I -B tests/test_amiibo.py [--cc gcc] """ import argparse @@ -135,18 +143,128 @@ def check_source(): print("PASS: the SDK's functions answer as before until a figure is chosen, and no key is read") +# ((Triforce) the game's once-a-day check as its lift has it, cut short: its head, today's date, the history's test of a +# figure, its return) +DAY_LIFT = ( + '#include "a64.h"\n' + "void f_8328cd20(Ctx *__restrict A64_NOESC c) {\n return;\n}\n" + "void f_8328cd30(Ctx *__restrict A64_NOESC c) {\n" + " uint8_t fn_ = c->n, fz_ = c->z, fc_ = c->c, fv_ = c->v;\n" + "c->x[30] = 0x8328cd74ULL; f_83290a50(c);\n" + " c->x[19]=recomp_load64(c,c->x[8] + 0);\n" + "c->x[30] = 0x8328ce58ULL; f_8328ee40(c);\n" + " return;\n}\n" + "void f_8328ce90(Ctx *__restrict A64_NOESC c) {\n return;\n}\n") + +# the host's answer, cut from its file, with stubs: what it asks of the renderer and what it does to the game's registers +DAY_HOST = r""" +#include +#include +typedef struct { uint64_t x[32]; } Ctx; +enum { HOS_OPT_AMIIBO_UNLIMITED = %d }; +static int row = -1, asked_id = -1, asked_otherwise = -1, logged; +int rx_option(int id, int otherwise) { asked_id = id, asked_otherwise = otherwise; return row < 0 ? otherwise : row; } +void hos_log(const char *fmt, ...) { (void)fmt; logged++; } +%s +int main(void) { + Ctx c; + int bad = 0; + for (int r = -1; r <= 1; r++) { /* (-1: a renderer that does not answer the option: the default) */ + for (int i = 0; i < 32; i++) c.x[i] = 0x5500 + i; + row = r, logged = 0; + const int took = hos_oot_amiibo_used_today(&c); + if (asked_id != HOS_OPT_AMIIBO_UNLIMITED || asked_otherwise != 0) bad |= 1; + if (r == 1 && (took != 1 || c.x[0] != 0 || logged != 1)) bad |= 2; + if (r != 1 && (took != 0 || logged)) bad |= 4; + for (int i = r == 1; i < 32; i++) if (c.x[i] != 0x5500ULL + i) bad |= 8; + } + printf(bad ? "bad %%d\n" : "ok\n", bad); + return bad; +} +""" + + +def menu_row(menu, name): + """vk_menu.cpp's row of that name: its text from the brace to its end""" + at = menu.index('{TAB_SYSTEM, "%s", ' % name) + return menu[at:menu.index("},\n", at) + 3] + + +def check_unlimited(cc): + """(Triforce) The Unlimited amiibo uses row: the patch, the host's answer, the row, its option and the launcher's copy""" + sys.path.insert(0, str(ROOT / "nx2")) + import oot_patches as op + out, n = op.patch_amiibo_uses(DAY_LIFT) + check(n == 1 and out.count(op.AMIIBO_DAY_HEAD + op.AMIIBO_DAY_HOOK) == 1 and out.count(op.AMIIBO_DAY_HOOK) == 1 and + out.count(op.AMIIBO_DAY_DECL) == 1 and out.index(op.AMIIBO_DAY_DECL) < out.index("void f_"), + "the once-a-day check is not called at the head of f_8328cd30, once, declared before the code") + check(op.patch_amiibo_uses(out) == (out, 1), "a second run of the patch changes the lift") + check(out.replace(op.AMIIBO_DAY_HOOK, "").replace(op.AMIIBO_DAY_DECL, "") == DAY_LIFT, "the patch changes more than the call") + other = DAY_LIFT.replace("f_8328cd30", "f_8328cd40") + check(op.patch_amiibo_uses(other) == (other, 0), "another function is patched") + for call in op.AMIIBO_DAY_CALLS: # (another build's function at that address: left as it is) + without = DAY_LIFT.replace(call, " f_80000000(c);\n") + check(op.patch_amiibo_uses(without) == (without, 0), "f_8328cd30 is patched without the call to" + call.strip()) + elsewhere = DAY_LIFT.replace(" return;\n}\nvoid f_8328ce90", op.AMIIBO_DAY_HOOK + " return;\n}\nvoid f_8328ce90") + check(op.patch_amiibo_uses(elsewhere) == (elsewhere, 0), "a call away from the function's head is taken as the patch") + patches = (ROOT / "nx2/oot_patches.py").read_text(encoding="utf-8") + apply = patches[patches.index("def apply(gen,"):patches.index("def apply_output_size(")] + check("unlimited, found = patch_amiibo_uses(out)" in apply and "amiibo_sites += found" in apply and + "if protect_hearts and amiibo_sites != 1:" in apply, "the build does not make the call, or does not say when it is not found") + # the host: the row read first; Off, nothing of the game read or written + host = (ROOT / "host/oot_amiibo_uses.c").read_text(encoding="utf-8") + fn = host[host.index("int hos_oot_amiibo_used_today(Ctx *c) {"):] + check(fn.index("if (!rx_option(HOS_OPT_AMIIBO_UNLIMITED, 0)) return 0;") < fn.index("c->x["), "the host reads the game before the row") + check(set(re.findall(r"c->x\[\d+\]", fn)) == {"c->x[0]"} and "recomp_" not in fn and "fopen" not in host and "fwrite" not in host, + "the host touches more of the game than its answer, or writes a file") + api = (ROOT / "gpu/vk/vk_api.h").read_text(encoding="utf-8") + m = re.search(r"enum \{ HOS_OPT_FOV = 200,([^}]*)\};", api) + names = ["HOS_OPT_FOV"] + [w.strip() for w in m.group(1).split(",") if w.strip()] + check("HOS_OPT_AMIIBO_UNLIMITED" in names and api.count("HOS_OPT_AMIIBO_UNLIMITED") == 2, "gpu/vk/vk_api.h: the row's option") + number = 200 + names.index("HOS_OPT_AMIIBO_UNLIMITED") + with tempfile.TemporaryDirectory() as tmp: + src, exe = Path(tmp) / "day.c", Path(tmp) / "day.exe" + src.write_text(DAY_HOST % (number, fn), encoding="utf-8") + subprocess.run([cc, "-std=c11", "-O1", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], check=True) + run = subprocess.run([str(exe)], capture_output=True, text=True) + check(run.returncode == 0 and run.stdout.strip() == "ok", "the host's answer (Off: the game's own, On: not used today): " + run.stdout) + # the row: the System tab's NFC group, after NFC tag; Off by default; the renderer's answer; the launcher's copy + menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8") + row = menu_row(menu, "Unlimited amiibo uses") + check(row.startswith('{TAB_SYSTEM, "Unlimited amiibo uses", &opts.amiibo_unlimited, 0, 1, 1, tx_onoff,') and row.endswith("nullptr, false, true},\n"), + "vk_menu.cpp: the row is not an Off/On row of opts.amiibo_unlimited") + group = menu[menu.index('MENU_HEADING(TAB_SYSTEM, "NFC")'):menu.index('MENU_HEADING(TAB_SYSTEM, "Online")')] + check(group.index("{TAB_SYSTEM, kNfcTag, ") < group.index(row), "the row is not in the NFC group, after NFC tag") + header = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8") + check(re.search(r"^\s*int amiibo_unlimited = 0;", header, re.M), "vk_menu.h: the row is not Off by default") + replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8") + check("if (id == HOS_OPT_AMIIBO_UNLIMITED) return opts.amiibo_unlimited != 0;" in replay, "the renderer does not answer the row's option") + helptext = "".join(re.findall(r'"((?:[^"\\]|\\.)*)"', row[row.index("tx_onoff,"):])) + schema = (ROOT / "launcher/Logic/GameOptions/GameOptionsSchema.cs").read_text(encoding="utf-8") + check('Row(GameOptionTab.System, "NFC", "Unlimited amiibo uses", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,\n' + ' "%s"),' % helptext in schema, "the launcher's copy of the row is not the menu's (NFC, Off, the same help)") + # the page sends a figure the game has read again (another touch); a figure's clock check never refuses here + check("const bool away = (said == HOS_AMIIBO_WAITING || said == HOS_AMIIBO_ON_READER) && amiibo_chosen == name;" in menu, + "the Scan amiibo page takes a figure off when it is chosen again after the game read it") + applet = (ROOT / "host/nn_applet.c").read_text(encoding="utf-8") + check("HLE(_ZN2nn4time48CalculateStandardUserSystemClockDifferenceByUserERKNS0_13ClockSnapshotES3_) { RET(0); }" in applet, + "host/nn_applet.c: the clock set by hand is not answered 0 (the game's clock check could refuse a figure)") + print("PASS: Unlimited amiibo uses: the once-a-day check's call, the host's answer, the row Off by default, its launcher copy") + + def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--cc", default="gcc") a = p.parse_args() check_source() + check_unlimited(a.cc) with tempfile.TemporaryDirectory() as tmp: exe = Path(tmp) / "amiibo_test.exe" subprocess.run([a.cc, "-std=c11", "-O1", "-Wall", "-Wextra", "-Werror", str(ROOT / "tests/amiibo_test.c"), "-o", str(exe)], check=True) run = subprocess.run([str(exe)], capture_output=True, text=True) if run.returncode or run.stdout.strip() != "ok": raise SystemExit("FAIL: tests/amiibo_test.c (exit %d)\n%s%s" % (run.returncode, run.stdout, run.stderr)) - print("PASS: the dump parser, the infos, the names, the readers' states and the game's task against them") + print("PASS: the dump parser, the infos, the names, the readers' states, the game's task against them and fifty scans in a row") if __name__ == "__main__": diff --git a/tests/test_auto_settings.py b/tests/test_auto_settings.py index 542f220..9d84627 100644 --- a/tests/test_auto_settings.py +++ b/tests/test_auto_settings.py @@ -119,6 +119,12 @@ def main(): m = re.search(r"void auto_row_set\(const int\* value\) \{(.*?)\n\}", menu, re.S) if not m or "opts.auto_pc = 0;" not in m.group(1): raise SystemExit("FAIL: auto_row_set no longer turns Auto Off on a hand change") + # ((11-30) the hardware read asks DLSS's and FSR 4's libraries first: before their probe both answer OK, and Auto chose + # AMD FSR 4 on an RX 580 (rainbow noise)) + h = re.search(r"auto_settings::Hardware auto_hardware\(\) \{(.*?)\n\}", menu, re.S) + if not h or not (0 <= h.group(1).find("dlss_probe();") < h.group(1).find("hw.dlss_runs")) or \ + not (0 <= h.group(1).find("fsr4_probe();") < h.group(1).find("hw.fsr4_runs")): + raise SystemExit("FAIL: auto_hardware reads whether DLSS and FSR 4 run before their libraries were asked") with tempfile.TemporaryDirectory(prefix="auto-settings-") as tmp: src = Path(tmp) / "t.cpp" src.write_text(C, encoding="utf-8") diff --git a/tests/test_bound_keys.py b/tests/test_bound_keys.py index 273cf4c..2c091e4 100644 --- a/tests/test_bound_keys.py +++ b/tests/test_bound_keys.py @@ -6,6 +6,8 @@ triforce_options.ini: the defaults (WASD, the arrows, the mouse's left button Y only while the mouse is captured and only once the click that captured it was let go, key_move_up from the file, a pad_ line for a keys-only control ignored, a key taken from the control that had it, and Enter with Alt still no key. The walk key (the Insert menu's Walk key row, tests/test_walk_key.py) is no control's key while it is the walk key. +((Triforce, 11-30) A key some control has, or the walk key, is no sensitivity key (key_is_a_control, sens_key): - bound to A +took a fifth off the mouse's sensitivity at every press. python -I -B tests/test_bound_keys.py (needs a C compiler) """ import shutil @@ -191,6 +193,26 @@ int main(int argc, char **argv) { CHECK(!hos_binding_is_default(HOS_SW_B) && !hos_reset_binding(HOS_SW_B) && !hos_reset_binding(HOS_SW_A)); /* (each has the other's) */ hos_bind(HOS_BIND_PAD, HOS_SW_A, 0, -1); /* (cleared: B's default is free) */ CHECK(hos_reset_binding(HOS_SW_B) && hos_reset_binding(HOS_SW_A) && hos_binding_is_default(HOS_SW_A) && hos_binding_is_default(HOS_SW_B)); + /* ((Triforce, 11-30) the sensitivity keys (- and =, Num - and Num +) are no shortcut while a control has them, nor while + one is the walk key: bound to A, - took a fifth off the sensitivity at every press (mouse_sens_keys) */ + release(); + CHECK(key_is_a_control('E') && key_is_a_control(VK_TAB) && key_is_a_control(VK_LBUTTON)); /* (A's, Plus's, Y's) */ + CHECK(!key_is_a_control(0xBD) && !key_is_a_control(0x6D) && !key_is_a_control(0xBB) && !key_is_a_control(0x6B)); + CHECK(!key_is_a_control(0)); + held[0xBD] = 1; + CHECK(sens_key(0xBD)); /* (no control's: the shortcut) */ + hos_bind(HOS_BIND_KEY, HOS_SW_A, 1, 0xBD); + CHECK(key_is_a_control(0xBD) && !sens_key(0xBD) && bound_down(HOS_SW_A, 0)); /* (A's alone) */ + hos_bind(HOS_BIND_KEY, HOS_SW_A, 1, 0); + CHECK(!key_is_a_control(0xBD) && sens_key(0xBD)); + hos_bind(HOS_BIND_KEY, HOS_KEY_OC_NOTE_A, 0, 0x6D); /* (a note row's key, Num -) */ + CHECK(key_is_a_control(0x6D)); + hos_bind(HOS_BIND_KEY, HOS_KEY_OC_NOTE_A, 0, 0); + walk_vk = 0x6D; + CHECK(key_is_a_control(0x6D)); + walk_vk = 0; + CHECK(!key_is_a_control(0x6D)); + release(); if (!fails) printf("PASS\n"); return fails != 0; } @@ -207,6 +229,8 @@ class BoundKeysTests(unittest.TestCase): between(hid, "static const char *const bind_names[HOS_KEY_N]", "\nvoid hos_bind("), # (its definition: the live input declares it) block(hid, "static uint64_t bound_pad_buttons("), between(hid, "static int mouse_vk_slot(", "static int bound_down("), + block(hid, "static int key_is_a_control(int vk) {"), # ((Triforce, 11-30) the sensitivity keys' rule + block(hid, "static int sens_key("), between(hid, "int hos_binding_is_default(", "int hos_rebind_control(")] # ((Triforce) the per-control reset) code = "\n".join(code).replace("GetModuleFileNameA(NULL,", "GetModuleFileNameA(0,") read = block(hid, "static void read_input(") diff --git a/tests/test_chunk_default.py b/tests/test_chunk_default.py index 1fb8f83..74ee214 100644 --- a/tests/test_chunk_default.py +++ b/tests/test_chunk_default.py @@ -6,10 +6,13 @@ and dispatches on every card, read once into a static of maybe_split, so nothing now RX_VK_CHUNK when set, else the RX_VK_LAB_AB knob chunk: in its phases, else the driver's default: 120 for every driver until the lab picks one. (11-26) The lab picked NVIDIA's: 240 (measured in the benchmark's four scenes); every other driver keeps 120. NVIDIA's driver is the device's driver id (VK_DRIVER_ID_NVIDIA_PROPRIETARY, one id on Windows and Linux), not the -card's vendor: NVK, Dozen and Venus on an NVIDIA card keep 120. +card's vendor: NVK, Dozen and Venus on an NVIDIA card keep 120. (11-29) On NVIDIA's driver a part ends where the game ends its +render pass by default, Threaded rendering or not (barrier_rules.h part_pass_end_default, vk_replay.cpp pass_end_parts): the +counted 240 applies there with RX_VK_PART_PASS_END=0. Compiles a driver against barrier_rules.h, lab_ab.h and the Vulkan headers and checks: the default is 240 for NVIDIA's driver, and 120 for NVK, Dozen, Venus, RADV, AMD's, Intel's, any other driver id and none; + the pass-end parts are the default for NVIDIA's driver alone (by its id: not NVK, not any other, not none); the rule's id for NVIDIA's driver is Vulkan's; with no knob the size is what the old read gave, for 100,000 random texts of the variable (unset, 0, 120, negative, words, any number) on random drivers, except unset on NVIDIA's driver (240): the default path splits where it split elsewhere; @@ -18,7 +21,8 @@ Compiles a driver against barrier_rules.h, lab_ab.h and the Vulkan headers and c default beside the measured knob chunk:120, and the pass-end parts' test (value_of("chunk", -1) < 0) true only outside it. And reads vk_replay.cpp: maybe_split has no static size and asks part_draws() at each call, still returns for a size of 0 or less and still counts ++part_work against it after the tail's test, and takes Threaded rendering's pass-end parts only -outside the knob's phases; part_draws reads the variable once and the knob at each call, asks the rule with the device's +outside the knob's phases; pass_end_parts turns them on by default with Threaded rendering or the rule (the device's driver +id), and its line says which; part_draws reads the variable once and the knob at each call, asks the rule with the device's driver id (no platform test) and says when Threaded rendering's parts decide instead; barrier_rules.h's comment names NVK, Threaded rendering's parts and both measurements; the switches table has the row, with NVK, the measured PC, where the size applies under Threaded rendering and a lab example against 120, and no longer says the in-pass split is on with NVIDIA's @@ -67,6 +71,13 @@ int main() { for (const auto& d : kDrivers) CHECK(d.what, br::part_draws_default(d.driver) == d.want); static_assert(br::kDriverNvidiaProprietary == VK_DRIVER_ID_NVIDIA_PROPRIETARY, "the rule's id for NVIDIA's driver is Vulkan's"); CHECK("the constants", br::kPartDraws == 120 && br::kPartDrawsNvidia == 240); + // ((Triforce, 11-29) the pass-end parts by default, Threaded rendering off: NVIDIA's driver alone, by its id (the drivers + // that run on NVIDIA's cards beside it keep the parts cut by count, as every other driver, until the lab has measured them) + for (const auto& d : kDrivers) + CHECK("the pass-end parts by default on NVIDIA's driver alone", br::part_pass_end_default(d.driver) == (d.driver == VK_DRIVER_ID_NVIDIA_PROPRIETARY)); + CHECK("the pass-end parts by default: NVIDIA's driver", br::part_pass_end_default(VK_DRIVER_ID_NVIDIA_PROPRIETARY)); + CHECK("the pass-end parts not by default: NVK", !br::part_pass_end_default(VK_DRIVER_ID_MESA_NVK)); + CHECK("the pass-end parts not by default: no driver id", !br::part_pass_end_default(0)); // with no knob: the old read, whatever the variable says uint64_t rng = 0xD1B54A32D192ED03ull; @@ -130,6 +141,14 @@ def function(text, head): return text[at:text.index("\n}\n", at)] +def in_order(text, needles, where): + at = 0 + for n in needles: + i = text.find(n, at) + check(i >= 0, "%s: %r missing or out of order" % (where, n)) + at = i + len(n) + + def check_source(): replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8") split = function(replay, "void maybe_split(VkCommandBuffer& cmd) {") @@ -158,8 +177,13 @@ def check_source(): # ((Triforce) and once by Threaded rendering's parts, only to step aside when it is set: pass_end_parts) ends = function(replay, "PassEndParts& pass_end_parts() {") check(replay.count('getenv("RX_VK_CHUNK")') == 2 and ends.count('getenv("RX_VK_CHUNK")') == 1, "RX_VK_CHUNK is read somewhere else") - check('v.on = e && *e ? atoi(e) != 0 : threaded_on() && !getenv("RX_VK_CHUNK");' in ends, + check('v.on = e && *e ? atoi(e) != 0 : by_default && !getenv("RX_VK_CHUNK");' in ends, "pass_end_parts' switch changed: the docs say any RX_VK_CHUNK turns Threaded rendering's parts off") + # ((Triforce, 11-29) and NVIDIA's driver has them by default, Threaded rendering or not: the rule asked with the driver id) + check("const bool by_default = threaded_on() || barrier_rules::part_pass_end_default((uint32_t)dev.driver_id);" in ends, + "pass_end_parts' default is not Threaded rendering or the rule's, by the device's driver id") + check('"NVIDIA\'s driver\'s default since 11-29"' in ends and '"Threaded rendering"' in ends, + "pass_end_parts' line does not say why the pass-end parts are on") check("every RX_VK_CHUNK, as before" not in ends and "default 120;" not in replay, "vk_replay.cpp still says the counted size is 120 as before") rules = (ROOT / "gpu/vk/barrier_rules.h").read_text(encoding="utf-8") @@ -181,8 +205,38 @@ def check_source(): check("(the first part from 32)" in row[0] and "whole submissions" in there, "the RX_VK_CHUNK row does not say Threaded rendering's first part is from 32 draws, or that RX_VK_CHUNK=0 there gives " "whole submissions") + # ((Triforce, 11-29) the pass-end parts' own row: its default on NVIDIA's driver, the way back, and where it was measured) + pe = [line for line in dev.splitlines() if line.startswith("| `RX_VK_PART_PASS_END=0` or `=1`,")] + check(len(pe) == 1 and "**on by default on NVIDIA's driver since 11-29**" in pe[0] and "part_pass_end_default" in pe[0] and + "`=0`: counted parts" in pe[0] and "Not measured:" in pe[0] and "RTX 5090" in pe[0], + "docs/development.md: no row for RX_VK_PART_PASS_END with its default on NVIDIA's driver, =0 and where it was measured") check("parts of 120 draws" not in dev, "docs/development.md still says a part is 120 draws on every card") check("Unset: `pass` with NVIDIA's driver" not in dev, "docs/development.md still says the in-pass split is on with NVIDIA's driver") + # ((Triforce, 11-29) RX_VK_PART_IDLE / the knob partidle: a part after the first may end from the idle size once the GPU has + # done everything sent. Off unset; asked through part_min_now in place of pe.min, so maybe_split's control flow (and its + # renderer profile) is the same; the GPU looked at every 8th draw at most, below RX_VK_PART_MIN only) + check('v.idle = std::clamp(num("RX_VK_PART_IDLE", 0), 0, v.min);' in ends, "RX_VK_PART_IDLE is not off unset and at most PART_MIN") + split = function(replay, "void maybe_split(VkCommandBuffer& cmd) {") + check("const int64_t need = rec_parts == 0 && pe.first ? pe.first : part_min_now(pe);" in split, + "maybe_split does not ask part_min_now for a later part's size in place of pe.min") + pm = function(replay, "int64_t part_min_now(PassEndParts& pe) {") + # (and RX_VK_PART_RB / partrb: a part that writes back a page the CPU reads back, below PART_MIN only; the binding notes it + # through a call, so the binding's control flow (and its profile) is the same; cleared at each part's end) + # ((11-29, the owner's decision) 32 unset with RX_VK_RB_REC_END=3, the default with these parts; off with another mode set) + check('v.rb = std::clamp(num("RX_VK_PART_RB", range ? 32 : 0), 0, v.min);' in ends, + "RX_VK_PART_RB is not 32 unset with mode 3 (off with another) and at most PART_MIN") + mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8") + bind = function(mem, "BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) {") + check("rb_write_note(p->lo + off, p->lo + wb_end);" in bind and "rb_watched(" not in bind and "part_rb_write" not in bind, + "gpu_buffer_bind does not note a read-back page's write-back through rb_write_note alone (a branch there loses its profile)") + check("part_rb_write.store(false, std::memory_order_relaxed);" in function(mem, "void memory_end_submission(VkCommandBuffer cmd) {"), + "a part's end does not clear the read-back write note") + in_order(pm, ['const int64_t rb = lab_ab::value_of("partrb", pe.rb);', + "if (rb > 0 && n >= rb && n < pe.min && memory_part_rb_write()) {", "return rb;", + 'lab_ab::value_of("partidle", pe.idle);', "if (idle <= 0 || n < idle) {", "return pe.min;", + "if (part_idle_now) return idle;", "if (n >= pe.min || (n & 7) != 0 || !rec_timeline) return pe.min;", + "vkGetSemaphoreCounterValue(dev.device, rec_timeline, &done) == VK_SUCCESS && done >= rec_seq;"], + "part_min_now (off at 0, kept for the part once seen, the GPU looked at every 8th draw below PART_MIN)") def main(): diff --git a/tests/test_dlss_actor.cpp b/tests/test_dlss_actor.cpp index dc8ff17..25a597c 100644 --- a/tests/test_dlss_actor.cpp +++ b/tests/test_dlss_actor.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #define CHECK(name, condition) do { if (!(condition)) { std::fprintf(stderr, "FAIL %s at line %d\n", name, __LINE__); return 1; } } while (0) @@ -133,6 +134,151 @@ int main() { CHECK("none then, none now", da::pair_by_place(stones, {}, 1.0f) == std::vector(4, -1) && da::pair_by_place({}, stones, 1.0f).empty()); + // copies without a place: their n-th draw the frame before is a guess when the model is drawn more than once (a row of + // trees drawn in another order as the camera turns: a tree's motion pointed at its neighbour) + { + const uint64_t t0 = da::key(0x5000, 0x6000, 300, 0, 0x77, 0), t1 = da::key(0x5000, 0x6000, 300, 0, 0x77, 1); + const uint64_t hill = da::key(0x7000, 0x8000, 9000, 0, 0x77, 0); + const auto none = [](uint64_t) { return false; }; + const auto had_second = [&](uint64_t k) { return k == t1; }; + const auto same_c = [](const std::vector& a, std::vector b) { return a == b; }; + CHECK("a model drawn once, now and before: sure", same_c(da::unsure_copies({hill}, {0}, none), {0})); + CHECK("two copies now, no place: both unsure", same_c(da::unsure_copies({t0, t1, hill}, {0, 0, 0}, none), {1, 1, 0})); + CHECK("one copy now, two the frame before: unsure", same_c(da::unsure_copies({t0, hill}, {0, 0}, had_second), {1, 0})); + CHECK("copies with a place pair by it: sure", same_c(da::unsure_copies({t0, t1}, {1, 1}, none), {0, 0})); + CHECK("one copy with a place, one without: the one without unsure", + same_c(da::unsure_copies({t0, t1}, {1, 0}, none), {0, 1})); + CHECK("none", da::unsure_copies({}, {}, none).empty()); + } + + // copies without a skin placed by their object's origin (a rock a trail of its kind): a copy that moved among static ones + // keeps its own pairing, static copies whose draw order swapped are not mixed up, and copies that can't be told apart + // (one place, or about equally near) are flagged for the camera's motion + { + const std::vector

row_then = {{{0, 0, 0}, 0}, {{10, 0, 0}, 1}, {{20, 0, 0}, 2}}; + const auto same_c = [](const std::vector& a, std::vector b) { return a == b; }; + // (1) the middle one moves 0.5 (a rock carried), the others stand + const std::vector

moved_now = {{{0, 0, 0}, 0}, {{10.5f, 0, 0}, 1}, {{20, 0, 0}, 2}}; + const auto p1 = da::pair_by_place(moved_now, row_then, 1.0f); + CHECK("a moving copy among static ones: its own pairing", same(p1, {0, 1, 2})); + CHECK("a moving copy among static ones: sure", same_c(da::ambiguous_by_place(moved_now, row_then, p1), {0, 0, 0})); + // (2) the same copies drawn in another order, none moved + const std::vector

swapped_now = {{{20, 0, 0}, 0}, {{0, 0, 0}, 1}, {{10, 0, 0}, 2}}; + const auto p2 = da::pair_by_place(swapped_now, row_then, 1.0f); + CHECK("static copies, draw order swapped: each its own", same(p2, {2, 0, 1})); + CHECK("static copies, draw order swapped: sure", same_c(da::ambiguous_by_place(swapped_now, row_then, p2), {0, 0, 0})); + // ... and with one of them moving too + const std::vector

both_now = {{{20, 0, 0}, 0}, {{0.4f, 0, 0}, 1}, {{10, 0, 0}, 2}}; + const auto p2b = da::pair_by_place(both_now, row_then, 1.0f); + CHECK("swapped and one moving: its own", same(p2b, {2, 0, 1}) && + same_c(da::ambiguous_by_place(both_now, row_then, p2b), {0, 0, 0})); + // (3) the ambiguous cases: copies at one place; one in the middle of two; two now at one place of one before + const std::vector

stacked = {{{5, 5, 5}, 0}, {{5, 5, 5}, 1}}; + CHECK("copies at one place: both flagged", + same_c(da::ambiguous_by_place(stacked, stacked, da::pair_by_place(stacked, stacked, 1.0f)), {1, 1})); + const std::vector

two_then = {{{0, 0, 0}, 0}, {{0.3f, 0, 0}, 1}}, middle_now = {{{0.15f, 0, 0}, 0}}; + CHECK("about equally near two before: flagged", + same_c(da::ambiguous_by_place(middle_now, two_then, da::pair_by_place(middle_now, two_then, 1.0f)), {1})); + const std::vector

one_then = {{{5, 5, 5}, 0}}; + CHECK("two now at the place of one before: the paired one flagged", + same_c(da::ambiguous_by_place(stacked, one_then, da::pair_by_place(stacked, one_then, 1.0f)), {1, 0})); + CHECK("no pair, nothing to flag", same_c(da::ambiguous_by_place(moved_now, {}, {-1, -1, -1}), {0, 0, 0}) && + da::ambiguous_by_place({}, {}, {}).empty()); + // the doubt limit's factor (kTieFactor 2): a near tie, flagged at 2 and not at 1; a far second copy, never flagged + const std::vector

tie_then = {{{0, 0, 0}, 0}, {{2.8f, 0, 0}, 1}}, tie_now = {{{1, 0, 0}, 0}}; + const auto p_tie = da::pair_by_place(tie_now, tie_then, 3.0f); + CHECK("a near tie (1.0 moved, another 1.8 away): flagged", + same(p_tie, {0}) && same_c(da::ambiguous_by_place(tie_now, tie_then, p_tie), {1})); + const std::vector

far_then = {{{0, 0, 0}, 0}, {{11, 0, 0}, 1}}; + const auto p_far = da::pair_by_place(tie_now, far_then, 3.0f); + CHECK("a far second copy (1.0 moved, another 10 away): sure", + same(p_far, {0}) && same_c(da::ambiguous_by_place(tie_now, far_then, p_far), {0})); + // a model over the cap: none placed by origin (all its copies take the camera's motion by unsure_copies), at the cap: placed + { + const auto no_before = [](uint64_t) { return false; }; + const auto build = [&](size_t n) { + std::vector keys; + for (size_t i = 0; i < n; i++) keys.push_back(da::key(0x1000, 0x2000, 96, 0, 0xabc, (int)i % 256)); + return keys; + }; + const auto count = [](const std::vector& v) { size_t n = 0; for (char c : v) n += c != 0; return n; }; + const auto at_cap = build(da::kCopyCap), over_cap = build(da::kCopyCap + 1); + CHECK("a model at the cap: all placed by origin", + count(da::place_by_origin(at_cap, std::vector(at_cap.size(), 1), no_before)) == at_cap.size()); + const auto over_placed = da::place_by_origin(over_cap, std::vector(over_cap.size(), 1), no_before); + CHECK("a model over the cap: none placed by origin", count(over_placed) == 0); + const auto flagged = da::unsure_copies(over_cap, over_placed, no_before); + CHECK("a model over the cap: all its copies flagged for the camera's motion", count(flagged) == over_cap.size()); + // (a single copy whose 2nd the frame before existed is placed; one whose origin is unreadable is not) + const std::vector one = {da::key(0x1000, 0x2000, 96, 0, 0xabc, 0)}; + const auto had_second = [&](uint64_t k) { return k == da::key(0x1000, 0x2000, 96, 0, 0xabc, 1); }; + CHECK("a lone copy with a 2nd before: placed", count(da::place_by_origin(one, {1}, had_second)) == 1); + CHECK("a lone copy, no 2nd before: not", count(da::place_by_origin(one, {1}, no_before)) == 0); + CHECK("an unreadable origin: not placed", count(da::place_by_origin(one, {0}, had_second)) == 0); + // the frame before's 2nd copy was not placed (origin unreadable): its copy is flagged, as without origins + const auto not_placed = [](uint64_t) { return false; }; + const auto placed_second = [&](uint64_t k) { return had_second(k); }; + CHECK("a 2nd before that was not placed: flagged", + same_c(da::lost_second_copy(one, {1}, had_second, not_placed), {1})); + CHECK("a 2nd before that was placed: not flagged", + same_c(da::lost_second_copy(one, {1}, had_second, placed_second), {0})); + CHECK("no 2nd before, or not placed by origin: not flagged", + same_c(da::lost_second_copy(one, {1}, no_before, not_placed), {0}) && + same_c(da::lost_second_copy(one, {0}, had_second, not_placed), {0})); + } + // the trace's numbers + const da::Spread constant = da::origin_spread(stacked), spread = da::origin_spread(row_then); + CHECK("origin spread: one place", constant.distinct == 1 && constant.max_gap == 0.0f); + CHECK("origin spread: a row", spread.distinct == 3 && spread.min_gap == 10.0f && spread.max_gap == 20.0f); + } + + // a non-skinned draw's place: the translation of its 3x4 row-major world matrix, if that is one + { + const float good[12] = {0, 2, 0, 10, -2, 0, 0, 20, 0, 0, 3, 30}; // rotation-scale (rows 2, 2, 3 long) + float o[3] = {-1, -1, -1}; + CHECK("a world matrix: its translation", da::object_place(good, o) && o[0] == 10 && o[1] == 20 && o[2] == 30); + float m[12]; + const auto refused = [&](const char* name, int at, float v) { + std::memcpy(m, good, sizeof m); + m[at] = v; + float r[3] = {-1, -1, -1}; + const bool no = !da::object_place(m, r) && r[0] == -1; + if (!no) std::fprintf(stderr, "not refused: %s\n", name); + return no; + }; + CHECK("NaN refused", refused("nan", 1, std::nanf("")) && refused("nan translation", 7, std::nanf(""))); + CHECK("infinity refused", refused("inf", 11, INFINITY)); + CHECK("a huge translation refused", refused("huge", 3, 2e5f) && refused("huge neg", 11, -2e5f)); + std::memcpy(m, good, sizeof m); + m[4] = m[5] = m[6] = 0; + float r[3]; + CHECK("a zero row refused", !da::object_place(m, r)); + std::memcpy(m, good, sizeof m); + m[0] = m[1] = m[2] = 0; + m[0] = 1, m[1] = 1.0f; // row 0 (1,1,0) against row 1 (-2,0,0): 45 degrees + CHECK("skewed rows refused", !da::object_place(m, r)); + const float k = 0.70710678f; + const float rs[12] = {k, -3 * k, 0, 10, k, 3 * k, 0, 20, 0, 0, 1, 30}; // R(45 deg) * diag(1,3,1): columns orthogonal, rows skewed + const float sr[12] = {k, -k, 0, 10, 3 * k, 3 * k, 0, 20, 0, 0, 1, 30}; // diag(1,3,1) * R: rows orthogonal, columns skewed + CHECK("R*S (orthogonal columns) accepted", da::object_place(rs, r) && r[0] == 10 && r[1] == 20 && r[2] == 30); + CHECK("S*R (orthogonal rows) accepted", da::object_place(sr, r) && r[2] == 30); + const float both[12] = {1, 1, 0, 10, 0, 1, 0, 20, 0, 0, 1, 30}; // rows and columns both skewed 45 degrees + CHECK("skewed in rows and columns refused", !da::object_place(both, r)); + // (a short axis alone, kAxisMin: a diagonal matrix is orthogonal both ways, so only the length refuses it) + const float tiny[12] = {0, 2, 0, 10, -2, 0, 0, 20, 0, 0, 1e-5f, 30}; + CHECK("a 1e-5 row and column refused for length only", !da::object_place(tiny, r)); + const float shortrow[12] = {2, 0, 0, 10, 0, 1e-5f, 0, 20, 0, 0, 2, 30}; + CHECK("a short axis refused", !da::object_place(shortrow, r)); + const float okdiag[12] = {2, 0, 0, 10, 0, 1e-3f, 0, 20, 0, 0, 2, 30}; + CHECK("the same with the axis over kAxisMin accepted", da::object_place(okdiag, r)); + // (copies sharing one matrix have one place: stacked, so none is sure and all keep the camera's motion) + std::vector same(3); + for (auto& c : same) da::object_place(good, c.place); + const auto pr = da::pair_by_place(same, same, 1.0f); + const auto amb = da::ambiguous_by_place(same, same, pr); + CHECK("identical origins: unsure", amb.size() == 3 && amb[0] && amb[1] && amb[2]); + } + // a draw's place: its origin plus its bones' mean translation (copies at one origin, placed by their bones, differ) const auto pose_of = [](float ox, float oy, float oz, std::vector> moves) { std::vector p(16 + moves.size() * 48, 0); diff --git a/tests/test_mem_parts.py b/tests/test_mem_parts.py index a51492a..b83dfab 100644 --- a/tests/test_mem_parts.py +++ b/tests/test_mem_parts.py @@ -231,6 +231,8 @@ int main() { CHECK(query_used_on(nullptr, "0", "1") && !query_used_on(nullptr, "0", "0") && !query_used_on("0", "0", "2")); CHECK(keep_all_small_pc(true, 15731 * MB, true) && !keep_all_small_pc(false, 15731 * MB, true)); CHECK(!keep_all_small_pc(true, 15731 * MB, false) && !keep_all_small_pc(true, 20 * GB, true) && !keep_all_small_pc(true, 0, true)); + // ((11-30) not on AMD's driver: the RX 580s of 16 GB kept 16,963 pipelines and ran out of RAM) + CHECK(!keep_all_small_pc(true, 15731 * MB, true, true) && keep_all_small_pc(true, 15731 * MB, true, false)); // (11-22: the capture's spares held to 32 MB on a small card or a PC of under 20 GB; a 16 GB PC reports ~15.7 GB) CHECK(spare_capped(true, 64 * GB) && spare_capped(false, 15731 * MB) && spare_capped(false, 20 * GB - 1)); CHECK(!spare_capped(false, 20 * GB) && !spare_capped(false, 32 * GB) && !spare_capped(false, 0)); @@ -283,7 +285,10 @@ def check_source(): raise SystemExit("the precompile's keep goes by the PC's total RAM, not the RAM the game can have") if "mem_parts::own_for_keep(ws, cache_read, amd)" not in keep or "pcache_read_ws.load()" not in keep: raise SystemExit("the precompile's keep counts the pipeline cache's read as room for the pipelines") - small = "if (!e && mem_parts::keep_all_small_pc(discrete, ms.ullTotalPhys, query_on)) {" + small = "if (!e && mem_parts::keep_all_small_pc(discrete, ms.ullTotalPhys, query_on, amd)) {" + if "const bool amd = dev.props.vendorID == 0x1002;" not in keep or \ + keep.index("const bool amd = dev.props.vendorID == 0x1002;") > keep.index(small): + raise SystemExit("the small PC's rule is not told whether the driver is AMD's") if small not in keep or "VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU" not in keep or \ not keep.index("allowed < (6656ull << 20)") < keep.index(small) < keep.index("mem_parts::keep_all_pipelines("): raise SystemExit("the precompile does not keep every pipeline on a discrete GPU in a PC of under 20 GB (after the card's " diff --git a/tests/test_merged_rows.py b/tests/test_merged_rows.py index 4365a4e..db9afec 100644 --- a/tests/test_merged_rows.py +++ b/tests/test_merged_rows.py @@ -418,7 +418,7 @@ def main(): parser.add_argument("--cxx", default="g++") args = parser.parse_args() menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8") - check('out += "options_version=10\\n";' in definition(menu, "void save"), "save does not write options_version=10") + check('out += "options_version=11\\n";' in definition(menu, "void save"), "save does not write options_version=11") check("for (const char* dropped : merged_rows::kDropped) mine |= key == dropped;" in definition(menu, "void save"), "save writes back the lines of the rows that went") with tempfile.TemporaryDirectory(prefix="merged-rows-") as tmp: diff --git a/tests/test_mouse_settings.py b/tests/test_mouse_settings.py index aec62c7..feb4d96 100644 --- a/tests/test_mouse_settings.py +++ b/tests/test_mouse_settings.py @@ -56,6 +56,19 @@ def main(): ("mouse_look_move(invert_x ? -dx : dx, invert ? dy : -dy);", hid)): if text not in where: raise SystemExit("the mouse's left and right are not swapped where it is read: " + text) + # ((Triforce, 11-30) every change of the sensitivity is logged with its writer: the file at the start, the host's keys, the + # options' own input at a tick's end, and any other at a tick's start (a player's 0.30 that nobody's log explained) + watch = menu[menu.index("void sens_watch(const char* why) {"):] + watch = watch[:watch.index("\n}\n")] + if "opts.mouse_sens" not in watch or "logf(" not in watch: + raise SystemExit("sens_watch no longer logs the sensitivity's changes") + tick = menu[menu.index("void menu_tick() {"):] + if not tick.startswith('void menu_tick() {\n sens_watch("another writer'): + raise SystemExit("menu_tick does not look for another writer of the sensitivity first") + for need in ("sens_watch(\"the options' input at this tick", 'sens_watch("the host: its - or = key', + 'sens_watch("as the options file has it, at the start")'): + if need not in menu: + raise SystemExit("a writer of the sensitivity is not logged: " + need) if not preset_exempt(menu, "mouse_sens"): raise SystemExit("a mouse setting turns the quality preset to Custom") print("PASS: the mouse's settings are the menu's") diff --git a/tests/test_movie_frame_count.py b/tests/test_movie_frame_count.py index 34609a1..da76068 100644 --- a/tests/test_movie_frame_count.py +++ b/tests/test_movie_frame_count.py @@ -3,8 +3,10 @@ The game's movie player counts its updates while a movie plays, and a cutscene that shows a movie places its narration, its rumble and its end by that count. The movie's picture and sound follow the clock, so at 120 fps the cues came twice too early: narration lines started over each other. nx2/oot_patches.py makes the count's step hos_movie_frames(player), and host/nn_vi.c -answers 1 while the host gives no frame time (a cap of 60: as shipped) and the frames' time in 60ths, the rest carried to the -player's next update, while it does (HOS_FPS_MOVIE=0: 1 then too, for comparisons). A game version whose code differs keeps +answers 1 while the host gives no frame time at 60 fps (as shipped), the frames' time in 60ths, the rest carried to the +player's next update, while it does, and (11-30) below 60 fps the game's own step, 60 / its rate: one an update had the ending's +second staff roll end at half its count at 30 fps, its end screen never opened, the game stuck before "The End" +(HOS_FPS_MOVIE=0: 1 always, for comparisons). A game version whose code differs keeps its own code and the build goes on with a warning. python -I -B tests/test_movie_frame_count.py [--cc gcc] @@ -60,6 +62,9 @@ static void ReleaseSRWLockExclusive(SRWLOCK *l) { CHECK(*l); *l = 0; } volatile uint32_t hos_frame_seconds_bits; static int movies_seen; /* (each update says a movie plays, for the frame pacing: host/nn_vi.c movie_seen, tests/test_pace_handoff.py) */ static void movie_seen(void) { movies_seen++; } +/* (host/nn_vi.c movie_game_rate: the game's rate under 60, 0 at 60) */ +static int game_rate; +static int movie_game_rate(void) { return game_rate; } @HOST@ /* (the lifted update with the patch, on a small guest: the count at +760 of the player) */ typedef struct { uint64_t x[31]; } Ctx; @@ -86,6 +91,9 @@ int main(int argc, char **argv) { seconds(1.0 / 120); for (int i = 0; i < 600; i++) n = update(0); CHECK(n == 600); + seconds(0), game_rate = 30; /* (and below 60) */ + for (int i = 0; i < 600; i++) n = update(0); + CHECK(n == 1200); printf("PASS: off\n"); return 0; } @@ -168,6 +176,29 @@ int main(int argc, char **argv) { before = n; for (int i = 0; i < 10; i++) n = update(0); CHECK(n - before == 10); + /* (11-30) below 60 fps, no frame time: the game's step, 60 / its rate. At 30 two an update: the ending's second staff roll + (Dm_StaffCredit_0005: 7343 pictures at 60, its end screen opened at frame 6260 of the count) played in 3672 frames ended + its count near 3672 with one an update, the end screen never opened; now at 7344 */ + game_rate = 30; + before = n; + for (int i = 0; i < 3672; i++) { + const uint32_t was = n; + n = update(0); + CHECK(n - was == 2); + } + CHECK(n - before == 7344); + game_rate = 48; /* (1.25 an update, the rest carried) */ + before = n; + for (int i = 0; i < 400; i++) { + const uint32_t was = n; + n = update(0); + CHECK(n - was == 1 || n - was == 2); + } + CHECK(within(n - before, 500)); + game_rate = 0; /* (60 again) */ + before = n; + for (int i = 0; i < 10; i++) n = update(0); + CHECK(n - before == 10); printf("PASS\n"); return 0; } diff --git a/tests/test_oot_adult_map.py b/tests/test_oot_adult_map.py new file mode 100644 index 0000000..31a6bd6 --- /dev/null +++ b/tests/test_oot_adult_map.py @@ -0,0 +1,241 @@ +"""Check that an adult who left the Temple of Time without its first walk out gets the map page and the minimap back. + +The pause menu's Map page (f_80b47d70, asked by UIMapMenuScreen f_834012c0: "Unavailable right now.", MapMessage_01, when +it answers no) and the HUD's minimap (f_805a2cf0) say yes for the child and, for the adult, only once +HavePlayedEvent.Dm_TimeTemple_0065 is 1 (Bool 0xc1b29b0a; the code reads it as struct HavePlayedEvent 0x2b05cbb9, member +Dm_TimeTemple_0065 0xc367dcdc). The adult Market's map plays that event when Link steps through an Area at the Temple of +Time's door (Market_Adult_Static, Market_Adult_Prefab_50e3's logic); nothing else in the romfs plays it or sets the flag. +An adult who leaves the temple another way (a teleport, the age switch, the no-clip flight) has no maps as an adult for +good (#1576602300313506086). `oot_adult_map_fix`, asked by `oot_inventory_refresh` twice a second while a save is loaded, +sets the flag through the game's own Bool setter (the live value and the save's copy) for an adult outside the Market, +the Chamber of Sages and the dream world, once no event plays, and logs it. + +This cuts the real `oot_inventory_refresh`, `oot_first_night_fix` and `oot_adult_map_fix` out of host/hos_main.c and runs +them against made-up save state, with no game and no romfs. Run it with: + + python -I tests/test_oot_adult_map.py --cc gcc +""" +import argparse +import os +import re +import subprocess +import tempfile +from pathlib import Path + +RUN_ALL_ARGS = ["--cc", "gcc"] +ROOT = Path(__file__).resolve().parents[1] + + +def murmur3(text): + """MurmurHash3 x86 32, seed 0: the game's GameData names (as oot_murmur3 in host/hos_main.c).""" + data = text.encode() + h = 0 + mask = 0xFFFFFFFF + for i in range(0, len(data) // 4 * 4, 4): + k = int.from_bytes(data[i:i + 4], "little") + k = (k * 0xCC9E2D51) & mask + k = ((k << 15) | (k >> 17)) & mask + k = (k * 0x1B873593) & mask + h ^= k + h = ((h << 13) | (h >> 19)) & mask + h = (h * 5 + 0xE6546B64) & mask + tail = data[len(data) // 4 * 4:] + k = 0 + for i in reversed(range(len(tail))): + k ^= tail[i] << (8 * i) + if tail: + k = (k * 0xCC9E2D51) & mask + k = ((k << 15) | (k >> 17)) & mask + k = (k * 0x1B873593) & mask + h ^= k + h ^= len(data) + h ^= h >> 16 + h = (h * 0x85EBCA6B) & mask + h ^= h >> 13 + h = (h * 0xC2B2AE35) & mask + h ^= h >> 16 + return h + + +NAMES = { + 0xC1B29B0A: "HavePlayedEvent.Dm_TimeTemple_0065", + 0x2B05CBB9: "HavePlayedEvent", + 0xC367DCDC: "Dm_TimeTemple_0065", + 0xCEA220D3: "Sequence_IsChildhood", + 0x7BDF3694: "Sequence_IsInDreamWorld", +} + +FIXTURE = r''' +#include +#include +#include +#include + +typedef struct { uint64_t x[32]; } Ctx; + +static int played; /* HavePlayedEvent.Dm_TimeTemple_0065, the live value */ +static int saved; /* (its copy in the save) */ +static int child = 1; /* Sequence_IsChildhood: 1 child, 0 adult */ +static int age_known = 1, flag_known = 1; +static int event_playing; /* the game's event manager has an active event */ +static const char *map_name = "Market_Child"; +static int sets, logs, live_only; + +static void hos_log(const char *fmt, ...) { (void)fmt; logs++; } +static void rx_option_set(int id, int value) { (void)id; (void)value; } +static int oot_item_get(Ctx *c, const char *name) { (void)c; (void)name; return 0; } +static int oot_pouch_count(Ctx *c, const char *name) { (void)c; (void)name; return 0; } /* (a save is loaded) */ +static int oot_gamedata_bool(Ctx *c, uint32_t hash, int *value) { + (void)c; + if (hash == 0xcea220d3u && age_known) { *value = child; return 1; } + if (hash == 0xc1b29b0au && flag_known) { *value = played; return 1; } + return 0; /* (HrlField_HasEnteredFirstTime_Adult not found: the first night's repair leaves it) */ +} +/* (the live byte alone: never for this flag, the save would keep 0) */ +__attribute__((unused)) static int oot_gamedata_set_bool(Ctx *c, uint32_t hash, int value) { + (void)c, (void)value; + if (hash == 0xc1b29b0au) live_only++; + return 0; +} +static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size) { + (void)c; + if (hash != 0x1d6189dau) return 0; + snprintf(buf, size, "%s", map_name); + return 1; +} +#define OOT_EVENTMGR_SLOT 0x84c9e090ULL +#define OOT_GAMEDATA_SLOT 0x84c9e180ULL +__attribute__((unused)) static uint64_t oot_singleton(Ctx *c, uint64_t slot) { + (void)c; + return slot == OOT_EVENTMGR_SLOT ? 0x1000 : slot == OOT_GAMEDATA_SLOT ? 0x2000 : 0; +} +__attribute__((unused)) static uint64_t recomp_load64(Ctx *c, uint64_t a) { (void)c; return a == 0x1000 + 104 ? (uint64_t)event_playing : 0; } +/* (the game's SetBool: the live value and the save's copy) */ +__attribute__((unused)) static int oot_gd_set(Ctx *c, uint64_t mgr, uint32_t hash, uint32_t value, int is_bool) { + (void)c; + if (mgr != 0x2000 || hash != 0xc1b29b0au || !is_bool) return 0; + sets++; + played = saved = (int)value; + return 1; +} + +#define OOT_CHEAT_ITEM_BASE 100 +#define OOT_CHEAT_AGE_ID 200 +enum { HOS_OPT_SIM_TURF_AREA_TEXT = 410, HOS_OPT_SIM_TURF_AREA }; +#define OOT_ITEM_COUNT 2 +static const char *const oot_item_names[OOT_ITEM_COUNT] = {"Item_A", "Item_B"}; + +// FIX + +// REFRESH + +static void check(const char *what, int want, int want_sets) { + if (played != want || saved != want || sets != want_sets || live_only || (want_sets && logs < want_sets)) { + fprintf(stderr, "FAIL: %s: flag %d saved %d (want %d), sets %d (want %d), logs %d, live-only writes %d\n", what, + played, saved, want, sets, want_sets, logs, live_only); + exit(1); + } +} + +static void at(Ctx *c, int64_t *now, int flag, int is_child, const char *map) { + *now += 500000000LL; + played = saved = flag, child = is_child, map_name = map, sets = 0, logs = 0; + oot_inventory_refresh(c, *now); +} + +int main(void) { + Ctx c = {0}; + int64_t now = 0; + +#ifdef SWITCH_OFF + at(&c, &now, 0, 0, "ForestTemple"); + check("the switch off leaves the flag", 0, 0); + puts("PASS: HOS_OOT_ADULT_MAP_FIX=0 leaves the flag alone"); + return 0; +#else + /* The report's save: an adult in the Forest Temple who never walked out of the Temple of Time's door. */ + at(&c, &now, 0, 0, "ForestTemple"); + check("an adult in the Forest Temple", 1, 1); + at(&c, &now, 0, 0, "HyruleField_Adult"); + check("an adult in Hyrule Field", 1, 1); + at(&c, &now, 0, 0, "IceCavern"); + check("an adult in the Ice Cavern", 1, 1); + + /* The game's own first walk out is still to come: the Market (the Temple of Time is in it), the Chamber of Sages. */ + at(&c, &now, 0, 0, "Market_Adult"); + check("an adult in the Market", 0, 0); + at(&c, &now, 0, 0, "SageRoom"); + check("an adult in the Chamber of Sages", 0, 0); + at(&c, &now, 0, 0, "DreamWorld"); + check("an adult in the dream world", 0, 0); + + /* The child's maps never ask for it, and his first walk out is ahead of him. */ + at(&c, &now, 0, 1, "KokiriForest_Child"); + check("a child", 0, 0); + + /* Already played: nothing written. */ + at(&c, &now, 1, 0, "ForestTemple"); + check("a save that has it", 1, 0); + + /* Age or flag not known, no map name: nothing to decide on. */ + age_known = 0; + at(&c, &now, 0, 0, "ForestTemple"); + check("the age not known", 0, 0); + age_known = 1, flag_known = 0; + at(&c, &now, 0, 0, "ForestTemple"); + check("the flag not known", 0, 0); + flag_known = 1; + at(&c, &now, 0, 0, ""); + check("no map", 0, 0); + + /* An event playing waits for the next refresh. */ + event_playing = 1; + at(&c, &now, 0, 0, "ForestTemple"); + check("an event playing", 0, 0); + event_playing = 0; + now += 500000000LL; + oot_inventory_refresh(&c, now); + check("after the event", 1, 1); + + puts("PASS: an adult outside the Market, the Chamber of Sages and the dream world without the Temple of Time's first " + "walk out gets HavePlayedEvent.Dm_TimeTemple_0065 through the game's setter; the child and the Market are left"); + return 0; +#endif +} +''' + + +def cut(source, pattern, what): + match = re.search(pattern, source, re.M | re.S) + if not match: + raise SystemExit("could not find %s in host/hos_main.c" % what) + return match.group() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cc", default="gcc") + args = parser.parse_args() + for value, name in NAMES.items(): + if murmur3(name) != value: + raise SystemExit("FAIL: MurmurHash3(%r) is %#010x, not %#010x" % (name, murmur3(name), value)) + host = (ROOT / "host/hos_main.c").read_text(encoding="utf-8") + refresh = cut(host, r"^static void oot_inventory_refresh\(Ctx \*c, int64_t now\) \{.*?^\}", "oot_inventory_refresh") + night = cut(host, r"^static int oot_first_night_fix\(Ctx \*c, const char \*map\) \{.*?^\}", "oot_first_night_fix") + maps = cut(host, r"^static int oot_adult_map_fix\(Ctx \*c, const char \*map\) \{.*?^\}", "oot_adult_map_fix") + if "oot_adult_map_fix(c, map)" not in refresh: + raise SystemExit("FAIL: oot_inventory_refresh does not ask oot_adult_map_fix") + body = FIXTURE.replace("// FIX", night + "\n\n" + maps).replace("// REFRESH", refresh) + with tempfile.TemporaryDirectory(prefix="oot-adult-map-") as tmp: + source = Path(tmp) / "test.c" + source.write_text(body, encoding="utf-8") + env = {k: v for k, v in os.environ.items() if k not in ("HOS_OOT_ADULT_MAP_FIX", "HOS_OOT_FIRST_NIGHT_FIX")} + for name, flags, switch in (("on", [], {}), ("off", ["-DSWITCH_OFF"], {"HOS_OOT_ADULT_MAP_FIX": "0"})): + binary = Path(tmp) / ("test-%s.exe" % name) + subprocess.run([args.cc, "-std=gnu11", "-Wall", "-Wextra", "-Werror"] + flags + [str(source), "-o", str(binary)], + check=True) + subprocess.run([str(binary)], check=True, env=dict(env, **switch)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_oot_first_night.py b/tests/test_oot_first_night.py index d7c0016..a4da6ea 100644 --- a/tests/test_oot_first_night.py +++ b/tests/test_oot_first_night.py @@ -1,14 +1,17 @@ -"""Check that a save which still holds the first adult night's time lock is repaired outside Hyrule Field. +"""Check that a save holding the first adult night's time lock where the game can never let it go is repaired, and only there. -The game holds the clock at 20:00 while `HrlField_isFirstNightTime_Adult` (MurmurHash3 0x8592aa82) is 1 and quest -0x4dbca27f is not Ready (f_8347c020, called from f_803edf70). The flag is only meaningful in Hyrule Field's first adult -night; a save in the Market, the castle or anywhere else with the flag still 1 can never leave night. -`oot_inventory_refresh` runs twice a second while a save is loaded and reads the map for it, so the repair lives there: -outside Hyrule Field, clear the flag with the game's own Bool and log it once. +The game holds the clock at 20:00 while the Bool 0x8592aa82 is 1 and quest 0x4dbca27f (Meet_DekuTree) is past its step +Ready (f_8347c020, called from f_803edf70). 0x8592aa82 is `HrlField_HasEnteredFirstTime_Adult` by its MurmurHash3 (it was +named HrlField_isFirstNightTime_Adult here, which is 0xf1024b60). Sheik's cutscene sets it the first time Link becomes an +adult (Dm_TimeTemple_0055) and the adult Market's gate into Hyrule Field clears it on arrival +(Dm_SY_BancChangeArrive_HyruleField_02): the night is the adult Market's until then, the game's own. A child holding it +(no child's way out clears it) or an adult in Hyrule Field's map holding it (out without that arrival) is held for good. +`oot_inventory_refresh` runs twice a second while a save is loaded and reads the map and age for it, so the repair lives +there: clear the flag for those two through the game's own Bool setter (the live value and the save's copy: the live byte +alone came back as 1 at the next load) and log it once; an adult anywhere else keeps it. This cuts the real `oot_inventory_refresh` (and `oot_first_night_fix` when the source has it) out of host/hos_main.c and -runs it against made-up save state, with no game and no romfs. Without the repair the flag stays 1 and the first case -fails; with it the flag is cleared. Run it with: +runs it against made-up save state, with no game and no romfs. Run it with: python -I tests/test_oot_first_night.py --cc gcc """ @@ -30,11 +33,13 @@ FIXTURE = r''' typedef struct { uint64_t x[32]; } Ctx; -static int flag = 1; /* HrlField_isFirstNightTime_Adult */ +static int flag = 1; /* HrlField_HasEnteredFirstTime_Adult, the live value */ +static int saved = 1; /* (its copy in the save) */ static int child = 1; /* Sequence_IsChildhood: 1 child, 0 adult */ +static int age_known = 1; static int event_playing; /* the game's event manager has an active event */ static const char *map_name = "Market_Child"; -static int cleared; +static int cleared, live_only; static void hos_log(const char *fmt, ...) { (void)fmt; } static void rx_option_set(int id, int value) { (void)id; (void)value; } @@ -42,16 +47,15 @@ static int oot_item_get(Ctx *c, const char *name) { (void)c; (void)name; return static int oot_pouch_count(Ctx *c, const char *name) { (void)c; (void)name; return 0; } /* (a save is loaded) */ static int oot_gamedata_bool(Ctx *c, uint32_t hash, int *value) { (void)c; - if (hash == 0xcea220d3u) { *value = child; return 1; } + if (hash == 0xcea220d3u && age_known) { *value = child; return 1; } if (hash == 0x8592aa82u) { *value = flag; return 1; } return 0; } +/* (the live byte alone: never for this flag, the save would keep 1) */ __attribute__((unused)) static int oot_gamedata_set_bool(Ctx *c, uint32_t hash, int value) { - (void)c; - if (hash != 0x8592aa82u) return 0; - if (flag != value) cleared++; - flag = value; - return 1; + (void)c, (void)value; + if (hash == 0x8592aa82u) live_only++; + return 0; } static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size) { (void)c; @@ -59,10 +63,22 @@ static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size) { snprintf(buf, size, "%s", map_name); return 1; } -/* (the event manager, and its +104: the event playing) */ +/* (the event manager, and its +104: the event playing; the game data manager) */ #define OOT_EVENTMGR_SLOT 0x84c9e090ULL -__attribute__((unused)) static uint64_t oot_singleton(Ctx *c, uint64_t slot) { (void)c; return slot == OOT_EVENTMGR_SLOT ? 0x1000 : 0; } +#define OOT_GAMEDATA_SLOT 0x84c9e180ULL +__attribute__((unused)) static uint64_t oot_singleton(Ctx *c, uint64_t slot) { + (void)c; + return slot == OOT_EVENTMGR_SLOT ? 0x1000 : slot == OOT_GAMEDATA_SLOT ? 0x2000 : 0; +} __attribute__((unused)) static uint64_t recomp_load64(Ctx *c, uint64_t a) { (void)c; return a == 0x1000 + 104 ? (uint64_t)event_playing : 0; } +/* (the game's SetBool: the live value and the save's copy) */ +__attribute__((unused)) static int oot_gd_set(Ctx *c, uint64_t mgr, uint32_t hash, uint32_t value, int is_bool) { + (void)c; + if (mgr != 0x2000 || hash != 0x8592aa82u || !is_bool) return 0; + if (flag != (int)value) cleared++; + flag = saved = (int)value; + return 1; +} #define OOT_CHEAT_ITEM_BASE 100 #define OOT_CHEAT_AGE_ID 200 @@ -75,66 +91,79 @@ static const char *const oot_item_names[OOT_ITEM_COUNT] = {"Item_A", "Item_B"}; // REFRESH static void check(const char *what, int want_flag, int want_cleared) { - if (flag != want_flag || cleared != want_cleared) { - fprintf(stderr, "FAIL: %s: flag %d (want %d), clears %d (want %d)\n", what, flag, want_flag, cleared, want_cleared); + if (flag != want_flag || saved != want_flag || cleared != want_cleared || live_only) { + fprintf(stderr, "FAIL: %s: flag %d saved %d (want %d), clears %d (want %d), live-only writes %d\n", what, flag, saved, + want_flag, cleared, want_cleared, live_only); exit(1); } } +static void at(Ctx *c, int64_t *now, int set, int is_child, const char *map) { + *now += 500000000LL; + flag = saved = set, child = is_child, map_name = map, cleared = 0; + oot_inventory_refresh(c, *now); +} + int main(void) { Ctx c = {0}; int64_t now = 0; #ifdef SWITCH_OFF /* HOS_OOT_FIRST_NIGHT_FIX=0: the repair is off for the whole run. */ - flag = 1, map_name = "Market_Child", cleared = 0; - oot_inventory_refresh(&c, now); + at(&c, &now, 1, 1, "Market_Child"); check("the switch off leaves the flag", 1, 0); + at(&c, &now, 1, 0, "HyruleField_Adult"); + check("the switch off leaves the flag in the Field", 1, 0); puts("PASS: HOS_OOT_FIRST_NIGHT_FIX=0 leaves the flag alone"); return 0; #else - /* The report's state: the adult first-night flag left set in a save that is in the Market. */ - flag = 1, map_name = "Market_Child", cleared = 0; - oot_inventory_refresh(&c, now); - check("the flag is cleared outside Hyrule Field", 0, 1); + /* #1064: a child back from his first adult visit before the gate, in the Market: no child's way out clears it. */ + at(&c, &now, 1, 1, "Market_Child"); + check("a child in the Market", 0, 1); + at(&c, &now, 1, 1, "HyruleField_Child"); + check("a child in the Field", 0, 1); - /* Hyrule Field is where the first night belongs: the repair must not touch it. */ - now += 500000000LL; - flag = 1, map_name = "HyruleField", cleared = 0; - oot_inventory_refresh(&c, now); - check("the flag is left alone in Hyrule Field", 1, 0); + /* The report's save: an adult at Lon Lon Ranch, in Hyrule Field's map, held at 20:00 for good. */ + at(&c, &now, 1, 0, "HyruleField_Adult"); + check("an adult in the Field", 0, 1); + + /* The first night itself: an adult in the Market or the Temple of Time keeps it, the gate's arrival clears it. */ + at(&c, &now, 1, 0, "Market_Adult"); + check("an adult in the Market", 1, 0); + at(&c, &now, 1, 0, "GanonCastle"); + check("an adult outside Ganon's castle", 1, 0); + + /* Age not known: nothing to decide on. */ + age_known = 0; + at(&c, &now, 1, 1, "Market_Child"); + check("the age not known", 1, 0); + age_known = 1; /* A save that is already clear is not written again. */ - now += 500000000LL; - flag = 0, map_name = "Market_Child", cleared = 0; - oot_inventory_refresh(&c, now); + at(&c, &now, 0, 1, "Market_Child"); check("a clear flag is left clear", 0, 0); /* No map name this refresh: nothing to decide on. */ - now += 500000000LL; - flag = 1, map_name = "", cleared = 0; - oot_inventory_refresh(&c, now); + at(&c, &now, 1, 1, ""); check("an empty map leaves the flag", 1, 0); - /* An event running (the escape's cutscene, say) leaves the flag for a later refresh. */ - now += 500000000LL; - flag = 1, map_name = "Market_Child", event_playing = 1, cleared = 0; - oot_inventory_refresh(&c, now); + /* An event running (the gate's own arrival, say) leaves the flag for a later refresh... */ + event_playing = 1; + at(&c, &now, 1, 0, "HyruleField_Adult"); check("an event running leaves the flag", 1, 0); - - /* The event over, the next refresh clears it. */ + /* ...and the event over, the next refresh clears it, if the event has not. */ now += 500000000LL; event_playing = 0, cleared = 0; oot_inventory_refresh(&c, now); check("after the event it clears", 0, 1); - /* A map change after the Field: the next refresh clears it. */ - now += 500000000LL; - flag = 1, map_name = "Market_Child", cleared = 0; - oot_inventory_refresh(&c, now); - check("a later map clears it", 0, 1); + /* Twice a second: a refresh within the half second does nothing. */ + flag = saved = 1, cleared = 0; + oot_inventory_refresh(&c, now + 100000000LL); + check("within the half second", 1, 0); - puts("PASS: the first adult night's time lock is cleared outside Hyrule Field, and only there"); + puts("PASS: the first adult night's time lock is cleared for a child and for an adult in Hyrule Field, through the " + "game's setter, and kept for an adult in the Market"); return 0; #endif } @@ -155,7 +184,10 @@ def main(): host = (ROOT / "host/hos_main.c").read_text(encoding="utf-8") refresh = cut(host, r"^static void oot_inventory_refresh\(Ctx \*c, int64_t now\) \{.*?^\}", "oot_inventory_refresh") fix = re.search(r"^static int oot_first_night_fix\(Ctx \*c, const char \*map\) \{.*?^\}", host, re.M | re.S) - body = FIXTURE.replace("// FIX", fix.group() if fix else "").replace("// REFRESH", refresh) + # (the adult's map repair is asked from the same place: tests/test_oot_adult_map.py checks it; here it finds no flag) + maps = re.search(r"^static int oot_adult_map_fix\(Ctx \*c, const char \*map\) \{.*?^\}", host, re.M | re.S) + fixes = "\n\n".join(m.group() for m in (fix, maps) if m) + body = FIXTURE.replace("// FIX", fixes).replace("// REFRESH", refresh) with tempfile.TemporaryDirectory(prefix="oot-first-night-") as tmp: source = Path(tmp) / "test.c" source.write_text(body, encoding="utf-8") diff --git a/tests/test_oot_menu_mouse.py b/tests/test_oot_menu_mouse.py index 4d29f0a..3559502 100644 --- a/tests/test_oot_menu_mouse.py +++ b/tests/test_oot_menu_mouse.py @@ -648,6 +648,7 @@ int hos_oot_autoload_menu(uint64_t vt, int focused_entry) { (void)vt, (void)focu void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr); void hos_oot_menu_tick(Ctx *c, uint64_t screen); int hos_oot_options_front(void); +int hos_oot_pause_front(void); static int fails; #define CHECK(x) do { if (!(x)) { printf("FAIL line %d: %s\n", __LINE__, #x); fails++; } } while (0) int main(void) { @@ -685,13 +686,16 @@ int main(void) { const uint64_t pause = FAKE_BASE + 0x3000, pause_vt = 0x84c0baa8ULL; memcpy(GP(pause), &pause_vt, 8); now_ns += 300000000; + CHECK(!hos_oot_pause_front()); hos_oot_menu_tick(&ctx, pause); CHECK(told == 2); /* (the pause menu is not the Options screen) */ + CHECK(hos_oot_pause_front() && !hos_oot_options_front()); /* ((Triforce, 11-30) nn_hid.c compare_to_play's B on it) */ now_ns += 16000000; hos_oot_menu_tick(&ctx, options); CHECK(told == 3 && told_value == 2); for (int i = 0; i < 60; i++) now_ns += 16000000, hos_oot_menu_tick(&ctx, options); CHECK(told == 63 && told_value == 2); + CHECK(!hos_oot_pause_front()); /* (its updates stopped under the Options: no B for it while they are in front) */ now_ns += 1000000000; /* (closed, back in play, then the title's Options) */ hos_oot_menu_tick(&ctx, options); CHECK(told == 64 && told_value == 1); diff --git a/tests/test_output_resolution.py b/tests/test_output_resolution.py index 20a7f2a..03d8b44 100644 --- a/tests/test_output_resolution.py +++ b/tests/test_output_resolution.py @@ -91,8 +91,9 @@ def main(): and "output_choice(opts.output_res) == OUTPUT_CUSTOM) &&" in shown, "the Custom size's rows show without Custom chosen") check("if ((value == &opts.output_width || value == &opts.output_height) && custom_env()) return true;" in menu, "the Custom size's rows can be changed while HOS_OUTPUT_SIZE sets the size") - # (10: the keys' Plus alone changed, host/nn_hid.c binds_load; the output numbers' schema is OUTPUT_OPTIONS_VERSION, 9, on) - check('out += "options_version=10\\n";' in menu, "the options file is not written as version 10 (output_sizes.h OUTPUT_OPTIONS_VERSION and later)") + # (10: the keys' Plus alone changed, host/nn_hid.c binds_load; 11: Threaded rendering's default alone, vk_menu.cpp menu_init; + # the output numbers' schema is OUTPUT_OPTIONS_VERSION, 9, on) + check('out += "options_version=11\\n";' in menu, "the options file is not written as version 11 (output_sizes.h OUTPUT_OPTIONS_VERSION and later)") check("#define OUTPUT_OPTIONS_VERSION 9" in (ROOT / "gpu/vk/output_sizes.h").read_text(encoding="utf-8"), "output_sizes.h: the 5120-wide sizes are not pictures from options_version 8") check("rows[i].name != kUseWindowSize || (opts.output_res == OUTPUT_CUSTOM && !custom_env())" in shown diff --git a/tests/test_play_rows.py b/tests/test_play_rows.py index a2f533b..27572aa 100644 --- a/tests/test_play_rows.py +++ b/tests/test_play_rows.py @@ -307,6 +307,7 @@ ROWS = ( ("Skip opening", "TAB_SYSTEM", "skip_opening", "0", "1", 1, 0, "HOS_OPT_SKIP_OPENING", "Game"), ("Skip title screen", "TAB_SYSTEM", "skip_title", "0", "1", 1, 0, "HOS_OPT_SKIP_TITLE", "Game"), ("Autosave", "TAB_SYSTEM", "autosave", "0", "1", 1, 1, "HOS_OPT_AUTOSAVE", "Saves & reports"), + ("Unlimited amiibo uses", "TAB_SYSTEM", "amiibo_unlimited", "0", "1", 1, 0, "HOS_OPT_AMIIBO_UNLIMITED", "NFC"), ("Mute in background", "TAB_AUDIO", "mute_background", "0", "1", 1, 0, "HOS_OPT_MUTE_BACKGROUND", "Sound"), ("Microphone gain", "TAB_AUDIO", "mic_gain", "25", "400", 25, 100, "HOS_OPT_MIC_GAIN", "Microphone"), ) diff --git a/tests/test_readback_rec_end.cpp b/tests/test_readback_rec_end.cpp index 9cb5208..d4941e3 100644 --- a/tests/test_readback_rec_end.cpp +++ b/tests/test_readback_rec_end.cpp @@ -29,6 +29,7 @@ struct Gpu { wr::Parts table; uint64_t first_noted = 0; // (value_rec: the first part, emplace) uint64_t range = 0; // ((11-28) the part whose write-back last covered the read's range, 0: none known) + int range_part = -1; // ((11-29) the part (its index) whose submit makes the range known: its write-back copied it) void submit_up_to(size_t n) { for (; sent < n && sent < parts.size(); sent++) note(sent); @@ -36,6 +37,7 @@ struct Gpu { void note(size_t i) { table.submitted(value, parts[i], i + 1 == parts.size()); if (!first_noted) first_noted = parts[i]; + if ((int)i == range_part) range = parts[i]; } void begin() { for (size_t i = 0; i < sent; i++) note(i); @@ -97,6 +99,20 @@ int main() { CHECK("mode 2, the CPU only reads it: the first part", !wr::rec_end_applies(wr::kRecEndCpuWritten, false)); CHECK("mode 1: the rule either way", wr::rec_end_applies(wr::kRecEndAll, false) && wr::rec_end_applies(wr::kRecEndAll, true)); CHECK("mode 0: never", !wr::rec_end_applies(wr::kRecEndOff, true)); + // ((11-29) mode 3: mode 2's rule for the CPU-written ranges, and the read-only ranges at their part (range_applies)) + CHECK("mode 3", wr::rec_end_mode("3") == wr::kRecEndRange && wr::rec_end_on("3")); + // ((11-29, the owner's decision) the reader's default where the parts end at the game's render passes: unset or empty alone + CHECK("unset with the pass-end parts: 3", wr::rec_end_mode(nullptr, wr::kRecEndRange) == wr::kRecEndRange + && wr::rec_end_mode("", wr::kRecEndRange) == wr::kRecEndRange); + CHECK("set with the pass-end parts: as set", wr::rec_end_mode("2", wr::kRecEndRange) == wr::kRecEndCpuWritten + && wr::rec_end_mode("0", wr::kRecEndRange) == wr::kRecEndOff + && wr::rec_end_mode("1", wr::kRecEndRange) == wr::kRecEndAll + && wr::rec_end_mode("7", wr::kRecEndRange) == wr::kRecEndCpuWritten); + CHECK("mode 3, the CPU writes it: the rule", wr::rec_end_applies(wr::kRecEndRange, true) && !wr::range_applies(wr::kRecEndRange, true)); + CHECK("mode 3, the CPU only reads it: its range's part", + !wr::rec_end_applies(wr::kRecEndRange, false) && wr::range_applies(wr::kRecEndRange, false)); + CHECK("the range's part in mode 3 alone", !wr::range_applies(wr::kRecEndCpuWritten, false) && !wr::range_applies(wr::kRecEndAll, false) + && !wr::range_applies(wr::kRecEndOff, false)); // the parts' table: the newest part and whether it ended the recording; an older note changes nothing; a later recording // under the same value takes the entry over from its first part; nothing for no value or no number; the oldest past the cap @@ -318,5 +334,111 @@ int main() { CHECK("random: the old wait ended early at every one of them", old_early == cases_going_on); std::printf("readback rec end: %d of 20000 reads came before their recording's end; the old wait ended early at all %d\n", cases_going_on, old_early); + + // ((11-29) RX_VK_RB_REC_END=3, readback_range_wait: a range the CPU only reads waits for the part that copied it back. The + // flicker's case: parts end at the game's render passes, the first after ~32 draws; the read comes after the first part's + // submit, its range copied back by the second. The first part's wait read it a frame late (the exposure moved for 15 presents) + { + Gpu g, g0; + g.parts = {10, 11, 12}; + g.range_part = 1; + g0 = g; + g.begin(), g0.begin(); + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("range: known and done", r.known && r.ok); + CHECK("range: ends at the part that copied it back, not the first, not the last", g.rec_done == 11 && g.hangs == 0); + const wr::ReadbackWait r0 = wr::readback_wait(false, g0); + CHECK("range: the first part's wait ended before it (the frame-late read)", r0.known && g0.rec_done == 10); + } + { // the range's part submitted already: one wait, for it, nothing sliced + Gpu g; + g.parts = {10, 11, 12}; + g.sent = 2; + g.range_part = 0; + g.begin(); + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("range known: one wait, for its part", r.known && r.ok && !r.went_on && g.rec_waits == 1 && g.rec_done == 10 && g.slices == 0); + } + { // no part copies the range back: the recording's end, as the last-part rule + Gpu g; + g.parts = {10, 11, 12}; + g.begin(); + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("range never copied: the last part", r.known && r.ok && r.went_on && g.rec_done == 12 && g.hangs == 0); + } + { // an ended recording whose range no part noted (its runs dropped once done): one wait, for the last part + Gpu g; + g.parts = {10, 11, 12}; + g.sent = 3; + g.begin(); + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("ended, range not noted: one wait", r.known && r.ok && !r.went_on && g.rec_waits == 1 && g.rec_done == 12); + } + { // the parts not known, the first part is (value_rec): that, as before + Gpu g; + g.parts = {10, 11}; + g.first_noted = 10; + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("parts not known: the first part", r.known && r.ok && g.rec_waits == 1 && g.rec_done == 10); + Gpu n; + n.parts = {10, 11}; + const wr::ReadbackWait rn = wr::readback_range_wait(n); + CHECK("not known at all: the fallback's", !rn.known && n.rec_waits == 0); + } + { // the replay stuck before the range's part: slices of the submissions' timeline, ended once it reaches the value + Gpu g; + g.parts = {10, 11, 12}; + g.range_part = 2; + g.step = 0; + g.timeline_after = 4; + g.begin(); + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("range, stuck: ended by the timeline", r.known && r.ok && r.went_on && r.slices == 4 && g.timeline_at_v && g.hangs == 0); + } + { // an error ends it, not done + Gpu g; + g.parts = {10, 11, 12}; + g.range_part = 1; + g.rec_wait_error_at = 0; + g.begin(); + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("range, error: not done", r.known && !r.ok && g.rec_waits == 1); + } + // 20,000 random recordings, the range copied back by one of the parts or by none: never back before the range's part is done + // (none: the last part), never past it but for the timeline, never a wait for a part not submitted, one wait when its part was + // submitted before the read; the first part's wait read it early whenever a later part copied it + int range_later = 0, first_early = 0; + for (int k = 0; k < 20000; k++) { + Gpu g, g0; + const size_t n = 1 + rng() % 8; + uint64_t s = 5000000 + (uint64_t)k * 16; + for (size_t i = 0; i < n; i++) g.parts.push_back(s++); + g.sent = 1 + rng() % n; + g.step = (int)(rng() % 4); + if (g.step == 0) g.timeline_after = 1 + (int)(rng() % 20); + g.range_part = (int)(rng() % (n + 1)) - 1; + g0 = g; + g.begin(), g0.begin(); + const size_t sent0 = g.sent; + const wr::ReadbackWait r = wr::readback_range_wait(g); + CHECK("range random: known and done", r.known && r.ok); + CHECK("range random: never a wait for a part not submitted", g.hangs == 0); + CHECK("range random: waits bounded", g.rec_waits <= (int)n + 1); + const uint64_t want = g.range_part < 0 ? g.parts.back() : g.parts[(size_t)g.range_part]; + CHECK("range random: never before the range's part is done", g.rec_done >= want || g.timeline_at_v); + CHECK("range random: never past it but for the timeline", g.rec_done == want || g.timeline_at_v); + if (g.range_part >= 0 && (size_t)g.range_part < sent0) + CHECK("range random: its part submitted before the read: one wait", g.rec_waits == 1 && !r.went_on && g.slices == 0); + const wr::ReadbackWait r0 = wr::readback_wait(false, g0); + CHECK("range random old: known", r0.known && r0.ok); + if (g.range_part > 0) { + range_later++; + if (g0.rec_done < want) first_early++; + } + } + CHECK("range random: ranges a later part copied were many", range_later > 5000); + CHECK("range random: the first part's wait read every one of them early", first_early == range_later); + std::printf("readback range wait: %d of 20000 ranges were copied back after the first part; the first part's wait read all %d early\n", + range_later, first_early); return 0; } diff --git a/tests/test_readback_rec_end.py b/tests/test_readback_rec_end.py index 5dba05d..5c75112 100644 --- a/tests/test_readback_rec_end.py +++ b/tests/test_readback_rec_end.py @@ -11,7 +11,9 @@ to come in a later part. Compiles and runs the header's rule against a made-up GPU (tests/test_readback_rec_end.cpp: the parts' table, the meter's case, an ended recording, one part, not known, a stuck replay ended by the timeline, an error, and 20,000 random recordings: never back before the last part is done, never a wait for a part not submitted; the old wait ends at the first part at every read that came -before the recording's end), and reads the source for what needs the game: +before the recording's end; (11-29) RX_VK_RB_REC_END=3's wait for a range the CPU only reads, readback_range_wait: at the part +that copied the range back, never before it, past it only by the timeline, the last part when none did; 20,000 random recordings +again), and reads the source for what needs the game: - submit_recording's registration notes every submit, part or end, by the recording's own value, under rec_map_mu; - readback_rec_wait runs the header's rule by RX_VK_RB_REC_END, looks the tables up under rec_map_mu, flushes the held submits before it waits on the recordings' timeline (a batched recording's signal goes out only with the batch), and slices the @@ -56,7 +58,8 @@ def in_order(text, needles, where): def check_source(): head = (ROOT / "gpu/vk/wb_rec_wait.h").read_text(encoding="utf-8") for needle in ("struct Parts {", "inline bool rec_end_on(const char* text)", "struct ReadbackWait {", - "ReadbackWait readback_wait(bool rec_end, D& d) {", + "ReadbackWait readback_wait(bool rec_end, D& d) {", "ReadbackWait readback_range_wait(D& d) {", + "inline bool range_applies(int mode, bool cpu_written) { return mode == kRecEndRange && !cpu_written; }", "void part_submitted(uint64_t value, uint64_t seq, bool part) { submitted(value, seq, !part); }"): check(needle in head, "gpu/vk/wb_rec_wait.h: %s is missing" % needle) @@ -72,20 +75,38 @@ def check_source(): "vk_replay.cpp: the parts are noted somewhere past the registration") on = function(replay, "int rb_rec_end_mode() {") - check('wr::rec_end_mode(getenv("RX_VK_RB_REC_END"))' in on and "static const int v" in on, + check('const char* e = getenv("RX_VK_RB_REC_END");' in on and "static const int v" in on, "RX_VK_RB_REC_END is not read once through the header's rule") + # ((Triforce, 11-29, the owner's decision) unset: 3 where the parts end at the game's render passes (their first part is + # ~32 draws, and mode 2 read a later part's result a frame late: the brightness pulses), else 2 as before + check("const int m = wr::rec_end_mode(e, parts ? wr::kRecEndRange : wr::kRecEndCpuWritten);" in on + and "const bool parts = pass_end_parts_on();" in on, + "RX_VK_RB_REC_END's default is not 3 with the pass-end parts and 2 with counted parts") + ends = function(replay, "PassEndParts& pass_end_parts() {") + check("rb_rec_end_mode(" not in ends and "rb_rec_end_on(" not in ends, + "pass_end_parts asks the readback mode's reader, which asks pass_end_parts: the two statics would wait on each other") + check('rec_end_mode(getenv("RX_VK_RB_REC_END"), ::mkwvk::wb_rec_wait::kRecEndRange)' in ends + and 'num("RX_VK_PART_RB", range ? 32 : 0)' in ends, + "RX_VK_PART_RB's default does not follow mode 3 (32 there, off with another mode set)") # ((Triforce, 11-28) mode 2, the default: the last-part rule only where the CPU writes the range after reading it) - fr = function(replay, "bool rb_rec_end_for(uint64_t guest, uint64_t size) {") - check("m == wr::kRecEndCpuWritten && memory_rb_cpu_written(guest, size)" in fr and "return wr::rec_end_applies(m, cpu);" in fr, - "rb_rec_end_for does not ask the memory whether the CPU writes the range (mode 2) through the header's rule") + # ((11-29) mode 3: the same, and a range the CPU only reads at the part that copied it back, by the header's range_applies) + fr = function(replay, "bool rb_rec_end_for(uint64_t guest, uint64_t size, bool* range) {") + check("(m == wr::kRecEndCpuWritten || m == wr::kRecEndRange) && memory_rb_cpu_written(guest, size)" in fr + and "return wr::rec_end_applies(m, cpu);" in fr, + "rb_rec_end_for does not ask the memory whether the CPU writes the range (modes 2 and 3) through the header's rule") + check("*range = wr::range_applies(m, cpu);" in fr, "rb_rec_end_for does not say a read-only range's wait (mode 3) by the header's rule") mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8") check(mem.count("memory_rb_cpu_collected(pages, n);") == 2, "the two collections of the CPU's pages do not both note the read-back pages") check("memory_rb_watch(guest, size);" in function(mem, "void memory_note_readback(uint64_t guest, uint64_t size) {"), "a readback's pages are not watched for the CPU's writes") - w = function(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) {") + w = function(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok, bool range) {") for needle, why in ( ("if (!rec_timeline || per_queue_fences_off()) return false;", "it waits by recordings where there are none"), - ("::mkwvk::wb_rec_wait::readback_wait(rb_rec_end_on(), calls);", "it does not run the header's rule by the switch"), + ("range ? ::mkwvk::wb_rec_wait::readback_range_wait(calls) : ::mkwvk::wb_rec_wait::readback_wait(rb_rec_end_on(), calls);", + "it does not run the header's rule by the switch, or a read-only range's wait (mode 3) by the header's"), + ("uint64_t range_seq() { return memory_wb_part_seq(guest, size, v); }", + "the range's part is not the memory's part that copied the range back under v"), + ("st_rb_range.fetch_add(1, std::memory_order_relaxed);", "the read-only ranges' waits (mode 3) are not counted"), ("return rec_parts_by_value.of(v);", "it does not look the parts up"), ("const auto it = value_rec.find(v);", "the old lookup is not value_rec's"), ("void flush() { queue_flush_for(FR_WAIT); }", "its looks do not flush the held submits"), @@ -101,8 +122,10 @@ def check_source(): check("pSemaphores = &rec_timeline;" in rw and "UINT64_MAX" in rw, "the recording's wait is not the recordings' timeline, unbounded") both = function(replay, "bool readback_recorded_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) {") - check("return rb_rec_end_for(guest, size) ? readback_rec_wait(v, guest, size, ok) : wait_recorded(v, UINT64_MAX, ok);" in both, - "readback_recorded_wait does not take the rule by the switch (the old wait kept for =0)") + in_order(both, ["bool range = false;", + "if (rb_rec_end_for(guest, size, &range)) return readback_rec_wait(v, guest, size, ok, false);", + "return range ? readback_rec_wait(v, guest, size, ok, true) : wait_recorded(v, UINT64_MAX, ok);"], + "readback_recorded_wait (the rule by the switch, a read-only range at its part for =3, the old wait kept for =0 and 2)") inv = function(replay, "void invalidate(uint64_t gpu, uint64_t size) {") check(inv.count("readback_recorded_wait(v, host->gpu_guest(gpu), size, &ok)") == 2, "invalidate's two waits by recordings do not both take the rule") check("if (!(unforced && readback_recorded_wait(v, host->gpu_guest(gpu), size, &ok))) {" in inv, "the submitting thread's wait does not take the rule") @@ -120,11 +143,39 @@ def check_source(): gl = function(replay, "void readback_went_on_line() {") check("st_rb_went_on.exchange(0)" in gl and "(RX_VK_RB_REC_END=0: the first part, as before)" in gl, "the 3000-readback line does not count the reads that waited past a part") + check("st_rb_range.exchange(0)" in gl and "st_rb_range_later.exchange(0)" in gl, + "the 3000-readback line does not count the read-only ranges' waits (mode 3) and those past the first part") dev = (ROOT / "docs/development.md").read_text(encoding="utf-8") rows = [line for line in dev.splitlines() if line.startswith("| `RX_VK_RB_REC_END=0` |")] check(len(rows) == 1, "docs/development.md: RX_VK_RB_REC_END is not in the switches table once") check("tests/test_readback_rec_end.py" in rows[0] and "wb_rec_wait.h" in rows[0], "docs/development.md: the row names neither the rule nor its test") + check("`=3`" in rows[0], "docs/development.md: the RX_VK_RB_REC_END row does not say mode 3") + + # ((Triforce, 11-29) RX_VK_LATE_PART: the queue's late-page wait at the part that wrote the pages back last, the value's + # wait as before whenever that part is not known; off unless set (or the lab knob latepart)) + flush = function(replay, "void late_fix_flush_locked() {") + in_order(flush, ["const uint64_t v = memory_late_fix_pending();", "if (completed() < v && !late_fix_part_wait()) {", + "vk_timeline_wait_sent(v)", "memory_late_fix_apply(UINT64_MAX);"], + "late_fix_flush_locked (the part's wait first, the value's when it was not made, then the fixes)") + pw = function(replay, "bool late_fix_part_wait() {") + in_order(pw, ["if (!rec_timeline || !memory_late_part_on()) return false;", "const uint64_t seq = memory_late_fix_part();", + "if (!seq) {", "wi.pSemaphores = &rec_timeline, wi.pValues = &seq;", "return done;"], + "late_fix_part_wait (off, no timeline or no part known: the value's wait)") + mem_on = function(mem, "bool memory_late_part_on() {") + check('getenv("RX_VK_LATE_PART")' in mem_on and 'lab_ab::on("latepart")' in mem_on and "atoi(e) != 0" in mem_on, + "RX_VK_LATE_PART is not off unless set, with the lab knob latepart") + lp = function(mem, "uint64_t late_pages_part(const std::vector>& slots, uint64_t done) {") + in_order(lp, ["std::lock_guard lk(wb_pages_mu);", "if (wb_runs_lost > done) return 0;", "if (r.value <= done", + "if (b == wb_batch_seq.end()) return 0;", "part = std::max(part, b->second);"], + "late_pages_part (a run cut or a part not submitted: not known)") + fp = function(mem, "uint64_t memory_late_fix_part() {") + check("if (!f.part) return 0;" in fp, "memory_late_fix_part does not give 0 when one pending fix's part is not known") + check("if (memory_late_part_on()) f.part = late_pages_part(f.slots, vk_timeline_completed());" in mem, + "the take does not note a put-off fix's part") + lrows = [line for line in dev.splitlines() if line.startswith("| `RX_VK_LATE_PART=1` |")] + check(len(lrows) == 1 and "off unless set" in lrows[0] and "tests/test_readback_rec_end.py" in lrows[0], + "docs/development.md: no RX_VK_LATE_PART row naming its default and its test") def main(): diff --git a/tests/test_recorded_wait_flush.py b/tests/test_recorded_wait_flush.py index b318941..734acb8 100644 --- a/tests/test_recorded_wait_flush.py +++ b/tests/test_recorded_wait_flush.py @@ -31,12 +31,13 @@ def main(): if "readback_recorded_wait(v, host->gpu_guest(gpu), size, &ok)" not in inv or "wait_recorded(v, UINT64_MAX, ok)" not in rrw: raise SystemExit("invalidate's readback wait no longer goes through wait_recorded: update this test") # ((Triforce, 11-27) RX_VK_RB_REC_END: the readback's wait by its own rule, readback_rec_wait, flushes the same way) - rb = body(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) {") + rb = body(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok, bool range) {") rw = rb[rb.index("int rec_wait(uint64_t seq) {"):] flush = rw.find("queue_flush_for(") if "vkWaitSemaphores(" not in rw or flush < 0 or flush > rw.index("vkWaitSemaphores("): raise SystemExit("readback_rec_wait waits without sending the held batch: a batched recording's signal never comes") - if "readback_rec_wait(v, guest, size, ok)" not in rrw: + # ((11-29) and the read-only ranges' wait at their part, RX_VK_RB_REC_END=3, the same function) + if "readback_rec_wait(v, guest, size, ok, false)" not in rrw or "readback_rec_wait(v, guest, size, ok, true)" not in rrw: raise SystemExit("invalidate's readback wait no longer goes through readback_rec_wait: update this test") print("PASS: wait_recorded and readback_rec_wait send the held batch before they wait") diff --git a/tests/test_renhdrum.py b/tests/test_renhdrum.py index 19cb045..0f2eccc 100644 --- a/tests/test_renhdrum.py +++ b/tests/test_renhdrum.py @@ -15,7 +15,8 @@ out); libopus is compiled by the same C compiler that links it, its paths relati crates Cargo.lock names, unpacked from the cache (each checked by its Cargo.lock SHA-256, one that is not refused); what fails the check is not copied out. A Rust download whose SHA-256 is not the pinned one is refused and not kept. -(Triforce) It is built by hand; nx2/build.py copies it beside the game when third_party/renhdrum/ has it, and +(Triforce) The releases build it: setup/pack_tools.ps1 into the tools zip, scripts/linux/appimage.sh into the AppImage +(a pack without it stops unless told); nx2/build.py copies it beside the game when third_party/renhdrum/ has it, and nx2/make_game.py stages it with the game's other files. third_party/renhdrum holds the source, with its upstream archive named. @@ -378,5 +379,19 @@ class Ships(unittest.TestCase): self.assertIn("SetThreadErrorMode(SEM_FAILCRITICALERRORS", module) self.assertIn("LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", module) + def test_the_releases_build_it(self): + # ((11-29) v0.8.0 to v0.8.5.2 shipped the code without the library: git ignores renhdrum.dll, and the tools zip packs + # tracked files. The pack builds it into the tools' third_party/renhdrum/, where build.py looks, and stops without it) + pack = (ROOT / "setup" / "pack_tools.ps1").read_text(encoding="utf-8") + self.assertIn("scripts\\renhdrum.py') build --target windows --llvm-mingw $rhMingw", pack) + self.assertIn("$rhOut = Join-Path $tools 'third_party\\renhdrum\\renhdrum.dll'", pack) + self.assertIn("if (-not $AllowNoRenhdrum) { throw", pack) + self.assertLess(pack.index("$rhOut = "), pack.index("# 5. the zips")) + # (the AppImage: renhdrum.so, the Linux target named, into its tools' third_party/renhdrum/) + image = (ROOT / "scripts" / "linux" / "appimage.sh").read_text(encoding="utf-8") + self.assertIn('scripts/renhdrum.py build --target linux --cache "$B/renhdrum-rust" ' + '--out "$T/third_party/renhdrum/renhdrum.so"', image) + self.assertLess(image.index("renhdrum.py build"), image.index("# ---- what it builds with ----")) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_reshade_compare_play.py b/tests/test_reshade_compare_play.py new file mode 100644 index 0000000..7d1a2f1 --- /dev/null +++ b/tests/test_reshade_compare_play.py @@ -0,0 +1,142 @@ +"""((Triforce, 11-30) The ReShade comparison asked inside the pause menu's Options goes to play first ("ReShade Compare not +taking you to gameplay screen", v0.8.5.2): the game is paused there and its scene draws nothing, so the comparison over its +screens showed the Options and the pause menu. + +host/nn_hid.c's compare_to_play is compiled alone with stand-ins for the option and the screens: B once on the Options, once +more only if that screen still runs 1.5 s later, then B on the pause menu, the renderer told 2 once neither has run for +300 ms, 3 when they are still up after 4 s, nothing while nothing is asked. The menu's side is read from the sources: the +Compare row's way there (compare_leaves_menus, not from the title's Options nor with a close question waiting), the host's +word taken, the comparison opened over the game and its Back closing the options, and the option answered by the renderer. +python -I -B tests/test_reshade_compare_play.py (needs a C compiler) +""" +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def block(text, marker): + start = text.index(marker) + end = text.index("{", start) + 1 + depth = 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end] + + +FIXTURE = r""" +#include +#include +#include +enum { HOS_OPT_COMPARE_PLAY = 432 }; +static int option_now, told, told_value, options_up, pause_up, taps; +static int64_t now; +static char last_tap[32]; +static int rx_option(int id, int otherwise) { return id == HOS_OPT_COMPARE_PLAY ? option_now : otherwise; } +static void rx_option_set(int id, int value) { if (id == HOS_OPT_COMPARE_PLAY) told++, told_value = value, option_now = value; } +static void hos_hid_tap(const char *press) { taps++, snprintf(last_tap, sizeof last_tap, "%s", press); } +static void hos_log(const char *f, ...) { (void)f; } +int hos_oot_options_front(void) { return options_up; } +int hos_oot_pause_front(void) { return pause_up; } +""" + +MAIN = r""" +static int fails; +#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0) +static void run(int64_t ms) { for (int64_t t = 0; t < ms; t += 16) now += 16000000LL, compare_to_play(now); } +int main(void) { + now = 1000000000LL; + options_up = 1; + run(500); + CHECK(taps == 0 && told == 0); /* (nothing asked: nothing pressed) */ + option_now = 1; /* (Compare confirmed inside the pause menu's Options) */ + run(16); + CHECK(taps == 1 && !strcmp(last_tap, "0:B/80")); /* (B on the Options) */ + run(1000); + CHECK(taps == 1); /* (its animation: no second B yet) */ + run(600); + CHECK(taps == 2); /* (still up 1.5 s on: the press was lost, once more) */ + run(2000); + CHECK(taps == 2); /* (twice at most) */ + options_up = 0, pause_up = 1; /* (back on the pause menu) */ + run(16); + CHECK(taps == 3 && told == 0); /* (B on the pause menu) */ + pause_up = 0; /* (it closed: in play once 300 ms pass with neither screen) */ + run(200); + CHECK(told == 0); + run(200); + CHECK(told == 1 && told_value == 2 && taps == 3); + run(1000); + CHECK(told == 1 && taps == 3); /* (the word given: nothing more while it is not asked again) */ + /* a second ask whose menus stay up: 3 after 4 s, the comparison where it is */ + option_now = 1, options_up = 1, taps = 0; + run(4100); + CHECK(told == 2 && told_value == 3 && taps == 2); + run(1000); + CHECK(told == 2 && taps == 2); + if (!fails) printf("PASS\n"); + return fails != 0; +} +""" + + +def check_sources(): + menu = (ROOT / "gpu" / "vk" / "vk_menu.cpp").read_text(encoding="utf-8") + replay = (ROOT / "gpu" / "vk" / "vk_replay.cpp").read_text(encoding="utf-8") + api = (ROOT / "gpu" / "vk" / "vk_api.h").read_text(encoding="utf-8") + hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8") + menu_c = (ROOT / "host" / "oot_menu.c").read_text(encoding="utf-8") + if "enum { HOS_OPT_COMPARE_PLAY = 432 };" not in api: + raise SystemExit("the option HOS_OPT_COMPARE_PLAY is gone") + if "if (id == HOS_OPT_COMPARE_PLAY) return menu_compare_play();" not in replay: + raise SystemExit("the renderer does not answer HOS_OPT_COMPARE_PLAY: the host never sees the ask") + leaves = block(menu, "bool compare_leaves_menus() {") + for need in ("embed_open", "game_options_from_pause", "!apply_ask()", "!restart_ask()"): + if need not in leaves: + raise SystemExit("compare_leaves_menus lost a condition: " + need) + press = "else if (press[7] && r.name == kReshadeCompare && compare_leaves_menus()) {" + if press not in menu or menu.index(press) > menu.index("else if (press[7] && reshade_menu::act(r.name))"): + raise SystemExit("the Compare row inside the pause menu's Options does not go to play first") + if "compare_play.store(1, std::memory_order_relaxed);" not in menu: + raise SystemExit("the Compare row does not ask the host") + if "if (id == HOS_OPT_COMPARE_PLAY) {" not in menu or "compare_exchange_strong(asked, value" not in menu: + raise SystemExit("the host's word (2 in play, 3 not) is not taken by the menu") + if "reshade_menu::start_comparison();" not in menu or "compare_from_game = ready == 2;" not in menu: + raise SystemExit("the comparison does not open once the host says so") + if "if (!reshade_menu::comparing() && compare_from_game) compare_from_game = false, open_now = false" not in menu: + raise SystemExit("the comparison's Back no longer closes the options it opened over the game") + read = block(hid, "static void read_input(") + if "compare_to_play(hos_now_ns());" not in read: + raise SystemExit("read_input does not run compare_to_play") + if menu_c.count("int hos_oot_pause_front(void) {") != 2: + raise SystemExit("hos_oot_pause_front is not in both halves of host/oot_menu.c") + + +def main(): + check_sources() + compiler = shutil.which("gcc") or shutil.which("clang") + if not compiler: + print("SKIP: no C compiler (the sources checked)") + return + hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8") + code = FIXTURE + block(hid, "static void compare_to_play(int64_t now) {") + "\n" + MAIN + with tempfile.TemporaryDirectory(prefix="triforce-compare-play-") as tmp: + tmp = Path(tmp) + (tmp / "t.c").write_text(code, encoding="utf-8") + binary = tmp / ("t.exe" if sys.platform == "win32" else "t") + build = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Werror", str(tmp / "t.c"), "-o", str(binary)], + text=True, capture_output=True) + if build.returncode: + raise SystemExit(build.stderr) + run = subprocess.run([str(binary)], text=True, capture_output=True, timeout=30) + if run.returncode: + raise SystemExit(run.stdout + run.stderr) + print("PASS: Compare from the pause menu's Options leaves its menus (B, B), opens over the game, and gives up after 4 s") + + +if __name__ == "__main__": + main() diff --git a/tests/test_sim_turf_hold.py b/tests/test_sim_turf_hold.py new file mode 100644 index 0000000..b1127a3 --- /dev/null +++ b/tests/test_sim_turf_hold.py @@ -0,0 +1,102 @@ +"""A simulated-turf list that a program reads the game's way never grows past the game's size (11-29 GPU hang). + +python -I -B tests/test_sim_turf_hold.py [--cxx clang++] + +Cuts `SimTurfPrivate` and `sim_turf_hold` out of gpu/vk/vk_draw.cpp and builds them against the real +gpu/vk/sim_turf_capacity.h, then plays the 11-29 crash at them. His Kokiri Forest edit asked for 132033 of the blade +list's 143360 records; the list grew to 165056, and the pool producer (3de6d86ec7e6720e, left as the game has it by the IR +pass) read record 143359 - i for i past 143359, far outside the buffer: the dispatch never ended, device lost. Checks: +without a hold the list grows (as before: the control); held, it stays at the game's size under the same demand; a list +already grown when the hold comes is made the game's size again at the next install. +""" +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) # (python -I leaves the check's own folder off the path) +from srccut import block # noqa: E402 + +RUN_ALL_ARGS = ["--cxx", "{cxx}"] + +ROOT = Path(__file__).resolve().parents[1] + +HARNESS = r""" +#include +#include +#include +#include "sim_turf_capacity.h" + +using VkBuffer = void*; +using VmaAllocation = void*; +#define VK_NULL_HANDLE nullptr +namespace Shader::Optimization { +inline constexpr uint32_t kSimTurfBladeCap = 143360; +inline constexpr uint32_t kSimTurfPoolCap = 138240; +} +namespace mkwvk { +@CUT@; +@HOLD@ +} + +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0) + +int main() { + using mkwvk::SimTurfPrivate; + for (const bool pool : {false, true}) { + const uint32_t stock = pool ? 138240u : 143360u, wanted = pool ? 127000u : 132033u; + { // the control: nobody reads it the game's way, so it grows as before + SimTurfPrivate g(pool, 1u << 20); + CHECK(g.policy.observe(wanted, 100)); + g.policy.installed(); + CHECK(g.policy.capacity() > stock); + } + { // held from the start (the unpatched reader runs every frame long before the demand): it never grows + SimTurfPrivate g(pool, 1u << 20); + mkwvk::sim_turf_hold(g, pool); + CHECK(!g.policy.observe(wanted, 100)); + CHECK(!g.policy.observe(1u << 19, 101)); + CHECK(g.policy.capacity() == stock && g.policy.target() == stock && g.policy.maximum() == stock); + } + { // grown first, held after: the next install is the game's size again + SimTurfPrivate g(pool, 1u << 20); + CHECK(g.policy.observe(wanted, 100)); + g.policy.installed(); + CHECK(g.policy.capacity() > stock); + mkwvk::sim_turf_hold(g, pool); + CHECK(g.policy.target() == stock); // (target != capacity: the producer's next binding resizes) + g.policy.installed(); + CHECK(g.policy.capacity() == stock); + CHECK(!g.policy.observe(wanted, 200)); + g.policy.limit(1u << 20); // (a reader's larger bound never lifts the hold) + CHECK(!g.policy.observe(wanted, 201) && g.policy.capacity() == stock); + } + } + std::puts("PASS: a simulated-turf list read the game's way stays at the game's size"); +} +""" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="clang++") + args = parser.parse_args() + draw = (ROOT / "gpu" / "vk" / "vk_draw.cpp").read_text(encoding="utf-8") + cut = block(draw, "struct SimTurfPrivate {") + hold = block(draw, "void sim_turf_hold(SimTurfPrivate& g, bool pool) {") + with tempfile.TemporaryDirectory(prefix="sim-turf-hold-") as folder: + src = Path(folder) / "sim_turf_hold.cpp" + src.write_text(HARNESS.replace("@CUT@", cut).replace("@HOLD@", hold), encoding="utf-8") + exe = Path(folder) / "sim_turf_hold.exe" + subprocess.run([args.cxx, "-std=c++20", "-I" + str(ROOT / "gpu" / "vk"), str(src), "-o", str(exe)], check=True) + env = os.environ.copy() + env["PATH"] = str(Path(args.cxx).resolve().parent) + os.pathsep + env.get("PATH", "") + subprocess.run([str(exe)], check=True, env=env) + + +if __name__ == "__main__": + main() diff --git a/tests/test_tex_pack_bc7.py b/tests/test_tex_pack_bc7.py new file mode 100644 index 0000000..f1a45e9 --- /dev/null +++ b/tests/test_tex_pack_bc7.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""gpu/vk/tex_pack_bc7.h: Evil HD's texture pack as BC7, prepared once (vk_texture.cpp texpack). + +Checks the prepared file's header and sizes, the levels, the 2 x 2 halving, the tiers by the card's memory, and that the +encoder writes BC7 mode 6 blocks that keep a flat colour exactly. Compiles a small harness with the C++ compiler given. + + python -I -B tests/test_tex_pack_bc7.py [--cxx g++] +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +RUN_ALL_ARGS = ["--cxx", "g++"] + +HARNESS = r''' +#include "tex_pack_bc7.h" +#include +static int failures; +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %d: %s\n", __LINE__, #x); failures++; } } while (0) +namespace tb = mkwvk::tex_pack_bc7; +// (mode 6: bit 6 of the first byte; the endpoints and p-bits of a flat block decode to its colour at every index) +static void decode6(const uint8_t b[16], uint8_t rgba[4]) { + uint64_t w[2]; + std::memcpy(w, b, 16); + auto bits = [&](int pos, int n) -> uint32_t { + uint64_t v = pos < 64 ? (w[0] >> pos) | (pos + n > 64 ? w[1] << (64 - pos) : 0) : w[1] >> (pos - 64); + return (uint32_t)(v & ((1ull << n) - 1)); + }; + int pos = 7, e[2][4]; + for (int c = 0; c < 4; c++) e[0][c] = bits(pos, 7), pos += 7, e[1][c] = bits(pos, 7), pos += 7; + const int p0 = bits(pos, 1), p1 = bits(pos + 1, 1); + pos += 2; + const int idx = bits(pos, 3); + static const int kw[16] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}; + for (int c = 0; c < 4; c++) { + const int a = e[0][c] * 2 + p0, z = e[1][c] * 2 + p1; + rgba[c] = (uint8_t)(((64 - kw[idx]) * a + kw[idx] * z + 32) >> 6); + } +} +int main() { + // sizes and levels + CHECK(tb::level_bytes(4, 4) == 16 && tb::level_bytes(5, 5) == 64 && tb::level_bytes(1, 1) == 16 && tb::level_bytes(2048, 2048) == 4194304); + CHECK(tb::full_levels(2048, 2048) == 12 && tb::full_levels(682, 682) == 10 && tb::full_levels(1, 1) == 1 && tb::full_levels(8, 2) == 4); + CHECK(tb::file_bytes(8, 8, 4) == tb::kHeader + 64 + 16 + 16 + 16); + // the header + uint8_t buf[256] = {}; + tb::Header h; + h.w = 8, h.h = 8, h.levels = 4, h.png_size = 123456789012ull; + tb::write_header(buf, h); + tb::Header r; + CHECK(tb::read_header(buf, (size_t)tb::file_bytes(8, 8, 4), &r) && r.w == 8 && r.h == 8 && r.levels == 4 && r.png_size == 123456789012ull); + CHECK(!tb::read_header(buf, (size_t)tb::file_bytes(8, 8, 4) - 1, &r)); // (cut short) + CHECK(!tb::read_header(buf, 10, &r)); + h.levels = 5; // (more levels than 8 x 8 has) + tb::write_header(buf, h); + CHECK(!tb::read_header(buf, (size_t)tb::file_bytes(8, 8, 4), &r)); + buf[0] ^= 1; + CHECK(!tb::read_header(buf, sizeof buf, &r)); + // halving: the mean of 2 x 2, an odd edge's last texel repeated + std::vector px(3 * 3 * 4); + for (size_t i = 0; i < px.size(); i++) px[i] = (uint8_t)(i * 7); + uint32_t ow = 0, oh = 0; + const auto hv = tb::half(px, 3, 3, &ow, &oh); + CHECK(ow == 1 && oh == 1 && hv.size() == 4); + CHECK(hv[0] == (uint8_t)((0 + 4 * 7 + 12 * 7 + 16 * 7 + 2) / 4)); + // the encoder: mode 6, a flat colour kept + std::vector flat(8 * 8 * 4); + for (size_t i = 0; i < flat.size(); i += 4) flat[i] = 200, flat[i + 1] = 100, flat[i + 2] = 50, flat[i + 3] = 255; + std::vector out((size_t)tb::level_bytes(8, 8)); + tb::encode(flat.data(), 8, 8, out.data()); + for (int b = 0; b < 4; b++) { + CHECK(out[b * 16] == 0x40); + uint8_t c[4]; + decode6(&out[b * 16], c); + CHECK(std::abs(c[0] - 200) <= 1 && std::abs(c[1] - 100) <= 1 && std::abs(c[2] - 50) <= 1 && c[3] >= 254); + } + // the tiers, by the card's own memory + CHECK(tb::tier_for(12282) == tb::kAll && tb::tier_for(16376) == tb::kAll && tb::tier_for(11000) == tb::kAll); + CHECK(tb::tier_for(10240) == tb::kNoBig && tb::tier_for(8192) == tb::kNoBig && tb::tier_for(6144) == tb::kSmall && tb::tier_for(4096) == tb::kNone); + CHECK(tb::tier_wants(tb::kAll, 1024, 1024) && tb::tier_wants(tb::kNoBig, 512, 1023) && !tb::tier_wants(tb::kNoBig, 1024, 256)); + CHECK(tb::tier_wants(tb::kSmall, 511, 256) && !tb::tier_wants(tb::kSmall, 512, 256) && !tb::tier_wants(tb::kNone, 256, 256)); + CHECK(tb::tier_env("3") == 3 && tb::tier_env("0") == 0 && tb::tier_env(nullptr) == -1 && tb::tier_env("") == -1 && tb::tier_env("4") == -1 && tb::tier_env("12") == -1); + std::fprintf(stderr, "%s\n", failures ? "failed" : "ok"); + return failures ? 1 : 0; +} +''' + + +def check_source(): + tex = (ROOT / "gpu/vk/vk_texture.cpp").read_text(encoding="utf-8") + problems = [] + for needle, why in ( + ('#include "tex_pack_bc7.h"', "vk_texture.cpp does not include the BC7 pack header"), + ("if (tex->pack_state == 1 || !texpack::on() || !texpack::ready.load(std::memory_order_acquire)) return VK_NULL_HANDLE;", + "pack_view uses the pack before it is prepared (textures would turn HD one by one)"), + ("ci.format = VK_FORMAT_BC7_UNORM_BLOCK;", "the pack's images are not BC7"), + ("tb::tier_wants((tb::Tier)tier, fw, fh)", "pack_view does not take the tier"), + ("if (now) texpack::prepare_start();", "the prepare does not start when Evil HD is on"), + ("tb::tier_for(heap >> 20)", "the tier is not by the card's own memory"), + ("? (uint64_t)std::clamp(atoi(getenv(\"RX_VK_TEX_PACK_LINE\")), 20, 98) : 95;", "the emergency line is not 95% by default")): + if needle not in tex: + problems.append(why) + for gone in ("texpack::cap", "kPackBudget", "make_line", "vkCmdBlitImage(cmd, tex->hd"): + if gone in tex: + problems.append("vk_texture.cpp still has the old pack budget or blits: " + gone) + menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8") + if "texpack_prepare_text(t, sizeof t)" not in menu: + problems.append("the menu does not show the prepare's progress") + return problems + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--cxx", default=os.environ.get("CXX", "g++")) + a = p.parse_args() + problems = check_source() + with tempfile.TemporaryDirectory(prefix="tex-pack-bc7-") as tmp: + src, exe = Path(tmp) / "t.cpp", Path(tmp) / "t" + src.write_text(HARNESS, encoding="utf-8") + build = subprocess.run([a.cxx, "-std=c++17", "-O1", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT / "gpu/vk"), str(src), "-o", str(exe)]) + if build.returncode: + raise SystemExit("the harness did not compile: see the compiler's output above") + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stderr.write(run.stderr) + if run.returncode: + problems.append("the harness failed (above)") + for pr in problems: + print("FAIL: " + pr) + if problems: + return 1 + print("PASS: the pack's BC7 files, levels, halving and encoder, and the tiers by the card") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_threaded_rendering.py b/tests/test_threaded_rendering.py index b8b486c..4989671 100644 --- a/tests/test_threaded_rendering.py +++ b/tests/test_threaded_rendering.py @@ -1,12 +1,13 @@ """Threaded rendering (gpu/vk/threaded_rendering.h, vk_main.cpp threaded_choice; no game/GPU). -The rule is compiled from the header and run on made-up PCs: Off (the row's default, 0) and any value that is none of the row's are +The rule is compiled from the header and run on made-up PCs: Off (0) and any value that is none of the row's are off whatever the CPU; On is both threads whatever the CPU; Auto is both threads from 4 physical cores and off below, off where the run is not safe, and with no buffer-pool mirrors the recorder thread alone from 6 cores, off below. RX_VK_THREADED's words. The source: the row is on the Debug tab with Off first, async_on reads the render thread's half only with RX_VK_ASYNC unset, the recorder's half goes through recorder_auto in pick_device, and the host asks HOS_OPT_RENDER_THREAD only with RX_VK_ASYNC unset. (11-27) The recorder's hand-off by part is not Threaded rendering's: RX_VK_RECORDER_PARTS=1 alone turns it on (with it the 3D was -drawn with wrong textures on the lab's RX 7900 XT, in v0.8.3 too). +drawn with wrong textures on the lab's RX 7900 XT, in v0.8.3 too). (11-29) The row is Auto (2) by default: a new options +file's, and an older file's (before options_version 11) Off turned into Auto once, at menu_init; the file is written as 11. python -I -B tests/test_threaded_rendering.py [--cxx clang++] """ @@ -69,8 +70,19 @@ def check_source(): menu_h = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8") replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8") backend = (ROOT / "host/rx_backend.c").read_text(encoding="utf-8") - if "int threaded_rendering = 0;" not in menu_h: - fail("the row's default is no longer Off (0)") + if "int threaded_rendering = 2;" not in menu_h: + fail("the row's default is no longer Auto (2)") + # ((Triforce, 11-29) an older file wrote the old Off default whether chosen or not: its Off becomes Auto once, at the start, + # before threaded_choice reads the row; On or Auto chosen stays, and a file of 11 on keeps what was chosen) + init = menu[menu.index("void menu_init() {"):] + init = init[:init.index("\n}\n")] + if "if (version < 11 && opts.threaded_rendering == 0) opts.threaded_rendering = 2;" not in init: + fail("menu_init no longer turns an older file's Off into Auto") + save = menu[menu.index("void save() {"):] + if 'out += "options_version=11\\n";' not in save[:save.index("\n}\n")]: + fail("save no longer writes options_version=11 (an older file's Off would become Auto at every start)") + if "threaded_choice() {" in menu or "opts.threaded_rendering =" in main: + fail("the row is set somewhere other than menu_init and the menu") if '{TAB_DEBUG, "Threaded rendering", &opts.threaded_rendering, 0, 2, 1, tx_threaded,' not in menu: fail("the Threaded rendering row moved or changed") pick = main[main.index("bool pick_device() {"):main.index("bool create_device() {")] @@ -85,13 +97,15 @@ def check_source(): fail("async_on no longer reads the row only with RX_VK_ASYNC unset") rec = (ROOT / "gpu/vk/vk_recorder.h").read_text(encoding="utf-8") internal = (ROOT / "gpu/vk/vk_internal.h").read_text(encoding="utf-8") - # the design's other pieces: each off unless Threaded rendering (or its own switch) turns it on + # the design's other pieces: each off unless Threaded rendering (or its own switch) turns it on ((Triforce, 11-29) but the + # parts, which NVIDIA's driver has by default too: barrier_rules.h part_pass_end_default, by the device's driver id) for needle, where in ( ('g_parts.store(pe && *pe ? atoi(pe) != 0 : g_parts_default && g_parts_default(), std::memory_order_relaxed);', rec), ("if (!g_parts.load(std::memory_order_relaxed)) return;", rec), # (queue_lock_event: nothing without the hand-off) ("const bool rec_parts_hooks = (::mkwvk::queue_lock_hook = ::mkwvk::rec::queue_lock_event, true);", replay), ("const bool post = rec::parts_wanted() && r.pieces.empty() && !memory_lazy_running();", replay), - ('v.on = e && *e ? atoi(e) != 0 : threaded_on() && !getenv("RX_VK_CHUNK");', replay), + ("const bool by_default = threaded_on() || barrier_rules::part_pass_end_default((uint32_t)dev.driver_id);", replay), + ('v.on = e && *e ? atoi(e) != 0 : by_default && !getenv("RX_VK_CHUNK");', replay), ("const bool v = e && *e ? atoi(e) == 1 : threaded_on();", replay), ("static const bool v = threaded_on();", replay), ("QueueMutex present_mu;", internal)): @@ -129,8 +143,8 @@ def main(): done = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60, creationflags=flags) if done.returncode or done.stdout.strip() != "OK": fail((done.stdout + done.stderr).strip()) - print("PASS: Threaded rendering: Off by default and as before, On both threads, Auto by physical cores (the recorder alone " - "without mirrors from 6); the row, the readers and the host's question in place") + print("PASS: Threaded rendering: Auto by default (an older file's Off once), Off as before, On both threads, Auto by physical " + "cores (the recorder alone without mirrors from 6); the row, the readers and the host's question in place") if __name__ == "__main__": diff --git a/tests/test_title_tabs.py b/tests/test_title_tabs.py index ffd2465..4f632d6 100644 --- a/tests/test_title_tabs.py +++ b/tests/test_title_tabs.py @@ -20,9 +20,16 @@ This compiles title_tabs.h alone (with game_grid.h) and checks where the tabs la - the point test: each label's and each icon's middle is its tab, the gap between them and the picture's middle none; with the save files off there is the one tab, Mods. -And the sources: the tabs are drawn with the game's own icons of what the Switch's X (Mods: the top face button, Y on an Xbox -pad, Triangle on a PlayStation one) and Y (Save Select: the left one, X and Square) are bound to; the pad's own buttons, a -click, or the host's words 6 and 7 (a test's scripted X and Y) choose them; the entry under the title's list is Quit Game. +And the sources: the tabs' prompts name the pad input the Switch's X (Mods: the top face button, Y on an Xbox pad, Triangle +on a PlayStation one) and Y (Save Select: the left one, X and Square) are bound to, as the button test reads it; the pad's +own buttons, a click, or the host's words 6 and 7 (a test's scripted X and Y) choose them; the entry under the title's list +is Quit Game. + +((Triforce, 11-30) two players on an Xbox and a PlayStation controller: "The X is supposed to open up the Mod Menu but instead +it is opening up the save selection". The prompt was the Switch button's own code, right only in a font pointed at this run's +controls: in the game's own font, or on a cap without one, the Switch's letter, the other button's name on those pads. Now +the icon of the bound input itself on the face shown (title_tabs.h icon_codes, the font's codes as host/prompts.c and +nx2/prompt_assets.py number them), or that input's name: checked for every face and the layout presets.) python -I -B tests/test_title_tabs.py [--cxx clang++] """ @@ -57,6 +64,7 @@ PROGRAM = r""" #include #include #include +#include #include "title_tabs.h" using namespace mkwvk; static int fails; @@ -121,7 +129,42 @@ static void one(const Case& c) { unit, m.kx, m.x(l.tab[0].x0), m.x(l.tab[0].x1), m.x(l.tab[1].x0), m.x(l.tab[1].x1), m.y(l.tab[1].y1), px0, py0); } +// ((Triforce, 11-30) the prompts: each tab's the icon of the pad input its button is bound to, on the face shown. The faces and +// the inputs as gpu/vk/vk_api.h numbers them (HOS_PROMPT_SWITCH .. HOS_PROMPT_STEAMDECK the controllers'; HOS_PAD_SOUTH, +// EAST, WEST, NORTH first), and the layout presets as vk_menu.cpp apply_pad_layout binds the Switch's X and Y +static void prompts_check() { + const char* name = "prompts"; + enum { SOUTH, EAST, WEST, NORTH, PADS = 17, FACES = 5, KEYBOARD = 5 }; + struct Preset { const char* name; int x, y; } presets[] = {{"Nintendo (Def)", NORTH, WEST}, {"Xbox / PC", WEST, NORTH}, {"Swap Face", NORTH, WEST}}; + for (const Preset& p : presets) + for (int face = 0; face < FACES; face++) { + unsigned mods[2], saves[2]; + title_tabs::icon_codes(face, p.x, FACES, PADS, mods); + title_tabs::icon_codes(face, p.y, FACES, PADS, saves); + // (the icon is the face's own of the very input menu_tick opens the tab with, never the Switch's X or Y code) + CHECK(mods[0] == 0xF800u + 32u * (unsigned)face + (unsigned)p.x && saves[0] == 0xF800u + 32u * (unsigned)face + (unsigned)p.y); + CHECK(mods[1] == 0xF700u + (unsigned)p.x && saves[1] == 0xF700u + (unsigned)p.y); + CHECK(mods[0] != saves[0] && mods[0] != 0xE042u && saves[0] != 0xE043u); + } + // (the default controls on an Xbox pad: Mods the Y button's icon (the top one); on a PlayStation 5 one Save Select + // Square's (the left one), as the owner asked) + unsigned c[2]; + title_tabs::icon_codes(1, NORTH, FACES, PADS, c); + CHECK(c[0] == 0xF800u + 32u + 3u); + title_tabs::icon_codes(3, WEST, FACES, PADS, c); + CHECK(c[0] == 0xF800u + 96u + 2u); + // (no face known, the keys' face, an unbound button, a paddle past the inputs with icons: no code, the input's name instead) + for (int face : {-1, (int)KEYBOARD, 9}) { title_tabs::icon_codes(face, NORTH, FACES, PADS, c); CHECK(c[0] == 0 && c[1] == 0); } + for (int input : {-1, (int)PADS, 21}) { title_tabs::icon_codes(1, input, FACES, PADS, c); CHECK(c[0] == 0 && c[1] == 0); } + // (UTF-8, as ImGui reads it) + char u[4]; + CHECK(std::string(title_tabs::utf8(0xF823, u)) == "\xEF\xA0\xA3" && std::string(title_tabs::utf8(0xE042, u)) == "\xEE\x81\x82"); + CHECK(std::string(title_tabs::utf8('X', u)) == "X" && std::string(title_tabs::utf8(0xE9, u)) == "\xC3\xA9"); + CHECK(!title_tabs::utf8(0, u)[0] && !title_tabs::utf8(0x1F600, u)[0]); +} + int main() { + prompts_check(); static const Case cases[] = { {"16:9 1920x1080", 1920, 1080, 1920, 1080, 0}, {"16:9 1280x720", 1280, 720, 1280, 720, 0}, @@ -168,11 +211,36 @@ def main(): and "const game_grid::Map m = game_grid::map_of(title_grid);" in tabs, "the tabs are not placed from the picture's top left corner on the game's grid") check('static const char* const labels[title_tabs::kTabs] = {"Mods", "Save Select"};' in tabs - and "static const char* const icons[title_tabs::kTabs] = {ui::kIconX, ui::kIconY};" in tabs, + and "static const int buttons[title_tabs::kTabs] = {HOS_SW_X, HOS_SW_Y};" in tabs, "Mods is not the Switch's X (the top face button) and Save Select its Y (the left one)") - check("const bool pad = game_prompts_pad();" in tabs and "if (!pad || show <= 0) continue;" in tabs + check("const bool pad = game_prompts_pad();" in tabs and "if (!pad || !bound[i] || show <= 0) continue;" in tabs and "c.d->AddText(c.f.glyph, ipx, at, ui::alpha(ui::kInk, show), icons[i]);" in tabs, "the prompts under the tabs are not the game's icons, shown with a controller and fading with the list") + # ((Triforce, 11-30) the prompt is the bound input's own, as the button test reads it: its icon on the face shown, else its + # name; never the Switch button's own code (U+E042, U+E043: the Switch's letter in the game's own font) nor its letter) + check("const int input = host && host->binding ? host->binding(HOS_BIND_PAD, buttons[i], 0) : -1;" in tabs + and "bound[i] = hos_pad_bindable(input);" in tabs + and "title_tabs::icon_codes(face, input, HOS_PROMPT_KEYBOARD, HOS_PAD_N, codes);" in tabs + and "c.f.glyph->IsGlyphInFont((ImWchar)code)) title_tabs::utf8(code, icons[i]);" in tabs + and "names[i] = pad_name(input);" in tabs + and "const int face = host && host->prompt_face ? host->prompt_face() : -1;" in tabs, + "a tab's prompt is not the icon (or the name) of the pad input its button is bound to") + check("kIconX" not in tabs and "kIconY" not in tabs and '{"X", "Y"}' not in tabs, + "a tab's prompt is still the Switch button's own icon or letter: the other button's on an Xbox or PlayStation pad") + check('const ui::Prompt p{ui::kKey, "", names[i]};' in tabs and "if (icons[i][0]) {" in tabs, + "without the input's icon in the font the prompt is not its name on a key's cap") + # (the codes as the host and the font builder number them) + prompts = (ROOT / "host" / "prompts.c").read_text(encoding="utf-8") + assets = (ROOT / "nx2" / "prompt_assets.py").read_text(encoding="utf-8") + check("#define FACE_BASE 0xF800" in prompts and "#define FACE_CODES 32" in prompts and "#define PAD_BASE 0xF700" in prompts + and "#define LIVE_FACES HOS_PROMPT_KEYBOARD" in prompts + and "\nFACE_BASE = 0xF800" in assets and "\nFACE_CODES = 32" in assets and "\nPAD_BASE = 0xF700" in assets + and "constexpr unsigned kPadBase = 0xF700;" in header and "constexpr unsigned kFaceBase = 0xF800, kFaceCodes = 32;" in header, + "title_tabs.h's icon codes are not host/prompts.c's and nx2/prompt_assets.py's") + check('PADS = ["south", "east", "west", "north",' in assets, "the font's pad inputs are not in HOS_PAD_* order") + check(all(l in menu for l in ("host->bind(HOS_BIND_PAD, HOS_SW_X, 0, HOS_PAD_NORTH);", "host->bind(HOS_BIND_PAD, HOS_SW_X, 0, HOS_PAD_WEST);", + "host->bind(HOS_BIND_PAD, HOS_SW_Y, 0, HOS_PAD_WEST);", "host->bind(HOS_BIND_PAD, HOS_SW_Y, 0, HOS_PAD_NORTH);")), + "the layout presets the prompts are checked with are not apply_pad_layout's") check("title_tab_layout = l, title_tab_map = m, title_tab_ns = prof_now();" in tabs, "where the tabs were drawn is not kept for the mouse") # ((Triforce) the lab's first run: on the owner's 21:9 picture the corner is left of the column, and nothing was drawn) check(tabs.index("title_tabs::picture_clip(title_grid, m,") < tabs.index("c.d->PushClipRect(ImVec2(clip[0], clip[1]), ImVec2(clip[2], clip[3]), false);") diff --git a/tests/test_vendor_fixes.py b/tests/test_vendor_fixes.py index e3bc246..3619e7e 100644 --- a/tests/test_vendor_fixes.py +++ b/tests/test_vendor_fixes.py @@ -3,7 +3,8 @@ vendor_fixes() is compiled with the Vulkan headers and run on the properties of GPUs players have: NVIDIA's driver on Windows and Linux (and NVK on the same cards), AMD's Windows driver in its two branches (RDNA 1/2: "AMD proprietary shader compiler"; RDNA 3/4: LLPC), RADV, AMDVLK, Intel's Windows driver on an integrated GPU and on an Arc card, ANV, -llvmpipe. Each fix must be on for the GPUs it is for and off for every other, and NVIDIA's driver must get none: that is +llvmpipe. Each fix must be on for the GPUs it is for and off for every other (robust buffer access: Intel's Windows driver alone, +11-30), and NVIDIA's driver must get none: that is what keeps the renderer and the translated shaders on NVIDIA as they were. The RX_VK_ switches force each one either way. Then the source: the device's fixes are made from its properties at device creation, and the translator is told fetch_bounds, nan_bits and the gather offset (and the program cache's stamp tells the three apart). @@ -20,29 +21,31 @@ RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{vulkan_headers}"] ROOT = Path(__file__).resolve().parents[1] VK = ROOT / "gpu" / "vk" -# name, vendor, driver id, device type, driverInfo -> fetch_bounds, nan_bits, gather_offset +# name, vendor, driver id, device type, driverInfo -> fetch_bounds, nan_bits, gather_offset, robust_buffers DEVICES = [ - ("RTX 3090, NVIDIA's Linux driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "580.105.08", "000"), - ("RTX 4070 laptop, NVIDIA's Windows driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "581.57", "000"), - ("GTX 1650, NVK", 0x10DE, "MESA_NVK", "DISCRETE_GPU", "Mesa 26.0.1", "000"), + ("RTX 3090, NVIDIA's Linux driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "580.105.08", "0000"), + ("RTX 4070 laptop, NVIDIA's Windows driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "581.57", "0000"), + ("GTX 1650, NVK", 0x10DE, "MESA_NVK", "DISCRETE_GPU", "Mesa 26.0.1", "0000"), ("RX 6700 XT, AMD's Windows driver (RDNA 2 branch)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", - "26.10.1 (AMD proprietary shader compiler)", "111"), + "26.10.1 (AMD proprietary shader compiler)", "1110"), ("RX 5700, AMD's Windows driver (RDNA 1 branch)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", - "25.9.1 (AMD proprietary shader compiler)", "111"), - ("RX 9070 XT, AMD's Windows driver (LLPC)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "26.10.1 (LLPC)", "101"), - ("RX 7600, AMD's Windows driver, no driverInfo", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "", "101"), + "25.9.1 (AMD proprietary shader compiler)", "1110"), + ("RX 9070 XT, AMD's Windows driver (LLPC)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "26.10.1 (LLPC)", "1010"), + ("RX 7600, AMD's Windows driver, no driverInfo", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "", "1010"), ("AMD's driver naming another shader compiler", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "26.10.1 (LLPC shader compiler)", - "101"), - ("RX 580, RADV", 0x1002, "MESA_RADV", "DISCRETE_GPU", "Mesa 26.2.5", "101"), - ("Steam Deck, RADV", 0x1002, "MESA_RADV", "INTEGRATED_GPU", "Mesa 25.1.0", "101"), - ("RX 6800, AMDVLK", 0x1002, "AMD_OPEN_SOURCE", "DISCRETE_GPU", "2025.Q2.1 (LLPC)", "101"), - ("UHD Graphics, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7088", "101"), - ("Iris Xe, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7092", "101"), - ("Arc B580, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "DISCRETE_GPU", "101.8132", "101"), - ("Iris Xe, ANV", 0x8086, "INTEL_OPEN_SOURCE_MESA", "INTEGRATED_GPU", "Mesa 26.0.1", "101"), - ("llvmpipe", 0x10005, "MESA_LLVMPIPE", "CPU", "Mesa 26.0.1 (LLVM 20.1.8)", "100"), + "1010"), + ("RX 580, RADV", 0x1002, "MESA_RADV", "DISCRETE_GPU", "Mesa 26.2.5", "1010"), + ("Steam Deck, RADV", 0x1002, "MESA_RADV", "INTEGRATED_GPU", "Mesa 25.1.0", "1010"), + ("RX 6800, AMDVLK", 0x1002, "AMD_OPEN_SOURCE", "DISCRETE_GPU", "2025.Q2.1 (LLPC)", "1010"), + ("UHD Graphics, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7088", "1011"), + ("Iris Xe, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7092", "1011"), + ("Arc B580, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "DISCRETE_GPU", "101.8132", "1011"), + ("Arc B570, Intel's Windows driver (the file select's lost device, 11-30)", 0x8086, "INTEL_PROPRIETARY_WINDOWS", + "DISCRETE_GPU", "101.9175", "1011"), + ("Iris Xe, ANV", 0x8086, "INTEL_OPEN_SOURCE_MESA", "INTEGRATED_GPU", "Mesa 26.0.1", "1010"), + ("llvmpipe", 0x10005, "MESA_LLVMPIPE", "CPU", "Mesa 26.0.1 (LLVM 20.1.8)", "1000"), ] -FIELDS = ['fetch_bounds', 'nan_bits', 'gather_offset'] +FIELDS = ['fetch_bounds', 'nan_bits', 'gather_offset', 'robust_buffers'] FIXTURE = r""" #include @@ -57,7 +60,7 @@ static const char* get(const char* name) { return it == env.end() ? nullptr : it->second.c_str(); } static void print(const char* what, const VendorFixes& x) { - std::printf("%s %d%d%d\n", what, x.fetch_bounds, x.nan_bits, x.gather_offset); + std::printf("%s %d%d%d%d\n", what, x.fetch_bounds, x.nan_bits, x.gather_offset, x.robust_buffers); } int main() { struct D { const char* name; uint32_t vendor; VkDriverId driver; VkPhysicalDeviceType type; const char* info; }; @@ -71,7 +74,7 @@ int main() { print(d.name, x); vendor_fixes_env(x, get); // (no switch set: as it was) print(d.name, x); - const char* names[] = {"RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET"}; + const char* names[] = {"RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET", "RX_VK_ROBUST"}; for (const char* n : names) for (const char* v : {"0", "1", ""}) { env.clear(); @@ -101,9 +104,16 @@ def cut(text, marker): def check_source(): main = (VK / "vk_main.cpp").read_text(encoding="utf-8") at = main.index("dev.fixes = vendor_fixes(facts);") - for text in ("vendor_fixes_env(dev.fixes,",): + for text in ("vendor_fixes_env(dev.fixes,", "robust = robust || dev.fixes.robust_buffers;", + "robust2.robustBufferAccess2 = robust_ok ? VK_TRUE : VK_FALSE;"): if main.find(text, at) < 0: raise SystemExit("FAIL: vk_main.cpp: %s not after the fixes are made" % text) + # ((Triforce, 11-30) the Intel fix decides the device's robustness: robust_ok made once, after it, and the features from it + # before the device) + if main.count("robust_ok = robust &&") != 1 or main.find("robust_ok = robust &&") < at: + raise SystemExit("FAIL: vk_main.cpp: robust_ok is made before the vendor fixes") + if "f.features.robustBufferAccess = robust_ok ? VK_TRUE : VK_FALSE;" not in main[at:main.index("vkCreateDevice(dev.physical, &ci")]: + raise SystemExit("FAIL: vk_main.cpp: robustBufferAccess not set from robust_ok before the device") if main.index("dev.fixes = vendor_fixes(facts);") > main.index("vkCreateDevice(dev.physical, &ci"): raise SystemExit("FAIL: the fixes are made after the device") for field in ("vendor_id = p2.properties.vendorID", "driver_id = drv.driverID", "device_type = p2.properties.deviceType", @@ -153,7 +163,7 @@ def main(): if line.split()[-1] != want: failures.append("%s: %s, expected %s" % (name, line.split()[-1], want)) for i, line in enumerate(lines[2:]): - switch, value = ["RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET"][i // 3], ["0", "1", ""][i % 3] + switch, value = ["RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET", "RX_VK_ROBUST"][i // 3], ["0", "1", ""][i % 3] got = list(line.split()[-1]) expect = list(want) if value: diff --git a/third_party/renhdrum/PROVENANCE.md b/third_party/renhdrum/PROVENANCE.md index b05fb54..cbc8bd8 100644 --- a/third_party/renhdrum/PROVENANCE.md +++ b/third_party/renhdrum/PROVENANCE.md @@ -25,7 +25,8 @@ upstream-root: RenHDrum-0.5.0 **How it reaches the game.** (Triforce) `py -3 -I scripts/renhdrum.py build` compiles it by hand into `renhdrum.dll` (ignored by git) for x86_64-pc-windows-gnullvm, with a pinned Rust and the llvm-mingw the game is built with (its clang compiles libopus too), and the `cc` crate downloaded by the SHA-256 `Cargo.lock` gives it; the same source gives the same -bytes. Triforce's release scripts do not build it yet. When it is in this folder, `nx2/build.py` copies it beside the +bytes. The releases build it (since 11-29): `setup/pack_tools.ps1` into the tools zip's `third_party/renhdrum/`, +`scripts/linux/appimage.sh` (`--target linux`, `renhdrum.so`) into the AppImage's. When it is in this folder, `nx2/build.py` copies it beside the game. `host/rumble_renhdrum.c` loads it (`renhdrum.dll`, `renhdrum.so` on Linux) from the game's own folder by full path; without it, or with a file that will not load, every controller keeps its motors or its own HD rumble, as before, and the log and the Controls tab's Vibration row say why.