[main] Merge branch 'nogs-m4': SC3's 2D drawn natively by default (menus, pause, previews, fight HUD; the game's 2D builders in C++, word-equal with the game), PS2Recomp sc3/nogs-m4 27ebdbc4

SC3_NATIVE_2D=0 keeps the game's packets as a diagnostic; anything not native falls back to them as before. 6 regress runs clean (default and versus), uncapped fight not slower. Native 3D code is included but stays off by default (SC3_NATIVE_MESHES).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
ArzarothandClaude Opus 5.5 committed 2026-11-03 23:23:58 +01:00
commit da8a761183
26 files changed
+9147 -20

No files matched your search

+3
View File
@@ -72,6 +72,9 @@ if(SC3_BUILD_TESTS)
runtime/sc3_vu1_port.cpp
runtime/sc3_vu1_programs.cpp
runtime/sc3_draw_sink.cpp
runtime/sc3_census.cpp
runtime/sc3_textures.cpp
runtime/sc3_texture_pack.cpp
$<TARGET_OBJECTS:sc3_vu1_port>
PS2Recomp/ps2xTest/src/test_function_table.cpp)
target_include_directories(sc3_tests PRIVATE runtime PS2Recomp/ps2xTest/include PS2Recomp/ps2xRuntime/include)
+6 -2
View File
@@ -90,9 +90,9 @@ PS2Recomp's `sc3/windows` branch (`sc3/native-vu1`, i.e. `native/renderer` plus
| No SPU2 emulation: libsd's calls played by PS2Recomp's native mixer, the SPU2 absent | 🔧 |
| Textures from an offline native pack of your disc, looked up by the game's own keys | 🔧 |
| Materials and 3D meshes from offline packs, drawn at the game's per-object hooks; no VIF stream read | ⏳ |
| 2D (menus, HUD, fonts) built in C++ from the game's variables, no GIF packet built or read | ⏳ |
| 2D (menus, fonts, the fight HUD) built in C++ from the game's variables by default, from an offline 2D pack of your disc (`SC3_NATIVE_2D=0`: the game's own packets); left to the game: the passes that read the frame (glow, display copy) and the frame's context writes | 🔧 |
| Shadow volumes, glow and the sun's depth probe as native passes | ⏳ |
| Movies as native pictures: full-screen ones the native renderer's backdrop, no libmpeg or IPU; menu previews still uploaded by the game until its sprite builder is C++ | 🔧 |
| Movies as native pictures: full-screen ones the native renderer's backdrop, no libmpeg or IPU; menu previews drawn by the native 2D from the host decoder's picture | 🔧 |
| The frame's end written to the game natively (SC3 waits on the GS's FINISH), GS DMA and VIF0 left unread | ⏳ |
| No GS front end, no copy of GS memory: the native renderer draws and presents the whole frame | ⏳ |
| IOP kernel layer (interrupts, timers, SIF) under the recompiled IOP modules: still PS2Recomp's model | ⏳ |
@@ -281,6 +281,10 @@ player 2:
| `SC3_NATIVE_VU1_PORT=0\|check` | Run the VU1 programs on the native sandbox (the AOT microcode on PS2Recomp's interpreter) instead of in C++, or both, compared |
| `SC3_NATIVE_VU1_PORT_SKIP=<A:0x10,…>` | Keep those entries on the sandbox |
| `SC3_NATIVE_VU1_DIRECT=0\|check\|@file` | Draw the C++ programs from their GIF packets (parsed, their register writes replayed on the GS) instead of directly, or both, compared; `@file` reads 0 / 1 / check at each frame end |
| `SC3_NATIVE_MESHES=1\|check` | The stage's rigid parts drawn natively from the offline mesh pack (`build/sc3_meshes.pack`, made by `scripts/sc3_mesh_pack.py` from your disc) at the game's part builder; needs the texture pack on (`SC3_TEXTURE_PACK_MODE=keep`); `check` compares each part with the lifted VU1 program. Opt-in, in progress: see RECOMP_NOTES |
| `SC3_NATIVE_2D=0\|check\|@file` | The 2D builders (menus, text, labels, icons, draw items, the fight HUD) are C++ by default, textured from the offline 2D pack (`build/sc3_2d.pack`, made by `scripts/sc3_2d_pack.py` from your disc); `0` gives them back to the game's own packets, `check` builds both and compares them word for word, `@file` reads 0 / 1 / check at each frame end |
| `SC3_TEXTURE_PACK_MODE=1\|keep\|@file` | Direct draws textured from the offline texture pack (`build/sc3_textures.pack`, made by `scripts/sc3_texture_pack.py` from your disc), the uploads it covers left out (`keep`: still sent); a diagnostic for now, see RECOMP_NOTES |
| `SC3_HIDE_EE=<addr,…>`, `SC3_TRACE_LOAD=1`, `SC3_TRACE_FRAMES=<frame>,<n>`, `SC3_TRACE_OT=1`, `SC3_RECORD_FRAME=<frame>` | Census: game functions returned at entry, file loads, one frame's batches / texture uploads / sync points / direct draws, ordering-table insertions, one frame's builder calls with their state and memory dumps (`SC3_RECORD_DIR`) |
| `SC3_NATIVE_VU0=0\|check` | Run the VU0 microprograms on PS2Recomp's interpreter instead of in C++, or both, compared (`SC3_NATIVE_VU0_LOG`, `SC3_NATIVE_VU0_RECORD` as for VU1) |
| `SC3_NATIVE_VU1_LOG=1` | Every 5 s, MSCALs by entry, the direct draws' counts; a line lists any without a C++ port |
| `SC3_NATIVE_VU1_RECORD=<file>` | Record sampled sandbox runs per entry (and, with `=check`, runs whose port differs) for `sc3_tests` (`SC3_VU1_TRACE`) |
+276
View File
@@ -474,6 +474,265 @@ with `SC3_NATIVE_VU1_DIRECT=0` for the packets):
| this branch, packets | 60.03, 60.03 | 60.72, 60.45 |
| this branch, direct draws | 60.05, 60.00 | 62.62, 62.42 |
#### Native meshes (`scripts/sc3_mesh_pack.py`, `runtime/sc3_meshes.cpp`, opt-in)
The 3D drawn from the game's part builders and an offline mesh pack instead of from the VIF1 stream (no-GS plan, M2 and
M3). Found with `SC3_RECORD_FRAME` (census): a fight frame calls 0x10A178 312 times (the stage: a REF to the part's raw
VIF data, flags in a2 whose low 16 bits are the routine, program A when bit 0x40000 is set) and 0x10A4E8 145 times
(fighters and weapons: a CALL to a DMA chain whose own MSCALs run 0x1388, 0x15E8, 0x1AB8, ...). Before a part the game
leaves in the scratchpad what goes with it: 0x368 (a header to send: 0x10AD18 copies the renderer's matrices, lights,
fog and guard band from scratchpad 0x100-0x340, 19 quadwords to VU TOP + 0x1AD, the setup at 0x10 loads them into
vf14-vf31 and jumps to the routine), 0x36C / 0x370 (the material A+D block to REF to TOP + 0x19F), 0x350-0x358 (bone
matrices and their indices), 0x384 / 0x388 (the microprogram upload when the program changes). Parts without a header
or material keep the registers and GS state of the last one. Leaves are read whole by sceCdRead and relocated in place
(pointers + the sub-entry's base); a material's TEX0 / MIPTBP get the texture ring's TBP / CBP at run time, so
materials and texture keys are taken from the disc's values.
- `scripts/sc3_mesh_pack.py` (stdlib, `python3 -I`, all cores, about 10 s): every raw part of every leaf (its tag
UNPACK, then V2-32 ST, V4-32 / S-32 colour, V4-32 position with the vertex flags in w, V3-32 normal, four quadwords a
vertex) as an object of PS2Recomp's generic mesh pack at its offset in the leaf, the exact words in section `SC3V`;
every A+D block as a register block (with the GIF tag's REGS word, the texture's used size, as register 0x100);
`build/sc3_meshes.leaves` maps pack files to ROOT.OLK. 1,647 leaves, 102,839 parts, 434 MB. Checked against the
recorded frame: the 312 parts at their offsets with the qwc the game passes, the 45 material blocks found.
- At run time (`SC3_NATIVE_MESHES=1`, needs `SC3_TEXTURE_PACK_MODE` on, `keep` for now): leaves are bound
(`LoadedImages`, size and CRC32) when sceCdRead has read them whole; 0x10A178 (and 0x109990, whose `j 0x10A178`
skips the table) draws a part of A's routines 0xD8 (lit, fogged), 0x2B0 (lit), 0xC18 (unlit), 0x1558 (unlit, fogged,
scrolled) and 0x1730 (unlit, scrolled) in plain C++ from the pack's vertices, the header (0x10AD18's copies rewritten
in C++, kept like the VU's registers), the pack's material and the texture pack (the latest upload group CALLed
before the part: 0x104AF0 runs a batch's texture CALL right before its draws). The routines' meaning, from their
microcode: position through vf28-31, Q = 1 / w, STQ = ST times vf14 (plus vf24.xy when scrolled) times Q; lit
colour vf19 + vf20-23 times max(vf24-26 . n, 0), times the vertex colour, clamped at vf16.x, else the colour times
vf19; guard band (xyz / w + vf17) times vf18 against 1 over the last three vertices for ADC; fog F from
(vf17.w + w) times vf18.w clamped to vf15.y..vf15.x, else the vertex's own F. Floats read as the VU reads them (an
exponent of 255 is the largest finite value: the header carries such words) and products saturate.
- No VIF packet is built for a native part: the scratchpad packet gets a CNT with a VIF MARK (and the program upload
when the game asked for one, for parts left to VU1). Its draw joins a `MeshViewList` as the game links the packet
(0x10F8B8: the VIF1 list, in order; 0x10D9A0 / 0x10DC90: an ordering-table bucket); at the frame kick 0x10F098 the
list is submitted through `MeshSubmitter` (GS-form batches, PS2Recomp `sc3/nogs-m3`), each draw a group, and the
VIF1 interpreter places each group in the GS stream at its MARK (`setVif1MarkGate`), so the native 3D sorts with
the 2D, shadows and glow the GS front end still draws until M4-M7. A part not drawn natively stays on VU1, its
header and material sent (scratchpad 0x368 / 0x36C set) since the native parts before it sent theirs to no one; with
native meshes on, the VU1 programs' C++ ports are off so that the groups are numbered by the MARKs alone.
- `[sc3:mesh]` every 250 frames: parts drawn natively and their triangles, parts left to VU1 by cause (routine not
native yet, not in the pack, no material, no pack texture: the texture places listed by TBP / PSM / CBP), chain parts
left to VU1, MARKs reached, out of the list's order, unknown; leaves bound. `SC3_NATIVE_MESHES=check` also runs each
native part's routine (through its setup with the same header) on the lifted program and compares the vertices.
State (2026-11-01), Free Training, three runs: about 98 % of the raw parts native (295 of 302 a fight frame; A:0xA48
and A:0x1D28 left, 2 each), about 6,900 triangles a frame; every MARK reached in the list's order (0 out of order, 0 unknown); every material and
texture found in the packs. Check against the lifted programs: positions, colours, STQ and ADC agree, F agrees since the
VU float reading; what differs is rounding (the VU truncates, the C++ rounds to nearest): Z off by 1-4 sixteenths at
depths past a million, X / Y a few ulps on vertices far outside the screen, STQ in the sixth digit; no part bit-equal
because of that. Open: with 0x1558 / 0x1730 native, VU1 faults about once a frame on a part left to it (a reserved
instruction at pc 0x1718, code memory that is neither A nor B there), and two of three runs stopped before the pause;
the fighters and weapons (0x10A4E8's chains: B:0x1388 skinning, B:0x15E8, A:0x1AB8, A:0x1F00 and the shine setups)
are not native yet, nor the VIF0 part lists (0x10B3F0). Off by default until those are done and the route is clean.
#### Texture pack (`scripts/sc3_texture_pack.py`, `runtime/sc3_textures.cpp`)
The direct draws took their textures from the GL back end's model of GS memory, filled by the game's uploads through
the GS front end. SC3's textures exist on the disc only as prebuilt GS uploads inside ROOT.OLK's models; they are now
converted offline from the user's disc, and a direct draw binds its texture from the pack.
How the game uploads (found with `SC3_TRACE_FRAMES` and the load tracers below): each model's command list, run by
0x104af0, CALLs texture CALL lists of that model (command 2; 3 through the OT; 20 an upload chain picked from a table
by a float: animated textures). A list is a run of DMA CALL tags into upload units ended by RET; a unit is a CNT with
GIF A+D BITBLTBUF / TRXPOS / TRXREG / TRXDIR and an IMAGE tag, then a REF to the texels, uploaded as PSMCT32 blocks
and sampled as T8 / T4 with CT32 CLUTs. The CALLs and the GIF side's SIGNAL 1 go into the GIF list, the VIF1 side's
SIGNAL 2 into the VIF1 list (a DIRECT); the two halves of the texture area (TBP 0x2c40 and 0x3800) alternate, so a TBP
is no identity. The game reads a leaf of ROOT.OLK whole with CRI's file layer (sceCdRead from 0x3ffad0) and relocates
it in place; a model's DMA addresses are relative to its own header (03 04 04 00), at a leaf's start (cdata) or
inside a container leaf (characters, stages). A material's GIF tag keeps the texture's used size in its spare REGS
bits (bits 32-47 width, 48-63 height); its TEX0 often selects more (TW 10 for a 128 x 64 texture).
The converter (stdlib Python, `python3 -I`, all cores; run by `scripts/build_runtime.sh` when there is no pack yet)
walks ROOT.OLK's sub-archives to their leaves and each leaf to its models, plays each CALL list's uploads into a model
of GS memory (offline only; PSMCT32 / PSMT8 / PSMT4 layouts from PS2Recomp's tables), notes which list entry wrote each
byte, and keeps every material texture of the model whose texels and CLUT the list wrote, at its used size: its
indices (or CT32 texels) and its palette (CT32, index order, alpha 0x80 = 1.0). It writes PS2Recomp's generic texture
pack (`PS2XTEX1`, `tools/native_pack/texture.py`; one file per CALL list, named `<leaf>@<list offset>`) and SC3's key
index beside it (`build/sc3_textures.keys`: where each list sits in ROOT.OLK, its entries and whether every texture
their uploads feed is in the pack, and which records a TEX0 and used size select). On the regress route's disc:
12,267 lists, 37,131 CALL entries, 73,122 records (textures and palettes), 559 MB; 213 upload shapes it does not
convert (short IMAGE data, T4 uploads, chains without an end) keep their GS uploads.
At run time (only on the native GS renderer):
- Where leaves load: ROOT.OLK's sector from the game's first index request (0x150418, a byte position) and the
sceCdRead serving it; every later sceCdRead into RDRAM maps its buffer to its ROOT.OLK bytes.
- Texture CALLs: 0x10f808 called from command 2 or 20, 0x10d9a0 from command 3 or 20. The target comes from the
game's command list (its word, or the table entry its float picks, `cvt.w.s` as the EE does), through the load map
to the pack's entry. With every texture of the entry in the pack, its CALL is not appended to the GIF list (0x10f808's
bookkeeping without its copy: the scratchpad half flips as it would), so the GS front end never reads those uploads.
The OT variants still send theirs. Each CALL also records its segment of the GIF / VIF1 handshake (the game's GIF
sync points before it, 0x10f9d0 with id 1).
- The frame kick 0x10f098 hands the frame's groups to the VIF1 thread; each frame end there takes the next frame's.
- On the VIF1 thread, the DIRECTs the stream carries give the game's own SIGNAL 2 sync points; a textured direct draw
takes the texture its TEX0 and used size select from the latest group that has it among those whose segment the
stream has reached, as the GS would sample it then, and hands it to `Renderer::drawGs` (`GsMaterial::texture`,
PS2Recomp `sc3/nogs-m1`): the GL back end binds it instead of decoding GS memory and loads no CLUT. A draw without
one samples GS memory as before and is counted by TEX0.
- `[sc3:packets]` and `[sc3:gs]` every 250 frames: texture uploads called, from the pack (left out, sent), not in
the pack, and the GS image transfers the GS front end still reads from GIF packets (`GS::imageTransfers`); direct
draws textured from the pack or from GS memory, the most frequent misses by TBP, PSM and CBP.
`SC3_TEXTURE_PACK=<file>` names the pack (the scripts pass `build/sc3_textures.pack` when it exists);
`SC3_TEXTURE_PACK_MODE=1` uses it (off by default: see the state below), `=keep` draws from it with the game's uploads
still sent, `=@file` reads 0 / keep / 1 every 16 frames (`REGRESS_TEXPACK_AB`). `PS2X_NATIVE_TEXTURE_CHECK=1`, with the uploads
sent, compares each pack texture with the texture cache's decode of GS memory where its TEX0 points (meaningful only
where the TBP is not reused within the frame: the cache sees the frame's uploads in DMA order).
State (2026-11-01): off by default, a diagnostic switch. Pause still of the Free Training fight with the pack on and
the covered uploads left out: 22.4 dB against a 32.3 dB floor of two stills without it; the counters show most direct
draws in the pause finding no pack texture (8,000 from the pack, 228,750 from GS memory per 250 frames), so with their
uploads left out they sample stale GS memory. What is missing is a draw's place among the upload groups: the direct
draws come from the VIF1 stream (the game's OT reorders the stage parts against the order the CALLs were built in),
and the GS-order position used here (the game's SIGNAL 2 in the VIF1 stream's DIRECTs, a GIF packet read, acceptable
only as this diagnostic) does not match the groups' segments in the pause. With the 3D drawn from the game's
per-object hooks (M3: 0x104af0's commands run in order, a batch's texture CALL right before its draws) the group is
known at the hook and none of this is needed.
#### Native 2D (`scripts/sc3_2d_pack.py`, `runtime/sc3_2d.cpp`, on by default)
The 2D is GIF data on PATH3: the ordering table (8192 buckets of 16 bytes at *(0x5BE754), one table cut into layers,
0x10D718 setting the layer base *(0x5BE750)) is part of the GIF channel's chain, a bucket a list of packets newest
first, buckets drawn in index order. 2D builders write a packet in the scratchpad and link it with 0x10DDF8 (a fixed
bucket), 0x10DF30 / 0x10E068 (the text layers, 0x1FF3 + 0..3), 0x10D9A0 (by depth, in the layer) or 0x10E1C8 (the
in-order GIF list); 0x120978 picks one of them by the mode word 0x468CB0 and is reached by tail jumps. A 2D texture
is a page of a texture file, a ROOT.OLK leaf with a 03 04 04 00 header: byte 4 its upload CALL lists, bytes 5 and 7 its
pages, word 8 the CALL table (20 bytes an entry when byte 0 or 3 is 3, else 12), word 0xC the page table (a GIF A+D
block: TEX1_2, TEX0_2, CLAMP_2, the used size in the tag's REGS word). 0x117A38 CALLs a file's upload lists (once a frame
into the OT), 0x1177E0 REFs a page's block before the draws. A page's texels and its CLUT come from different lists.
ALPHA_2 comes from the table of four at 0x46EFD8; TEST_2 is whatever the packets before left (0x10FE50 sets TEXA and
TEST_2 from an object's flags). 2D vertices go through 0x120DE8: the 2D view matrix *(*(0x46DA88) + 0x460) times
(x, y, z, 1), z times 1 / z, clamped at 0, ftoi4.
- `scripts/sc3_2d_pack.py` (stdlib, `python3 -I`, all cores, about 40 s): every leaf's register blocks into a
PS2Recomp mesh pack (`build/sc3_2d.pack`, `.leaves`), and for each page the texture the leaf's own uploads write,
played into the offline GS memory model of `scripts/sc3_texture_pack.py` and decoded at its used size into
`build/sc3_2d_textures.pack` (PS2XTEX1, one file per leaf, the records' numbers as registers 0x101 / 0x102 of the
block; each other CLUT block the file uploads as register 0x103 = CBP << 32 | record, for draws that pick another
CLUT with TEX2). The 11 texture files inside the ELF (the font at 0x4763B0, the menu icons at 0x4AF170, nine more
from 0x473E60) are converted from the user's SLUS_212.16 as `elf/<address>`, as the game has them before 0x118E18
relocates their pointers; the runtime binds them at install at their fixed address.
- At run time (`SC3_NATIVE_2D=1`, `=check`, or `=@<file>` following the file's first line; `SC3_2D_PACK`): leaves
are bound at sceCdRead as for the meshes. A rewritten builder draws its primitives from the game's variables as
`Renderer::drawGsKeyed` batches (sprites and lines by their two vertices, drawn by the GS renderer as the GS draws
them) with the page's TEX0 / TEX1 / CLAMP from the pack and its texture from the 2D texture pack, ALPHA_2 from the
game's values, TEST_2 from the context where it lands (`GsMaterial::testFromTarget`), registers the batches, then
links in C++ a marker where the game would have linked its packet: into an OT bucket (a CNT with QWC 0 whose upper
64 bits carry the key, then the NEXT to the bucket's old head, at the frame heap's next place) or appended to the
in-order GIF list (the CNT alone at *(0x5BE708), the list's count *(*(0x5BE710)) one more), and switches the
scratchpad's packet half as the game's insertions do: no scratchpad packet, SPR DMA or GIF packet. The GIF channel
finds the marker (PS2Recomp `setGifChainMarkGate`) and the GS front end draws the key's batches between the packets
around it. Batches go in before the marker: the GIF list can be read while the frame is still being built. A call
whose file, page or texture is missing goes to the game's packet, counted. A vertex written as PACKED XYZF2 (the
quads, lines, icons, labels, triangles, strips and object sprites) takes Z from bits 4..27 of its third word, as the
GS does (XYZ2 the whole word): drawn with the word itself, Z was 16 times the game's and wrapped in the 24-bit Z
buffer, so later draws testing GEQUAL failed (the pause panel's fill and text vanished with the mode-0 quad native).
- Rewritten: 0x1388E8 (labels: 0x28-byte items, two passes by page, sprites into bucket 0x1FF2), 0x124C80 (a
Gouraud-shaded blended triangle through 0x120978, every mode), 0x11EA80 (the text renderer: the state at 0x468540,
the call frame on the guest stack as the game's, glyph runs 0x11E160, measure 0x11E740, flushes 0x11E898 /
0x11E9B0, placement 0x11E068, TEX2_2 / ALPHA_2 writes 0x11DF40 / 0x11DFC8 with the packet's bookkeeping kept as
offsets so packets end where the game's do; the control codes 0x23..0x25 go to the game's formatter 0x11CBC8, game
logic that builds no packet), 0x123340 (untextured sprite, every mode), 0x1223D0 (antialiased line), 0x1280F8 (menu
icons), the screen-effect layer 0x12C690 / 0x12C7E0 (the background behind the 3D: a sky and a ground band split at
the projected horizon, opaque, Z written 0, context 1; a rolled camera and mode 1 stay the game's), 0x1134A0 and
0x110E50 (below). The once-a-frame uploads of the font (0x11FCF0), the labels' file (0x138860) and the icons
(0x128080) are dropped while those draws are native.
- Draw items: objects carry items dispatched by type through the table at 0x4676A8 (3 0x110E50 object sprites, 9
0x1134A0 textured triangle strips, 13 0x115600 a texture upload for later draws). An item's head (0x113300 /
0x10FE50): +0x1C 0 a REF of page +0x18 of the file +0x14; 1 a REF of a register block at +0x14 (for object sprites a
context-1 block in a leaf: TEX0_1, ALPHA_1, TEST_1 and the page's texture, from the 2D pack); 2 a copy of a page's
block made earlier by 0x1191D0 / 0x119318 / 0x119248 (file, out, page, CLUT: CBP as it is, plus an offset, or set),
recorded by where it went and resolved there (the page and its CLUT in the pack, found while the file is loaded: it
can be gone by the draw) so the draw needs neither the copy nor the file. Insertion by
+0xA & 3 through the table at 0x467510 (0x1132A8 the GIF list, 0x10D9A0, 0x110D78, 0x113250: 0x120978's modes).
- 0x1134A0 (VU0 macro code, in C++ on a copy of VU0 with the recompiler's float operations): packets of up to 0x9C
vertices (+0 ST, +0xC a restart word, +0x10 position, +0x20 colour) and the two before them, through the matrix +0x1D
picks (0x101058, in C++), Z from the projection when +0x1F is set, ADC on a vertex behind w 0.08 or off the GS's
range and on the two after it; PRIM 0x254 (0x54 in context 1) | +0xB, its own ALPHA_2; at the vertices' mean 1 / w
(a fixed depth when +0x28 < 0), +0x2C the mean w. Drawn as the strip's triangles (each vertex without ADC from the
third on).
- 0x110E50 (VU0 macro code): per 0x50-byte entry one rotated quad (a strip of four, PRIM 0x254) with its own head,
TEXA / TEST_2 when the item asks, colour from bytes times the view's +0x390 halfwords or from floats; the angle's sine
and cosine are 0x100AC0's set-up in C++ around its VU0 microprogram 0x38, run as vcallms runs it (calling 0x100AC0 as
EE code from a hook can resume after its indirect jump with other registers in a0 / a1: its stores then go to the
item). Page sizes for the ST table 0x467580 come from the pack's page (0x118020 reads them from the block).
- 0x1107E0 (type 6) and 0x110258 (type 2), 0x110E50's siblings in the 2D view: 0x10FD78 with a3 = 1 loads the matrix
*(view +0x460), the position's z is the depth (Z = the view's z times the depth scale +0x38 over z, drawn when z is
over 0.08), depth for the insertion +0x38 over z, or -(+0x38) (x 12.5 for mode 1) when +0x38 is not positive. Type 6:
a rotated quad per entry, its half sizes from one of the vectors 0x467620..0x467650 picked by +0x4A & 0x40 / 0x80,
the item's +0x1F & 0x80 and *(*(0x469230) +0x50) (the screen's aspect), X moved around 2048 by 1.2443 or 0.8036;
no range test. Type 2: a GS sprite per entry (+0xB 0: PRIM 0x256, NREG 6 or 7), size +0x30 / +0x34 times +0x40,
anchor +0x4A >> 4 & 3, colour bytes (b + 1) / 2, dropped off the GS's range; nothing while the heap is nearly full
(0x10D528); TEST_2 put back to 0x5002D after it; mode 0 appends through 0x10F808. +0x1D & 1 writes TEX1_2 from the
table 0x467528 by +0x4B (the native material's TEX1). Regress route in check mode: 0 differing.
- Calling game code from C++: a recompiled function returns to the dispatcher at a call when an EE checkpoint is due
(`ctx->pc` the callee), so a call that must finish runs to its return (`runToReturn`: `lookupFunction(ctx->pc)` until
the return address with the caller's stack pointer). SC3 keeps stacks and packets in the scratchpad: every guest
access goes through `guest()`. Conversions saturate as the EE's (`ps2FpuCvtWS`: no NaN or infinity on the EE).
- `check`: the game's packets built and drawn, each rewritten call compared word for word with the packet it linked
(the text: every A+D write and glyph of every packet, and the text state's words after the call; the native run on
restored registers and the formatter's globals). Regress route: text 678,385 calls / 707,096 glyphs, labels 843,740
sprites, quads, lines and icons, all equal.
- `[sc3:2d]` every 250 frames: GIF chain markers read, leaves bound, pages without a texture, per builder calls /
native / left to the game / GIF quadwords the game still built, uploads dropped, and the census of 2D packets the game
still builds by (return address > insertion function, the depth-sorted 0x10D9A0, 0x10DC90, 0x10E1F8, 0x10D2F0
included, and 0x10F808 when a builder appends to the in-order GIF list itself): calls / quadwords.
`scripts/regress.sh REGRESS_NATIVE_2D_AB=1`: Mode Select and pause stills off / on; `REGRESS_MENU_SERIES=<n>`
alternates pairs of stills off / on in Mode Select and Single Player Modes, whose backdrops never stand still.
- Census with 0x10F808 counted (native 2D on): 0x1410E8 / 0x1415E8 (~870 quadwords a frame, 64-pixel sprite columns
sampling the frame buffer, context 2: the off-screen pass of the menus and the fight, M5) were invisible before, as
were SCISSOR 0x1214D8 / XYOFFSET 0x12CB40's direct appends (frame context, M7), 0x12DB20 (from 0x18E240, ~27
quadwords a frame) and 0x127620 (one A+D write, from 0x12A400 / 0x12A8A0).
- 0x115600 (draw item 13: CALLs of a texture file's upload lists, or of a block +0x10, then TEXFLUSH) is dropped
while every page of its file +0x14 is in the pack and no item of that file linked a game packet for 120 frames (an
item type still the game's, 0x110258, 0x1107E0 and the rest of the table, marks the file of the item that runs when
a packet is linked from inside it: they draw from those uploads; a 0x1134A0 / 0x110E50 item left to the GS marks its
file too, a head-2 one the file its copy came from), never in the first two frames the upload is seen.
- The offline GS memory model (`scripts/sc3_texture_pack.py`) takes PSMT8H / PSMT4HL / PSMT4HH uploads: the pause
menu's leaf /2/6 uploads its fifteen pages as PSMT8H, so before it had no texture in the 2D pack. It takes PSMT8 /
PSMT4 uploads too: stage leaves such as /4/258 (sky, clouds, mountains) upload their pages that way, and their 2D
items (head-1 strips, object sprites and screen sprites of the stage) went to the GS for want of a texture.
- Still the game's on the pause menu: 0x1214D8 SCISSOR_2, 0x12CB40 XYOFFSET (frame context, M7).
- Menu preview movies (Single Player Modes: a 256x192 and a 128x96 alpha movie, both drawn through pages at TBP
0x3D00 of the 0x130-byte leaves /2/33 and /2/34, whose upload list has no texels on disc): the movie task 0x217F78
with flag 1 copies `mwPlyGetCurFrm`'s macroblocks into a texture file's pixels (0x217E28: rows of width x 4 bytes;
flag 8 copies the top half of the macroblock rows only) and points the file's upload there (0x118B68 -> 0x119BB0 ->
0x11A4F0); type-2 draw items (uploads 1, head 0) draw it: the picture and a dim copy over the whole screen (colour
19, ALPHA 0x52). With the native 2D on, 0x217E28 is skipped, the pages of a file 0x118B68 points at those pixels
take the host decoder's picture as a native texture (alpha from the mask half, 0x80 = 1.0; a version per picture in
three slots, PS2Recomp's `NativeTexture::version`), `mwPlyGetCurFrm` writes no macroblocks for a player the task
copied in the last 60 frames, and the items' uploads go with their packets. Check mode compares the game's copy
with the host picture over the rows it writes (regress route: 1,680 pictures, 0 texels differing). The GS path shows the top half of these previews only (flag 8
halves the height `mwPlyGetCurFrm` reports, already without the mask half): the native one shows the whole
picture, so off / on stills differ over the preview and the dim copy. The game on PCSX2 (USA BIOS, Single Player
Modes, Tales of Souls) shows the whole picture, as the native path does: the half picture is the GS path's fault
(the alpha movie's reported height), not the game's. The flag 0x20 path (0x2174C0 -> 0x216E60,
16x16 GIF image transfers to TBP 0x2C40 and a sprite) was not seen on the route.
- 0x21A8A8 and 0x2286B8 are not the fight's HUD: hidden in a fight (`SC3_HIDE_EE`) the attack data panel, the
HIGH / MID labels and the combo count stay; they run about once every two frames during hits, build vertices into a
buffer of their task (0x226FF0) and mark a group bit (0x2154F0): hit effects, drawn elsewhere (3D / effects).
- 0x12DB20 is the frame (from the main loop through 0x18E240): its own append (~24 quadwords) is SCANMSK, TEXA,
PABE, FBA_1 / FBA_2 and the two drawing environments of 0x13B3F0 (FRAME, ZBUF, XYOFFSET, SCISSOR, TEST, DTHE);
0x127620 appends one A+D write: TEXFLUSH from 0x12A400, TEXA (TA1 0x80) and TEXFLUSH from 0x12A8A0. Frame context,
M7.
- Census with the native 2D on (regress route, nested item insertions counted for the item's caller): menus and
pause: only frame context (0x1214D8, 0x12CB40, 0x12DB20, 0x12A400 / 0x127620: M7) and the frame-buffer-sampling
pass 0x1410E8 / 0x1415E8 (also from 0x141B24 / 0x141C48 during loads, M5). Type-2 sprites of a CT24 page at TBP
0x2C40 or 0 (a render target of the M5 pass) go to the GS after the menus.
- Versus fight (`REGRESS_VERSUS=1`): the HUD is native (gauge frames and round marks type 2, timer and names text
0x11EA80, gauge fill type 0x114B50, BATTLE n / FIGHT / K.O. drawn the same both ways). Census with the native 2D on:
no game-built 2D packet in the fight windows bar two M5 reads of the frame: strips of form 00000102 (head 0, through
0x10DDF8) on a CT16 page at TBP 0x1180 (the display copy, FBP 0x8C) or a CT24 page at TBP 0 (the frame), ~160 calls
in a round-transition window, and the CT24 type-2 sprites at TBP 0x2C40 (glow ring). Head-1 strips (a REF of a
context-1 register block) draw natively with ALPHA_1 / TEST_1 from the block, as object sprites do; a head-1 item
left to the GS keeps the uploads of the loaded leaf its block is in. An empty billboard (no entries) returns as
0x112148 does. Character select and load windows: only the CT24 type-2 sprites (M5) and, in a load, /2/0 items
of a kind 2 / 3 file with uploads. `REGRESS_VERSUS_PAUSE=1` takes the still rounds paused: off / on equal bar the pause menu's own
animations (the 1P PAUSE blink, the CLOSE colour).
#### VU0 microprograms in C++ (`runtime/sc3_vu0.cpp`)
VU0 runs SC3's math library as microcode (`VCALLMS` from about 15 EE functions): one program, the 172 pairs
@@ -495,6 +754,13 @@ interpreter. 0x18 and 0x438 never ran, in those modes or in the ones above.
full (240) and the opponent's (0x4D36A4) to 1, so the next scripted hit wins. Used to play Tales of Souls to
the credits with scripted input.
- `PS2X_SC3_TRACE_ENTRY=<addr,...>`: registers, a few stack slots, Timer0 and the EE cycle at each entry.
- `SC3_HIDE_EE=<addr,...>` (`runtime/sc3_census.cpp`): those game functions return at entry (diagnosis);
`=@file` with `SC3_HIDE_EE_ALL=<the candidates>` reads the list every 16 frames. `REGRESS_PAUSE_HIDE_EE` takes one
pause still per function (`pause_hide_ee.txt`).
- `SC3_TRACE_LOAD=1`: the file requests (0x150418), sceCdRead calls and copies of 4 KB or more (0x42d2ac);
`SC3_TRACE_OT=1`: ordering-table insertions per caller every 300 frames; `SC3_TRACE_FRAMES=<frame>,<count>`: for
those frames (counted at the frame kick 0x10f098), the batches (0x104af0), texture CALL targets, sync points, the GS
interrupt handler's SIGNAL counts and each direct draw's TEX0 and material tag.
- `PS2X_SC3_TRACE_OBJ=<fn>:<off,...>`: the words at those offsets of the object in `$a0` whenever they change
(state machines such as the Art Gallery task, state at +0x130).
- `PS2X_SC3_RATE=<addr,...>`: calls per 60 vsyncs of each function.
@@ -565,6 +831,16 @@ branch: `native/renderer` plus the SC3 fixes below, on their way into `native/re
them back, `=check` compares).
The regression route holds 60.0 fps capped; uncapped fights run about 62.5 fps drawing directly (61 from the packets), against 55.8 with everything on
the sandbox and VU0's interpreter.
- **2D in C++** by default (`runtime/sc3_2d.cpp`, 2026-11-03): the 2D builders (text, labels, icons, quads, lines,
triangles, the draw item types: object sprites, strips, screen sprites and quads, billboards, the fight's gauges)
draw from the game's variables, textured from the offline 2D pack of the user's disc (`build/sc3_2d.pack`, made by
`scripts/build_runtime.sh` when missing); no GIF packet built for them. `SC3_NATIVE_2D=0` gives them back to the
game's packets (diagnostic), `check` compares both word for word (0 differing over the regress and versus routes).
What is not native yet falls back to the game's own packets as before: the passes that read the frame (CT24 / CT16
pages at TBP 0x2C40, 0x1180, 0: M5), the frame context writes (M7) and the draw item type at 0x115018 (one load
window). Three regress and three versus runs clean; bench with the fight uncapped, interleaved: fps 57.4 / 65.2 /
66.6 native against 60.1 / 60.7 / 58.7 with `SC3_NATIVE_2D=0` (GS frames per 5 s 302 / 331 / 336 against 302 / 308
/ 302).
- **Speed**: the regression route runs at 59.6 fps (58.2 on the vblank grid), with 5 frames over 25 ms instead of
about 590; uncapped (`PS2X_FRAME_CAP=0`) it reaches 90 GS frames per second, 112 game frames per second.
+5168
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <cstdint>
#include <vector>
class PS2Runtime;
namespace sc3
{
// The game's 2D builders rewritten in C++ from their MIPS, drawn natively from the game's own variables at their place
// in the ordering table (SC3_NATIVE_2D=1, or =@<file> following the file's first line): RECOMP_NOTES "Native 2D".
void installNative2d(PS2Runtime &runtime, bool nativeGs);
// A small movie's current picture by its player handle (the host decoder's): RGBA rows, alpha 0x80 = 1.0, and its
// number; rgba is left as it is while known is still that number.
using MoviePicture = bool (*)(uint32_t handle, uint32_t known, std::vector<uint32_t> &rgba, uint32_t &width, uint32_t &height,
uint32_t &number);
void setMoviePictures(MoviePicture pictures);
// The native 2D draws this player's pictures from the host decoder: they need not be written into the game's memory.
bool native2dMovie(uint32_t handle);
}
+426
View File
@@ -0,0 +1,426 @@
#include "sc3_census.h"
#include "ps2_runtime.h"
#include "ps2_recompiled_functions.h"
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <mutex>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace sc3
{
namespace census
{
namespace
{
constexpr uint32_t kFrameKick = 0x0010F098u;
constexpr uint32_t kFileRequest = 0x00150418u;
constexpr uint32_t kCdRead = 0x00424E28u;
constexpr uint32_t kMemcpy = 0x0042D2ACu;
constexpr uint32_t kBatchFlush = 0x00104AF0u;
constexpr uint32_t kGifPacketClose = 0x0010F808u;
constexpr uint32_t kOtInsertDepth = 0x0010D9A0u;
constexpr uint32_t kGsHandler = 0x0010E658u;
constexpr uint32_t kTextureCallReturns[] = {0x00104DCCu, 0x00104E48u};
constexpr uint32_t kTextureOtCallReturns[] = {0x00104E34u, 0x00104E94u};
constexpr uint32_t kSyncPoints[] = {0x0010FBB8u, 0x0010FC08u, 0x0010FC60u, 0x0010FC90u};
constexpr uint32_t kOtInserts[] = {0x0010D9A0u, 0x0010DDF8u, 0x0010DC90u, 0x0010E1F8u, 0x0010D2F0u};
constexpr uint32_t kSignalCounts = 0x005BE792u;
using Function = PS2Runtime::RecompiledFunction;
struct State
{
uint8_t *rdram = nullptr;
uint8_t *scratchpad = nullptr;
std::map<uint32_t, Function> originals;
std::set<uint32_t> hidden;
std::string hidePath, hideSpec;
std::map<uint32_t, uint64_t> hiddenCalls;
bool traceLoads = false;
uint64_t traceFirst = ~0ull, traceCount = 0;
bool traceOt = false;
std::map<std::pair<uint32_t, uint32_t>, uint64_t> otCalls;
std::atomic<uint64_t> frame{0};
std::mutex logMutex;
uint64_t recordFrame = ~0ull;
std::string recordDir;
std::map<uint32_t, Function> recordOriginals;
FILE *records = nullptr;
uint32_t recordSeq = 0;
};
constexpr uint32_t kRecordedDefault[] = {
0x001040B0u, 0x00105278u, 0x00104AF0u, 0x00108A58u, 0x0010A178u, 0x0010A4E8u, 0x00109618u, 0x001096A0u, 0x00109728u,
0x001097B0u, 0x00109990u, 0x00109A18u, 0x00109A60u, 0x00109A88u, 0x00109AC8u, 0x0010A100u, 0x0010B330u, 0x0010B3F0u,
0x0010B4D8u, 0x0010D9A0u, 0x0010DC90u, 0x0010DDF8u, 0x0010E1F8u, 0x0010D2F0u, 0x0010F8B8u, 0x0010F808u, 0x00108980u,
0x00109AF0u, 0x0010AC40u, 0x001088A0u, 0x00108850u, 0x0010F4B8u, 0x00108D40u, 0x00108F28u, 0x00108F48u, 0x00109278u,
};
State g_state;
uint32_t peek32(uint32_t address)
{
uint32_t value = 0;
if ((address & 0xF0000000u) == 0x70000000u)
std::memcpy(&value, g_state.scratchpad + (address & 0x3FFCu), 4);
else
std::memcpy(&value, g_state.rdram + (address & PS2_RAM_MASK & ~3u), 4);
return value;
}
uint8_t peek8(uint32_t address) { return g_state.rdram[address & PS2_RAM_MASK]; }
bool tracingFrame()
{
const uint64_t frame = g_state.frame.load(std::memory_order_relaxed);
return frame >= g_state.traceFirst && frame - g_state.traceFirst < g_state.traceCount;
}
void callOriginal(uint32_t address, uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_state.originals.at(address)(rdram, ctx, runtime);
}
std::vector<uint32_t> parseAddresses(const std::string &text)
{
std::vector<uint32_t> out;
size_t start = 0;
while (start < text.size())
{
size_t end = text.find_first_of(", ", start);
if (end == std::string::npos)
end = text.size();
if (end > start)
out.push_back(static_cast<uint32_t>(std::strtoul(text.substr(start, end - start).c_str(), nullptr, 16)));
start = end + 1;
}
return out;
}
void followHideFile()
{
State &s = g_state;
if (s.hidePath.empty())
return;
std::ifstream file(s.hidePath);
std::string spec;
std::getline(file, spec);
if (spec == s.hideSpec)
return;
s.hideSpec = spec;
s.hidden.clear();
for (const uint32_t address : parseAddresses(spec))
s.hidden.insert(address);
std::fprintf(stderr, "[sc3:hide] hiding '%s' from the next frame\n", spec.c_str());
}
void hideable(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t address = ctx->pc;
if (g_state.hidden.count(address) != 0u)
{
++g_state.hiddenCalls[address];
setReturnU32(ctx, 0u);
ctx->pc = getRegU32(ctx, 31);
return;
}
callOriginal(address, rdram, ctx, runtime);
}
void report()
{
State &s = g_state;
const uint64_t frame = s.frame.load(std::memory_order_relaxed);
if (frame % 300u != 0u)
return;
if (!s.hiddenCalls.empty())
{
std::fprintf(stderr, "[sc3:hide] frame %llu: hidden calls:", static_cast<unsigned long long>(frame));
for (const auto &[address, calls] : s.hiddenCalls)
std::fprintf(stderr, " %#x x%llu", address, static_cast<unsigned long long>(calls));
std::fprintf(stderr, "\n");
s.hiddenCalls.clear();
}
if (s.traceOt && !s.otCalls.empty())
{
std::fprintf(stderr, "[sc3:ot] frame %llu: insertions per 300 frames (function<-caller):", static_cast<unsigned long long>(frame));
for (const auto &[key, calls] : s.otCalls)
std::fprintf(stderr, " %#x<-%#x x%llu", key.first, key.second, static_cast<unsigned long long>(calls));
std::fprintf(stderr, "\n");
s.otCalls.clear();
}
}
void dumpMemory(const char *name, const uint8_t *data, size_t size)
{
const std::string path = g_state.recordDir + "/" + name;
if (FILE *f = std::fopen(path.c_str(), "wb"))
{
std::fwrite(data, 1, size, f);
std::fclose(f);
}
}
// One record a call: "SC3R" u32, the function (bit 31: after it returned), a sequence number, the GPRs' low
// words, the FPRs, VU0's vf registers, scratchpad 0x0000-0x0400 and 0x1b00-0x1d00.
void writeRecord(uint32_t function, R5900Context *ctx)
{
State &s = g_state;
const uint32_t head[3] = {0x52334353u, function, s.recordSeq++};
std::fwrite(head, sizeof(head), 1, s.records);
for (int r = 0; r < 32; ++r)
{
const uint32_t value = getRegU32(ctx, r);
std::fwrite(&value, 4, 1, s.records);
}
std::fwrite(ctx->f, 4, 32, s.records);
std::fwrite(ctx->vu0_vf, 16, 32, s.records);
std::fwrite(s.scratchpad, 1, 0x400u, s.records);
std::fwrite(s.scratchpad + 0x1B00u, 1, 0x200u, s.records);
}
void recorded(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t address = ctx->pc;
State &s = g_state;
const bool on = s.records && s.frame.load(std::memory_order_relaxed) == s.recordFrame;
if (on)
writeRecord(address, ctx);
s.recordOriginals.at(address)(rdram, ctx, runtime);
if (on && s.records)
writeRecord(address | 0x80000000u, ctx);
}
void recordFrameEdge(uint64_t frame)
{
State &s = g_state;
if (s.recordFrame == ~0ull)
return;
if (frame == s.recordFrame)
{
const std::string path = s.recordDir + "/parts.bin";
s.records = std::fopen(path.c_str(), "wb");
dumpMemory("rdram_begin.bin", s.rdram, PS2_RAM_SIZE);
dumpMemory("scratch_begin.bin", s.scratchpad, 0x4000u);
std::fprintf(stderr, "[sc3:record] frame %llu: recording to %s\n", static_cast<unsigned long long>(frame), path.c_str());
}
else if (frame == s.recordFrame + 1u && s.records)
{
std::fclose(s.records);
s.records = nullptr;
dumpMemory("rdram_end.bin", s.rdram, PS2_RAM_SIZE);
dumpMemory("scratch_end.bin", s.scratchpad, 0x4000u);
std::fprintf(stderr, "[sc3:record] frame %llu: %u records, memory dumped\n", static_cast<unsigned long long>(frame), s.recordSeq);
}
}
void frameKick(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint64_t frame = g_state.frame.fetch_add(1, std::memory_order_relaxed) + 1u;
recordFrameEdge(frame);
if ((frame & 15u) == 0u)
followHideFile();
report();
if (tracingFrame())
std::fprintf(stderr, "[sc3:trace] f%llu kick\n", static_cast<unsigned long long>(frame));
hideable(rdram, ctx, runtime);
}
void fileRequest(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t sp = getRegU32(ctx, 29);
std::fprintf(stderr,
"[sc3:load] f%llu request ra=%#x a0=%#x mode=%u pos=%#x size=%#x dest=%#x t1=%#x s0=%#x s1=%#x s2=%#x\n",
static_cast<unsigned long long>(g_state.frame.load()), getRegU32(ctx, 31), getRegU32(ctx, 4),
getRegU32(ctx, 5), getRegU32(ctx, 6), getRegU32(ctx, 7), getRegU32(ctx, 8), getRegU32(ctx, 9),
peek32(sp), peek32(sp + 8u), peek32(sp + 16u));
callOriginal(kFileRequest, rdram, ctx, runtime);
}
void cdRead(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
std::fprintf(stderr, "[sc3:load] f%llu sceCdRead lbn=%#x sectors=%u buf=%#x ra=%#x\n",
static_cast<unsigned long long>(g_state.frame.load()), getRegU32(ctx, 4), getRegU32(ctx, 5), getRegU32(ctx, 6),
getRegU32(ctx, 31));
callOriginal(kCdRead, rdram, ctx, runtime);
}
void memcpyTraced(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (getRegU32(ctx, 6) >= 0x1000u)
std::fprintf(stderr, "[sc3:load] f%llu memcpy dst=%#x src=%#x size=%#x ra=%#x\n",
static_cast<unsigned long long>(g_state.frame.load()), getRegU32(ctx, 4), getRegU32(ctx, 5), getRegU32(ctx, 6),
getRegU32(ctx, 31));
callOriginal(kMemcpy, rdram, ctx, runtime);
}
void batchFlush(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (tracingFrame())
std::fprintf(stderr, "[sc3:trace] f%llu batch obj=%#x list=%#x a2=%#x ra=%#x\n",
static_cast<unsigned long long>(g_state.frame.load()), getRegU32(ctx, 4), getRegU32(ctx, 5),
getRegU32(ctx, 6), getRegU32(ctx, 31));
hideable(rdram, ctx, runtime);
}
void gifPacketClose(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
if (tracingFrame() && (ra == kTextureCallReturns[0] || ra == kTextureCallReturns[1]))
{
const uint32_t cursor = peek32(0x70000000u);
const uint32_t target = peek32(cursor + 4u);
std::fprintf(stderr, "[sc3:trace] f%llu texture call %#x tag %#x ra=%#x at target: %08x %08x %08x %08x %08x %08x\n",
static_cast<unsigned long long>(g_state.frame.load()), target, peek32(cursor), ra, peek32(target),
peek32(target + 4u), peek32(target + 16u), peek32(target + 20u), peek32(target + 32u), peek32(target + 36u));
}
callOriginal(kGifPacketClose, rdram, ctx, runtime);
}
void otInsert(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t address = ctx->pc;
const uint32_t ra = getRegU32(ctx, 31);
if (g_state.traceOt)
++g_state.otCalls[{address, ra}];
if (address == kOtInsertDepth && tracingFrame() && (ra == kTextureOtCallReturns[0] || ra == kTextureOtCallReturns[1]))
{
const uint32_t start = getRegU32(ctx, 5) - 0x10u;
std::fprintf(stderr, "[sc3:trace] f%llu texture call (ot) %#x tag %#x ra=%#x\n",
static_cast<unsigned long long>(g_state.frame.load()), peek32(start + 4u), peek32(start), ra);
}
hideable(rdram, ctx, runtime);
}
void syncPoint(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (tracingFrame())
std::fprintf(stderr, "[sc3:trace] f%llu sync %#x ra=%#x\n", static_cast<unsigned long long>(g_state.frame.load()), ctx->pc,
getRegU32(ctx, 31));
callOriginal(ctx->pc, rdram, ctx, runtime);
}
void gsHandler(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const bool trace = tracingFrame();
const uint32_t before = peek32(kSignalCounts & ~3u);
const uint32_t sig = runtime->memory().read32(0x12001080u);
callOriginal(kGsHandler, rdram, ctx, runtime);
if (trace)
std::fprintf(stderr, "[sc3:trace] f%llu gs-handler sig=%#x counts %u/%u -> %u/%u\n",
static_cast<unsigned long long>(g_state.frame.load()), sig, (before >> 16) & 0xFFu, (before >> 24) & 0xFFu,
peek8(kSignalCounts), peek8(kSignalCounts + 1u));
}
void wrap(PS2Runtime &runtime, uint32_t address, Function hook)
{
if (g_state.originals.count(address) != 0u)
return;
Function original = runtime.lookupFunction(address);
if (!original)
{
std::fprintf(stderr, "[sc3] census: no function at %#x\n", address);
return;
}
g_state.originals[address] = original;
runtime.registerFunction(address, hook);
}
}
}
bool censusTracingDraws()
{
return census::g_state.traceCount != 0u && census::tracingFrame();
}
void censusNoteDraw(uint64_t tex0, uint64_t tag, uint32_t triangles)
{
std::fprintf(stderr, "[sc3:trace] f%llu draw tex0=%#llx tag=%#llx tris=%u counts %u/%u\n",
static_cast<unsigned long long>(census::g_state.frame.load()), static_cast<unsigned long long>(tex0),
static_cast<unsigned long long>(tag), triangles, census::peek8(census::kSignalCounts), census::peek8(census::kSignalCounts + 1u));
}
void installCensus(PS2Runtime &runtime)
{
census::State &s = census::g_state;
s.rdram = runtime.memory().getRDRAM();
s.scratchpad = runtime.memory().getScratchpad();
const char *hide = std::getenv("SC3_HIDE_EE");
const char *loads = std::getenv("SC3_TRACE_LOAD");
const char *frames = std::getenv("SC3_TRACE_FRAMES");
const char *ot = std::getenv("SC3_TRACE_OT");
s.traceLoads = loads && *loads == '1';
s.traceOt = ot && *ot == '1';
if (frames && *frames)
{
s.traceFirst = std::strtoull(frames, nullptr, 10);
const char *comma = std::strchr(frames, ',');
s.traceCount = comma ? std::strtoull(comma + 1, nullptr, 10) : 1u;
}
std::vector<uint32_t> candidates;
if (hide && *hide == '@')
{
s.hidePath = hide + 1;
if (const char *all = std::getenv("SC3_HIDE_EE_ALL"))
candidates = census::parseAddresses(all);
census::followHideFile();
}
else if (hide && *hide)
{
candidates = census::parseAddresses(hide);
s.hidden.insert(candidates.begin(), candidates.end());
}
if (const char *record = std::getenv("SC3_RECORD_FRAME"); record && *record)
{
s.recordFrame = std::strtoull(record, nullptr, 10);
const char *dir = std::getenv("SC3_RECORD_DIR");
s.recordDir = dir && *dir ? dir : ".";
}
if (candidates.empty() && !s.traceLoads && s.traceCount == 0u && !s.traceOt && s.recordFrame == ~0ull)
return;
census::wrap(runtime, census::kFrameKick, census::frameKick);
if (s.traceLoads)
{
census::wrap(runtime, census::kFileRequest, census::fileRequest);
census::wrap(runtime, census::kCdRead, census::cdRead);
census::wrap(runtime, census::kMemcpy, census::memcpyTraced);
}
if (s.traceCount != 0u)
{
census::wrap(runtime, census::kBatchFlush, census::batchFlush);
census::wrap(runtime, census::kGifPacketClose, census::gifPacketClose);
for (const uint32_t address : census::kSyncPoints)
census::wrap(runtime, address, census::syncPoint);
census::wrap(runtime, census::kGsHandler, census::gsHandler);
}
if (s.traceOt || s.traceCount != 0u)
for (const uint32_t address : census::kOtInserts)
census::wrap(runtime, address, census::otInsert);
for (const uint32_t address : candidates)
census::wrap(runtime, address, census::hideable);
if (s.recordFrame != ~0ull)
{
std::vector<uint32_t> recorded(std::begin(census::kRecordedDefault), std::end(census::kRecordedDefault));
if (const char *list = std::getenv("SC3_RECORD_FUNCTIONS"); list && *list)
recorded = census::parseAddresses(list);
for (const uint32_t address : recorded)
if (address != census::kFrameKick && s.recordOriginals.count(address) == 0u)
if (census::Function original = runtime.lookupFunction(address))
{
s.recordOriginals[address] = original;
runtime.registerFunction(address, census::recorded);
}
}
std::fprintf(stderr, "[sc3] census: %zu function(s) hideable%s%s%s\n", candidates.size(), s.traceLoads ? ", loads traced" : "",
s.traceCount ? ", frames traced" : "", s.traceOt ? ", OT insertions counted" : "");
}
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <cstdint>
class PS2Runtime;
namespace sc3
{
void installCensus(PS2Runtime &runtime);
bool censusTracingDraws();
void censusNoteDraw(uint64_t tex0, uint64_t tag, uint32_t triangles);
}
+18
View File
@@ -1,8 +1,11 @@
#include "sc3_draw_sink.h"
#include "sc3_census.h"
#include "sc3_textures.h"
#include "runtime/gs/gs_registers.h"
#include "runtime/native/native_renderer.h"
#include <algorithm>
#include <cstring>
namespace sc3
@@ -125,6 +128,7 @@ namespace sc3
else
{
++m_stats.materials;
m_materialTag = hi;
for (uint32_t i = 0; i < nloop; ++i)
{
const uint8_t *entry = m_data + ((qword + total + 1u + i) & 0x3FFu) * 16u;
@@ -152,6 +156,8 @@ namespace sc3
case 0x07u:
m.tex0 = ps2x::gs::decodeTex0(value);
m.loadClut = true;
m_rawTex0[&m == &m_material[1] ? 1 : 0] = value;
m_texSize[&m == &m_material[1] ? 1 : 0] = static_cast<uint32_t>(m_materialTag >> 32);
break;
case 0x08u:
case 0x09u:
@@ -228,6 +234,18 @@ namespace sc3
ps2x::native::GsMaterial draw = material;
draw.prim = ps2x::gs::decodePrim(m_prim);
material.loadClut = false;
const int ctxt = draw.prim.ctxt ? 1 : 0;
if (draw.prim.tme)
{
const auto used = [](uint32_t size, uint32_t log2) {
const uint32_t whole = 1u << std::min<uint32_t>(log2, 10u);
return size != 0u && size < whole ? size : whole;
};
const uint32_t width = used(m_texSize[ctxt] & 0xFFFFu, draw.tex0.tw), height = used(m_texSize[ctxt] >> 16, draw.tex0.th);
draw.texture = packTexture(m_rawTex0[ctxt], width, height);
}
if (censusTracingDraws())
censusNoteDraw(m_rawTex0[draw.prim.ctxt ? 1 : 0], m_materialTag, static_cast<uint32_t>(m_triangles.size() / 3u));
if (m_capture)
{
m_capture->push_back({draw, m_triangles});
+3
View File
@@ -100,6 +100,9 @@ namespace sc3
std::array<Vertex, kVertices> m_vertices{};
ps2x::native::GsMaterial m_material[2];
uint64_t m_prim = 0;
uint64_t m_rawTex0[2] = {};
uint64_t m_materialTag = 0;
uint32_t m_texSize[2] = {};
std::vector<ps2x::native::GsVertex> m_triangles;
std::vector<Draw> *m_capture = nullptr;
Stats m_stats;
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
#pragma once
class PS2Runtime;
namespace sc3
{
// The 3D drawn natively from the offline mesh pack (scripts/sc3_mesh_pack.py) at the game's part builders
// (SC3_NATIVE_MESHES=1, =check against the lifted VU1 programs): RECOMP_NOTES "Native meshes".
void installNativeMeshes(PS2Runtime &runtime, bool nativeGs);
bool nativeMeshesOn();
}
+10
View File
@@ -1,5 +1,7 @@
#include "sc3_native.h"
#include "sc3_draw_sink.h"
#include "sc3_meshes.h"
#include "sc3_textures.h"
#include "sc3_vu1_port.h"
#include "ps2_runtime.h"
@@ -189,6 +191,8 @@ namespace sc3
++s.stats.calls[entry];
s.portNext = false;
s.recordNext = false;
if (nativeMeshesOn()) // its groups are the native meshes' alone
return Vu1StreamAdapter::Choice::Vu1;
if (!s.hidden.empty() && s.hidden.contains(s.names[program], pc))
{
++s.stats.hidden;
@@ -679,6 +683,7 @@ namespace sc3
followPortFile();
followDirectFile();
report();
packFrameEnd();
Vu1StreamAdapter::instance().frameEnd();
};
if (g_state.onVif1Thread)
@@ -750,6 +755,11 @@ namespace sc3
config.screen = screen();
config.choose = choose;
config.draw = drawPort;
config.drawDirect = [](Vu1StreamAdapter &, const uint32_t *packet, size_t qwords)
{
packNoteDirect(packet, qwords);
return false;
};
if (const char *port = std::getenv("SC3_NATIVE_VU1_PORT"); port && *port == '@')
{
s.portPath = port + 1;
+49 -4
View File
@@ -2,10 +2,14 @@
#include "ps2_runtime.h"
#include "ps2_recompiled_functions.h"
#include "runtime/ee_scheduler.h"
#include "sc3_census.h"
#include "sc3_2d.h"
#include "sc3_meshes.h"
#include "runtime/gs/gs_frontend.h"
#include "runtime/native/native_gs_hook.h"
#include "runtime/native/native_renderer.h"
#include "sc3_native.h"
#include "sc3_textures.h"
#include <algorithm>
#include <atomic>
@@ -168,8 +172,9 @@ namespace
}
// The current frame as IPU CSC output: RGBA32 16x16 macroblocks, column by column. Alpha
// movies carry their alpha as the luma of the frame's bottom half.
bool currentMacroblocks(uint8_t *out, uint32_t capacity, bool alphaMovie, uint32_t &width, uint32_t &height, uint32_t &number)
// movies carry their alpha as the luma of the frame's bottom half. write false: the frame advances, nothing
// is written.
bool currentMacroblocks(uint8_t *out, uint32_t capacity, bool alphaMovie, bool write, uint32_t &width, uint32_t &height, uint32_t &number)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_active || m_fullScreen)
@@ -182,7 +187,7 @@ namespace
width = m_width;
height = outHeight;
number = m_number;
if (m_written == m_number)
if (!write || m_written == m_number)
return true;
m_written = m_number;
uint8_t *dst = out;
@@ -201,6 +206,32 @@ namespace
return true;
}
// The current frame as the movie task's copy into a texture's pixels (0x217E28) has it: RGBA rows, alpha as
// in the macroblocks. Nothing is copied while known is still the current frame's number.
bool currentPicture(bool alphaMovie, uint32_t known, std::vector<uint32_t> &rgba, uint32_t &width, uint32_t &height, uint32_t &number)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_active || m_fullScreen || m_current.empty())
return false;
const uint32_t outHeight = alphaMovie ? m_height / 2u : m_height;
width = m_width;
height = outHeight;
number = m_number;
if (known == m_number)
return true;
rgba.resize(static_cast<size_t>(m_width) * outHeight);
for (uint32_t y = 0; y < outHeight; ++y)
for (uint32_t x = 0; x < m_width; ++x)
{
const uint8_t *src = m_current.data() + (static_cast<size_t>(y) * m_width + x) * 4u;
const uint8_t *mask = src + static_cast<size_t>(outHeight) * m_width * 4u;
const uint32_t luma = (mask[0] * 77u + mask[1] * 150u + mask[2] * 29u) >> 8;
const uint32_t alpha = alphaMovie ? (luma * 0x80u + 127u) / 255u : 0x80u;
rgba[static_cast<size_t>(y) * m_width + x] = src[0] | (src[1] << 8) | (src[2] << 16) | (alpha << 24);
}
return true;
}
private:
void report()
{
@@ -673,7 +704,7 @@ namespace
std::cerr << "[sc3] mwPlyGetCurFrm handle=0x" << std::hex << handle << " buffer=0x" << buffer << " limit=0x" << limit
<< " ra=0x" << getRegU32(ctx, 31) << std::dec << " alpha=" << alphaMovie << " active=" << player->active() << std::endl;
}
if (capacity != 0u && player->currentMacroblocks(rdram + (buffer & PS2_RAM_MASK), capacity, alphaMovie, width, height, number))
if (capacity != 0u && player->currentMacroblocks(rdram + (buffer & PS2_RAM_MASK), capacity, alphaMovie, !sc3::native2dMovie(handle), width, height, number))
{
if (std::getenv("PS2X_SC3_TRACE_MOVIE") && number % 60u == 1u)
std::cerr << "[sc3] movie frame handle=0x" << std::hex << handle << " buffer=0x" << buffer << std::dec << " " << width
@@ -686,6 +717,15 @@ namespace
ctx->pc = getRegU32(ctx, 31);
}
bool moviePicture(uint32_t handle, uint32_t known, std::vector<uint32_t> &rgba, uint32_t &width, uint32_t &height, uint32_t &number)
{
const auto player = g_movies.find(handle);
if (!player || !g_movieRuntime)
return false;
const bool alphaMovie = g_movieRuntime->memory().read32(handle + kMwPlyCompoMode) == kMwPlyCompoAlpha;
return player->currentPicture(alphaMovie, known, rgba, width, height, number);
}
void mwPlyRelCurFrmHost(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (!g_movies.find(getRegU32(ctx, 4)))
@@ -1635,6 +1675,11 @@ namespace
runtime.registerFunction(kCreateTask, createTaskTraced);
sc3::installNativeVu1(runtime, nativeGs);
sc3::installNativeVu0(runtime);
sc3::installTexturePack(runtime, nativeGs);
sc3::installNativeMeshes(runtime, nativeGs);
sc3::installNative2d(runtime, nativeGs);
sc3::setMoviePictures(moviePicture);
sc3::installCensus(runtime);
installMovieCounters(runtime);
// Full-screen movies as the native renderer's held backdrop, Sofdec's decoder set-up without libmpeg or the IPU.
// SC3_NATIVE_MOVIES=0 (or a GS renderer without the native renderer): the presentation override instead.
+149
View File
@@ -0,0 +1,149 @@
#include "sc3_texture_pack.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
namespace sc3
{
namespace texture_keys
{
namespace
{
constexpr char kMagic[8] = {'S', 'C', '3', 'K', 'E', 'Y', 'S', '1'};
constexpr uint64_t kTex0Key = 0x3FFFull | (0x3Full << 14) | (0x3Full << 20) | (0xFull << 26) | (0xFull << 30) |
(0x3FFFull << 37) | (0xFull << 51) | (1ull << 55) | (0x1Full << 56);
constexpr uint32_t kNoPalette = 0xFFFFFFFFu;
template <typename T>
bool read(std::ifstream &file, T &out)
{
file.read(reinterpret_cast<char *>(&out), sizeof(T));
return static_cast<bool>(file);
}
uint64_t key(uint64_t tex0, uint32_t width, uint32_t height)
{
return (tex0 & kTex0Key) ^ (static_cast<uint64_t>(width) << 1) ^ (static_cast<uint64_t>(height) << 17);
}
std::string keysPath(const std::string &packPath)
{
const size_t dot = packPath.find_last_of('.');
const size_t slash = packPath.find_last_of("/\\");
return (dot != std::string::npos && (slash == std::string::npos || dot > slash) ? packPath.substr(0, dot) : packPath) + ".keys";
}
}
}
bool TextureKeys::open(const std::string &packPath)
{
if (!m_pack.load(packPath))
{
std::fprintf(stderr, "[sc3] texture pack: %s is not a PS2XTEX1 pack\n", packPath.c_str());
return false;
}
const std::string path = texture_keys::keysPath(packPath);
std::ifstream file(path, std::ios::binary);
char magic[8] = {};
uint64_t archiveSize = 0;
uint32_t lists = 0;
file.read(magic, 8);
if (!file || std::memcmp(magic, texture_keys::kMagic, 8) != 0 || !texture_keys::read(file, archiveSize) ||
!texture_keys::read(file, lists))
{
std::fprintf(stderr, "[sc3] texture pack: %s is not an SC3KEYS1 index\n", path.c_str());
return false;
}
std::map<uint64_t, Leaf> leaves;
for (uint32_t l = 0; l < lists; ++l)
{
uint16_t nameLength = 0;
if (!texture_keys::read(file, nameLength))
return false;
std::string name(nameLength, '\0');
file.read(name.data(), nameLength);
uint64_t offset = 0;
uint32_t size = 0, entries = 0, keys = 0;
if (!texture_keys::read(file, offset) || !texture_keys::read(file, size) || !texture_keys::read(file, entries) ||
!texture_keys::read(file, keys))
return false;
List &list = m_lists.emplace_back();
list.records = m_pack.file(name);
Leaf &leaf = leaves[offset];
leaf.offset = offset;
leaf.size = size;
for (uint32_t e = 0; e < entries; ++e)
{
uint32_t at = 0, complete = 0;
if (!texture_keys::read(file, at) || !texture_keys::read(file, complete))
return false;
leaf.entries[at] = Entry{&list, e, complete != 0u};
}
m_entries += entries;
for (uint32_t k = 0; k < keys; ++k)
{
Key key;
if (!texture_keys::read(file, key.tex0) || !texture_keys::read(file, key.width) || !texture_keys::read(file, key.height) ||
!texture_keys::read(file, key.firstEntry) || !texture_keys::read(file, key.texels) || !texture_keys::read(file, key.palette))
return false;
list.keys.push_back(key);
}
for (uint32_t k = 0; k < list.keys.size(); ++k)
list.byKey.emplace(texture_keys::key(list.keys[k].tex0, list.keys[k].width, list.keys[k].height), k);
}
for (auto &[offset, leaf] : leaves)
m_leaves.push_back(std::move(leaf));
return true;
}
const TextureKeys::Entry *TextureKeys::entryAt(uint64_t archiveOffset) const
{
const auto leaf = std::upper_bound(m_leaves.begin(), m_leaves.end(), archiveOffset,
[](uint64_t offset, const Leaf &l) { return offset < l.offset; });
if (leaf == m_leaves.begin())
return nullptr;
const Leaf &found = *std::prev(leaf);
if (archiveOffset >= found.offset + found.size)
return nullptr;
const auto entry = found.entries.find(static_cast<uint32_t>(archiveOffset - found.offset));
return entry == found.entries.end() ? nullptr : &entry->second;
}
const ps2x::native::NativeTexture *TextureKeys::texture(const Entry &entry, uint64_t tex0, uint32_t width, uint32_t height)
{
const List &list = *entry.list;
if (!list.records)
return nullptr;
const auto [first, last] = list.byKey.equal_range(texture_keys::key(tex0, width, height));
for (auto it = first; it != last; ++it)
{
const Key &key = list.keys[it->second];
if (key.firstEntry < entry.index || key.texels >= list.records->size())
continue;
std::lock_guard<std::mutex> lock(m_mutex);
auto decoded = m_decoded.find(&key);
if (decoded == m_decoded.end())
{
const ps2x::native::packs::TextureRecord &texels = (*list.records)[key.texels];
uint32_t palette[256] = {};
if (key.palette != texture_keys::kNoPalette && key.palette < list.records->size())
{
const ps2x::native::packs::TextureRecord &colours = (*list.records)[key.palette];
std::memcpy(palette, colours.texels.data(), std::min<size_t>(sizeof(palette), colours.texels.size()));
}
Decoded &out = m_decoded[&key];
ps2x::native::packs::decodeRecord(out.image, key.width, key.height, texels.psm, texels, palette, 0);
out.native.width = out.image.width;
out.native.height = out.image.height;
out.native.rgba = out.image.rgba.data();
out.native.key = reinterpret_cast<uintptr_t>(&key);
decoded = m_decoded.find(&key);
}
return decoded->second.native.rgba ? &decoded->second.native : nullptr;
}
return nullptr;
}
}
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "runtime/native/native_gs_hook.h"
#include "runtime/native/native_texture_pack.h"
#include <cstdint>
#include <deque>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace sc3
{
// SC3's texture keys over PS2Recomp's generic texture pack (scripts/sc3_texture_pack.py writes both): a texture is
// found by the CALL list entry the game CALLs (where it sits in ROOT.OLK) and the TEX0 and used size a draw selects.
class TextureKeys
{
public:
struct List;
struct Entry
{
const List *list = nullptr;
uint32_t index = 0;
bool complete = false; // every texture its uploads feed is in the pack
};
// The pack and the key index beside it (<pack without extension>.keys).
bool open(const std::string &packPath);
size_t lists() const { return m_lists.size(); }
size_t entries() const { return m_entries; }
size_t records() const { return m_pack.recordCount(); }
// The CALL list entry starting `archiveOffset` bytes into ROOT.OLK, or null.
const Entry *entryAt(uint64_t archiveOffset) const;
// The texture TEX0 selects at that used size among the uploads from `entry` to its list's end, or null.
// Decoded on first use and kept for the program's life.
const ps2x::native::NativeTexture *texture(const Entry &entry, uint64_t tex0, uint32_t width, uint32_t height);
struct Key
{
uint64_t tex0 = 0;
uint16_t width = 0, height = 0;
uint32_t firstEntry = 0, texels = 0, palette = 0;
};
struct List
{
const std::vector<ps2x::native::packs::TextureRecord> *records = nullptr;
std::vector<Key> keys;
std::unordered_multimap<uint64_t, uint32_t> byKey;
};
private:
struct Leaf
{
uint64_t offset = 0;
uint32_t size = 0;
std::unordered_map<uint32_t, Entry> entries;
};
struct Decoded
{
ps2x::native::TextureCache::Texture image;
ps2x::native::NativeTexture native;
};
ps2x::native::packs::TexturePack m_pack;
std::vector<Leaf> m_leaves; // by offset
std::deque<List> m_lists;
size_t m_entries = 0;
std::unordered_map<const Key *, Decoded> m_decoded;
std::mutex m_mutex;
};
}
+455
View File
@@ -0,0 +1,455 @@
#include "sc3_textures.h"
#include "sc3_census.h"
#include "sc3_texture_pack.h"
#include "ps2_runtime.h"
#include "ps2_recompiled_functions.h"
#include "ps2_runtime_macros.h"
#include "runtime/gs/gs_frontend.h"
#include "runtime/native/native_gs_hook.h"
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
namespace sc3
{
namespace texpack
{
namespace
{
constexpr uint32_t kFrameKick = 0x0010F098u;
constexpr uint32_t kFileRequest = 0x00150418u;
constexpr uint32_t kCdRead = 0x00424E28u;
constexpr uint32_t kGifPacketClose = 0x0010F808u;
constexpr uint32_t kOtInsertDepth = 0x0010D9A0u;
constexpr uint32_t kSyncPoint = 0x0010F9D0u;
constexpr uint64_t kSignal = 0x60u;
constexpr uint32_t kGifSyncId = 1u;
constexpr uint32_t kVif1SyncId = 2u;
constexpr uint32_t kTextureCall = 0x00104DCCu;
constexpr uint32_t kAnimatedTextureCall = 0x00104E48u;
constexpr uint32_t kTextureCallOt = 0x00104E94u;
constexpr uint32_t kAnimatedTextureCallOt = 0x00104E34u;
constexpr uint32_t kScratchpad = 0x70000000u;
constexpr uint32_t kSector = 2048u;
using Function = PS2Runtime::RecompiledFunction;
// One upload group: the CALL list entry a texture CALL started from (null: not in the pack).
struct Group
{
const TextureKeys::Entry *entry = nullptr;
uint32_t syncs = 0; // GIF sync points before its CALL: its segment of the GIF / VIF1 handshake
};
struct Read
{
uint32_t end = 0;
uint64_t olk = 0;
};
struct Stats
{
uint64_t calls = 0, packed = 0, leftOut = 0, unknown = 0;
std::atomic<uint64_t> bound{0}, missed{0};
};
enum class PackMode
{
Off,
Keep, // pack textures drawn, the game's uploads still sent (PS2X_NATIVE_TEXTURE_CHECK compares them)
On, // and the uploads of the groups the pack covers left out
};
std::atomic<PackMode> g_mode{PackMode::Off};
std::string g_switchPath;
TextureKeys g_pack;
uint8_t *g_rdram = nullptr;
uint8_t *g_scratchpad = nullptr;
PS2Runtime *g_runtime = nullptr;
std::map<uint32_t, Function> g_originals;
int64_t g_olkLbn = -1;
uint32_t g_requestDest = 0, g_requestPos = 0;
bool g_requestPending = false;
std::map<uint32_t, Read> g_reads; // EE start -> what ROOT.OLK bytes the game read there
std::vector<Group> g_building; // the frame being built
std::mutex g_framesMutex;
std::deque<std::vector<Group>> g_kicked; // frames kicked, oldest first, for the VIF1 thread
Stats g_stats;
uint64_t g_frames = 0;
uint64_t g_lastTransfers = 0, g_lastBytes = 0;
// VIF1 thread.
std::vector<Group> g_drawing;
uint32_t g_syncs = 0; // the frame being built
uint32_t g_streamSyncs = 0; // VIF1 thread: the drawn frame's sync points passed
bool g_wantFrame = true;
std::map<uint64_t, uint64_t> g_misses; // TEX0 (TBP, PSM, CBP) -> draws without a pack texture
std::mutex g_missMutex;
uint32_t peek32(uint32_t address)
{
uint32_t value = 0;
if ((address & 0xF0000000u) == kScratchpad)
std::memcpy(&value, g_scratchpad + (address & 0x3FFCu), 4);
else
std::memcpy(&value, g_rdram + (address & PS2_RAM_MASK & ~3u), 4);
return value;
}
void poke32(uint32_t address, uint32_t value)
{
if ((address & 0xF0000000u) == kScratchpad)
std::memcpy(g_scratchpad + (address & 0x3FFCu), &value, 4);
else
std::memcpy(g_rdram + (address & PS2_RAM_MASK & ~3u), &value, 4);
}
// The pack entry a texture CALL's target is: the ROOT.OLK bytes the game read where it sits, in a packed leaf.
const TextureKeys::Entry *entryAt(uint32_t address)
{
auto read = g_reads.upper_bound(address);
if (read == g_reads.begin())
return nullptr;
--read;
if (address >= read->second.end)
return nullptr;
return g_pack.entryAt(read->second.olk + (address - read->first));
}
void callOriginal(uint32_t address, uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
g_originals.at(address)(rdram, ctx, runtime);
}
void fileRequest(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (getRegU32(ctx, 5) == 1u && g_olkLbn < 0)
{
g_requestDest = getRegU32(ctx, 8);
g_requestPos = getRegU32(ctx, 6);
g_requestPending = true;
}
callOriginal(kFileRequest, rdram, ctx, runtime);
}
void cdRead(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t lbn = getRegU32(ctx, 4), sectors = getRegU32(ctx, 5), buffer = getRegU32(ctx, 6) & PS2_RAM_MASK;
if (g_olkLbn < 0 && g_requestPending && buffer == (g_requestDest & PS2_RAM_MASK) && (g_requestPos % kSector) == 0u)
g_olkLbn = static_cast<int64_t>(lbn) - g_requestPos / kSector;
if (g_olkLbn >= 0 && lbn >= g_olkLbn && sectors != 0u)
{
const uint32_t end = buffer + sectors * kSector;
auto it = g_reads.lower_bound(buffer);
if (it != g_reads.begin() && std::prev(it)->second.end > buffer)
--it;
while (it != g_reads.end() && it->first < end)
it = g_reads.erase(it);
g_reads[buffer] = Read{end, static_cast<uint64_t>(lbn - g_olkLbn) * kSector};
}
callOriginal(kCdRead, rdram, ctx, runtime);
}
// The texture CALL's target, from the game's own command list (0x104AF0's commands 2, 3 and 20).
uint32_t callTarget(R5900Context *ctx, uint32_t ra)
{
const uint32_t command = getRegU32(ctx, 20);
if (ra == kTextureCall)
return peek32(command - 8u);
if (ra == kTextureCallOt)
return peek32(command - 4u);
const uint32_t table = peek32(command + 4u);
float frame;
const uint32_t bits = peek32(peek32(command + 8u));
std::memcpy(&frame, &bits, 4);
return peek32(table + static_cast<uint32_t>(ps2FpuCvtWS(frame)) * 4u);
}
const TextureKeys::Entry *noteCall(R5900Context *ctx, uint32_t ra)
{
const uint32_t target = callTarget(ctx, ra);
const TextureKeys::Entry *entry = entryAt(target);
if (censusTracingDraws())
std::fprintf(stderr, "[sc3:trace] pack group %zu after %u syncs: call %#x ra=%#x %s\n", g_building.size(), g_syncs, target, ra,
entry ? "in the pack" : "not in the pack");
g_building.push_back(Group{entry, g_syncs});
++g_stats.calls;
if (entry)
++g_stats.packed;
else
++g_stats.unknown;
return entry;
}
// 0x10F808 without its copy to the GIF list (0x10EF78): the scratchpad half flips as it would.
void closeWithoutUpload(R5900Context *ctx)
{
const uint32_t half = peek32(kScratchpad + 4u) ^ 1u;
poke32(kScratchpad + 4u, half);
poke32(kScratchpad, peek32(kScratchpad + 8u + half * 4u));
ctx->pc = getRegU32(ctx, 31);
}
void gifPacketClose(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
if (ra == kTextureCall || ra == kAnimatedTextureCall)
{
const TextureKeys::Entry *entry = noteCall(ctx, ra);
if (g_mode == PackMode::On && entry && entry->complete && getRegU32(ctx, 4) == peek32(kScratchpad) + 16u)
{
++g_stats.leftOut;
closeWithoutUpload(ctx);
return;
}
}
callOriginal(kGifPacketClose, rdram, ctx, runtime);
}
void otInsert(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
const uint32_t ra = getRegU32(ctx, 31);
if (ra == kTextureCallOt || ra == kAnimatedTextureCallOt)
noteCall(ctx, ra);
callOriginal(kOtInsertDepth, rdram, ctx, runtime);
}
void report()
{
if (++g_frames % 250u != 0u)
return;
GS &gs = g_runtime->gs();
const uint64_t transfers = gs.imageTransfers(), bytes = gs.imageBytes();
std::fprintf(stderr,
"[sc3:packets] %llu frames: texture uploads called %llu, from the pack %llu (left out %llu, sent %llu), not "
"in the pack %llu; GS image transfers read from GIF packets %llu (%llu bytes)\n",
250ull, static_cast<unsigned long long>(g_stats.calls), static_cast<unsigned long long>(g_stats.packed),
static_cast<unsigned long long>(g_stats.leftOut),
static_cast<unsigned long long>(g_stats.packed - g_stats.leftOut),
static_cast<unsigned long long>(g_stats.unknown), static_cast<unsigned long long>(transfers - g_lastTransfers),
static_cast<unsigned long long>(bytes - g_lastBytes));
std::string misses;
{
std::lock_guard<std::mutex> lock(g_missMutex);
std::vector<std::pair<uint64_t, uint64_t>> sorted(g_misses.begin(), g_misses.end());
std::sort(sorted.begin(), sorted.end(), [](const auto &a, const auto &b) { return a.second > b.second; });
char item[96];
for (size_t i = 0; i < sorted.size() && i < 8u; ++i)
{
const uint64_t t = sorted[i].first;
std::snprintf(item, sizeof(item), " tbp %#x psm %#x cbp %#x x%llu", static_cast<unsigned>(t & 0x3FFFu),
static_cast<unsigned>((t >> 20) & 0x3Fu), static_cast<unsigned>((t >> 37) & 0x3FFFu),
static_cast<unsigned long long>(sorted[i].second));
misses += item;
}
g_misses.clear();
}
std::fprintf(stderr, "[sc3:gs] %llu frames: direct draws textured from the pack %llu, from GS memory %llu;%s\n", 250ull,
static_cast<unsigned long long>(g_stats.bound.exchange(0)), static_cast<unsigned long long>(g_stats.missed.exchange(0)),
misses.empty() ? " no misses" : misses.c_str());
g_lastTransfers = transfers;
g_lastBytes = bytes;
g_stats.calls = g_stats.packed = g_stats.leftOut = g_stats.unknown = 0;
}
PackMode parseMode(const std::string &value)
{
if (value == "keep")
return PackMode::Keep;
return value.empty() || value == "0" ? PackMode::Off : PackMode::On;
}
void followSwitch()
{
std::ifstream file(g_switchPath);
std::string value;
if (!std::getline(file, value))
return;
const PackMode mode = parseMode(value);
if (mode != g_mode)
std::fprintf(stderr, "[sc3] texture pack: %s from the next frame\n",
mode == PackMode::Off ? "off" : mode == PackMode::Keep ? "on, uploads still sent" : "on");
g_mode = mode;
}
void frameKick(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (!g_switchPath.empty() && (g_frames & 15u) == 0u)
followSwitch();
{
std::lock_guard<std::mutex> lock(g_framesMutex);
g_kicked.push_back(std::move(g_building));
g_syncs = 0;
while (g_kicked.size() > 4u)
g_kicked.pop_front();
}
g_building.clear();
report();
callOriginal(kFrameKick, rdram, ctx, runtime);
}
void wrap(PS2Runtime &runtime, uint32_t address, Function hook)
{
Function original = runtime.lookupFunction(address);
if (!original)
return;
g_originals[address] = original;
runtime.registerFunction(address, hook);
}
// As the GS would sample it: from the latest group that covers it among those whose GIF segment (the GIF sync
// points before its CALL) VIF1 has reached (as many of its own sync points passed).
const ps2x::native::NativeTexture *find(uint64_t tex0, uint32_t width, uint32_t height)
{
for (size_t g = g_drawing.size(); g-- > 0;)
if (g_drawing[g].syncs <= g_streamSyncs)
if (const TextureKeys::Entry *entry = g_drawing[g].entry)
if (const ps2x::native::NativeTexture *texture = g_pack.texture(*entry, tex0, width, height))
return texture;
return nullptr;
}
void syncPoint(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime)
{
if (getRegU32(ctx, 5) == kGifSyncId)
++g_syncs;
callOriginal(kSyncPoint, rdram, ctx, runtime);
}
}
}
const ps2x::native::NativeTexture *packTexture(uint64_t tex0, uint32_t width, uint32_t height)
{
if (texpack::g_mode == texpack::PackMode::Off)
return nullptr;
if (texpack::g_wantFrame)
{
std::lock_guard<std::mutex> lock(texpack::g_framesMutex);
if (!texpack::g_kicked.empty())
{
texpack::g_drawing = std::move(texpack::g_kicked.front());
texpack::g_kicked.pop_front();
texpack::g_wantFrame = false;
}
}
const ps2x::native::NativeTexture *texture = texpack::find(tex0, width, height);
if (censusTracingDraws())
std::fprintf(stderr, "[sc3:trace] pack tex0=%#llx %ux%u after %zu syncs, %zu groups: %s\n", static_cast<unsigned long long>(tex0), width,
height, static_cast<size_t>(texpack::g_streamSyncs), texpack::g_drawing.size(), texture ? "pack" : "GS memory");
if (texture)
{
texpack::g_stats.bound.fetch_add(1u, std::memory_order_relaxed);
return texture;
}
texpack::g_stats.missed.fetch_add(1u, std::memory_order_relaxed);
std::lock_guard<std::mutex> lock(texpack::g_missMutex);
++texpack::g_misses[tex0 & ((0x3FFFull) | (0x3Full << 20) | (0x3FFFull << 37))];
return nullptr;
}
bool texturePackReady() { return texpack::g_runtime != nullptr; }
const ps2x::native::NativeTexture *packTextureAtHook(uint64_t tex0, uint32_t width, uint32_t height)
{
for (size_t g = texpack::g_building.size(); g-- > 0;)
if (const TextureKeys::Entry *entry = texpack::g_building[g].entry)
if (const ps2x::native::NativeTexture *texture = texpack::g_pack.texture(*entry, tex0, width, height))
return texture;
return nullptr;
}
void packNoteDirect(const uint32_t *words, size_t qwords)
{
if (!texpack::g_runtime)
return;
size_t q = 0;
while (q < qwords)
{
uint64_t lo, hi;
std::memcpy(&lo, words + q * 4u, 8);
std::memcpy(&hi, words + q * 4u + 2u, 8);
const uint32_t nloop = static_cast<uint32_t>(lo & 0x7FFFu), format = static_cast<uint32_t>((lo >> 58) & 3u);
const uint32_t nreg = ((lo >> 60) & 0xFu) ? static_cast<uint32_t>((lo >> 60) & 0xFu) : 16u;
++q;
if (format == 0u && nreg == 1u && (hi & 0xFu) == 0xEu)
{
for (uint32_t i = 0; i < nloop && q < qwords; ++i, ++q)
{
uint64_t value, reg;
std::memcpy(&value, words + q * 4u, 8);
std::memcpy(&reg, words + q * 4u + 2u, 8);
if ((reg & 0xFFu) == texpack::kSignal && (value & texpack::kVif1SyncId))
++texpack::g_streamSyncs;
}
}
else
q += format == 0u ? size_t{nloop} * nreg : format == 1u ? (size_t{nloop} * nreg + 1u) / 2u : nloop;
if ((lo >> 15) & 1u)
return;
}
}
void packFrameEnd()
{
if (!texpack::g_runtime)
return;
if (texpack::g_wantFrame)
{
std::lock_guard<std::mutex> lock(texpack::g_framesMutex);
if (!texpack::g_kicked.empty())
texpack::g_kicked.pop_front();
}
texpack::g_drawing.clear();
texpack::g_streamSyncs = 0;
texpack::g_wantFrame = true;
}
void installTexturePack(PS2Runtime &runtime, bool nativeGs)
{
const char *path = std::getenv("SC3_TEXTURE_PACK");
const char *mode = std::getenv("SC3_TEXTURE_PACK_MODE");
if (!path || !*path || !mode || !*mode || *mode == '0')
return;
const bool followed = mode && *mode == '@';
if (!nativeGs)
{
std::fprintf(stderr, "[sc3] texture pack: only with the native GS renderer, not used\n");
return;
}
if (!texpack::g_pack.open(path))
return;
std::fprintf(stderr, "[sc3] texture pack: %s, %zu upload lists, %zu entries, %zu records\n", path, texpack::g_pack.lists(),
texpack::g_pack.entries(), texpack::g_pack.records());
if (followed)
{
texpack::g_switchPath = mode + 1;
texpack::followSwitch();
}
else
texpack::g_mode = std::strcmp(mode, "keep") == 0 ? texpack::PackMode::Keep : texpack::PackMode::On;
texpack::g_runtime = &runtime;
texpack::g_rdram = runtime.memory().getRDRAM();
texpack::g_scratchpad = runtime.memory().getScratchpad();
texpack::wrap(runtime, texpack::kFileRequest, texpack::fileRequest);
texpack::wrap(runtime, texpack::kCdRead, texpack::cdRead);
texpack::wrap(runtime, texpack::kGifPacketClose, texpack::gifPacketClose);
texpack::wrap(runtime, texpack::kOtInsertDepth, texpack::otInsert);
texpack::wrap(runtime, texpack::kFrameKick, texpack::frameKick);
texpack::wrap(runtime, texpack::kSyncPoint, texpack::syncPoint);
std::fprintf(stderr, "[sc3] texture pack: direct draws textured from it%s\n",
followed ? ", as its switch file says" : texpack::g_mode == texpack::PackMode::On ? ", uploads it covers left out" : ", the game's uploads still sent");
}
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <cstddef>
#include <cstdint>
class PS2Runtime;
namespace ps2x::native
{
struct NativeTexture;
}
namespace sc3
{
void installTexturePack(PS2Runtime &runtime, bool nativeGs);
// VIF1 thread, for a direct draw: the pack texture its TEX0 selects, at the used size its material gives, in the
// upload group being drawn, or null (the draw samples GS memory as before).
const ps2x::native::NativeTexture *packTexture(uint64_t tex0, uint32_t width, uint32_t height);
// VIF1 thread, each DIRECT the VIF1 stream carries: the game's sync points (the SIGNAL 2 its VIF1 list carries between
// an upload group and the draws after it) tell how far the GS has got through the frame's uploads.
void packNoteDirect(const uint32_t *words, size_t qwords);
// VIF1 thread, where the game's frame ends: the next draws belong to the next kicked frame's upload groups.
void packFrameEnd();
// Game thread, at a per-part hook (0x104AF0's commands run in order: a batch's texture CALLs come right before its
// draws): the pack texture this TEX0 (as the pack's material has it) and used size select among the upload groups the
// frame being built has CALLed, the latest first, or null. True from texturePackReady() on.
const ps2x::native::NativeTexture *packTextureAtHook(uint64_t tex0, uint32_t width, uint32_t height);
bool texturePackReady();
}
+12 -1
View File
@@ -1,5 +1,7 @@
#!/usr/bin/env bash
# Builds ps2EntryRunner with the generated code linked in -> build/game/PS2Recomp/ps2xRuntime/ps2EntryRunner
# Builds ps2EntryRunner with the generated code linked in -> build/game/PS2Recomp/ps2xRuntime/ps2EntryRunner, and the
# packs from the disc files in game/ when there are none yet: build/sc3_textures.pack and .keys (about 10 minutes on
# 6 cores), build/sc3_meshes.pack, build/sc3_2d.pack (+ _textures.pack, .leaves; the native 2D's).
# Usage: scripts/build_runtime.sh [Release|RelWithDebInfo|Debug]
source "$(dirname "$0")/common.sh"
BUILD_TYPE="${1:-RelWithDebInfo}"
@@ -11,3 +13,12 @@ fi
cmake -S "$ROOT" -B "$GAME_BUILD" -G Ninja -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DPS2X_BUILD_STUDIO=OFF "${compiler[@]}"
cmake --build "$GAME_BUILD" --target ps2EntryRunner -j "$JOBS"
case "$(uname -s)" in MINGW* | MSYS*) "$ROOT/scripts/stage_dlls.sh" "$GAME_BUILD" ;; esac
if [ ! -f "$TEXTURE_PACK" ] && [ -f "$GAME_DIR/ROOT.OLK" ]; then
"${PYTHON:-python3}" -I "$ROOT/scripts/sc3_texture_pack.py" "$GAME_DIR" "$TEXTURE_PACK"
fi
if [ ! -f "$MESH_PACK" ] && [ -f "$GAME_DIR/ROOT.OLK" ]; then
"${PYTHON:-python3}" -I "$ROOT/scripts/sc3_mesh_pack.py" "$GAME_DIR" "$MESH_PACK"
fi
if [ ! -f "$TWO_D_PACK" ] && [ -f "$GAME_DIR/ROOT.OLK" ]; then
"${PYTHON:-python3}" -I "$ROOT/scripts/sc3_2d_pack.py" "$GAME_DIR" "$TWO_D_PACK"
fi
+3
View File
@@ -6,4 +6,7 @@ CONFIG="$ROOT/recomp/sc3.toml"
GENERATED="$ROOT/generated"
TOOLS_BUILD="$ROOT/build/tools"
GAME_BUILD="$ROOT/build/game"
TEXTURE_PACK="$ROOT/build/sc3_textures.pack"
MESH_PACK="$ROOT/build/sc3_meshes.pack"
TWO_D_PACK="$ROOT/build/sc3_2d.pack"
JOBS="${JOBS:-$(nproc)}"
+213 -11
View File
@@ -39,10 +39,41 @@
# the run with the programs drawn from their packets (SC3_NATIVE_VU1_DIRECT=@file); in the pause
# menu pause_packets.png a little after pause.png (pause_direct_floor_psnr), then direct draws
# switched on for pause_direct.png (pause_direct_psnr, against pause.png)
# REGRESS_TEXPACK_AB=1|keep
# the run with the texture pack off (SC3_TEXTURE_PACK_MODE=@file); in the pause menu
# pause_texpack_off.png a little after pause.png (pause_texpack_floor_psnr), then the pack switched
# on (keep: its textures drawn, the game's uploads still sent) for pause_texpack.png
# (pause_texpack_psnr, against pause.png)
# REGRESS_NATIVE_2D_AB=1
# the run with the native 2D off (SC3_NATIVE_2D=@file, SC3_2D_PACK); in Mode Select menu_2d_off.png
# and menu_2d_off2.png a little later (menu_2d_floor_psnr), then the native 2D switched on for
# menu_2d.png (menu_2d_psnr, against menu_2d_off.png) and off again; in the pause menu
# pause_2d_off.png a little after pause.png (pause_2d_floor_psnr), then on for pause_2d.png
# (pause_2d_psnr, against pause.png)
# REGRESS_MENU_SERIES=<n>
# with REGRESS_NATIVE_2D_AB=1: in the main menu and in Single Player Modes, n rounds of four
# stills a presented frame apart, two with the native 2D off and two on (menu_<screen>_<i>_<off|on>.png);
# menu_<screen>_floor_psnr is the mean psnr of neighbours drawn the same way, menu_<screen>_psnr of
# neighbours drawn one each way (animated backdrops: no two stills are the same scene)
# REGRESS_VERSUS=1 World Competition instead of Practice: a tournament match against the CPU with the fight HUD
# (health gauges, timer, round marks, names, BATTLE / K.O. / RING OUT / YOU LOSE), the attacks
# from its BATTLE 1 on for REGRESS_FIGHT_SECS (default 120: three battles and the results), no
# pause menu; with REGRESS_NATIVE_2D_AB=1 four stills after every round of attacks, as the menu
# series (versus_fight_<i><a-d>_<off|on>.png, versus_fight_floor_psnr / versus_fight_psnr)
# REGRESS_VERSUS_PAUSE=1
# with REGRESS_VERSUS=1 and REGRESS_NATIVE_2D_AB=1: each round's four stills taken with the fight
# paused (START before, START after), the same frame under both ways of drawing
# (versus_pause_<i><a-d>_<off|on>.png, versus_pause_floor_psnr / versus_pause_psnr)
# REGRESS_PAUSE_HIDE_EE="0x1f8598 0x10a178 ..."
# in the pause menu, one still per game function returned at entry (SC3_HIDE_EE), as
# pause_hide_ee_<address>.png, and pause_hide_ee.txt: each one's imgdiff against pause.png
# REGRESS_PAUSE_HIDE="A:0x10 B:0x1388 ..."
# in the pause menu, one still per entry with that VU1 program hidden (SC3_NATIVE_VU1_HIDE), as
# pause_hide_<entry>.png, and pause_hide.txt: each one's imgdiff against pause.png
# SC3_ELF game ELF (default: game/SLUS_212.16 of this repo)
# SC3_TEXTURE_PACK the texture pack (default: build/sc3_textures.pack of this repo, when there is one)
# SC3_MESH_PACK the mesh pack (default: build/sc3_meshes.pack of this repo, when there is one)
# SC3_2D_PACK the 2D material pack (default: build/sc3_2d.pack of this repo, when there is one)
# PS2X_SPU2_WALLCLOCK default 1, as scripts/run.sh
set -euo pipefail
export PS2X_SPU2_WALLCLOCK="${PS2X_SPU2_WALLCLOCK:-1}"
@@ -56,6 +87,8 @@ fight_secs=${REGRESS_FIGHT_SECS:-60}
pause_secs=${REGRESS_PAUSE_SECS:-3}
shot_secs=${REGRESS_SHOT_SECS:-5}
keep_shots=${REGRESS_KEEP_SHOTS:-0}
versus=${REGRESS_VERSUS:-0}
[ "$versus" != 1 ] || fight_secs=${REGRESS_FIGHT_SECS:-120}
period=5
runner=
@@ -79,7 +112,7 @@ frames=$out/frames
shots=$out/shots
log=$out/run.log
input=$out/pad_input.txt
rm -rf "$frames" "$shots" "$out"/last_frame.* "$out"/pause*.png "$out"/pause_hide.txt "$out/summary.txt" "$out/details.txt" "$out/errors.txt" "$out/pad.txt"
rm -rf "$frames" "$shots" "$out"/last_frame.* "$out"/pause*.png "$out"/menu_*.png "$out"/versus_*.png "$out"/pause_hide.txt "$out"/pause_hide_ee.txt "$out/summary.txt" "$out/details.txt" "$out/errors.txt" "$out/pad.txt"
mkdir -p "$frames" "$shots"
user=$out/user
rm -rf "$user"
@@ -112,6 +145,33 @@ if [ -n "${REGRESS_FIGHT_FRAME_CAP:-}" ]; then
rm -f "$cap_file"
export SC3_FRAME_CAP_FILE="$cap_file"
fi
if [ -z "${SC3_TEXTURE_PACK+x}" ] && [ -f "$root/build/sc3_textures.pack" ]; then
export SC3_TEXTURE_PACK="$root/build/sc3_textures.pack"
fi
if [ -z "${SC3_MESH_PACK+x}" ] && [ -f "$root/build/sc3_meshes.pack" ]; then
export SC3_MESH_PACK="$root/build/sc3_meshes.pack"
fi
if [ -z "${SC3_2D_PACK+x}" ] && [ -f "$root/build/sc3_2d.pack" ]; then
export SC3_2D_PACK="$root/build/sc3_2d.pack"
fi
native2d_switch=
if [ "${REGRESS_NATIVE_2D_AB:-0}" = 1 ]; then
native2d_switch=$out/native_2d.switch
echo 0 > "$native2d_switch"
export SC3_NATIVE_2D="@$native2d_switch"
fi
texpack_switch=
if [ -n "${REGRESS_TEXPACK_AB:-}" ] && [ "${REGRESS_TEXPACK_AB}" != 0 ]; then
texpack_switch=$out/texpack.switch
echo 0 > "$texpack_switch"
export SC3_TEXTURE_PACK_MODE="@$texpack_switch"
fi
hide_ee_file=
if [ -n "${REGRESS_PAUSE_HIDE_EE:-}" ]; then
hide_ee_file=$out/hide_ee.txt
: > "$hide_ee_file"
export SC3_HIDE_EE="@$hide_ee_file" SC3_HIDE_EE_ALL="$REGRESS_PAUSE_HIDE_EE"
fi
hide_file=
if [ -n "${REGRESS_PAUSE_HIDE:-}" ]; then
hide_file=$out/native_vu1.hide
@@ -182,13 +242,83 @@ await()
done
}
still_round()
{
echo 0 > "$native2d_switch"; await 1 || return 1; pause_still "$1_$2a_off.png"
await 1 || return 1; pause_still "$1_$2b_off.png"
echo 1 > "$native2d_switch"; await 1 || return 1; pause_still "$1_$2c_on.png"
await 1 || return 1; pause_still "$1_$2d_on.png"
}
menu_series()
{
local i
[ -n "$native2d_switch" ] && [ "${REGRESS_MENU_SERIES:-0}" -gt 0 ] || return 0
for i in $(seq "$REGRESS_MENU_SERIES"); do
still_round "menu_$1" "$i" || return 1
done
echo 0 > "$native2d_switch"
await 1
}
fight()
{
[ -z "$cap_file" ] || echo "$REGRESS_FIGHT_FRAME_CAP" > "$cap_file"
fight_mark=$(grep -a -c '^\[state\] gs frames=' "$log" || true)
fight_at_s=$(( $(date +%s) - start ))
local t=0 n=0
while [ "$t" -lt "$fight_secs" ]; do
press SQUARE; await 1 || return 1
press TRIANGLE; await 1 || return 1
if [ "$versus" = 1 ]; then press CROSS; else press RIGHT; fi
await 1 || return 1
t=$((t + 3))
if [ "$versus" = 1 ] && [ -n "$native2d_switch" ]; then
n=$((n + 1))
if [ "${REGRESS_VERSUS_PAUSE:-0}" = 1 ]; then
press START; await 2 || return 1
still_round versus_pause "$n" || return 1
press START; await 1 || return 1
t=$((t + 7))
else
still_round versus_fight "$n" || return 1
t=$((t + 4))
fi
fi
done
}
route()
{
local i
await 26 || return 1
for i in 1 2 3 4; do press START; await 3 || return 1; done
await 6 || return 1
menu_series main || return 1
if [ "$versus" = 1 ]; then
press CROSS; await 4 || return 1
press DOWN; await 1 || return 1
press DOWN; await 1 || return 1
press CROSS; await 4 || return 1
for i in $(seq 16); do press CROSS; await 3 || return 1; done
fight || return 1
echo 0 > "${native2d_switch:-/dev/null}"
route_reached=1
return 0
fi
press CROSS; await 4 || return 1
menu_series single || return 1
if [ -n "$native2d_switch" ]; then
await 2 || return 1
pause_still menu_2d_off.png
await 1 || return 1
pause_still menu_2d_off2.png
echo 1 > "$native2d_switch"
await 1 || return 1
pause_still menu_2d.png
echo 0 > "$native2d_switch"
await 1 || return 1
fi
for i in 1 2 3 4; do press DOWN; await 1 || return 1; done
await 1 || return 1
press CROSS; await 4 || return 1
@@ -199,16 +329,7 @@ route()
press RIGHT; await 2 || return 1
for i in 1 2 3 4 5; do press CROSS; await 4 || return 1; done
await 20 || return 1
[ -z "$cap_file" ] || echo "$REGRESS_FIGHT_FRAME_CAP" > "$cap_file"
fight_mark=$(grep -a -c '^\[state\] gs frames=' "$log" || true)
fight_at_s=$(( $(date +%s) - start ))
local t=0
while [ "$t" -lt "$fight_secs" ]; do
press SQUARE; await 1 || return 1
press TRIANGLE; await 1 || return 1
press RIGHT; await 1 || return 1
t=$((t + 3))
done
fight || return 1
press START; await "$pause_secs" || return 1
pause_still pause.png
if [ -n "$native_switch" ]; then
@@ -232,6 +353,29 @@ route()
await "$pause_secs" || return 1
pause_still pause_direct.png
fi
if [ -n "$texpack_switch" ]; then
await "$pause_secs" || return 1
pause_still pause_texpack_off.png
if [ "$REGRESS_TEXPACK_AB" = keep ]; then echo keep > "$texpack_switch"; else echo 1 > "$texpack_switch"; fi
await "$pause_secs" || return 1
pause_still pause_texpack.png
fi
if [ -n "$native2d_switch" ]; then
await "$pause_secs" || return 1
pause_still pause_2d_off.png
echo 1 > "$native2d_switch"
await "$pause_secs" || return 1
pause_still pause_2d.png
fi
if [ -n "$hide_ee_file" ]; then
local address
for address in $REGRESS_PAUSE_HIDE_EE; do
echo "$address" > "$hide_ee_file"
await "$pause_secs" || return 1
pause_still "pause_hide_ee_$address.png"
done
: > "$hide_ee_file"
fi
if [ -n "$hide_file" ]; then
local entry
for entry in $REGRESS_PAUSE_HIDE; do
@@ -314,6 +458,46 @@ pause_port_floor_psnr=$(pause_psnr pause_sandbox.png)
pause_port_psnr=$(pause_psnr pause_port.png)
pause_direct_floor_psnr=$(pause_psnr pause_packets.png)
pause_direct_psnr=$(pause_psnr pause_direct.png)
pause_texpack_floor_psnr=$(pause_psnr pause_texpack_off.png)
pause_texpack_psnr=$(pause_psnr pause_texpack.png)
pause_2d_floor_psnr=$(pause_psnr pause_2d_off.png)
pause_2d_psnr=$(pause_psnr pause_2d.png)
menu_psnr()
{
if [ -f "$out/menu_2d_off.png" ] && [ -f "$out/$1" ]; then
python3 -I "$root/scripts/imgdiff.py" "$out/menu_2d_off.png" "$out/$1" --diff "$out/${1%.png}_diff.png" \
| sed -n 's/^psnr=\([^ ]*\).*/\1/p'
else
echo NA
fi
}
menu_2d_floor_psnr=$(menu_psnr menu_2d_off2.png)
menu_2d_psnr=$(menu_psnr menu_2d.png)
series_psnr()
{
local prev= kind= still now p
for still in $(ls "$out" | grep -E "^$1_[0-9]+[a-d]_(off|on)\.png$" | sort -V); do
now=${still##*_}
if [ -n "$prev" ]; then
p=$(python3 -I "$root/scripts/imgdiff.py" "$out/$prev" "$out/$still" | sed -n 's/^psnr=\([^ ]*\).*/\1/p')
[ -z "$p" ] || echo "$([ "$now" = "$kind" ] && echo same || echo mixed) $p"
fi
prev=$still; kind=$now
done | awk '$2 ~ /^[0-9.]+$/ { s[$1] += $2; n[$1]++ }
END { if (n["same"] && n["mixed"]) printf "%.2f %.2f %d %d\n", s["same"] / n["same"], s["mixed"] / n["mixed"], n["same"], n["mixed"];
else print "NA NA 0 0" }'
}
read -r menu_main_floor_psnr menu_main_psnr menu_main_same_pairs menu_main_mixed_pairs < <(series_psnr menu_main)
read -r menu_single_floor_psnr menu_single_psnr menu_single_same_pairs menu_single_mixed_pairs < <(series_psnr menu_single)
read -r versus_fight_floor_psnr versus_fight_psnr versus_fight_same_pairs versus_fight_mixed_pairs < <(series_psnr versus_fight)
read -r versus_pause_floor_psnr versus_pause_psnr versus_pause_same_pairs versus_pause_mixed_pairs < <(series_psnr versus_pause)
if [ -n "$hide_ee_file" ]; then
for address in $REGRESS_PAUSE_HIDE_EE; do
still=pause_hide_ee_$address.png
[ -f "$out/$still" ] || continue
echo "$address $(python3 -I "$root/scripts/imgdiff.py" "$out/pause.png" "$out/$still" --diff "$out/${still%.png}_diff.png")"
done > "$out/pause_hide_ee.txt"
fi
if [ -n "$hide_file" ]; then
for entry in $REGRESS_PAUSE_HIDE; do
still=pause_hide_$(echo "$entry" | tr ':*' '__').png
@@ -346,6 +530,24 @@ pause_port_floor_psnr=$pause_port_floor_psnr
pause_port_psnr=$pause_port_psnr
pause_direct_floor_psnr=$pause_direct_floor_psnr
pause_direct_psnr=$pause_direct_psnr
pause_texpack_floor_psnr=$pause_texpack_floor_psnr
pause_texpack_psnr=$pause_texpack_psnr
pause_2d_floor_psnr=$pause_2d_floor_psnr
pause_2d_psnr=$pause_2d_psnr
menu_2d_floor_psnr=$menu_2d_floor_psnr
menu_2d_psnr=$menu_2d_psnr
menu_main_floor_psnr=$menu_main_floor_psnr
menu_main_psnr=$menu_main_psnr
menu_main_pairs=$menu_main_same_pairs/$menu_main_mixed_pairs
menu_single_floor_psnr=$menu_single_floor_psnr
menu_single_psnr=$menu_single_psnr
menu_single_pairs=$menu_single_same_pairs/$menu_single_mixed_pairs
versus_fight_floor_psnr=$versus_fight_floor_psnr
versus_fight_psnr=$versus_fight_psnr
versus_fight_pairs=$versus_fight_same_pairs/$versus_fight_mixed_pairs
versus_pause_floor_psnr=$versus_pause_floor_psnr
versus_pause_psnr=$versus_pause_psnr
versus_pause_pairs=$versus_pause_same_pairs/$versus_pause_mixed_pairs
EOF
cat > "$out/details.txt" <<EOF
fight_at_s=$fight_at_s
+5 -1
View File
@@ -1,9 +1,13 @@
#!/usr/bin/env bash
# Launches the recompiled game with game/ as cdrom0:. Extra args are passed to ps2EntryRunner.
# The SPU2 follows the host's clock unless PS2X_SPU2_WALLCLOCK=0.
# The SPU2 follows the host's clock unless PS2X_SPU2_WALLCLOCK=0. SC3_TEXTURE_PACK_MODE=1 draws the direct draws'
# textures from build/sc3_textures.pack (SC3_TEXTURE_PACK names another; off by default, a diagnostic for now).
source "$(dirname "$0")/common.sh"
export PS2X_SPU2_WALLCLOCK="${PS2X_SPU2_WALLCLOCK:-1}"
BIN="$GAME_BUILD/PS2Recomp/ps2xRuntime/ps2EntryRunner"
[ -n "${SC3_TEXTURE_PACK+x}" ] || [ ! -f "$TEXTURE_PACK" ] || export SC3_TEXTURE_PACK="$TEXTURE_PACK"
[ -n "${SC3_MESH_PACK+x}" ] || [ ! -f "$MESH_PACK" ] || export SC3_MESH_PACK="$MESH_PACK"
[ -n "${SC3_2D_PACK+x}" ] || [ ! -f "$TWO_D_PACK" ] || export SC3_2D_PACK="$TWO_D_PACK"
[ -x "$BIN" ] || { echo "missing $BIN, run scripts/build_runtime.sh first"; exit 1; }
[ -f "$ELF" ] || { echo "missing $ELF, run scripts/extract_iso.sh first"; exit 1; }
exec "$BIN" "$ELF" "$@"
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Soulcalibur III 2D material pack from the user's own disc, with the standard library only (python3 -I).
usage: scripts/sc3_2d_pack.py <disc dir> <out.pack> [--only /2/17,...] [--jobs N]
The 2D builders (runtime/sc3_2d.cpp) draw sprites whose texture registers the game REFs from a block inside a loaded
ROOT.OLK leaf (a texture file: a GIF A+D block with TEX1, TEX0 and CLAMP per texture page). Those blocks are converted
here into PS2Recomp's generic mesh pack (PS2XMSH1), one file per leaf with register blocks only, each at its offset in
the leaf with its writes and, as register 0x100, the tag's REGS word (the game keeps the texture's used size there: bits
32-47 width, 48-63 height), as scripts/sc3_mesh_pack.py records them for the 3D. Leaves without such blocks are left out.
A page's texture is uploaded by the file's own CALL lists, its texels by one list and its CLUT by another (the 3D's
texture pack keys a texture by one list and so has none of these): every upload list of the file (each model of the
leaf: a 03 04 04 00 header) is played into one offline GS memory model (scripts/sc3_texture_pack.py's), and each page's
texture is decoded from it at its used size into <out without extension>_textures.pack (PS2XTEX1, one file per leaf
named as the leaf, a texel record and for an indexed texture a CT32 palette record, alpha 0x80 = 1.0). The page's block
then carries the records' numbers as registers 0x101 (texels) and 0x102 (palette, 0xFFFFFFFF none); a page whose
texels or CLUT the file does not upload itself has neither.
An indexed page's other colours: the game may draw it with another CLUT the file uploads (a TEX2 write changing CBP: the
text renderer's colours are the font's 16 CLUTs); each CLUT block the file's lists write besides the page's own gets
a CT32 palette record of the page's size, named in the block as register 0x103 = CBP << 32 | record.
Texture files inside the game's ELF (SLUS_212.16 in the disc dir: the font at 0x4763B0, the menu icons at 0x4AF170 and
nine more) are converted as well, named elf/<address>, as the game has them before 0x118E18 relocates their pointers,
each up to the end of its tables and of the data its upload lists reach (at most the next one's start).
Beside it, <out>.leaves: one line per pack file, its name, the leaf's byte offset in ROOT.OLK and its size (hex).
The output lives in the build tree and is never committed: it is the user's game data.
"""
import argparse
import multiprocessing
import os
import struct
import sys
sys.dont_write_bytecode = True
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, '..', 'PS2Recomp', 'tools'))
sys.path.insert(0, HERE)
from native_pack import mesh, texture # noqa: E402
from sc3_mesh_pack import register_blocks # noqa: E402
from sc3_texture_pack import (MODEL_MAGIC, PSM_CT32, GsMemory, Unsupported, call_lists, clut_ct32, decode, # noqa: E402
dma_tag, olk_leaves, play_gif, texture_units, walk_chain)
TEXELS_REG = 0x101
PALETTE_REG = 0x102
CLUT_REG = 0x103
NO_RECORD = 0xFFFFFFFF
ELF_NAME = 'SLUS_212.16'
ELF_FILES = [0x473E60, 0x4742D0, 0x474630, 0x4749E0, 0x474DF0, 0x475200, 0x475610, 0x475970, 0x475DE0, 0x4763B0, 0x4AF170]
def clut_uploads(data):
"""The DBPs of the stream's small CT32 image transfers (256 texels or fewer: CLUTs)."""
regs, out, q = {}, set(), 0
while q + 16 <= len(data):
lo, hi = struct.unpack_from('<QQ', data, q)
nloop, flg = lo & 0x7FFF, (lo >> 58) & 3
q += 16
if flg == 0 and (hi & 0xF) == 0xE:
for _ in range(nloop):
value, reg = struct.unpack_from('<QQ', data, q)
regs[reg & 0xFF] = value
q += 16
elif flg == 2:
q += nloop * 16
bitbltbuf, trxreg = regs.get(0x50, 0), regs.get(0x52, 0)
if (bitbltbuf >> 56) & 0x3F == PSM_CT32 and (trxreg & 0xFFF) * ((trxreg >> 32) & 0xFFF) <= 256:
out.add((bitbltbuf >> 32) & 0x3FFF)
else:
break
return out
def page_textures(d, blocks):
"""{block offset: (psm, w, h, texels, palette)} for the blocks whose texture the leaf's own upload lists write."""
starts = sorted({0} | {q for q in range(0, len(d) - 4, 16) if struct.unpack_from('<I', d, q)[0] == MODEL_MAGIC})
out = {}
for i, start in enumerate(starts):
end = starts[i + 1] if i + 1 < len(starts) else len(d)
m = d[start:end]
units = texture_units(m)
if not units:
continue
gs = GsMemory()
cluts = set()
try:
for k, entries in enumerate(call_lists(m, units)):
for _, target in entries:
if target is None:
continue
gs.entry = k + 1
data = walk_chain(m, target)
if data is not None:
play_gif(gs, data)
cluts |= clut_uploads(data)
except Unsupported:
continue
for q, writes in blocks:
if not start <= q < end:
continue
regs = dict(writes)
tex0 = regs.get(0x07, regs.get(0x06))
tag = regs.get(0x100, 0)
if tex0 is None:
continue
tw, th = (tex0 >> 26) & 0xF, (tex0 >> 30) & 0xF
w, h = (tag >> 32) & 0xFFFF, (tag >> 48) & 0xFFFF
if tw > 10 or th > 10:
continue
if not w or w > (1 << tw):
w = 1 << tw
if not h or h > (1 << th):
h = 1 << th
try:
psm, texels, palette, touched = decode(gs, tex0, w, h)
except Unsupported:
continue
if not touched or 0 in touched:
continue
others = []
if palette is not None:
for cbp in sorted(cluts - {(tex0 >> 37) & 0x3FFF}):
seen = set()
other = clut_ct32(gs, (tex0 & ~(0x3FFF << 37)) | (cbp << 37), len(palette), seen)
if seen and 0 not in seen:
others.append((cbp, other))
out[q] = (psm, w, h, texels, palette, others)
return out
def elf_image(path, address, size, partial=False):
"""size bytes of the ELF's loaded image at address (its PT_LOAD segments; partial: up to the segment's end)."""
with open(path, 'rb') as f:
elf = f.read()
phoff, = struct.unpack_from('<I', elf, 0x1C)
phentsize, phnum = struct.unpack_from('<HH', elf, 0x2A)
for i in range(phnum):
kind, off, vaddr, _, filesz = struct.unpack_from('<5I', elf, phoff + phentsize * i)
if kind == 1 and vaddr <= address and (address + size <= vaddr + filesz or partial and address < vaddr + filesz):
return elf[off + address - vaddr:off + min(address + size, vaddr + filesz) - vaddr]
raise ValueError('%s: %#x + %#x not in a loaded segment' % (path, address, size))
def elf_file_size(path, address):
"""How far the texture file at address reaches: its CALL and page tables, its upload units and their data."""
d = elf_image(path, address, 0x40000, partial=True)
calls, pages = d[4], d[5] + d[7] * 256
call_table, page_table = struct.unpack_from('<II', d, 8)
end = max(0x20, call_table + 20 * calls, page_table + 4 * pages)
for p in range(pages):
block = struct.unpack_from('<I', d, page_table + 4 * p)[0]
end = max(end, (block & ~0xF) + 16 * ((block & 0xF) + 2))
for unit in texture_units(d[:end + 0x40000]):
q = unit
while q + 16 <= len(d):
qwc, tid, addr = dma_tag(d, q)
if tid == 1:
q += 16 * (qwc + 1)
elif tid == 3:
end = max(end, addr + 16 * qwc)
q += 16
else:
break
end = max(end, q + 16)
following = [a - address for a in ELF_FILES if a > address]
return min([(end + 15) & ~15] + following)
def convert_leaf(job):
olk, path, offset, size = job
if path.startswith('elf/'):
d = elf_image(olk, offset, size)
else:
with open(olk, 'rb') as f:
f.seek(offset)
d = f.read(size)
blocks = register_blocks(d)
if not blocks:
return path, offset, size, None, []
pages = page_textures(d, blocks)
records = []
f = mesh.MeshFile(path, d)
for q, writes in blocks:
if q in pages:
psm, w, h, texels, palette, others = pages[q]
records.append((psm, w, h, texels))
writes = writes + [(TEXELS_REG, len(records) - 1)]
if palette is not None:
records.append((texture.PSMCT32, len(palette), 1, struct.pack('<%dI' % len(palette), *palette)))
writes.append((PALETTE_REG, len(records) - 1))
else:
writes.append((PALETTE_REG, NO_RECORD))
for cbp, other in others:
records.append((texture.PSMCT32, len(other), 1, struct.pack('<%dI' % len(other), *other)))
writes.append((CLUT_REG, (cbp << 32) | (len(records) - 1)))
f.add_register_block(q, writes)
return path, offset, size, f.encode(), records
def main():
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
parser.add_argument('disc')
parser.add_argument('out')
parser.add_argument('--only', default='', help='comma-separated leaf paths (/2/17,...)')
parser.add_argument('--jobs', type=int, default=os.cpu_count() or 1, help='leaves converted at once (default: all cores)')
args = parser.parse_args()
olk = os.path.join(args.disc, 'ROOT.OLK')
only = set(p for p in args.only.split(',') if p)
with open(olk, 'rb') as f:
listed = olk_leaves(f)
jobs = [(olk, path, offset, size) for path, offset, size in listed if size and (not only or path in only)]
elf = os.path.join(args.disc, ELF_NAME)
if os.path.exists(elf):
jobs += [(elf, 'elf/%x' % address, address, elf_file_size(elf, address)) for address in ELF_FILES
if not only or 'elf/%x' % address in only]
files, leaves = [], []
pack = texture.TexturePackWriter()
textured = 0
with multiprocessing.Pool(max(1, args.jobs)) as pool:
for n, (path, offset, size, encoded, records) in enumerate(pool.imap(convert_leaf, jobs, chunksize=4)):
if encoded is not None:
files.append(encoded)
leaves.append('%s %x %x' % (path, offset, size))
if records:
pack.add_file(path).extend(records)
textured += 1
if n % 500 == 0:
print('%d/%d leaves, %d with register blocks' % (n, len(jobs), len(files)), file=sys.stderr)
with open(args.out + '.tmp', 'wb') as out:
out.write(mesh.MAGIC + struct.pack('<I', len(files)))
for encoded in files:
out.write(encoded)
os.replace(args.out + '.tmp', args.out)
index = os.path.splitext(args.out)[0] + '.leaves'
with open(index + '.tmp', 'w') as out:
out.write('\n'.join(leaves) + '\n')
os.replace(index + '.tmp', index)
textures = os.path.splitext(args.out)[0] + '_textures.pack'
pack.write(textures + '.tmp')
os.replace(textures + '.tmp', textures)
print('%s: %d leaves with register blocks, %d with page textures in %s' % (args.out, len(files), textured, textures))
if __name__ == '__main__':
main()
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""Soulcalibur III mesh pack from the user's own disc, with the standard library only (python3 -I).
usage: scripts/sc3_mesh_pack.py <disc dir> <out.pack> [--only /4/204,...] [--jobs N]
Walks ROOT.OLK to its leaf files (scripts/sc3_texture_pack.py's walk). A leaf is loaded whole into EE memory by the game
and relocated in place, so the pack's image of a leaf is its bytes on the disc, and every object is keyed by its offset
in the leaf.
Objects (PS2Recomp's generic mesh pack, PS2XMSH1, tools/native_pack/mesh.py), one per model part the game hands its
part builder 0x10A178 (a REF to raw VIF data): STCYCL 1,1 and an UNPACK of its GIF tag to VU TOP + 0, then STCYCL 4,1 and
one UNPACK a vertex field (V2-32 ST at TOP + 1, V4-32 or S-32 colour at + 2, V4-32 position at + 3, V3-32 normal at + 4,
four quadwords a vertex). kind 1; positions x, y, z and the vertex flags (the position's w word: bit 15 ADC, bits 4-11
the GS F) as a float; one strip (the tag's PRIM, its word 3 as the material word); and section 'SC3V' with the exact
words the UNPACKs leave in VU memory: u32 vertex count, u32 fields (bit 0 normals, bit 1 one colour for all, an S-32
UNPACK), the 16-byte GIF tag, then per vertex 16 u32: ST, colour, position, normal (normal zero without them).
Register blocks: every GS A+D block of a leaf (a PACKED GIF tag of 1-8 A+D writes, the model's materials, the block the
game REFs to VU TOP + 0x19F), at the tag's offset, with its writes (the register in the address's low byte: the game
keeps other bits above it) and, as register 0x100 (no GS register), the tag's
REGS word: the game keeps a texture's used size there (bits 32-47 width, 48-63 height).
Beside it, <out>.leaves: one line per pack file, its name, the leaf's byte offset in ROOT.OLK and its size (hex).
The output lives in the build tree and is never committed: it is the user's game data.
"""
import argparse
import multiprocessing
import os
import struct
import sys
sys.dont_write_bytecode = True
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, '..', 'PS2Recomp', 'tools'))
sys.path.insert(0, HERE)
from native_pack import mesh # noqa: E402
from sc3_texture_pack import olk_leaves # noqa: E402
STCYCL_11 = 0x01000101
TAG_UNPACK = 0x6C018000
KIND_RAW_PART = 1
GS_REGISTER_LIMIT = 0x63
TAG_REGS = 0x100
def raw_part_size(d, q):
"""Bytes of the raw VIF part at q (its tag UNPACK, then the vertex field UNPACKs), or None."""
if q + 32 > len(d) or struct.unpack_from('<II', d, q) != (STCYCL_11, TAG_UNPACK):
return None
pos, last, fields = q + 24, q + 24, 0
while pos + 4 <= len(d):
code = struct.unpack_from('<I', d, pos)[0]
cmd, num, imm = (code >> 24) & 0x7F, (code >> 16) & 0xFF, code & 0xFFFF
if code == 0:
pos += 4
continue
if cmd == 1:
if code == STCYCL_11 and pos + 8 <= len(d) and struct.unpack_from('<I', d, pos + 4)[0] == TAG_UNPACK:
break
pos += 4
continue
if cmd >= 0x60 and (cmd & 3) == 0 and (imm & 0x8000) and (imm & 0x3FF) in (1, 2, 3, 4):
pos += 4 + (((cmd >> 2) & 3) + 1) * 4 * (num or 256)
last = pos
fields += 1
continue
break
if fields < 2 or last > len(d):
return None
return ((last + 15) & ~15) - q
def decode_raw_part(d, q, size):
"""(tag, vertices, fields): the GIF tag words and per vertex the 16 words VU memory holds after the part's UNPACKs."""
tag = list(struct.unpack_from('<4I', d, q + 8))
count = tag[0] & 0x7FFF
vertices = [[0] * 16 for _ in range(count)]
fields = 0
pos, end = q + 24, q + size
while pos + 4 <= end:
code = struct.unpack_from('<I', d, pos)[0]
pos += 4
cmd, num, imm = (code >> 24) & 0x7F, (code >> 16) & 0xFF, code & 0xFFFF
if cmd < 0x60:
continue
comps = ((cmd >> 2) & 3) + 1
n = num or 256
field = (imm & 0x3FF) - 1
for i in range(min(n, count)):
words = list(struct.unpack_from('<%dI' % comps, d, pos + i * comps * 4))
if comps == 1:
words = words * 4
fields |= 2
row = vertices[i]
for c in range(min(comps, 4)):
row[field * 4 + c] = words[c]
if field == 3:
fields |= 1
pos += comps * 4 * n
return tag, vertices, fields
def as_float(word):
return struct.unpack('<f', struct.pack('<I', word))[0]
def add_raw_part(f, d, q, size):
tag, vertices, fields = decode_raw_part(d, q, size)
o = f.add_object(q, kind=KIND_RAW_PART, attributes=struct.pack('<I', size))
o.positions = [(as_float(v[8]), as_float(v[9]), as_float(v[10]), float(v[11] & 0xFFFF)) for v in vertices]
prim = (tag[1] >> 15) & 0x7FF
strip = []
for k, v in enumerate(vertices):
rgba = tuple(max(0, min(255, int(as_float(w)))) for w in v[4:8])
s, t = (max(-32768, min(32767, int(as_float(w) * 4096.0))) for w in v[0:2])
strip.append((k, 0, 0, 0, mesh.VERTEX_ADC if v[11] & 0x8000 else 0, rgba, s, t))
o.add_strip(prim, ((tag[1] >> 14) & 1) | (((tag[0] >> 15) & 1) << 1), tag[3], -1, strip)
blob = [struct.pack('<II4I', len(vertices), fields, *tag)]
blob.extend(struct.pack('<16I', *v) for v in vertices)
o.add_section('SC3V', b''.join(blob))
def register_blocks(d):
"""(offset, writes) of the leaf's A+D blocks: a PACKED tag of 1-8 A+D writes to GS registers."""
out = []
for q in range(0, len(d) - 32, 16):
lo, hi = struct.unpack_from('<QQ', d, q)
nloop = lo & 0x7FFF
if (lo >> 58) & 3 or ((lo >> 60) & 0xF) != 1 or (hi & 0xF) != 0xE or not 1 <= nloop <= 8:
continue
if q + 16 * (nloop + 1) > len(d):
continue
writes = []
for i in range(nloop):
value, reg = struct.unpack_from('<QQ', d, q + 16 * (i + 1))
reg &= 0xFF
if reg > GS_REGISTER_LIMIT:
writes = None
break
writes.append((reg, value))
if writes and any(r in (0x06, 0x07, 0x42, 0x43, 0x47, 0x48) for r, _ in writes):
out.append((q, writes + [(TAG_REGS, hi)]))
return out
def convert_leaf(job):
olk, path, offset, size = job
with open(olk, 'rb') as f:
f.seek(offset)
d = f.read(size)
parts = []
q = 0
while q < len(d) - 32:
n = raw_part_size(d, q)
if n:
parts.append((q, n))
q += n
else:
q += 16
if not parts:
return path, offset, size, None
f = mesh.MeshFile(path, d)
for q, n in parts:
add_raw_part(f, d, q, n)
for q, writes in register_blocks(d):
f.add_register_block(q, writes)
return path, offset, size, f.encode()
def main():
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
parser.add_argument('disc')
parser.add_argument('out')
parser.add_argument('--only', default='', help='comma-separated leaf paths (/4/204,...)')
parser.add_argument('--jobs', type=int, default=os.cpu_count() or 1, help='leaves converted at once (default: all cores)')
args = parser.parse_args()
olk = os.path.join(args.disc, 'ROOT.OLK')
only = set(p for p in args.only.split(',') if p)
with open(olk, 'rb') as f:
listed = olk_leaves(f)
jobs = [(olk, path, offset, size) for path, offset, size in listed if size and (not only or path in only)]
files, leaves = [], []
with multiprocessing.Pool(max(1, args.jobs)) as pool:
for n, (path, offset, size, encoded) in enumerate(pool.imap(convert_leaf, jobs, chunksize=4)):
if encoded is not None:
files.append(encoded)
leaves.append('%s %x %x' % (path, offset, size))
if n % 500 == 0:
print('%d/%d leaves, %d with parts' % (n, len(jobs), len(files)), file=sys.stderr)
with open(args.out + '.tmp', 'wb') as out:
out.write(mesh.MAGIC + struct.pack('<I', len(files)))
for encoded in files:
out.write(encoded)
os.replace(args.out + '.tmp', args.out)
index = os.path.splitext(args.out)[0] + '.leaves'
with open(index + '.tmp', 'w') as out:
out.write('\n'.join(leaves) + '\n')
os.replace(index + '.tmp', index)
print('%s: %d leaves with parts' % (args.out, len(files)))
if __name__ == '__main__':
main()
+547
View File
@@ -0,0 +1,547 @@
#!/usr/bin/env python3
"""Soulcalibur III texture pack from the user's own disc, with the standard library only (python3 -I).
usage: scripts/sc3_texture_pack.py <disc dir> <out.pack> [--only /2/0,/4/12] [--report FILE] [--jobs N]
Walks ROOT.OLK (an "olnk" archive of archives) to its leaf files and each leaf to its models (a 03 04 04 00 header;
a model's DMA addresses are relative to it). A model's texture uploads are CALL lists the game CALLs at run time
(runs of DMA CALL tags into upload units, ended by RET; a unit is a CNT with GIF A+D BITBLTBUF / TRXPOS / TRXREG /
TRXDIR and an IMAGE tag, then a REF to the texels) and upload chains it CALLs itself (animated textures). Each list
is played into a model of GS memory (offline only), and every texture a material of the model selects (its TEX0, at
the used size the material's GIF tag keeps) whose texels and CLUT the list wrote becomes a record.
Writes <out.pack>, PS2Recomp's generic texture pack (PS2XTEX1, tools/native_pack/texture.py): one file per CALL list,
named '<leaf>@<list offset in the leaf>', its records the textures (indexed: an index a byte; CT32) each followed by
its palette for an indexed one (CT32, index order, alpha 0x80 = 1.0). Beside it, <out>.keys, SC3's key scheme
(write_keys): where each list sits in ROOT.OLK, its entries, and which records a TEX0 and used size select.
The output lives in the build tree and is never committed: it is the user's game data.
"""
import argparse
import multiprocessing
import os
import struct
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'PS2Recomp', 'tools'))
from native_pack import texture # noqa: E402
TEX0_KEY_MASK = (0x3FFF | (0x3F << 14) | (0x3F << 20) | (0xF << 26) | (0xF << 30) | (0x3FFF << 37) | (0xF << 51) |
(1 << 55) | (0x1F << 56))
BLOCK32 = [[0, 1, 4, 5, 16, 17, 20, 21], [2, 3, 6, 7, 18, 19, 22, 23], [8, 9, 12, 13, 24, 25, 28, 29],
[10, 11, 14, 15, 26, 27, 30, 31]]
COLUMN32 = [[0, 1, 4, 5, 8, 9, 12, 13], [2, 3, 6, 7, 10, 11, 14, 15], [16, 17, 20, 21, 24, 25, 28, 29],
[18, 19, 22, 23, 26, 27, 30, 31], [32, 33, 36, 37, 40, 41, 44, 45], [34, 35, 38, 39, 42, 43, 46, 47],
[48, 49, 52, 53, 56, 57, 60, 61], [50, 51, 54, 55, 58, 59, 62, 63]]
BLOCK8 = BLOCK32
COLUMN8 = [
[0, 4, 16, 20, 32, 36, 48, 52, 2, 6, 18, 22, 34, 38, 50, 54],
[8, 12, 24, 28, 40, 44, 56, 60, 10, 14, 26, 30, 42, 46, 58, 62],
[33, 37, 49, 53, 1, 5, 17, 21, 35, 39, 51, 55, 3, 7, 19, 23],
[41, 45, 57, 61, 9, 13, 25, 29, 43, 47, 59, 63, 11, 15, 27, 31],
[96, 100, 112, 116, 64, 68, 80, 84, 98, 102, 114, 118, 66, 70, 82, 86],
[104, 108, 120, 124, 72, 76, 88, 92, 106, 110, 122, 126, 74, 78, 90, 94],
[65, 69, 81, 85, 97, 101, 113, 117, 67, 71, 83, 87, 99, 103, 115, 119],
[73, 77, 89, 93, 105, 109, 121, 125, 75, 79, 91, 95, 107, 111, 123, 127],
[128, 132, 144, 148, 160, 164, 176, 180, 130, 134, 146, 150, 162, 166, 178, 182],
[136, 140, 152, 156, 168, 172, 184, 188, 138, 142, 154, 158, 170, 174, 186, 190],
[161, 165, 177, 181, 129, 133, 145, 149, 163, 167, 179, 183, 131, 135, 147, 151],
[169, 173, 185, 189, 137, 141, 153, 157, 171, 175, 187, 191, 139, 143, 155, 159],
[224, 228, 240, 244, 192, 196, 208, 212, 226, 230, 242, 246, 194, 198, 210, 214],
[232, 236, 248, 252, 200, 204, 216, 220, 234, 238, 250, 254, 202, 206, 218, 222],
[193, 197, 209, 213, 225, 229, 241, 245, 195, 199, 211, 215, 227, 231, 243, 247],
[201, 205, 217, 221, 233, 237, 249, 253, 203, 207, 219, 223, 235, 239, 251, 255],
]
BLOCK4 = [[0, 2, 8, 10], [1, 3, 9, 11], [4, 6, 12, 14], [5, 7, 13, 15], [16, 18, 24, 26], [17, 19, 25, 27],
[20, 22, 28, 30], [21, 23, 29, 31]]
COLUMN4 = [
[0, 8, 32, 40, 64, 72, 96, 104, 2, 10, 34, 42, 66, 74, 98, 106, 4, 12, 36, 44, 68, 76, 100, 108, 6, 14, 38, 46, 70, 78, 102, 110],
[16, 24, 48, 56, 80, 88, 112, 120, 18, 26, 50, 58, 82, 90, 114, 122, 20, 28, 52, 60, 84, 92, 116, 124, 22, 30, 54, 62, 86, 94, 118, 126],
[65, 73, 97, 105, 1, 9, 33, 41, 67, 75, 99, 107, 3, 11, 35, 43, 69, 77, 101, 109, 5, 13, 37, 45, 71, 79, 103, 111, 7, 15, 39, 47],
[81, 89, 113, 121, 17, 25, 49, 57, 83, 91, 115, 123, 19, 27, 51, 59, 85, 93, 117, 125, 21, 29, 53, 61, 87, 95, 119, 127, 23, 31, 55, 63],
[192, 200, 224, 232, 128, 136, 160, 168, 194, 202, 226, 234, 130, 138, 162, 170, 196, 204, 228, 236, 132, 140, 164, 172, 198, 206, 230, 238, 134, 142, 166, 174],
[208, 216, 240, 248, 144, 152, 176, 184, 210, 218, 242, 250, 146, 154, 178, 186, 212, 220, 244, 252, 148, 156, 180, 188, 214, 222, 246, 254, 150, 158, 182, 190],
[129, 137, 161, 169, 193, 201, 225, 233, 131, 139, 163, 171, 195, 203, 227, 235, 133, 141, 165, 173, 197, 205, 229, 237, 135, 143, 167, 175, 199, 207, 231, 239],
[145, 153, 177, 185, 209, 217, 241, 249, 147, 155, 179, 187, 211, 219, 243, 251, 149, 157, 181, 189, 213, 221, 245, 253, 151, 159, 183, 191, 215, 223, 247, 255],
[256, 264, 288, 296, 320, 328, 352, 360, 258, 266, 290, 298, 322, 330, 354, 362, 260, 268, 292, 300, 324, 332, 356, 364, 262, 270, 294, 302, 326, 334, 358, 366],
[272, 280, 304, 312, 336, 344, 368, 376, 274, 282, 306, 314, 338, 346, 370, 378, 276, 284, 308, 316, 340, 348, 372, 380, 278, 286, 310, 318, 342, 350, 374, 382],
[321, 329, 353, 361, 257, 265, 289, 297, 323, 331, 355, 363, 259, 267, 291, 299, 325, 333, 357, 365, 261, 269, 293, 301, 327, 335, 359, 367, 263, 271, 295, 303],
[337, 345, 369, 377, 273, 281, 305, 313, 339, 347, 371, 379, 275, 283, 307, 315, 341, 349, 373, 381, 277, 285, 309, 317, 343, 351, 375, 383, 279, 287, 311, 319],
[448, 456, 480, 488, 384, 392, 416, 424, 450, 458, 482, 490, 386, 394, 418, 426, 452, 460, 484, 492, 388, 396, 420, 428, 454, 462, 486, 494, 390, 398, 422, 430],
[464, 472, 496, 504, 400, 408, 432, 440, 466, 474, 498, 506, 402, 410, 434, 442, 468, 476, 500, 508, 404, 412, 436, 444, 470, 478, 502, 510, 406, 414, 438, 446],
[385, 393, 417, 425, 449, 457, 481, 489, 387, 395, 419, 427, 451, 459, 483, 491, 389, 397, 421, 429, 453, 461, 485, 493, 391, 399, 423, 431, 455, 463, 487, 495],
[401, 409, 433, 441, 465, 473, 497, 505, 403, 411, 435, 443, 467, 475, 499, 507, 405, 413, 437, 445, 469, 477, 501, 509, 407, 415, 439, 447, 471, 479, 503, 511],
]
GS_BYTES = 4 * 1024 * 1024
PSM_CT32, PSM_CT24, PSM_T8, PSM_T4, PSM_T8H, PSM_T4HL, PSM_T4HH = 0x00, 0x01, 0x13, 0x14, 0x1B, 0x24, 0x2C
def addr32(bp, bw, x, y):
page = (bp >> 5) + (y >> 5) * max(bw, 1) + (x >> 6)
block = (bp & 0x1F) + BLOCK32[(y >> 3) & 3][(x >> 3) & 7]
return ((page << 13) + ((block >> 5) << 13) + (block & 0x1F) * 256 + COLUMN32[y & 7][x & 7] * 4) % GS_BYTES
def addr8(bp, bw, x, y):
page = (bp >> 5) + (y >> 6) * max(bw >> 1, 1) + (x >> 7)
block = (bp & 0x1F) + BLOCK8[(y >> 4) & 3][(x >> 4) & 7]
return ((page << 13) + ((block >> 5) << 13) + (block & 0x1F) * 256 + COLUMN8[y & 15][x & 15]) % GS_BYTES
def addr4(bp, bw, x, y):
page = (bp >> 5) + (y >> 7) * max(bw >> 1, 1) + (x >> 7)
block = (bp & 0x1F) + BLOCK4[(y >> 4) & 7][(x >> 5) & 3]
return ((page << 14) + ((block >> 5) << 14) + (block & 0x1F) * 512 + COLUMN4[y & 15][x & 31]) % (GS_BYTES * 2)
class GsMemory:
"""GS local memory as a CALL list's uploads leave it, with the list entry (1-based) that last wrote each byte
(offline model only)."""
def __init__(self):
self.mem = bytearray(GS_BYTES)
self.written = bytearray(GS_BYTES)
self.entry = 1
def write_ct32(self, bp, bw, sx, sy, w, h, data):
mem, written = self.mem, self.written
mark = bytes([self.entry]) * 4
i = 0
for y in range(sy, sy + h):
for x in range(sx, sx + w):
a = addr32(bp, bw, x, y)
mem[a:a + 4] = data[i:i + 4]
written[a:a + 4] = mark
i += 4
def write_high(self, psm, bp, bw, sx, sy, w, h, data):
mem, written = self.mem, self.written
i = 0
for y in range(sy, sy + h):
for x in range(sx, sx + w):
a = addr32(bp, bw, x, y) + 3
if psm == PSM_T8H:
mem[a] = data[i]
else:
v = (data[i >> 1] >> ((i & 1) * 4)) & 0xF
mem[a] = (mem[a] & 0xF0) | v if psm == PSM_T4HL else (mem[a] & 0x0F) | (v << 4)
written[a] = self.entry
i += 1
def write_indexed(self, psm, bp, bw, sx, sy, w, h, data):
mem, written = self.mem, self.written
i = 0
for y in range(sy, sy + h):
for x in range(sx, sx + w):
if psm == PSM_T8:
a = addr8(bp, bw, x, y)
mem[a] = data[i]
else:
n = addr4(bp, bw, x, y)
a = n >> 1
v = (data[i >> 1] >> ((i & 1) * 4)) & 0xF
mem[a] = (mem[a] & 0x0F) | (v << 4) if n & 1 else (mem[a] & 0xF0) | v
written[a] = self.entry
i += 1
def ct32(self, bp, bw, x, y, touched):
a = addr32(bp, bw, x, y)
e = self.written[a]
touched.add(e)
return struct.unpack_from('<I', self.mem, a)[0]
class Unsupported(Exception):
pass
def clut_ct32(gs, tex0, entries, touched):
cbp = (tex0 >> 37) & 0x3FFF
csm = (tex0 >> 55) & 1
if csm:
raise Unsupported('CSM2 CLUT')
out = []
for e in range(entries):
s = (e & ~0x18) | ((e & 0x08) << 1) | ((e & 0x10) >> 1)
out.append(gs.ct32(cbp, 1, s & 15, s >> 4, touched))
return out
def decode(gs, tex0, w, h):
"""The w x h top-left part of the texture TEX0 selects, as a pack record (PSM, texels: an index a byte for the
indexed formats, CT32 four bytes) with its palette for an indexed one (its CT32 colours in index order, as the GS
looks them up: CSM1 order, 16 entries from CBP for T4 whatever CSA, alpha 0x80 = 1.0), and the list entries
(1-based, 0 for bytes no entry wrote) its texels and CLUT were read from."""
tbp = tex0 & 0x3FFF
tbw = (tex0 >> 14) & 0x3F
psm = (tex0 >> 20) & 0x3F
tw = (tex0 >> 26) & 0xF
th = (tex0 >> 30) & 0xF
cpsm = (tex0 >> 51) & 0xF
if tw > 10 or th > 10:
raise Unsupported('size %d x %d' % (tw, th))
mem, written = gs.mem, gs.written
touched = set()
if psm in (PSM_T8, PSM_T4, PSM_T8H, PSM_T4HL, PSM_T4HH):
if cpsm != PSM_CT32:
raise Unsupported('CLUT psm %#x' % cpsm)
four = psm in (PSM_T4, PSM_T4HL, PSM_T4HH)
palette = clut_ct32(gs, tex0, 16 if four else 256, touched)
out = bytearray(w * h)
i = 0
for y in range(h):
for x in range(w):
if psm == PSM_T8:
a = addr8(tbp, tbw, x, y)
touched.add(written[a])
out[i] = mem[a]
elif psm == PSM_T4:
n = addr4(tbp, tbw, x, y)
touched.add(written[n >> 1])
out[i] = (mem[n >> 1] >> ((n & 1) * 4)) & 0xF
else:
a = addr32(tbp, tbw, x, y)
touched.add(written[a + 3])
v = mem[a + 3]
out[i] = v if psm == PSM_T8H else (v & 0xF if psm == PSM_T4HL else v >> 4)
i += 1
return psm, bytes(out), palette, touched
if psm == PSM_CT32:
out = bytearray(w * h * 4)
i = 0
for y in range(h):
for x in range(w):
struct.pack_into('<I', out, i, gs.ct32(tbp, tbw, x, y, touched))
i += 4
return psm, bytes(out), None, touched
raise Unsupported('texture psm %#x' % psm)
def olk_entries(f, base):
f.seek(base)
h = f.read(0x20)
if len(h) < 0x20 or h[4:8] != b'olnk':
return None
count = struct.unpack_from('<I', h, 0)[0]
data = struct.unpack_from('<I', h, 0x10)[0]
f.seek(base + 0x20)
return [(base + data + offset, size) for offset, size, _, _ in (struct.unpack('<IIII', f.read(16)) for _ in range(count))]
def olk_leaves(f):
"""(path, byte offset in ROOT.OLK, size) of every leaf: ROOT.OLK holds sub-archives, they hold the files."""
out = []
for i, (base, _) in enumerate(olk_entries(f, 0) or []):
for j, (offset, size) in enumerate(olk_entries(f, base) or []):
out.append(('/%d/%d' % (i, j), offset, size))
return out
def dma_tag(d, q):
lo = struct.unpack_from('<Q', d, q)[0]
return lo & 0xFFFF, (lo >> 28) & 7, (lo >> 32) & 0x7FFFFFF0
def walk_chain(d, start, limit=1 << 16):
"""GIF data of the DMA chain from `start` (file-relative addresses), and whether it is a whole chain."""
out = []
stack = []
q = start
for _ in range(limit):
if q < 0 or q + 16 > len(d):
return None
qwc, tid, addr = dma_tag(d, q)
if tid == 1: # CNT
out.append(d[q + 16:q + 16 + qwc * 16])
q += 16 + qwc * 16
elif tid == 3 or tid == 4: # REF, REFS
if addr + qwc * 16 > len(d):
return None
out.append(d[addr:addr + qwc * 16])
q += 16
elif tid == 0: # REFE
out.append(d[addr:addr + qwc * 16])
return b''.join(out)
elif tid == 2: # NEXT
out.append(d[q + 16:q + 16 + qwc * 16])
q = addr
elif tid == 5: # CALL
out.append(d[q + 16:q + 16 + qwc * 16])
if len(stack) == 2:
return None
stack.append(q + 16 + qwc * 16)
q = addr
elif tid == 6: # RET
out.append(d[q + 16:q + 16 + qwc * 16])
if not stack:
return b''.join(out)
q = stack.pop()
elif tid == 7: # END
out.append(d[q + 16:q + 16 + qwc * 16])
return b''.join(out)
return None
def play_gif(gs, data):
"""Plays the GIF stream's image transfers into gs. Returns the number of transfers, or raises Unsupported."""
regs = {}
q = 0
transfers = 0
while q + 16 <= len(data):
lo, hi = struct.unpack_from('<QQ', data, q)
nloop = lo & 0x7FFF
flg = (lo >> 58) & 3
nreg = (lo >> 60) & 0xF or 16
q += 16
if flg == 0:
if nreg != 1 or (hi & 0xF) != 0xE:
raise Unsupported('PACKED tag regs %#x' % hi)
for _ in range(nloop):
value, reg = struct.unpack_from('<QQ', data, q)
regs[reg & 0xFF] = value
q += 16
elif flg == 2:
payload = data[q:q + nloop * 16]
q += nloop * 16
bitbltbuf, trxpos, trxreg = regs.get(0x50, 0), regs.get(0x51, 0), regs.get(0x52, 0)
if regs.get(0x53, 0) & 3:
raise Unsupported('TRXDIR %d' % (regs.get(0x53, 0) & 3))
dbp, dbw, dpsm = (bitbltbuf >> 32) & 0x3FFF, (bitbltbuf >> 48) & 0x3F, (bitbltbuf >> 56) & 0x3F
dsx, dsy = (trxpos >> 32) & 0x7FF, (trxpos >> 48) & 0x7FF
w, h = trxreg & 0xFFF, (trxreg >> 32) & 0xFFF
if dpsm not in (PSM_CT32, PSM_T8, PSM_T4, PSM_T8H, PSM_T4HL, PSM_T4HH) or ((trxpos >> 59) & 3):
raise Unsupported('upload psm %#x dir %d' % (dpsm, (trxpos >> 59) & 3))
bits = 32 if dpsm == PSM_CT32 else 8 if dpsm in (PSM_T8, PSM_T8H) else 4
if len(payload) * 8 < w * h * bits:
raise Unsupported('short IMAGE')
if dpsm == PSM_CT32:
gs.write_ct32(dbp, dbw, dsx, dsy, w, h, payload)
elif dpsm in (PSM_T8, PSM_T4):
gs.write_indexed(dpsm, dbp, dbw, dsx, dsy, w, h, payload)
else:
gs.write_high(dpsm, dbp, dbw, dsx, dsy, w, h, payload)
transfers += 1
else:
raise Unsupported('GIF format %d' % flg)
return transfers
def texture_units(d):
"""Offsets of the upload units (CNT tag, A+D BITBLTBUF..TRXDIR, IMAGE tag) in a leaf."""
units = set()
for q in range(0, len(d) - 0x70, 16):
qwc, tid, _ = dma_tag(d, q)
if tid != 1 or qwc != 6:
continue
lo, hi = struct.unpack_from('<QQ', d, q + 16)
if (lo & 0x7FFF) != 4 or ((lo >> 58) & 3) != 0 or (hi & 0xFF) != 0xE:
continue
if all(struct.unpack_from('<Q', d, q + 40 + 16 * i)[0] & 0xFF == 0x50 + i for i in range(4)):
units.add(q)
return units
def call_lists(d, units):
"""The leaf's CALL lists: runs of CALL tags into upload units, ended by RET. A game CALLs one at any entry, and the
uploads run from there to the list's RET. The RETs right after a list are empty lists (one entry, no target)."""
lists = []
q = 0
while q < len(d) - 16:
qwc, tid, addr = dma_tag(d, q)
if tid == 5 and qwc == 0 and addr in units:
entries = []
while q < len(d) - 16:
qwc, tid, addr = dma_tag(d, q)
if tid != 5 or qwc != 0 or addr not in units:
break
entries.append((q, addr))
q += 16
if dma_tag(d, q)[1] == 6:
lists.append(entries)
q += 16
while q < len(d) - 16 and dma_tag(d, q)[1] == 6:
lists.append([(q, None)])
q += 16
continue
q += 16
return lists
def material_textures(d):
"""(TEX0, width, height) of the model's materials: an A+D GIF tag whose spare REGS bits carry the texture's used
size (bits 32-47 width, 48-63 height, as the game stores it), followed by its register writes, TEX0 among them."""
out = set()
for q in range(0, len(d) - 32, 16):
lo, hi = struct.unpack_from('<QQ', d, q)
nloop = lo & 0x7FFF
if (lo >> 58) & 3 or ((lo >> 60) & 0xF) != 1 or (hi & 0xF) != 0xE or not 1 <= nloop <= 8 or q + 16 * (nloop + 1) > len(d):
continue
for i in range(nloop):
value, reg = struct.unpack_from('<QQ', d, q + 16 * (i + 1))
if (reg & 0xFF) not in (0x06, 0x07):
continue
psm, tw, th = (value >> 20) & 0x3F, (value >> 26) & 0xF, (value >> 30) & 0xF
if psm not in (PSM_CT32, PSM_T8, PSM_T4, PSM_T8H, PSM_T4HL, PSM_T4HH) or tw > 10 or th > 10:
continue
w, h = (hi >> 32) & 0xFFFF, (hi >> 48) & 0xFFFF
if not w or w > (1 << tw):
w = 1 << tw
if not h or h > (1 << th):
h = 1 << th
out.add((value & TEX0_KEY_MASK, w, h))
return out
def convert_model(d, report):
"""[(entries, textures, complete)] per CALL list of one model (its addresses are relative to its start), and per
upload chain no list CALLs (the game CALLs those itself: animated textures), as a list of one entry at its start: entries are the CALL tags' offsets; textures (tex0, w, h, rgba,
first entry) are those whose texels and CLUT the entries from `first entry` to the list's end all wrote; complete[k]
says every material texture reading what entries k.. wrote is among them (their uploads can be left out)."""
units = texture_units(d)
if not units:
return []
materials = sorted(material_textures(d))
out = []
lists = call_lists(d, units)
called = {target for entries in lists for _, target in entries if target is not None}
heads = [u for u in sorted(units) if u not in called and (u < 16 or dma_tag(d, u - 16)[1] != 3)]
for entries in lists + [[(u, u)] for u in heads]:
if len(entries) > 254:
report.append('list %#x: %d entries' % (entries[0][0], len(entries)))
continue
gs = GsMemory()
try:
for k, (_, target) in enumerate(entries):
if target is None:
continue
gs.entry = k + 1
data = walk_chain(d, target)
if data is None:
raise Unsupported('entry %d: chain does not end' % k)
play_gif(gs, data)
except Unsupported as e:
report.append('list %#x: %s' % (entries[0][0], e))
continue
textures, reads = [], []
for tex0, w, h in materials:
try:
psm, texels, palette, touched = decode(gs, tex0, w, h)
except Unsupported as e:
report.append('list %#x tex0 %#x: %s' % (entries[0][0], tex0, e))
continue
written = sorted(e for e in touched if e)
if not written:
continue
reads.append((0 in touched, written[0] - 1, written[-1] - 1))
if 0 not in touched:
textures.append((tex0, w, h, psm, texels, palette, written[0] - 1))
complete = [all(not (last >= k) or (not unwritten and first >= k) for unwritten, first, last in reads)
for k in range(len(entries))]
out.append(([q for q, _ in entries], textures, complete))
return out
MODEL_MAGIC = 0x00040403
def convert_leaf(d, report):
"""The leaf's models (a 03 04 04 00 header, at the leaf's start or inside a container) converted one by one; a
model's DMA addresses are relative to its own start. CALL tag offsets come back relative to the leaf."""
starts = sorted({0} | {q for q in range(0, len(d) - 4, 16) if struct.unpack_from('<I', d, q)[0] == MODEL_MAGIC})
out = []
for i, start in enumerate(starts):
end = starts[i + 1] if i + 1 < len(starts) else len(d)
model_report = []
for calls, textures, complete in convert_model(d[start:end], model_report):
out.append(([start + q for q in calls], textures, complete))
report += ['model %#x %s' % (start, line) for line in model_report]
return out
KEYS_MAGIC = b'SC3KEYS1'
def write_keys(path, olk_size, leaves):
"""The SC3 key index beside the texture pack: per pack file (one per CALL list, named '<leaf>@<list offset>'), the
leaf's offset and size in ROOT.OLK, its list's entries (CALL offset in the leaf, complete) and its textures (TEX0
bits that select texels, used size, first entry, record number of the texels and of the palette or 0xffffffff).
"SC3KEYS1", u64 ROOT.OLK size, u32 list count, then per list: u16 name length, name, u64 leaf offset, u32 leaf
size, u32 entry count, u32 texture count, entries (u32 offset, u32 complete), textures (u64 tex0, u16 width,
u16 height, u32 first entry, u32 texel record, u32 palette record)."""
with open(path + '.tmp', 'wb') as out:
lists = [(name, offset, size, calls, keys, complete) for name, offset, size, calls, keys, complete in leaves]
out.write(KEYS_MAGIC + struct.pack('<QI', olk_size, len(lists)))
for name, offset, size, calls, keys, complete in lists:
encoded = name.encode()
out.write(struct.pack('<H', len(encoded)) + encoded + struct.pack('<QIII', offset, size, len(calls), len(keys)))
for q, done in zip(calls, complete):
out.write(struct.pack('<II', q, 1 if done else 0))
for tex0, w, h, first, texel_record, palette_record in keys:
out.write(struct.pack('<QHHIII', tex0, w, h, first, texel_record, palette_record))
os.replace(path + '.tmp', path)
def convert_file(job):
olk, path, offset, size = job
with open(olk, 'rb') as f:
f.seek(offset)
d = f.read(size)
report = []
return path, offset, size, convert_leaf(d, report), report
def keys_path(pack_path):
return os.path.splitext(pack_path)[0] + '.keys'
def main():
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
parser.add_argument('disc')
parser.add_argument('out')
parser.add_argument('--only', default='', help='comma-separated leaf paths (/2/0,...)')
parser.add_argument('--report', default='', help='file listing the upload shapes not converted')
parser.add_argument('--jobs', type=int, default=os.cpu_count() or 1, help='leaves converted at once (default: all cores)')
args = parser.parse_args()
olk = os.path.join(args.disc, 'ROOT.OLK')
only = set(p for p in args.only.split(',') if p)
report = []
pack = texture.TexturePackWriter()
lists = []
with open(olk, 'rb') as f:
olk_size = os.fstat(f.fileno()).st_size
listed = olk_leaves(f)
jobs = [(olk, path, offset, size) for path, offset, size in listed if size and (not only or path in only)]
with multiprocessing.Pool(max(1, args.jobs)) as pool:
for n, (path, offset, size, converted, leaf_report) in enumerate(pool.imap(convert_file, jobs, chunksize=4)):
report += ['%s %s' % (path, line) for line in leaf_report]
for calls, textures, complete in converted:
name = '%s@%x' % (path, calls[0])
records = pack.add_file(name)
keys = []
for tex0, w, h, psm, texels, palette, first in textures:
records.append((psm, w, h, texels))
texel_record = len(records) - 1
palette_record = 0xFFFFFFFF
if palette is not None:
records.append((texture.PSMCT32, len(palette), 1, struct.pack('<%dI' % len(palette), *palette)))
palette_record = len(records) - 1
keys.append((tex0, w, h, first, texel_record, palette_record))
lists.append((name, offset, size, calls, keys, complete))
if n % 200 == 0:
print('%d/%d leaves, %d upload lists' % (n, len(jobs), len(lists)), file=sys.stderr)
pack.write(args.out + '.tmp')
os.replace(args.out + '.tmp', args.out)
write_keys(keys_path(args.out), olk_size, lists)
print('%s: %d upload lists, %d CALL entries, %d records; %d shapes not converted' %
(args.out, len(lists), sum(len(c) for _, _, _, c, _, _ in lists), pack.record_count(), len(report)))
if args.report:
with open(args.report, 'w') as f:
f.write('\n'.join(report) + '\n')
if __name__ == '__main__':
main()
+2
View File
@@ -9,6 +9,8 @@ root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
name=$1; secs=$2; shift 2
runs=${SC3_RUNS:-$root/build/runs}
runner=${SC3_RUNNER:-$root/build/game/PS2Recomp/ps2xRuntime/ps2EntryRunner}
[ -n "${SC3_TEXTURE_PACK+x}" ] || [ ! -f "$root/build/sc3_textures.pack" ] || export SC3_TEXTURE_PACK="$root/build/sc3_textures.pack"
[ -n "${SC3_2D_PACK+x}" ] || [ ! -f "$root/build/sc3_2d.pack" ] || export SC3_2D_PACK="$root/build/sc3_2d.pack"
elf=$(realpath -s "${SC3_ELF:-$root/game/SLUS_212.16}")
mkdir -p "$runs/user"; cd "$runs"; runs=$PWD
elf_dir=$(dirname "$elf")