diff --git a/.gitignore b/.gitignore index 4eac60ec29..ecae0d042f 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ RpfPreview/ *.glb *.ogg *.wav +*.navmesh-decode.json # ---- build output and caches ---- /ucode.elf diff --git a/AGENTS.md b/AGENTS.md index d5ca869746..6baca4668f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -124,9 +124,9 @@ Shard runs write `index.part*.json`; merge them into `index.json` with `--merge` ## Conventions - Python tools run with `python -I` and use only the standard library unless a file says otherwise; the exceptions - are the texture, model and control tools that import numpy or Pillow: `bc_feature.py`, `amd_swizzle.py`, + are the texture and model tools that import numpy or Pillow: `bc_feature.py`, `amd_swizzle.py`, `tile_probe.py`, `swizzle_search.py`, `tex_export.py`, `tex_mode_probe.py`, `calibrated_texture.py`, - `world_grid_atlas.py`, `port_ctl.py`, `tex_headers.py` and `skinned_glb.py` (the last two fall back to the + `world_grid_atlas.py`, `tex_headers.py` and `skinned_glb.py` (the last two fall back to the standard library when numpy is absent). - A text file a tool writes names its line ending - `open(path, "w", encoding="utf-8", newline="\n")` - so the same input gives the same bytes on every platform; `tests/test_text_write_line_endings.py` catches a writer that forgets. diff --git a/docs/port_status.md b/docs/port_status.md index 6b9a7314ad..889f369cae 100644 --- a/docs/port_status.md +++ b/docs/port_status.md @@ -20,11 +20,9 @@ work folders outside the repository (`G:\gta6port` on the test machine). | Path | What | |---|---| | `runtime/`, `tools/`, `make_game.py`, `Build.bat` | Leonida: the product | -| `victory/` | DexNom/VIctory subtree with full history, the patch source. A background poller fetches `victory/main` every 15 minutes and speaks up only when new commits exist; they are then merged with `python -I scripts/sync_victory.py --merge` and reviewed for fixes to port | -| `scripts/sync_victory.py` | Fetches `victory/main`, lists new commits, merges them with `git subtree pull` | -| remote `victory7900` | avatarmanz/VIctory-7900XTX, a second patch source (fetch only, not merged: it diverges from DexNom's line, 408 commits ahead and 334 behind at the time of adding; much of its recent work is frame time). Also polled every 15 minutes in the background. Port from it commit by commit (`git show victory7900/main:`) | +| `victory/` | DexNom/VIctory subtree with full history (historical patch source; superseded by `d3d12/`) | +| remote `victory7900` | avatarmanz/VIctory-7900XTX, a second patch source (fetch only, not merged: it diverges from DexNom's line, 408 commits ahead and 334 behind at the time of adding; much of its recent work is frame time). Polled every 15 minutes in the background. Port from it commit by commit (`git show victory7900/main:`) | | `tools/victory_saves.py` | Converts a VIctory data folder's saves and local storage into gta6rt's layout, so a save made under VIctory skips the first-boot screens | -| `scripts/port_ctl.py` | Drives a reference run of VIctory's runtime (start, pad presses from a file, frame captures, fps lines, stop) | ## Test machine diff --git a/navmeshes.navmesh-decode.json b/navmeshes.navmesh-decode.json deleted file mode 100644 index 37e62d8c14..0000000000 --- a/navmeshes.navmesh-decode.json +++ /dev/null @@ -1,518 +0,0 @@ -{ - "input": "navmeshes.rpf", - "mode": "rpf", - "start": 1920, - "end": 6707512496, - "span": 6707510576, - "carver_streams": { - "streams": 90295, - "stored": 6540238392, - "inflated": 20551068624, - "zero_padding": 161191191, - "unread": 6080993, - "tiny_continuations": 10, - "tiny_orphans": 0, - "past_window": 0, - "past_window_stored": 0 - }, - "resources": { - "0drp": { - "resources": 9603, - "streams": { - "1": 7122, - "2": 2481 - }, - "stored": 765075110, - "inflated": 2802161120, - "incomplete": 0 - }, - "grid": { - "resources": 27482, - "streams": { - "1": 27476, - "2": 6 - }, - "stored": 375890383, - "inflated": 2325782256, - "incomplete": 0 - }, - "navmesh": { - "resources": 27644, - "streams": { - "1": 4598, - "2": 23046 - }, - "stored": 5397713337, - "inflated": 15420757856, - "incomplete": 0 - }, - "psin": { - "resources": 22, - "streams": { - "1": 1, - "2": 21 - }, - "stored": 1559767, - "inflated": 2367712, - "incomplete": 1 - } - }, - "checks": { - "0drp": { - "block_map": { - "pass": 9603, - "fail": 0 - }, - "blocks_disjoint": { - "pass": 9603, - "fail": 0 - }, - "blocks_in_bounds": { - "pass": 9603, - "fail": 0 - }, - "cover_nodes_whole": { - "pass": 9585, - "fail": 0 - }, - "enum_values_dense": { - "pass": 9603, - "fail": 0 - }, - "enums_in_bounds": { - "pass": 9603, - "fail": 0 - }, - "pages_4k_rule": { - "pass": 9603, - "fail": 0 - }, - "payload_at_0x60": { - "pass": 9603, - "fail": 0 - }, - "prefix_zero": { - "pass": 9603, - "fail": 0 - }, - "q40_in_bounds": { - "pass": 9603, - "fail": 0 - }, - "region_array_count": { - "pass": 8412, - "fail": 0 - }, - "reserved_zero": { - "pass": 9603, - "fail": 0 - }, - "root_index_valid": { - "pass": 9603, - "fail": 0 - }, - "root_is_struct": { - "pass": 9603, - "fail": 0 - }, - "structs_in_bounds": { - "pass": 9603, - "fail": 0 - }, - "version_122": { - "pass": 9603, - "fail": 0 - } - }, - "grid": { - "block_map": { - "pass": 27482, - "fail": 0 - }, - "control_bytes": { - "pass": 27482, - "fail": 0 - }, - "cubic_extent": { - "pass": 27482, - "fail": 0 - }, - "inner_payload_ff00": { - "pass": 27482, - "fail": 0 - }, - "keys_octree": { - "pass": 27482, - "fail": 0 - }, - "occupied_equals_entries": { - "pass": 27482, - "fail": 0 - }, - "payload_in_bounds": { - "pass": 27482, - "fail": 0 - }, - "prefix_zero": { - "pass": 27482, - "fail": 0 - }, - "reserved_zero": { - "pass": 27482, - "fail": 0 - }, - "sector_origin": { - "pass": 27482, - "fail": 0 - }, - "table_in_bounds": { - "pass": 27482, - "fail": 0 - }, - "values_bijective": { - "pass": 27482, - "fail": 0 - } - }, - "navmesh": { - "block_map": { - "pass": 27644, - "fail": 0 - }, - "data_size_identity": { - "pass": 27644, - "fail": 0 - }, - "extents_match_root": { - "pass": 27644, - "fail": 0 - }, - "flag0_set": { - "pass": 27644, - "fail": 0 - }, - "flag1_links": { - "pass": 27644, - "fail": 0 - }, - "flag2_no_sector": { - "pass": 27644, - "fail": 0 - }, - "identity_matrix": { - "pass": 27644, - "fail": 0 - }, - "indices_below_vertices": { - "pass": 27644, - "fail": 0 - }, - "links_in_bounds": { - "pass": 27644, - "fail": 0 - }, - "polygons_chain": { - "pass": 27644, - "fail": 0 - }, - "prefix_zero": { - "pass": 27644, - "fail": 0 - }, - "quadtree_root": { - "pass": 27644, - "fail": 0 - }, - "quadtree_valid": { - "pass": 27644, - "fail": 0 - }, - "reserved_zero": { - "pass": 27644, - "fail": 0 - }, - "sector_origin": { - "pass": 27482, - "fail": 0 - }, - "split_70": { - "pass": 27644, - "fail": 0 - }, - "split_80": { - "pass": 27644, - "fail": 0 - }, - "split_88": { - "pass": 27644, - "fail": 0 - }, - "split_98": { - "pass": 27644, - "fail": 0 - }, - "tile_128m": { - "pass": 27482, - "fail": 0 - }, - "volumes_in_bounds": { - "pass": 27644, - "fail": 0 - } - }, - "psin": {} - }, - "0drp": { - "schemas": { - "CCoverPointRegion/12 structs": 7635, - "0x4712787b/7 structs": 932, - "CCoverPointRegion/11 structs": 777, - "0x4712787b/9 structs": 219, - "0x4712787b/8 structs": 22, - "0x4712787b/3 structs": 14, - "CCoverPointRegionManifest/4 structs": 1, - "0xb6dbe11b/2 structs": 1, - "0x339accda/2 structs": 1, - "0x2bf76252/2 structs": 1 - }, - "root": { - "CCoverPointRegion": 8412, - "0x4712787b": 1187, - "0x2bf76252": 1, - "0x339accda": 1, - "0xb6dbe11b": 1, - "CCoverPointRegionManifest": 1 - }, - "block_at_0x60": { - "CCoverPointNode": 9378, - "0xde5f1345": 207, - "0x00000100": 16, - "0x0904902e": 1, - "CCoverPointRegionDef": 1 - }, - "block_hash": { - "CCoverPointNode": 9585, - "0x00000100": 8825, - "0x00000013": 8412, - "0xde5f1345": 8412, - "CCoverPointRegion": 8412, - "CCoverSpatialTreeNode": 8412, - "0x4712787b": 1187, - "0x57ad0b12": 1187, - "0xdd53676a": 241, - "0xf2dd6348": 219, - "0x0904902e": 1, - "0x2bf76252": 1, - "0x339accda": 1, - "0xb6dbe11b": 1, - "CCoverPointRegionDef": 1, - "CCoverPointRegionManifest": 1 - }, - "enums": { - "eCoverFlags": 9585, - "eCoverHeight": 9585, - "eCoverUsage": 9585, - "0x32ff8fb9": 1187, - "eCoverRegionFlags": 1 - }, - "q40_shape": { - "[('0x101', 32)]": 6462, - "[]": 1324, - "[('0x101', 48)]": 1182, - "[('0x101', 64)]": 600, - "[('0x101', 80)]": 31, - "[('0x101', 141824)]": 1, - "[('0x101', 2800)]": 1, - "[('0x101', 95792), ('0x211', 8624)]": 1, - "[('0x207', 26560)]": 1 - }, - "root_index": { - "3": 7650, - "4": 932, - "2": 779, - "6": 219, - "5": 22, - "1": 1 - }, - "u16_0x48": { - "n_structs": { - "12": 7635, - "7": 932, - "11": 777, - "9": 219, - "8": 22, - "3": 14, - "2": 3, - "4": 1 - }, - "n_enums": { - "3": 8412, - "4": 1173, - "1": 15, - "0": 3 - }, - "n_blocks": { - "6": 7854, - "4": 932, - "5": 799, - "3": 15, - "2": 3 - } - }, - "pages_4k_zero": 2578, - "pages_4k_boundary": { - "nonzero": 93, - "zero": 214 - }, - "cover_nodes": 15629979, - "region_cover_nodes": 15474729, - "dynamic_cover_nodes": 155250, - "region_points": 15474744, - "region_inumpoints": { - "match": 8411, - "mismatch": 1 - }, - "first_node": { - "id0_index_zero": 9378, - "id1_index_ffffffff": 3966, - "pages": 9378 - }, - "region_bounds": { - "min": [ - -10368.0, - -8448.0, - -500.0 - ], - "max": [ - 10411.852, - 9472.0, - 1350.0 - ] - } - }, - "navmesh": { - "flags": { - "9": 18791, - "11": 5507, - "3": 3149, - "7": 161, - "1": 35, - "69": 1 - }, - "build_ids": 7, - "totals": { - "vertices": 138041746, - "polygons": 124768148, - "pool": 493024188, - "special_links": 26679246, - "link_indices": 26903247, - "volumes": 6246890 - }, - "max": { - "vertices": 52608, - "polygons": 71803, - "pool": 235411, - "special_links": 30324, - "link_indices": 30324, - "volumes": 7868 - }, - "static_sectors": 24480, - "sector_x": [ - 160, - 295 - ], - "sector_y": [ - 179, - 358 - ], - "split_blocks_max": { - "0x70": 20, - "0x80": 29, - "0x88": 173, - "0x98": 194 - }, - "tile_bounds": { - "min": [ - -12288.0, - -9856.0, - -78.55 - ], - "max": [ - 5120.0, - 13184.0, - 403.838 - ] - }, - "water_bit3": { - "b3_1_w_1": 24009, - "b3_0_w_0": 3346, - "b3_1_w_0": 289 - }, - "quadtree": { - "nodes": 2337904, - "leaves": 1760339, - "max_depth": 9 - } - }, - "grid": { - "groups": { - "8": 12778, - "256": 7131, - "512": 6263, - "32": 377, - "64": 356, - "1024": 338, - "16": 184, - "128": 54, - "2048": 1 - }, - "extent": { - "128": 16487, - "256": 7466, - "1024": 2662, - "512": 866, - "4096": 1 - }, - "origin_z": { - "0.0": 16826, - "-128.0": 7048, - "-512.0": 2670, - "-256.0": 844, - "128.0": 81, - "256.0": 12, - "-2048.0": 1 - }, - "sectors": 24480, - "sectors_not_in_navmesh": 0, - "navmesh_sectors_not_in_grid": 0, - "entries_total": 53835068, - "entries_max": 14903, - "key_depth": { - "6": 20640002, - "5": 17413561, - "7": 5569707, - "4": 4278022, - "8": 3601634, - "3": 1767427, - "2": 431181, - "1": 101453, - "0": 27482, - "10": 3649, - "9": 950 - }, - "inner_nodes": 8617353, - "leaf_payload": { - "low_byte_01": 26659574, - "low_byte_03": 16767045, - "ff00": 1791096 - } - }, - "psin": { - "version": { - "256": 21, - "79": 1 - }, - "complete": 21 - }, - "elapsed_s": 157.9 -} \ No newline at end of file diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index efe770cac5..f43a950b4d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2141,6 +2141,25 @@ if(BUILD_TESTING) add_test(NAME spirv_capability COMMAND spirv_capability_test) endif() +# CPU-only header tests (no Vulkan or Windows headers): indirect draw stats, dev-overlay build status, +# title image census, and compute warm-up pipeline wait window. +add_executable(indirect_draw_stats_test test/indirect_draw_stats_test.cpp) +add_executable(dev_status_test test/dev_status_test.cpp) +add_executable(d3d12_title_image_census_test test/d3d12_title_image_census_test.cpp) +add_executable(pipeline_wait_test test/pipeline_wait_test.cpp) +if(MSVC) + target_compile_definitions(indirect_draw_stats_test PRIVATE _CRT_SECURE_NO_WARNINGS) + foreach(_cpu_test indirect_draw_stats_test dev_status_test d3d12_title_image_census_test pipeline_wait_test) + target_compile_options(${_cpu_test} PRIVATE /W4 /permissive- /EHsc /utf-8) + endforeach() +endif() +if(BUILD_TESTING) + add_test(NAME indirect_draw_stats COMMAND indirect_draw_stats_test) + add_test(NAME dev_status COMMAND dev_status_test) + add_test(NAME d3d12_title_image_census COMMAND d3d12_title_image_census_test) + add_test(NAME pipeline_wait COMMAND pipeline_wait_test) +endif() + # GPU test and pipeline tools load Vulkan at run time, so only the Vulkan headers are needed at build time. # Nothing is downloaded unless asked: set VULKAN_SDK, install the Vulkan headers, pass # -DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release once at configure time @@ -2193,6 +2212,15 @@ if(TARGET Vulkan::Headers) add_executable(vulkan_device_markers_test test/vulkan_device_markers_test.cpp) target_link_libraries(vulkan_device_markers_test PRIVATE Vulkan::Headers) add_test(NAME vulkan_device_markers COMMAND vulkan_device_markers_test) + # Queue-family selection, slot load balancing and timestamp support (src/queue_families.h), on the CPU. + add_executable(queue_families_test test/queue_families_test.cpp) + target_link_libraries(queue_families_test PRIVATE Vulkan::Headers) + if(MSVC) + target_compile_options(queue_families_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME queue_families COMMAND queue_families_test) + endif() # The submit lock's owner tracking, waiter count, submit handoff and compile gate (SubmitMutex), on the CPU. if(WIN32) add_executable(submit_mutex_test test/submit_mutex_test.cpp) diff --git a/runtime/shims/d3d12_xs_command_list_iid.h b/runtime/shims/d3d12_xs_command_list_iid.h deleted file mode 100644 index fc149cea90..0000000000 --- a/runtime/shims/d3d12_xs_command_list_iid.h +++ /dev/null @@ -1,68 +0,0 @@ -// Console command-list interface IDs for device slot 73 (CreateCommandListX). The console passes an IID whose PC -// counterpart is a different GUID with the same first 32 bits, so a call that asks for it fails on the PC device -// with E_NOINTERFACE. Only measured pairs go in the table: -// - console c3827890-4024-474c-98cf-645b51dc4874: the riid the 1.0.2.1 executable passes to slot 73 (its only GUID -// of that form in .rdata); also in TomBox's console QueryInterface list (crates/compat/d3d12_xs/src/perfctr_xs.rs -// line 230, commit f89e4106fe of omonkeyz/xbox-emulator, GPL-3.0); -// - PC ID3D12GraphicsCommandList6, c3827890-e548-4cfa-96cf-5689a9370f80 (Windows SDK 10.0.26100.0 d3d12.h). -// Matching is on the whole GUID. An IID that is not in the table is forwarded unchanged, and logged once. -#pragma once - -#include -#include -#include - -#include -#include - -namespace rt::d3d12_xs { - -struct CommandListIidPair { - GUID console; - GUID pc; -}; - -inline constexpr CommandListIidPair kCommandListIidPairs[] = { - // ID3D12GraphicsCommandList6 - {{0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}, - {0xc3827890, 0xe548, 0x4cfa, {0x96, 0xcf, 0x56, 0x89, 0xa9, 0x37, 0x0f, 0x80}}}, -}; - -// True for the PC command-list IIDs a title may also pass (ID3D12CommandList, ID3D12GraphicsCommandList..7): those -// need no mapping and no log line. -inline bool is_pc_command_list_iid(const GUID& iid) { - static const GUID kPcIids[] = { - __uuidof(ID3D12CommandList), __uuidof(ID3D12GraphicsCommandList), - __uuidof(ID3D12GraphicsCommandList1), __uuidof(ID3D12GraphicsCommandList2), - __uuidof(ID3D12GraphicsCommandList3), __uuidof(ID3D12GraphicsCommandList4), - __uuidof(ID3D12GraphicsCommandList5), __uuidof(ID3D12GraphicsCommandList6), - __uuidof(ID3D12GraphicsCommandList7), - }; - for (const GUID& pc : kPcIids) { - if (IsEqualGUID(pc, iid)) return true; - } - return false; -} - -// The PC IID for a console command-list IID in the table; `requested` itself otherwise. `mapped` (optional) reports -// whether a substitution was made. -inline const GUID& command_list_iid_for_pc(const GUID& requested, bool* mapped = nullptr) { - for (const CommandListIidPair& pair : kCommandListIidPairs) { - if (IsEqualGUID(pair.console, requested)) { - if (mapped) *mapped = true; - return pair.pc; - } - } - if (mapped) *mapped = false; - if (is_pc_command_list_iid(requested)) return requested; // already a PC IID: nothing to report - static std::atomic logged{false}; - if (!logged.exchange(true)) { - std::fprintf(stderr, - "[rt] d3d12_xs: command list IID %08lx-%04x-%04x is not in the console table; forwarded unchanged\n", - static_cast(requested.Data1), static_cast(requested.Data2), - static_cast(requested.Data3)); - } - return requested; -} - -} // namespace rt::d3d12_xs diff --git a/runtime/test/shaders/cs_cbv_vector_rows.asm b/runtime/test/shaders/cs_cbv_vector_rows.asm deleted file mode 100644 index 6dd26a845d..0000000000 --- a/runtime/test/shaders/cs_cbv_vector_rows.asm +++ /dev/null @@ -1,42 +0,0 @@ -; group: 1,1,1 -; Read four 16-byte register rows through the actual Xbox constant-buffer descriptor staged at byte 64. -s_mov_b32 s4, 64 -s_mov_b32 s5, 0 -s_load_dwordx4 s[8:11], s[4:5], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32 v20, 0 -v_mov_b32 v0, 0 -buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen -s_waitcnt vmcnt(0) -buffer_store_dword v4, v20, s[0:3], 0 offen offset:0 -v_mov_b32 v0, 1 -buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen -s_waitcnt vmcnt(0) -buffer_store_dword v4, v20, s[0:3], 0 offen offset:4 -v_mov_b32 v0, 2 -buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen -s_waitcnt vmcnt(0) -buffer_store_dword v4, v20, s[0:3], 0 offen offset:8 -v_mov_b32 v0, 3 -buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen -s_waitcnt vmcnt(0) -buffer_store_dword v4, v20, s[0:3], 0 offen offset:12 -s_buffer_load_dwordx2 s[12:13], s[8:11], 0x30 -s_waitcnt lgkmcnt(0) -v_mov_b32 v4, s12 -v_mov_b32 v5, s13 -buffer_store_dword v4, v20, s[0:3], 0 offen offset:16 -buffer_store_dword v5, v20, s[0:3], 0 offen offset:20 -v_mov_b32 v0, 16 -buffer_load_dword v4, v0, s[8:11], 0 idxen -s_waitcnt vmcnt(0) -buffer_store_dword v4, v20, s[0:3], 0 offen offset:24 -v_mov_b32 v0, 15 -buffer_load_dword v4, v0, s[8:11], 0 idxen offset:12 -s_waitcnt vmcnt(0) -buffer_store_dword v4, v20, s[0:3], 0 offen offset:28 -s_buffer_load_dword s14, s[8:11], 0x100 -s_waitcnt lgkmcnt(0) -v_mov_b32 v4, s14 -buffer_store_dword v4, v20, s[0:3], 0 offen offset:32 -s_endpgm diff --git a/runtime/test/vk_bindless_dimensions_test.cpp b/runtime/test/vk_bindless_dimensions_test.cpp index c3da54a036..ad48a3019f 100644 --- a/runtime/test/vk_bindless_dimensions_test.cpp +++ b/runtime/test/vk_bindless_dimensions_test.cpp @@ -380,13 +380,20 @@ int main() { std::printf("device: %s\n", properties.properties.deviceName); // Sized as the D3D12 device sizes it (d3d12_vulkan_device.cpp): from the update-after-bind limits, past - // maxPerSetDescriptors where vkGetDescriptorSetLayoutSupport accepts the layout. + // maxPerSetDescriptors where vkGetDescriptorSetLayoutSupport accepts the layout. MoltenVK's answer is not asked + // for, as there: it refuses every layout of maxPerSetDescriptors (1212) or more and runs the full set, so with + // it the set would stay at the default 256 indices of each dimension and the test would fail on every Mac. BindlessFeatures features; features.update_after_bind = true; features.partially_bound = d.partially_bound; + VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; + VkPhysicalDeviceProperties2 driver_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; + d.instance_fn("vkGetPhysicalDeviceProperties2")(d.physical, &driver_properties); + const bool moltenvk = driver.driverID == VK_DRIVER_ID_MOLTENVK; const auto layout_support = d.fn("vkGetDescriptorSetLayoutSupport"); const auto layout_supported = [&](const BindlessFeatures& candidate) { + if (moltenvk) return true; if (!layout_support) return false; const bindless::SetLayout layout(candidate); VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; diff --git a/scripts/play.ps1 b/scripts/play.ps1 index 76b9f51393..70a990685d 100644 --- a/scripts/play.ps1 +++ b/scripts/play.ps1 @@ -41,7 +41,7 @@ Set-Default "LEONIDA_KEYBOARD_PAD" "1" # keyboard and mouse as a pad wh # The title's soft asserts (an int3 the console build carries on from) are stepped over and logged; the one known # site is game+0x4ffd879 after the start screen (docs/port_status.md, open items). Set-Default "LEONIDA_SKIP_INT3" "1" -$tables = Join-Path $repo "victory\crates\victory-formats\src\bcpack-tables.bin" +$tables = Join-Path $repo "d3d12\crates\leonida-formats\src\bcpack-tables.bin" if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables } $logs = Join-Path $Work "logs" diff --git a/scripts/port_ctl.py b/scripts/port_ctl.py deleted file mode 100644 index 9a7e595d07..0000000000 --- a/scripts/port_ctl.py +++ /dev/null @@ -1,320 +0,0 @@ -#!/usr/bin/env python3 -"""Drive a VIctory run of the title for testing: start, press, shot, fps, stop. - -Everything the run writes (logs, frame captures, saves, caches) goes under a -work folder outside the repository (``--work``, default ``G:\\gta6port`` or -``LEONIDA_PORT_WORK``). Nothing from the game is read or written here beyond -what the runtime itself does. - - python -I scripts/port_ctl.py start --name run1 # launch the title - python -I scripts/port_ctl.py press Enter # tap A on the stand-in pad - python -I scripts/port_ctl.py press W 3000 # hold left stick up for 3 s - python -I scripts/port_ctl.py shot # save the next presented frame - python -I scripts/port_ctl.py fps # latest frame-rate lines - python -I scripts/port_ctl.py status # running?, fps, last warnings - python -I scripts/port_ctl.py stop # end the run - -Keys (the stand-in pad's table): sticks W A S D / I J K L, triggers Z C, -buttons X Y Q E F H, Enter (A), Back (B), Esc (Menu), Tab (View), -Up Down Left Right (D-pad). The runtime reads the pad file only while no real -controller is connected. -""" - -import argparse -import json -import os -import re -import subprocess -import sys -import time - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -VICTORY = os.path.join(REPO, "victory") -DEFAULT_WORK = os.environ.get("LEONIDA_PORT_WORK", r"G:\gta6port") -DEFAULT_GAME = os.environ.get("LEONIDA_GAME_DIR", os.path.expanduser(r"~\Documents\GTA6")) -TITLE_EXE = "game_scarlett_master.exe" - -FPS_RE = re.compile(r"(\d+(?:\.\d+)?) fps, (\d+(?:\.\d+)?) ms/frame") -ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") - - -def read_log(log): - try: - with open(log, encoding="utf-8", errors="replace") as f: - return [ANSI_RE.sub("", ln) for ln in f] - except OSError: - return [] - - -def paths(work): - ctl = os.path.join(work, "ctl") - return { - "work": work, - "ctl": ctl, - "state": os.path.join(ctl, "state.json"), - "pad": os.path.join(ctl, "pad.txt"), - "shot": os.path.join(ctl, "shot.txt"), - "logs": os.path.join(work, "logs"), - "captures": os.path.join(work, "captures"), - "cache": os.path.join(work, "cache"), - "data": os.path.join(work, "data"), - } - - -def load_state(p): - try: - with open(p["state"], encoding="utf-8") as f: - return json.load(f) - except (OSError, ValueError): - return {} - - -def save_state(p, state): - os.makedirs(p["ctl"], exist_ok=True) - with open(p["state"], "w", encoding="utf-8", newline="\n") as f: - json.dump(state, f, indent=1) - - -def alive(pid): - if not pid: - return False - out = subprocess.run( - ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"], - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, - ).stdout - return f'"{pid}"' in out - - -def write_atomic(path, text): - tmp = path + ".tmp" - with open(tmp, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - os.replace(tmp, path) - - -def cmd_start(args, p): - state = load_state(p) - if alive(state.get("pid")): - print(f"a run is already going: pid {state['pid']} ({state.get('name')}); stop it first") - return 1 - exe = args.exe or os.path.join(VICTORY, "target", args.profile, "victory.exe") - if not os.path.isfile(exe): - print(f"no runtime at {exe}; build it first (cargo build --release -p victory --features diagnostics --bins)") - return 1 - title = os.path.join(args.game, TITLE_EXE) - if not os.path.isfile(title): - print(f"no title executable at {title}") - return 1 - name = args.name or time.strftime("run-%Y%m%d-%H%M%S") - for key in ("ctl", "logs", "captures", "cache", "data"): - os.makedirs(p[key], exist_ok=True) - captures = os.path.join(p["captures"], name) - os.makedirs(captures, exist_ok=True) - data = args.data or p["data"] - os.makedirs(data, exist_ok=True) - # Fresh command files: the runtime only acts on increasing numbers. - for f in (p["pad"], p["shot"]): - if os.path.exists(f): - os.remove(f) - env = dict(os.environ) - env.update({ - "VICTORY_GAME_DIR": args.game, - "VICTORY_CACHE_DIR": p["cache"], - "VICTORY_DATA_DIR": data, - "VICTORY_LOG": args.log, - "VICTORY_CAPTURE": captures, - "VICTORY_CAPTURE_REQUEST": p["shot"], - "VICTORY_MOVEMENT_FILE": p["pad"], - }) - if args.world: - env["VICTORY_CAPTURE_WORLD"] = "1" - for item in args.env or []: - k, _, v = item.partition("=") - env[k] = v - log = os.path.join(p["logs"], f"{name}.log") - cmd = [exe, "run", title, "--execute", "--console", args.console] - flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP - # The runtime writes its own bytes here; newline only keeps the repository's line-ending rule. - with open(log, "w", encoding="utf-8", newline="\n") as out: - proc = subprocess.Popen(cmd, cwd=args.game, env=env, stdout=out, stderr=subprocess.STDOUT, - stdin=subprocess.DEVNULL, creationflags=flags) - state = { - "pid": proc.pid, "name": name, "log": log, "captures": captures, "started": time.time(), - "pad_seq": 0, "shot_seq": 0, "cmd": cmd, - "env": {k: v for k, v in env.items() if k.startswith("VICTORY_")}, - } - save_state(p, state) - print(f"started pid {proc.pid} as {name}\n log {log}\n captures {captures}") - return 0 - - -def cmd_press(args, p): - state = load_state(p) - seq = int(time.time() * 1000) - seq = max(seq, state.get("pad_seq", 0) + 1) - write_atomic(p["pad"], f"{seq} {args.key} {args.ms}") - state["pad_seq"] = seq - save_state(p, state) - print(f"pressed {args.key} for {args.ms} ms (sequence {seq})") - if args.wait: - time.sleep(args.ms / 1000.0 + 0.4) - return 0 - - -def newest_png(folder, since): - best = None - try: - for entry in os.scandir(folder): - if entry.name.endswith(".png") and entry.stat().st_mtime >= since: - if best is None or entry.stat().st_mtime > best.stat().st_mtime: - best = entry - except OSError: - return None - return best.path if best else None - - -def shrink(path, width): - """A copy of the capture `width` pixels wide beside it (needs Pillow); the capture itself otherwise.""" - try: - from PIL import Image - except ImportError: - return path - with Image.open(path) as im: - height = max(1, round(im.height * width / im.width)) - small = im.resize((width, height), Image.LANCZOS) - out = path[:-4] + f"-w{width}.png" - small.save(out) - return out - - -def cmd_shot(args, p): - state = load_state(p) - seq = state.get("shot_seq", 0) + 1 - since = time.time() - 0.5 - write_atomic(p["shot"], str(seq)) - state["shot_seq"] = seq - save_state(p, state) - folder = state.get("captures") - deadline = time.time() + args.timeout - while time.time() < deadline: - found = newest_png(folder, since) - if found: - time.sleep(0.5) # let the writer finish - if args.small: - found = shrink(found, args.small) - print(found) - return 0 - time.sleep(0.25) - print(f"no new frame in {folder} after {args.timeout} s (the title may not be presenting)") - return 1 - - -def fps_lines(log, count): - hits = [ln.rstrip() for ln in read_log(log) if FPS_RE.search(ln)] - return hits[-count:] - - -def summarize(line): - m = FPS_RE.search(line) - if not m: - return line - tail = line[m.start():] - keep = [] - for pattern in (r"\d+(?:\.\d+)? fps, \d+(?:\.\d+)? ms/frame", r"\(\S+ preparing", r"[\d.]+ on the GPU", - r"\d+ draws/frame", r"dropped \d+ without a host pipeline \(\d+ being made\)", - r"cpu [\d.]+% gpu \d+% busy ram \d+ MB"): - mm = re.search(pattern, tail) - if mm: - keep.append(mm.group(0)) - stamp = line[:m.start()].split(" ")[0] - return f"{stamp} " + " | ".join(keep) - - -def cmd_fps(args, p): - state = load_state(p) - log = args.log or state.get("log") - if not log: - print("no run recorded") - return 1 - for line in fps_lines(log, args.count): - print(line if args.full else summarize(line)) - return 0 - - -def cmd_status(args, p): - state = load_state(p) - if not state: - print("no run recorded") - return 1 - up = time.time() - state.get("started", time.time()) - print(f"{state.get('name')}: pid {state.get('pid')} {'running' if alive(state.get('pid')) else 'NOT running'}, " - f"up {int(up // 60)}:{int(up % 60):02d}") - for line in fps_lines(state["log"], 3): - print(" " + summarize(line)) - lines = read_log(state["log"]) - bad = [ln.rstrip() for ln in lines if re.search(r"\b(ERROR|WARN)\b|panicked|crash|DEVICE_HUNG|DEVICE_REMOVED", ln)] - for line in bad[-args.warnings:]: - print(" ! " + line[:300]) - return 0 - - -def cmd_stop(args, p): - state = load_state(p) - pid = state.get("pid") - if not alive(pid): - print("no run is going") - return 0 - subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(40): - if not alive(pid): - break - time.sleep(0.25) - print(f"stopped pid {pid} ({state.get('name')})") - return 0 - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--work", default=DEFAULT_WORK, help="work folder outside the repository") - sub = ap.add_subparsers(dest="command", required=True) - - s = sub.add_parser("start", help="launch the title under VIctory") - s.add_argument("--name") - s.add_argument("--game", default=DEFAULT_GAME) - s.add_argument("--exe", help="runtime executable (default: victory/target//victory.exe)") - s.add_argument("--profile", default="release") - s.add_argument("--console", default="series-x", choices=["series-x", "series-s"]) - s.add_argument("--log", default="info", help="VICTORY_LOG filter") - s.add_argument("--data", help="data folder (saves); default /data") - s.add_argument("--world", action="store_true", help="also capture world frames (VICTORY_CAPTURE_WORLD)") - s.add_argument("--env", action="append", help="extra K=V for the run (repeatable)") - - s = sub.add_parser("press", help="press a stand-in pad key") - s.add_argument("key") - s.add_argument("ms", nargs="?", type=int, default=200) - s.add_argument("--wait", action="store_true", help="return after the hold ends") - - s = sub.add_parser("shot", help="save the next presented frame and print its path") - s.add_argument("--timeout", type=float, default=30.0) - s.add_argument("--small", type=int, default=0, metavar="WIDTH", - help="also write a copy this many pixels wide and print its path (needs Pillow)") - - s = sub.add_parser("fps", help="latest frame-rate lines of the run's log") - s.add_argument("--count", type=int, default=5) - s.add_argument("--log") - s.add_argument("--full", action="store_true") - - s = sub.add_parser("status", help="whether the run is going, its fps and last warnings") - s.add_argument("--warnings", type=int, default=5) - - sub.add_parser("stop", help="end the run") - - args = ap.parse_args() - p = paths(args.work) - return {"start": cmd_start, "press": cmd_press, "shot": cmd_shot, "fps": cmd_fps, - "status": cmd_status, "stop": cmd_stop}[args.command](args, p) - - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/scripts/sync_victory.py b/scripts/sync_victory.py deleted file mode 100644 index ccae2c459a..0000000000 --- a/scripts/sync_victory.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python3 -"""Check DexNom/VIctory for new commits and optionally merge them into victory/. - -VIctory lives in this repository as a git subtree under ``victory/`` (added with -``git subtree add --prefix=victory victory main``). This tool fetches the -``victory`` remote, reports the commits that are not merged yet and, with -``--merge``, pulls them in with ``git subtree pull`` so upstream history is kept -and local changes under ``victory/`` are merged, not overwritten. - -Run from anywhere inside the repository: - - python -I scripts/sync_victory.py # report only - python -I scripts/sync_victory.py --merge # report, then merge if clean - -Exit codes: 0 up to date or merged, 10 updates waiting (report only), -2 git failure, 3 working tree not clean (merge refused), 4 merge conflict. -""" - -import argparse -import datetime -import os -import subprocess -import sys - -REMOTE = "victory" -BRANCH = "main" -PREFIX = "victory" - - -def git(*args, check=True): - proc = subprocess.run( - ["git", *args], - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - encoding="utf-8", - errors="replace", - ) - if check and proc.returncode != 0: - print(f"git {' '.join(args)} failed ({proc.returncode}):\n{proc.stdout}") - sys.exit(2) - return proc - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--merge", action="store_true", help="merge new commits with git subtree pull") - args = ap.parse_args() - - top = git("rev-parse", "--show-toplevel").stdout.strip() - os.chdir(top) - stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") - - git("fetch", "--quiet", REMOTE, BRANCH) - upstream = git("rev-parse", f"{REMOTE}/{BRANCH}").stdout.strip() - merged = git("merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode == 0 - if merged: - print(f"[{stamp}] {REMOTE}/{BRANCH} {upstream[:9]} is already merged; nothing to do.") - return 0 - - new = git("log", "--oneline", "--no-decorate", f"HEAD..{upstream}").stdout.strip().splitlines() - print(f"[{stamp}] {len(new)} new {REMOTE}/{BRANCH} commit(s) up to {upstream[:9]}:") - for line in new: - print(f" {line}") - if not args.merge: - return 10 - - dirty = git("status", "--porcelain", "--untracked-files=no").stdout.strip() - if dirty: - print("Working tree has uncommitted changes; commit or stash them, then run --merge again.") - print(dirty) - return 3 - - msg = ( - f"Merge {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/ ({len(new)} commit(s))\n\n" - "Pulled with scripts/sync_victory.py --merge (git subtree pull).\n" - ) - pull = git("subtree", "pull", f"--prefix={PREFIX}", REMOTE, BRANCH, "-m", msg, check=False) - print(pull.stdout.strip()) - if pull.returncode != 0: - conflicts = git("diff", "--name-only", "--diff-filter=U", check=False).stdout.strip() - if conflicts: - print("Merge stopped on conflicts in:") - print(conflicts) - return 4 - print("git subtree pull failed.") - return 2 - print(f"Merged {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/.") - return 0 - - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/tests/test_ctest_registration.py b/tests/test_ctest_registration.py index 35777b44ea..7a4970f277 100644 --- a/tests/test_ctest_registration.py +++ b/tests/test_ctest_registration.py @@ -17,7 +17,10 @@ str(ROOT / "runtime" / "test" / "d3d12_indirect_rt_test.cpp"))) # d3d12_clear_test is deliberately run by hand until #521's tie rounding lands. -NOT_IN_CTEST = {"d3d12_clear_test"} +# vk_compute_test, vk_sampler_test, and vk_store_test are shader-runner tools invoked by scripts/run_gpu_tests.py. +NOT_IN_CTEST = {"d3d12_clear_test", "vk_compute_test", "vk_sampler_test", "vk_store_test"} +# Every runtime/test/*_test.cpp on disk must be wired into runtime/CMakeLists.txt. +UNWIRED_TEST_SOURCES = set() def strip_cmake_comments(text): @@ -34,14 +37,82 @@ def replace(match): return tokens.sub(replace, text) +def expand_cmake_foreach(text): + """Expand literal-item foreach(...)/endforeach() blocks in comment-stripped CMake text.""" + pattern = re.compile(r"\b(foreach|endforeach)\s*\(([^)]*)\)", re.IGNORECASE | re.S) + stack = [(None, [])] + pos = 0 + for match in pattern.finditer(text): + stack[-1][1].append(text[pos:match.start()]) + pos = match.end() + kind = match.group(1).lower() + if kind == "foreach": + stack.append((match.group(2), [])) + continue + if len(stack) == 1: + stack[0][1].append(match.group(0)) + continue + header, body_parts = stack.pop() + body = "".join(body_parts) + args = re.findall(r'"(?:\\.|[^"\\])*"|\S+', header) + if not args: + stack[-1][1].append(body) + continue + var, rest = args[0], args[1:] + if not re.fullmatch(r"[A-Za-z0-9_]+", var): + stack[-1][1].append(body) + continue + upper_rest = [tok.upper() for tok in rest] + if upper_rest and upper_rest[0] == "RANGE": + stack[-1][1].append(body) + continue + if upper_rest and upper_rest[0] == "IN": + if len(upper_rest) >= 2 and upper_rest[1] == "ITEMS": + items = [tok.strip('"') for tok in rest[2:]] + else: + stack[-1][1].append(body) + continue + else: + items = [tok.strip('"') for tok in rest] + placeholder = f"${{{var}}}" + for item in items: + stack[-1][1].append(body.replace(placeholder, item)) + stack[-1][1].append(text[pos:]) + while len(stack) > 1: + _, body_parts = stack.pop() + stack[-1][1].extend(body_parts) + return "".join(stack[0][1]) + + +def referenced_test_sources(text): + """Relative ``test/.../*_test.cpp`` paths wired into build targets in CMakeLists.txt.""" + expanded = expand_cmake_foreach(strip_cmake_comments(text)) + sources = set() + for match in re.finditer(r"\b(?:add_executable|add_library|target_sources)\s*\(([^)]*)\)", + expanded, re.IGNORECASE | re.S): + for src in re.findall(r"(?:^|[\s\"'/])(test/[A-Za-z0-9_./-]*_test\.cpp)\b", match.group(1)): + sources.add(src) + return sources + + +def disk_test_sources(runtime_dir): + """Relative ``test/.../*_test.cpp`` paths present on disk under ``runtime_dir / 'test'``.""" + test_dir = Path(runtime_dir) / "test" + if not test_dir.is_dir(): + return set() + return {p.relative_to(runtime_dir).as_posix() for p in test_dir.rglob("*_test.cpp")} + + def built_test_executables(text): - return {name for name in re.findall(r"add_executable\(\s*([A-Za-z0-9_]+)", strip_cmake_comments(text)) + expanded = expand_cmake_foreach(strip_cmake_comments(text)) + return {name for name in re.findall(r"add_executable\(\s*([A-Za-z0-9_]+)", expanded) if name.endswith("_test")} def registered_commands(text): # add_test may span lines, e.g. add_test(NAME x\n COMMAND foo_test ...). - return set(re.findall(r"add_test\([^)]*?\bCOMMAND\s+\"?([A-Za-z0-9_]+)", strip_cmake_comments(text), re.S)) + expanded = expand_cmake_foreach(strip_cmake_comments(text)) + return set(re.findall(r"add_test\([^)]*?\bCOMMAND\s+\"?([A-Za-z0-9_]+)", expanded, re.S)) class CTestRegistrationTest(unittest.TestCase): @@ -55,7 +126,70 @@ def test_all_test_executables_have_an_add_test(self): def test_the_exception_is_still_the_only_one(self): # An allowlist that grows unnoticed is how this bug happens again. - self.assertEqual(NOT_IN_CTEST & built_test_executables(self.cmake), {"d3d12_clear_test"}) + self.assertEqual( + NOT_IN_CTEST & built_test_executables(self.cmake), + {"d3d12_clear_test", "vk_compute_test", "vk_sampler_test", "vk_store_test"}, + ) + + def test_all_test_sources_on_disk_are_wired_in_cmake(self): + on_disk = disk_test_sources(ROOT / "runtime") + self.assertTrue(on_disk, "expected runtime/test/*_test.cpp files on disk") + wired = referenced_test_sources(self.cmake) + unwired = on_disk - wired - UNWIRED_TEST_SOURCES + self.assertEqual( + unwired, + set(), + f"runtime/test/*_test.cpp files not wired in runtime/CMakeLists.txt: {sorted(unwired)}", + ) + + def test_referenced_test_sources_handles_foreach_and_ignores_comments(self): + text = ( + "add_executable(direct_test test/direct_test.cpp)\n" + "target_sources(direct_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/test/extra_test.cpp)\n" + "foreach(_context_test alpha beta)\n" + " add_executable(${_context_test}_test test/${_context_test}_test.cpp)\n" + "endforeach()\n" + "foreach(target IN ITEMS gamma_test delta_test)\n" + " add_executable(${target} test/${target}.cpp)\n" + "endforeach()\n" + "# add_executable(commented_test test/commented_test.cpp)\n" + 'message(STATUS "test/message_only_test.cpp")\n' + ) + self.assertEqual( + referenced_test_sources(text), + { + "test/direct_test.cpp", + "test/extra_test.cpp", + "test/alpha_test.cpp", + "test/beta_test.cpp", + "test/gamma_test.cpp", + "test/delta_test.cpp", + }, + ) + with tempfile.TemporaryDirectory() as tmp: + tdir = Path(tmp) / "test" + tdir.mkdir() + (tdir / "direct_test.cpp").write_text("int main() { return 0; }\n", encoding="utf-8", newline="\n") + (tdir / "orphan_test.cpp").write_text("int main() { return 0; }\n", encoding="utf-8", newline="\n") + self.assertEqual( + disk_test_sources(Path(tmp)) - referenced_test_sources(text), + {"test/orphan_test.cpp"}, + ) + + def test_foreach_built_test_without_add_test_is_caught(self): + text = ( + "foreach(x IN ITEMS mandy_registration_probe)\n" + " add_executable(${x}_test test/${x}_test.cpp)\n" + "endforeach()\n" + "foreach(y alpha beta)\n" + " add_executable(${y}_test test/${y}_test.cpp)\n" + " add_test(NAME ${y} COMMAND ${y}_test)\n" + "endforeach()\n" + ) + self.assertEqual( + built_test_executables(text) - registered_commands(text), + {"mandy_registration_probe_test"}, + ) def test_comments_do_not_build_or_register_tests(self): text = ( diff --git a/tests/test_report_paths.py b/tests/test_report_paths.py index 46aa9da9fd..a6b85b5049 100644 --- a/tests/test_report_paths.py +++ b/tests/test_report_paths.py @@ -21,8 +21,9 @@ import report_paths # noqa: E402 # Tools that use report_paths and must not define their own copy again. -SHARED = ("anim_index", "awc_manifest", "gamedata_index", "gamedata_xml", "gen_d3d12_stubs", "glb_inspect", - "navmesh_index", "rpf_probe", "tile_probe", "world_index", "world_lights_paths", "world_names") +SHARED = ("anim_index", "awc_manifest", "bink_index", "gamedata_index", "gamedata_xml", "gen_d3d12_stubs", + "glb_inspect", "navmesh_index", "rpf_probe", "tile_probe", "world_index", "world_lights_paths", + "world_names") # The one tool that still carries its own copy (an open pull request edits its call site). Do not add to this list: # import report_paths instead. LEGACY_COPIES = {"navmesh_decode"} diff --git a/tools/bink_index.py b/tools/bink_index.py index 49cad26860..9db9a5ecd7 100644 --- a/tools/bink_index.py +++ b/tools/bink_index.py @@ -45,6 +45,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 +from report_paths import same_report_path # noqa: E402 SIG = re.compile(rb"KB2[a-z]") HDR = 0x2C @@ -430,14 +431,7 @@ def is_rpf_archive(path): return len(header) >= 16 and header[1:4] == b"FPR" -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False +same_output_path = same_report_path # True when writing the second would truncate the first def target_problem(path): diff --git a/tools/world_hotspots.py b/tools/world_hotspots.py deleted file mode 100644 index 93eb1fd074..0000000000 --- a/tools/world_hotspots.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python3 -"""Rank the densest cells of the placed world, to pick a teleport target (for example the high-rise cluster of the city). - -Reads the rows ``world_index.py --entities-out`` writes (one JSON line per placed entity; the file is derived from -your own copy of the game and stays in your local work folder) and counts the full-detail placements (``lod_level`` -0 and 5, the HD and ORPHAN_HD tiers of docs/world.md) in square cells of ``--cell`` metres (RAGE world x y, Z-up). -It prints the densest cells with the placements' mean x y, the median and 90th-percentile z, and a suggested -target ``x,y,z`` (the median ground height of the cell plus ``--above`` metres). ``--out FILE`` writes that -target of the densest cell (or of ``--pick N``) as ``x,y,z``, which the runtime reads from -``LEONIDA_VICE_CITY`` or from ``%TEMP%\\leonida-player\\vice.txt`` (docs/mod-menu.md). - -Nothing in the output is game content beyond a few coordinates; do not commit it. Standard library only. -Usage: ``python -I tools/world_hotspots.py /entities.jsonl [--cell 100] [--top 15] [--bbox x0 y0 x1 y1]``. -""" -import argparse -import json -import math -import os -import sys - -FULL_DETAIL = (0, 5) - - -def cells(path, cell, bbox): - """{(i, j): [xs, ys, zs]} of the full-detail placements, and the row counts.""" - out = {} - rows = kept = 0 - with open(path, encoding="utf-8") as f: - for line in f: - rows += 1 - try: - row = json.loads(line) - x, y, z = (float(v) for v in row["position"]) - except (ValueError, KeyError, TypeError): - continue - if row.get("lod_level") not in FULL_DETAIL or not all(map(math.isfinite, (x, y, z))): - continue - if bbox and not (bbox[0] <= x <= bbox[2] and bbox[1] <= y <= bbox[3]): - continue - kept += 1 - c = out.setdefault((math.floor(x / cell), math.floor(y / cell)), ([], [], [])) - c[0].append(x) - c[1].append(y) - c[2].append(z) - return out, rows, kept - - -def quantile(values, q): - v = sorted(values) - return v[min(len(v) - 1, int(q * len(v)))] - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("entities", help="world_index.py --entities-out file (JSON lines)") - ap.add_argument("--cell", type=float, default=100.0, help="cell size in metres (default 100)") - ap.add_argument("--top", type=int, default=15) - ap.add_argument("--bbox", type=float, nargs=4, metavar=("X0", "Y0", "X1", "Y1"), help="only placements inside") - ap.add_argument("--above", type=float, default=3.0, help="metres above the median z for the suggested target") - ap.add_argument("--pick", type=int, default=0, help="which of the listed cells --out writes (0 = densest)") - ap.add_argument("--out", help="write the picked target as x,y,z") - args = ap.parse_args(argv) - if not (math.isfinite(args.cell) and args.cell > 0) or args.top < 1: - ap.error("--cell must be positive and --top at least 1") - try: - found, rows, kept = cells(args.entities, args.cell, args.bbox) - except OSError as e: - print(f"ERROR: {e}", file=sys.stderr) - return 2 - if not found: - print("ERROR: no full-detail placement in the file", file=sys.stderr) - return 2 - ranked = sorted(found.items(), key=lambda kv: -len(kv[1][0]))[: args.top] - print(f"{rows} rows, {kept} full-detail placements in {len(found)} cells of {args.cell:g} m") - targets = [] - for n, ((i, j), (xs, ys, zs)) in enumerate(ranked): - mx, my = sum(xs) / len(xs), sum(ys) / len(ys) - # Ground: the placements nearest the mean position, not the cell's roofs. - near = sorted(range(len(xs)), key=lambda k: (xs[k] - mx) ** 2 + (ys[k] - my) ** 2)[: max(5, len(xs) // 10)] - ground = quantile([zs[k] for k in near], 0.5) - target = (round(mx, 1), round(my, 1), round(ground + args.above, 1)) - targets.append(target) - print( - f"#{n}: cell ({i},{j}) x {i * args.cell:.0f}..{(i + 1) * args.cell:.0f} y {j * args.cell:.0f}..{(j + 1) * args.cell:.0f}: " - f"{len(xs)} placements, mean ({mx:.1f}, {my:.1f}), z median {quantile(zs, 0.5):.1f} p90 {quantile(zs, 0.9):.1f}, " - f"target {target[0]},{target[1]},{target[2]}" - ) - if args.out: - if not 0 <= args.pick < len(targets): - ap.error("--pick is not among the listed cells") - os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) - with open(args.out, "w", encoding="utf-8", newline="\n") as f: - f.write("%s,%s,%s\n" % targets[args.pick]) - print(f"wrote #{args.pick} to {args.out}") - return 0 - - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main())