Compare commits

...

194 Commits

Author SHA1 Message Date
incentive 80bb88eb0d Suppress BB-only 6xBF for V1/V2 proxy clients 2026-05-13 05:24:15 -04:00
incentive 74bfe9683d Merge remote-tracking branch 'origin/sync/upstream-20260507'
CMake / build (macos-latest) (push) Has been cancelled
CMake / build (ubuntu-latest) (push) Has been cancelled
2026-05-11 09:10:04 -04:00
incentive e88ed98318 Merge upstream newserv master 2026-05-09 01:02:34 -04:00
Martin Michelsen 211d08710b add default item parameter tables 2026-05-08 18:25:57 -07:00
Martin Michelsen ee40425393 add ItemParameterTable binary serialization; make JSON the default format 2026-05-08 09:23:53 -07:00
Corrine 12f9a045ca Same treatment to AR Codes. 2026-05-07 19:35:21 -07:00
Corrine 8134243fb1 Prevent confusion. 2026-05-07 19:35:21 -07:00
Corrine c869ed27f1 Fixed a mistake with NoRareSelling 2026-05-07 19:35:21 -07:00
Corrine 321ba64016 Finished. 2026-05-07 19:35:21 -07:00
Corrine a8606d26a8 Added MoreSaveSlots.59NJ 2026-05-07 19:35:21 -07:00
Corrine a57cca6c12 Port 59NL server patches to 59NJ (pt. 1) 2026-05-07 19:35:21 -07:00
incentive 86a46df442 Treat proxy A0 lobby exit as intentional
CMake / build (macos-latest) (push) Has been cancelled
CMake / build (ubuntu-latest) (push) Has been cancelled
2026-05-06 02:03:51 -04:00
incentive cdb397f5ea Add GC EP1 and EP2 EXP client patches 2026-05-05 22:34:44 -04:00
incentive 2b73d58033 Add GC Normal Dragon HP client patch 2026-05-05 22:21:33 -04:00
incentive 5abd47ff72 Align BB Normal Dragon HP with V2 2026-05-05 19:39:05 -04:00
incentive 261cb5c76f Log Dragon boss action state 2026-05-05 19:12:20 -04:00
incentive ea1044c271 Merge boss flags when blocking damage rollback 2026-05-05 18:51:10 -04:00
incentive a1c358e13a Preserve boss flags when blocking damage rollback 2026-05-05 18:28:46 -04:00
incentive 1f00bf1d9b Clamp boss damage rollback from 6x0A 2026-05-05 18:12:36 -04:00
incentive 8bc602012e Allow DC V2 Falz death-drop pickup recovery 2026-05-05 16:52:25 -04:00
incentive e0c34fe700 PSO Peeps: block boosted clients from Vanilla and Hardcore
Add HAS_PSO_PEEPS_XP_PATCH for future V2/GC client-function XP patches.

Unify boosted-client proxy blocking so Vanilla/Hardcore reject:
- PC v2 clients using boosted BattleParams
- legacy boosted-disc listener ports
- future clients with the PSO Peeps XP patch flag

Normal unpatched V2/GC clients remain allowed.
2026-05-05 15:52:11 -04:00
incentive cbe9747fd4 PSO Peeps: block PC v2 from Vanilla/Hardcore ships
PC v2 clients receive boosted BattleParams via the patch server.
Vanilla and Hardcore run base XP rates and are incompatible.
Block Version::PC_V2 from proxy destinations on ports 19230/19530.
2026-05-05 15:52:08 -04:00
incentive de0104eec8 Forward in-game proxy command 1D 2026-05-05 14:13:11 -04:00
incentive c454068715 Merge preferred lobbies and mag feed fix 2026-05-04 14:29:52 -04:00
Martin Michelsen b8e7d81a22 add check for invalid defensive item type 2026-05-04 10:32:08 -07:00
Martin Michelsen d98e1f7478 fix mag evolution table reference 2026-05-04 13:31:59 -04:00
Martin Michelsen d384cf4f11 fix mag evolution table reference 2026-05-04 09:51:57 -07:00
Martin Michelsen 681ce135f8 add JSON encoding for ItemPMT 2026-05-03 22:55:53 -07:00
incentive c497f64376 Fix proxy savechar character backup 2026-05-03 22:21:45 -04:00
incentive 5d43acd9a2 Fix proxy savechar character backup 2026-05-03 22:21:37 -04:00
incentive 90a1f0f938 Allow loadchar in proxy sessions 2026-05-03 21:04:59 -04:00
incentive db52a15888 Allow loadchar in proxy sessions 2026-05-03 21:04:55 -04:00
incentive 71fc272133 Allow savechar in proxy sessions 2026-05-03 18:13:32 -04:00
incentive bef656077c Allow savechar in proxy sessions 2026-05-03 18:13:01 -04:00
incentive fff0f3a71d Fix README formatting on branch 2026-05-02 23:07:46 -04:00
incentive e94fcf035e Fix README formatting 2026-05-02 23:06:00 -04:00
incentive 0abdb50eca Add PSO Peeps README and preserve upstream README 2026-05-02 23:05:25 -04:00
incentive a0306ecaee Update README for PSO Peeps 2026-05-02 23:03:43 -04:00
incentive ce0aea1518 Add PSO Peeps README and preserve upstream README 2026-05-02 23:03:03 -04:00
incentive 1c3e8ca53c Merge upstream newserv preferred lobby changes 2026-05-02 22:46:20 -04:00
Martin Michelsen e19c0b8bc9 add 11/2000 mag table 2026-05-02 10:50:55 -07:00
Martin Michelsen 6b636c4694 rewrite MagEvolutionTable 2026-05-02 10:48:22 -07:00
Martin Michelsen 1fa3d18430 rewrite ItemParameterTable 2026-05-02 09:36:16 -07:00
Martin Michelsen 2f4a9462ea fix 6x17 filter in proxy 2026-05-01 21:56:21 -07:00
incentive f05e68492d PSO Peeps Start
Docker / Build (push) Has been cancelled
2026-05-01 23:14:17 -04:00
Martin Michelsen 826eb88e2e add __packed_ws_be__ 2026-04-26 17:57:59 -07:00
Martin Michelsen 80391df8b7 implement lobby assignment at login 2026-04-26 09:28:10 -07:00
Martin Michelsen 7f68d41bac fix port name in game server lookup 2026-04-25 22:21:46 -07:00
Martin Michelsen 75e7232096 handle BB not sending C6 after 08E8 2026-04-25 12:06:43 -07:00
Martin Michelsen 7a29b39771 allow 6xCB in free-play 2026-04-24 20:36:45 -07:00
Martin Michelsen cfcb56b13f update command notes 2026-04-24 20:17:48 -07:00
Martin Michelsen 9e6740b778 update 6x30 notes 2026-04-20 20:00:11 -07:00
Martin Michelsen 590f937959 add release script 2026-04-19 13:32:26 -07:00
Martin Michelsen 31abc24e81 don't allow players to pick up items if they are too far away 2026-04-19 09:35:20 -07:00
Martin Michelsen 507fbf0451 add another useless AR code 2026-04-19 08:57:49 -07:00
Martin Michelsen 1fa660129d add last-hit tracking for target subcommands 2026-04-11 08:28:40 -07:00
Martin Michelsen 67082f7b6b update static 2026-04-11 08:14:12 -07:00
Martin Michelsen b34c9a7c88 improve error message for missing quest common/rare item sets 2026-04-05 21:50:53 -07:00
Martin Michelsen 87e85932a4 switch rare drops to stacked space logic 2026-04-03 19:52:42 -07:00
Martin Michelsen b704d827ed add support for direct Xbox connections 2026-04-01 21:47:21 -07:00
Martin Michelsen 598ecf88e3 revise death_flags notes 2026-04-01 08:48:19 -07:00
Martin Michelsen a05971017d explain a few of the unknown player_flags bits 2026-03-30 19:38:15 -07:00
Martin Michelsen b7819413b0 handle missing DAR entries in HTML generator 2026-03-27 07:55:44 -07:00
Martin Michelsen 80e4b0e6fe clean up formatting on Ep3 drop rates comment 2026-03-23 20:39:44 -07:00
Martin Michelsen daee47b722 use new phosg parallel functions 2026-03-22 21:37:52 -07:00
Martin Michelsen 5724fb9a12 add $allrare debug command; closes #739 2026-03-22 21:37:43 -07:00
Martin Michelsen 983753f840 add FogDebug patch 2026-03-21 09:30:59 -07:00
Martin Michelsen 53d2318873 more details on player_flags 2026-03-20 22:21:21 -07:00
Martin Michelsen 83291d5501 more details on player_flags 2026-03-19 23:01:30 -07:00
Martin Michelsen 55be92a56f add game duration to info window 2026-03-19 10:42:01 -07:00
Martin Michelsen 6a23e5da0a make some sense out of game_flags and player_flags 2026-03-18 22:44:02 -07:00
Martin Michelsen 4571cf7fdc fix attribute count check in 6xDA 2026-03-11 07:19:53 -07:00
Martin Michelsen 4e3549ba6b use EnemyType in ItemCreator; fix incorrect drop tables 2026-03-08 20:40:15 -07:00
Martin Michelsen 3cbf64dda2 update quest collision opcode docs 2026-03-08 12:55:57 -07:00
Martin Michelsen 382bc6b7ce don't allow error cases for bb_exchange_pd_percent to destroy items 2026-03-04 21:37:54 -08:00
Martin Michelsen e05991ffb3 add test for trade window sequence 2026-03-03 20:43:46 -08:00
Martin Michelsen ffda97222d document --language option in disassemble-quest-script 2026-03-02 08:46:38 -08:00
Martin Michelsen 8f21604367 clean up CMakeLists a bit 2026-03-02 08:46:25 -08:00
Martin Michelsen 4045504b61 also send combatant info board entries in spectator teams 2026-02-28 20:49:36 -08:00
Martin Michelsen 4aad1514c2 port a few more bug fix patches to Xbox 2026-02-28 20:49:19 -08:00
Martin Michelsen a649a4a146 add WIP Xbox BugFixes patch
Docker / Build (push) Has been cancelled
2026-02-26 21:47:53 -08:00
Martin Michelsen 7e21d8a9a1 enable color codes in info-board proxy shell command 2026-02-26 21:47:31 -08:00
Martin Michelsen c0fc3014cf move C9 comment 2026-02-22 20:33:02 -08:00
Martin Michelsen 08dff98948 fix Influence assist effect 2026-02-22 07:36:11 -08:00
Martin Michelsen d1c1228308 track hits from TargetEntry commands instead of 6x0A 2026-02-16 20:44:21 -08:00
Martin Michelsen b5fd58722b delete bank file when creating new character 2026-02-16 20:39:20 -08:00
Martin Michelsen f0e8e35e2b fix typos in error messages 2026-02-16 20:20:11 -08:00
Martin Michelsen 68b495b4b4 make --restrict-room floor-specific 2026-02-15 10:50:16 -08:00
Martin Michelsen 1e459edfc4 add --restrict-room in random enemy optimizer 2026-02-15 08:32:27 -08:00
Martin Michelsen c6d7025f43 add more debug info to EXP computation 2026-02-15 08:31:59 -08:00
Martin Michelsen ccf4b723f5 add --pessimize option in optimize-materialized-map 2026-02-14 19:58:54 -08:00
Martin Michelsen 8717f00106 add param filtering in materialize optimizer 2026-02-12 21:37:33 -08:00
Martin Michelsen 99630c999d add optimize-materialized-map 2026-02-12 21:12:57 -08:00
Martin Michelsen e8c262223b simplify Ep3 spectator join logic 2026-02-09 21:20:22 -08:00
Martin Michelsen 3d7215d591 add only command in address translator 2026-02-09 21:20:11 -08:00
Martin Michelsen ba48236200 add 2OJ4 2026-02-09 21:19:44 -08:00
Martin Michelsen 8065300fae replace item names with IDs in config.json 2026-02-07 22:34:45 -08:00
Martin Michelsen e9dfa5d1de fail on unknown quest directives 2026-02-05 19:58:57 -08:00
Martin Michelsen d38be2f360 add default4 BB key 2026-02-05 19:58:57 -08:00
Martin Michelsen 2429c4d341 add decoder/encoder for AdEnding.rel 2026-02-01 17:32:04 -08:00
Martin Michelsen ef2d9fae03 add qdefault codes in ar-codes.txt 2026-02-01 16:38:41 -08:00
Martin Michelsen 7016d65313 make gsl commands easier to use 2026-01-27 20:01:50 -08:00
Martin Michelsen bdd066edb2 fix notes for npc_param regsA[2] 2026-01-18 22:53:39 -08:00
Martin Michelsen 1bd305d4e7 add client function for debugging movement data 2026-01-14 22:06:06 -08:00
Martin Michelsen 890014b223 add findings from first pass on movement data 2026-01-12 22:03:37 -08:00
Martin Michelsen e4ef96fcc5 add inventory debugging AR code 2026-01-12 22:03:37 -08:00
Martin Michelsen 641b3a7bef fix formatting in proxy handler table 2026-01-12 22:03:37 -08:00
Martin Michelsen 6f9f684cc9 add AR code to disable CCA dust 2026-01-05 10:06:20 -08:00
Martin Michelsen 2602196279 make downloading a quest not end the proxy session 2026-01-05 00:12:37 -08:00
Martin Michelsen ec16cb0ae3 rename fields in battle param structs 2026-01-04 21:08:38 -08:00
Martin Michelsen 6da7b26c9f add comment about common table JSON formats 2026-01-04 10:51:18 -08:00
Martin Michelsen 8663e6682a slightly more fanciness in AccurateKillCount patch 2026-01-04 10:07:06 -08:00
Martin Michelsen 9b14e5d400 don't let SuperMap's edit-distance allow subtypes of the same base_type to merge 2026-01-04 10:07:06 -08:00
Martin Michelsen a1e067cc52 add a few learnings from enemy RE 2026-01-04 10:07:06 -08:00
Martin Michelsen a469b4355e add option to change chat command character 2026-01-04 00:59:39 -08:00
Martin Michelsen 4aa206bd4b add all BP indexes and fix incorrect RT indexes 2026-01-04 00:59:39 -08:00
Martin Michelsen d9540ba414 add comment about game section ID changes 2026-01-01 11:14:27 -08:00
Martin Michelsen cb7c45ef27 reformat ItemCreator.cc 2026-01-01 11:14:17 -08:00
Martin Michelsen f98db20618 implement BB system, guild card, and stream files in proxy save files option 2026-01-01 10:58:47 -08:00
Martin Michelsen 8fbf2246e6 fix change_event applying when it shouldn't on BB 2026-01-01 10:58:47 -08:00
Martin Michelsen 6b1726c1b5 add $savefiles command 2026-01-01 10:58:47 -08:00
Martin Michelsen cac61e6763 add ability to delay $item until next drop on proxy 2026-01-01 10:58:47 -08:00
Martin Michelsen 227e88f906 add warning about ItemPT/RT not reloading at quest start 2025-12-30 21:17:38 -08:00
Martin Michelsen 7ab3175f80 make quest item exchange implementations more complete 2025-12-26 19:54:22 -08:00
Martin Michelsen cd0d13e98c update notes on 0122 command 2025-12-26 09:44:44 -08:00
Martin Michelsen 8eeb487bc7 make item data stack count consistent with bank item stack count at load time 2025-12-25 23:21:32 -08:00
Martin Michelsen d79d551c68 fix Momoka item exchange via menu object 2025-12-25 22:19:54 -08:00
Martin Michelsen 4b43333ce9 fix data race between save timer and client disconnect 2025-12-25 22:19:35 -08:00
Martin Michelsen b228ea847f show enemy type on proxy if debug and fast kills are both on 2025-12-25 14:58:47 -08:00
Martin Michelsen 4d97bdec7f fix type in compute_all_valid_primary_identifiers 2025-12-25 14:57:41 -08:00
Martin Michelsen 8133b20598 add battle param reload bugfix 2025-12-23 09:09:49 -08:00
Martin Michelsen 73ced9d229 print bank when team reward is given 2025-12-23 09:09:38 -08:00
Martin Michelsen 6e765fe1ed clarify comment in PSOV2Encryption::single 2025-12-23 09:09:20 -08:00
Martin Michelsen 26f9b90ef8 fix line numbers around .only_versions 2025-12-23 09:08:51 -08:00
Martin Michelsen 668c687d68 remove unused argument 2025-12-22 00:46:56 -08:00
Martin Michelsen 87b048dc15 implement PSOV2Encryption::single 2025-12-22 00:14:22 -08:00
Martin Michelsen ea23f18aa2 use amount in 6xCC handler 2025-12-21 21:22:28 -08:00
Martin Michelsen a0a7231d67 reformat remaining files 2025-12-21 21:15:49 -08:00
Martin Michelsen e5a03b7e9b move weights sum out of loops in materialize_random_sections 2025-12-21 14:58:10 -08:00
Martin Michelsen a013b8c9d3 reformat more files 2025-12-21 14:57:53 -08:00
Martin Michelsen 894ac6b8ff reformat more files; add Ep3 map endpoint in HTTP server 2025-12-21 10:35:41 -08:00
Martin Michelsen a462a774f5 reformat more files 2025-12-20 21:55:32 -08:00
Martin Michelsen a9fa138213 add MapFile::serialize 2025-12-20 18:52:45 -08:00
Martin Michelsen 0a4c9a0a61 document sorted restriction on random enemy room entries 2025-12-19 21:44:55 -08:00
Martin Michelsen f99bba67d0 update TObjAreaWarpQuest notes 2025-12-19 01:14:14 -08:00
Martin Michelsen 849cca37c8 add explanation in expr field in cards.html 2025-12-19 00:11:09 -08:00
Martin Michelsen 9ebaaacd46 reformat DCSerialNumbers 2025-12-19 00:10:36 -08:00
Martin Michelsen c1968dad27 document TObjRoomId 2025-12-17 23:49:09 -08:00
Martin Michelsen 2732f9c9f8 document materialize-map command 2025-12-17 23:48:00 -08:00
Martin Michelsen 1bd2e6cf62 add challenge location limit override patch 2025-12-12 14:51:43 -08:00
Martin Michelsen 1ab7a851be simulate arithmetic opcodes in quest script analysis 2025-12-11 00:20:55 -08:00
Martin Michelsen 342b4df8c4 add action for debugging random enemy sections 2025-12-11 00:20:39 -08:00
Martin Michelsen 8953ffc2b5 add slow gibbles fix code 2025-12-08 20:10:15 -08:00
Martin Michelsen af796a418a add another AR code 2025-12-08 20:10:15 -08:00
Martin Michelsen 60203bdfba fix formatting in EnemyType.cc 2025-12-07 18:07:23 -08:00
Martin Michelsen 6677908354 reformat Map.cc/hh 2025-12-07 16:44:08 -08:00
Martin Michelsen 96079700f7 fix SetDataTable formatting 2025-12-06 22:05:35 -08:00
Martin Michelsen 976a281e93 update formatting in src/Episode3 2025-12-06 00:18:53 -08:00
Martin Michelsen 6291e42ba9 make 04E8 handler match the client's logic 2025-12-05 19:53:09 -08:00
Martin Michelsen a89423e9f5 reformat CommandFormats and DataIndexes 2025-12-05 19:52:49 -08:00
Martin Michelsen 81169ba9d3 add lobby arrow AR codes 2025-12-05 19:51:58 -08:00
Martin Michelsen e715a8461a fix comment in EnableRandomEnemies include 2025-12-05 15:39:34 -08:00
Martin Michelsen 1ee6b21398 add warning if random enemy location count is too large 2025-12-05 15:39:25 -08:00
Martin Michelsen 9524020aaa improve disassembly for random enemy sections 2025-12-03 21:49:44 -08:00
Martin Michelsen 194bb5b393 actually enforce NOCOMMIT tags finally 2025-12-02 21:46:58 -08:00
Martin Michelsen 779ec9df3b add EnableRandomEnemies include 2025-12-02 21:07:47 -08:00
Martin Michelsen 82ed175a5c add param5 note for TObjCityMapWarp 2025-12-02 00:03:57 -08:00
Martin Michelsen 68f96129fe remove stray debug print 2025-12-02 00:03:31 -08:00
Martin Michelsen c482324a97 use area instead of floor during map construction 2025-11-30 23:12:55 -08:00
Martin Michelsen 800c70c401 skip non-BB clients in 6xC8 handler 2025-11-30 17:31:13 -08:00
Martin Michelsen f26c543977 handle extra data after quest label table 2025-11-30 11:56:20 -08:00
Martin Michelsen 23e31749e9 add transcode-text action 2025-11-30 11:56:20 -08:00
Martin Michelsen ad91b6f6b7 update some boss command notes 2025-11-30 08:50:11 -08:00
Martin Michelsen 2c333b51d2 add $fastkill command 2025-11-29 12:12:34 -08:00
Martin Michelsen 80f8ee1b09 fix flags in Account::str 2025-11-29 09:47:36 -08:00
Martin Michelsen 1498a6e68d fix meta.quest_number check 2025-11-28 15:02:28 -08:00
Martin Michelsen 1fc313505a use test config for quest compiler test 2025-11-28 14:47:51 -08:00
Martin Michelsen 435ac82c18 define most of the remining fields in BB extended quest header 2025-11-28 14:36:13 -08:00
Martin Michelsen 7ec267a7c0 fix solo quest unlock flags 2025-11-28 14:22:16 -08:00
Martin Michelsen 81293255b5 fix more quest metadata 2025-11-28 14:22:07 -08:00
Martin Michelsen 4fe225a302 fix multiple bugs in quest assembler 2025-11-28 12:41:42 -08:00
Martin Michelsen 3ef91b0159 allow whitespace in create item masks 2025-11-28 12:41:42 -08:00
Martin Michelsen e02a006b60 add support for cross-episode quests 2025-11-28 12:40:14 -08:00
Martin Michelsen 23eb6b29a5 fix metadata on more quests 2025-11-28 12:33:28 -08:00
Martin Michelsen afe48e7034 ignore .dec files 2025-11-27 21:06:00 -08:00
Martin Michelsen bd1cdfdb97 further improve quest assembler/disassembler matching 2025-11-26 23:06:04 -08:00
Martin Michelsen a783177420 rewrite quest disassembler for better consistency with assembler 2025-11-25 23:41:46 -08:00
Martin Michelsen 9d42f849c5 fix metadata in solo quest headers 2025-11-25 23:26:24 -08:00
Martin Michelsen 566de06fd1 rewrite quest disassembler 2025-11-24 01:03:24 -08:00
Martin Michelsen 474ad99396 document how wave events work 2025-11-23 17:35:52 -08:00
Martin Michelsen b53847d1b5 update .gitignore 2025-11-23 17:35:38 -08:00
Martin Michelsen d827c1bf5d fix random enemy definitions count check; closes #723 2025-11-20 08:31:43 -08:00
Martin Michelsen 886daa5880 add .evt to patch instructions in readme 2025-11-20 08:29:50 -08:00
Martin Michelsen cc72092b05 write 59NJ version of MomokaItemExchangeFix 2025-11-19 22:27:26 -08:00
362 changed files with 82835 additions and 17882 deletions
+24 -12
View File
@@ -2,19 +2,20 @@
.DS_Store
# Build products
src/Revision.cc
newserv
newserv.exe
src/Revision.cc
# CMake files
build
cmake_install.cmake
CMakeCache.txt
CMakeFiles
CTestTestFile.cmake
CTestTestfile.cmake
CTestTestFile.cmake
install_manifest.txt
Makefile
Testing
build
# Files modified by the user and/or server that don't have defaults
system/config.json
@@ -23,25 +24,36 @@ system/ep3/battle-records/*.mzrd
system/ep3/tournament-state.json
system/licenses.nsi
system/licenses/*.json
system/patch-bb/.metadata-cache.json
system/patch-pc/.metadata-cache.json
system/players/*.nsa
system/players/*.nsc
system/players/*.psobank
system/players/*.psocard
system/players/*.psochar
system/players/*.psosys
system/players/*.psocard
system/players/*.nsc
system/players/*.nsa
system/teams/*.json
system/teams/*.bmp
system/patch-pc/.metadata-cache.json
system/patch-bb/.metadata-cache.json
system/teams/*.json
# Files fuzziqersoftware uses that don't make sense to be committed to the main
# repository
*.dec
*.WIP-s
files
make_release.py
notes-private
old-khyller
old-newserv
release
release.zip
system/patch-bb/data
system/patch-bb/psobb.pat
all-quests
system/dol
system/patch-bb/data
system/client-functions/Debug-Private
system/config.2.json
system/ep3/banners
system/ep3/cardtex
system/ep3/cardtex-trial
system/players
system/quests/includes
system/quests/private
.vscode
+6 -4
View File
@@ -97,6 +97,7 @@ set(SOURCES
src/LevelTable.cc
src/Lobby.cc
src/Loggers.cc
src/MagEvolutionTable.cc
src/Main.cc
src/Map.cc
src/Menu.cc
@@ -134,11 +135,12 @@ set(SOURCES
add_executable(newserv ${SOURCES})
target_include_directories(newserv PUBLIC ${ASIO_INCLUDE_DIR} ${Iconv_INCLUDE_DIRS})
target_link_libraries(newserv phosg::phosg ${Iconv_LIBRARIES} pthread resource_file::resource_file)
target_link_libraries(newserv phosg::phosg ${Iconv_LIBRARIES} resource_file::resource_file)
if (WIN32)
target_compile_definitions(newserv PUBLIC -DWINVER=0x0A00 -D_WIN32_WINNT=0x0A00)
target_link_libraries(newserv ws2_32 mswsock bcrypt iphlpapi -static -static-libgcc -static-libstdc++)
target_compile_options(newserv PRIVATE -Wa,-mbig-obj)
target_compile_definitions(newserv PUBLIC WINVER=0x0A00 _WIN32_WINNT=0x0A00)
target_compile_options(newserv PRIVATE -Wa,-mbig-obj -Wno-mismatched-new-delete)
target_link_options(newserv PRIVATE -static -static-libgcc -static-libstdc++)
target_link_libraries(newserv ws2_32 mswsock bcrypt iphlpapi)
endif()
add_dependencies(newserv newserv-Revision-cc)
+17 -905
View File
@@ -1,921 +1,33 @@
# newserv <img align="right" src="static/s-newserv.png" />
# PSO Peeps newserv
newserv is a game server, proxy, and reverse-engineering tool for Phantasy Star Online (PSO). **To quickly get started using newserv, just read the [server setup](#server-setup) and [how to connect](#how-to-connect) sections.**
This is the PSO Peeps maintained version of [newserv](https://github.com/fuzziqersoftware/newserv), a game server, proxy, and reverse-engineering tool for Phantasy Star Online.
This project includes code that was reverse-engineered by the community in ages long past, and has been included in many projects since then. It also includes some game data from Phantasy Star Online itself, which was originally created by Sega.
The original project was created by fuzziqersoftware and contains years of reverse-engineering, documentation, and implementation work for PSO. This repository keeps that work as the foundation while carrying local changes used by PSO Peeps.
Feel free to submit GitHub issues if you find bugs or have feature requests. I'd like to make the server as stable and complete as possible, but I can't promise that I'll respond to issues in a timely manner, because this is a personal project undertaken primarily for the fun of reverse-engineering. If you want to contribute to newserv yourself, pull requests are welcome as well.
For the original upstream project, see:
See TODO.md for a list of known issues and future work I've curated, or go to the GitHub issue tracker for issues and requests submitted by the community.
https://github.com/fuzziqersoftware/newserv
**Table of contents**
* Background
* [History](#history)
* [Other server projects](#other-server-projects)
* [Using newserv in other projects](#using-newserv-in-other-projects)
* [Contributing to newserv](#contributing-to-newserv)
* [Compatibility](#compatibility)
* Setup
* [Server setup](#server-setup)
* [Client patch directories for PC and BB](#client-patch-directories)
* [How to connect](#how-to-connect)
* Features and configuration
* [User accounts](#user-accounts)
* [Installing quests](#installing-quests)
* [Item tables and drop modes](#item-tables-and-drop-modes)
* [Cross-version play](#cross-version-play)
* [Server-side saves](#server-side-saves)
* [Episode 3 features](#episode-3-features)
* [Memory patches, client functions, and DOL files](#memory-patches-and-client-functions)
* [Using newserv as a proxy](#using-newserv-as-a-proxy)
* [Chat commands](#chat-commands)
* [REST API](#rest-api)
* [Non-server features](#non-server-features)
## About this repository
# History
This repository is used for PSO Peeps server development and deployment. Changes here may include server configuration support, compatibility fixes, event behavior, gameplay experiments, operational tooling, and other changes specific to PSO Peeps.
The history of this project essentially mirrors my development as a software engineer from the beginning of my hobby until now. If you don't care about the story, skip to the "Compatibility" or "Setup" sections below.
Some changes may not be appropriate for upstream newserv or for general newserv deployments.
I originally purchased PSO GC when I heard about PSUL, and wanted to play around with running homebrew on my GameCube. This pathway eventually led to [GCARS-CS](https://github.com/fuzziqersoftware/gcars-cs), but that's another story.
## Original README
<img align="left" src="static/s-khyps.png" /> After playing PSO for a while, both offline and online, I wrote a proxy called Khyps sometime in 2003. This was back in the days of the official Sega servers, where vulnerabilities weren't addressed in a timely manner or at all. It was common for malicious players using their own proxies or Action Replay codes (a story for another time) to send invalid commands that the servers would blindly forward, and cause the receiving clients to crash. These crashes were more than simply inconvenient; they could also corrupt your save data, destroying the hours of work you may have put into hunting items and leveling up your character.
A copy of the upstream README is preserved here:
For a while it was essentially necessary to use a proxy to go online at all, so the proxy could block these invalid commands. Khyps was designed primarily with this function in mind, though it also implemented some convenient cheats, like the ability to give yourself or other players infinite HP and allow you to teleport to different places without using an in-game teleporter.
[docs/upstream-README.md](docs/upstream-README.md)
<img align="left" src="static/s-khyller.png" /> After Khyps I took on the larger challenge of writing a server, which resulted in Khyller sometime in 2005. This was the first server of any type I had ever written. This project eventually evolved into a full-featured environment supporting all versions of the game that I had access to - at the time, PC, GC, and BB. (However, I suspect from reading the ancient source files that Khyller's BB support was very buggy.) As Khyller evolved, the code became increasingly cumbersome, littered with debugging filth that I never cleaned up and odd coding patterns I had picked up over the years. My understanding of the C++ language was woefully incomplete as well (as opposed to now, when it is still incomplete but not woefully so), which resulted in Khyller being essentially a C project that had a couple of classes in it.
That document contains the original newserv history, setup notes, compatibility information, connection instructions, feature documentation, and technical reference material.
<img align="left" src="static/s-aeon.png" /> Sometime in 2006 or 2007, I abandoned Khyller and rebuilt the entire thing from scratch, resulting in Aeon. Aeon was substantially cleaner in code than Khyller but still fairly hard to work with, and it lacked a few of the more arcane features I had originally written (for example, the ability to convert any quest into a download quest). In addition, the code still had some stability problems... it turns out that Aeon's concurrency primitives were simply incorrect. I had derived the concept of a mutex myself, before taking any real computer engineering classes, but had implemented it incorrectly. I made the race window as small as possible, but Aeon would still randomly crash after running seemingly fine for a few days.
## Building
At the time of its inception, Aeon was also called newserv, and you may find some beta releases floating around the Internet with filenames like `newserv-b3.zip`. I had released betas 1, 2, and 3 before I released the entire source of beta 5 and stopped working on the project when I went to college. This was around the time when I switched from writing software primarily on Windows to primarily on macOS and Linux, so Aeon beta 5 was the last server I wrote that specifically targeted Windows. (newserv, which you're looking at now, is difficult to compile on Windows but does work.)
Build instructions are currently the same as upstream unless noted otherwise. See the original README for dependency and build details.
<img align="left" src="static/s-newserv.png" /> After a long hiatus from PSO and much professional and personal development in my technical abilities, I was reminiscing sometime in October 2018 by reading my old code archives. Somehow inspired when I came across Aeon, I spent a weekend and a couple more evenings rewriting the entire project again, cleaning up ancient patterns I had used eleven years ago, replacing entire modules with simple STL containers, and eliminating even more support files in favor of configuration autodetection. The code is now suitably modern and stable, and I'm not embarrassed by its existence, as I am by Aeon beta 5's source code and my archive of Khyller (which, thankfully, no one else ever saw).
## License and attribution
## Other server projects
This project remains based on newserv by fuzziqersoftware.
Independently of this project, there are many other PSO servers out there. Those that I know of that are (or were) public are listed here in approximate chronological order:
* (Early 2000s) **[Schtserv](https://schtserv.com/)**: The first public-access PSO server, written in Delphi by Schthack. Schtserv is the only other unofficial server to support Episode 3, their implementation of which is based on newserv's (which is based on Sega's).
* (2005) **Khyller**: An early attempt of mine to support PSO PC, GC, and BB. See above for more details.
* (2006) **Aeon**: My second attempt. Better than Khyller, but still unreliable.
* (2008) **Tethealla**: A fairly extensive implementation of PSOBB, written in C by Sodaboy. The public version of Tethealla has been [officially disowned](https://www.pioneer2.net/community/threads/tethealla-server-forums-removal.26365/) as it is now more than 15 years old, but closed-source development continues. [Ephinea](https://ephinea.pioneer2.net/) is the continuation of this project. Several other modern PSOBB servers are forks of the initial public version of Tethealla as well.
* (2008) **[Sylverant](https://sylverant.net/)** [(source)](https://sourceforge.net/projects/sylverant/): The second public-access PSO server, written in C by BlueCrab.
* (2015) **[Archon](https://github.com/dcrodman/archon)**: A PSOBB server written in Go by Drew Rodman.
* (2015) **[Idola](https://github.com/HybridEidolon/idolapsoserv)**: A PSOBB server written in Rust by HybridEidolon. Functionality status unknown; the project has been archived.
* (2017) **[Aselia](https://github.com/Solybum/Aselia)**: A PSOBB server written in C# by Soly. It seems this was planned to be open-source at some point, but that has not (yet) happened.
* (2018) **newserv**: This project right here.
* (2019) **[Mechonis](https://gitlab.com/sora3087/mechonis)**: A PSOBB server with a microservice architecture written in TypeScript by TrueVision.
* (2020) **[Booma.Server](https://github.com/HelloKitty/Booma.Server)**: A PSOBB server written in C# by Glader, with Soly's help.
* (2021) **[Phantasmal World](https://github.com/DaanVandenBosch/phantasmal-world)**: A set of PSO tools, including a web-based model viewer and quest builder, and a PSO server, written by Daan Vanden Bosch.
* (2021) **[Elseware](http://git.sharnoth.com/jake/elseware)**: A PSOBB server written in Rust by Jake.
## Using newserv in other projects
You are free to use code from newserv in your own open-source projects; the only condition is that the contents of the LICENSE file must be included in your project if you use code from newserv. Your project does not also have to use the MIT license; you can use any license you want.
If you want to use parts of newserv in your project, there are two easy ways to do so with proper licensing:
* If you're using a lot of code from newserv, you can put a copy of newserv's LICENSE file in your repository alongside your own license file, or include the contents of newserv's license in your own license file.
* If you're only using a few files from newserv, you can copy and paste the contents of the LICENSE file into a comment at the beginning of each copied file.
Some of the more likely useful files are:
* **src/CommandFormats.hh**: Complete listing of all network commands used in all known versions of the game, and their formats
* **src/CommonItemSet.hh/cc**: Format of ItemPT files, shop definition files, and tekker adjustment tables
* **src/DCSerialNumbers.hh/cc**: PSO DC serial number validation algorithm and serial number generator
* **src/ItemData.hh**: Item format reference
* **src/ItemCreator.hh/cc**: Reverse-engineered item generator from Episodes 1&2 (used for all versions)
* **src/ItemParameterTable.hh**: Format of many structures in ItemPMT.prs
* **src/Map.hh/cc**: Map file (.dat) structure, listing of object/enemy types and parameters, and reverse-engineered Challenge Mode random enemy generation algorithm
* **src/QuestScript.cc**: Complete listing of all quest opcodes on all versions, along with their arguments and behavior
* **src/RareItemSet.hh/cc**: Format of ItemRT files (rare item drop tables)
* **src/SaveFileFormats.hh**: Definitions of save file structures for all versions
* **src/Episode3/DataIndexes.hh**: Episode 3 file structures, including card definition format and map/quest format
* **system/item-tables/names-v4.json**: Names of all items, indexed by the first 3 bytes of data1
## Contributing to newserv
The goals of this project are:
* Build stable, extensible PSO server software that includes all vanilla functionality as well as optional modern conveniences, features, and cheats.
* Document the internals of PSO's network protocol, file formats, and game mechanics. This is mainly done through comments in the code.
This is a personal project; there is no official development team, official website, or official instance of newserv. Issues and pull requests are certainly welcome, but please only add content (e.g. quests or patches) that you've created, is already public, or you have permission to release publicly.
# Compatibility
newserv supports all known versions of PSO, including various development prototypes. This table lists all versions that newserv supports. (NTE stands for Network Trial Edition; the GameCube beta versions were called Trial Edition instead, but we use the NTE abbreviation anyway for consistency.)
| Version | Lobbies | Games | Proxy |
|-----------------|----------|----------|----------|
| DC NTE | Yes | Yes | Yes |
| DC 11/2000 | Yes | Yes | Yes |
| DC 12/2000 | Yes | Yes | Yes |
| DC 01/2001 | Yes | Yes | Yes |
| DC V1 | Yes | Yes | Yes |
| DC 08/2001 | Yes | Yes | Yes |
| DC V2 | Yes | Yes | Yes |
| PC NTE | Yes (1) | Yes | Yes |
| PC | Yes | Yes | Yes |
| GC Ep1&2 NTE | Yes | Yes | Yes |
| GC Ep1&2 | Yes | Yes | Yes |
| GC Ep1&2 Plus | Yes | Yes | Yes |
| GC Ep3 NTE | Yes | Yes (2) | Yes |
| GC Ep3 | Yes | Yes | Yes |
| Xbox Ep1&2 Beta | Yes (3) | Yes (3) | Yes (3) |
| Xbox Ep1&2 | Yes (3) | Yes (3) | Yes (3) |
| BB (vanilla) | Yes | Yes | Yes |
| BB (Tethealla) | Yes | Yes | Yes |
*Notes:*
1. *This is the only version of PSO that doesn't have any way to identify the player's account - there is no serial number or username. For this reason, AllowUnregisteredUsers must be enabled in config.json to support PC NTE, and PC NTE players receive a random Guild Card number every time they connect. To prevent abuse, PC NTE support can be disabled in config.json.*
2. *Episode 3 NTE battles are not well-tested; some things may not work. See notes/ep3-nte-differences.txt for a list of known differences between NTE and the final version. NTE and non-NTE players cannot battle each other.*
3. *PSO Xbox connects through Xbox Live, so you can't easily host a private server for this version of the game. See the [How to connect](#pso-xbox) section.*
# Setup
## Server setup
Currently newserv works on macOS, Windows, and Ubuntu Linux. It will likely work on other Linux flavors too.
### Windows/macOS
1. Download the latest release.zip file from the [releases page](https://github.com/fuzziqersoftware/newserv/releases).
2. Extract the contents of the archive to some location on your computer.
3. Go into the system/ folder, open config.json in a text editor, and edit it to your liking. There are comments in the file that describe what all the options do. Most of the options can be left alone if you want default behavior, but on Windows, you must change LocalAddress and ExternalAddress.
4. (Optional) If you plan to play Blue Burst on newserv, set up the patch directory. See [client patch directories](#client-patch-directories) for details.
5. Run the newserv executable.
### Linux
There are currently no precompiled releases for Linux. To run newserv on Linux, you'll have to build it from source - see the section below.
### Building from source (macOS/Linux)
To build on macOS or Linux:
1. Install the dependencies needed for your platform:
* macOS: `brew install cmake asio libiconv`
* Linux: `sudo apt-get install cmake libasio-dev` (or use your Linux distribution's package manager)
2. Build and install [phosg](https://github.com/fuzziqersoftware/phosg) and [resource_dasm](https://github.com/fuzziqersoftware/resource_dasm).
3. Run `cmake . && make` in the newserv directory.
After building newserv, edit system/config.example.json as needed **and rename it to system/config.json** (note that this step is not necessary for the precompiled releases), set up [client patch directories](#client-patch-directories) if you're planning to play Blue Burst, then run `./newserv` in newserv's directory.
The server has an interactive shell which can be used to make changes, such as managing user accounts, updating the server's configuration, managing Episode 3 tournaments, and more. Type `help` and press Enter to see all the commands.
On Linux and macOS, the server also responds to SIGUSR1 and SIGUSR2. SIGUSR1 does the equivalent of the shell's `reload config` command, which reloads config.json but not any dependent files (so quests, Episode 3 maps, etc. will not be reloaded). SIGUSR2 does the equivalent of the shell's `reload all` command, which reloads everything.
To use newserv in other ways (e.g. for translating data), see the end of this document.
### Building from source (Windows)
The current version of newserv is cross-compiled using mingw-w64 on a macOS build machine, with the necessary libraries manually installed. Setting up such a build environment is tedious and not recommended; it's recommended to just use a release version instead.
Here is a rough outline of the Windows build process. You should only attempt this yourself if you're familiar with setting up build environments and can deal with issues you may encounter along the way.
1. Install recent versions of MinGW and CMake.
2. Build and install zlib, libiconv, asio, phosg, and resource_dasm into your MinGW environment.
3. Clone the newserv repository with symlinks enabled: `git clone -c core.symlinks=true https://github.com/fuzziqersoftware/newserv.git`
4. Build newserv via CMake.
## Client patch directories
newserv implements a patch server for PSO PC and PSO BB game data. Any file or directory you put in the system/patch-bb or system/patch-pc directories will be synced to clients when they connect to the patch server.
For Blue Burst set up, the below is mandatory for a smooth experience:
1. Browse to your chosen client's data directory.
2. Copy all the `map_*.dat` files, `unitxt_*` files and the `data.gsl` file and place them in `system/patch-bb/data`.
3. If you're using game files from the Tethealla client, make a copy of `unitxt_j.prs` inside system/patch-bb/data and name it `unitxt_e.prs`. (If `unitxt_e.prs` already exists, replace it with the copied file.)
If you don't have a BB client, or if you're using a Tethealla client from another source, Tethealla clients that are compatible with newserv can be found here: [English](https://web.archive.org/web/20240402011115/https://ragol.org/files/bb/TethVer12513_English.zip) / [Japanese](https://web.archive.org/web/20240402013127/https://ragol.org/files/bb/TethVer12513_Japanese.zip). These clients connect to 127.0.0.1 (localhost) automatically.
For BB clients, newserv reads some files out of the patch data to implement game logic, so it's important that certain game files are synchronized between the server and the client. newserv contains defaults for these files in the system/maps/bb-v4 directory, but if these don't match the client's copies of the files, odd behavior will occur in games.
To make server startup faster, newserv caches the modification times, sizes, and checksums of the files in the patch directories. If the patch server appears to be misbehaving, try deleting the .metadata-cache.json file in the relevant patch directory to force newserv to recompute all the checksums. Also, in the case when checksums are cached, newserv may not actually load the data for a patch file until it's needed by a client. Therefore, modifying any part of the patch tree while newserv is running can cause clients to see an inconsistent view of it.
Patch directory contents are cached in memory. If you've changed any of these files, you can run `reload patch-indexes` in the interactive shell to make the changes take effect without restarting the server.
## How to connect
### PSO DC
Depending on the version of PSO DC that you have, the instructions to connect to a newserv instance will vary.
If you have NTE, USv1, EUv1, or EUv2 and a Broadband Adapter, edit the broadband DNS address to newserv's IP address with newserv's DNS server running. Otherwise, it is necessary to patch the disc or use a codebreaker code to remove the Hunter License server check and/or redirect PSO to the newserv instance. Patching the disc or creating a codebreaker code is beyond the scope of this document.
### PSO DC on Flycast
If you're emulating PSO DC, the NTE, USv1, EUv1, and EUv2 versions will connect to newserv by setting the following options in Flycast's `emu.cfg` file under `[network]`:
- DNS = Your newserv's server address (newserv's DNS server must be running on port 53)
- EmulateBBA = yes
- Enable = yes
It is also necessary to save any DNS information to the flash memory of the Dreamcast to use the BBA - the easiest way to do this is to use the website option in USv2 and then choose the save to flash option.
If the server is running on the same machine as Flycast, this might not work, even if you point Flycast's DNS queries at your local IP address (instead of 127.0.0.1). In this case, you can modify the loaded executable in memory to make it connect anywhere you want. There is a script included with newserv that can do this on macOS; a similar technique could be done manually using scanmem on Linux or Cheat Engine on Windows. To use the script, do this:
1. Build and install [memwatch](https://github.com/fuzziqersoftware/memwatch).
2. Start Flycast and run PSO. (You must start PSO before running the script; it won't work if you run the script before loading the game.)
3. Run `sudo patch_flycast_memory.py <original-destination>`. Replace `<original-destination>` with the hostname that PSO wants to connect to (you can find this out by using Wireshark and looking for DNS queries). The script may take up to a minute; you can continue using Flycast while it runs, but don't start an online game until the script is done.
4. Run newserv and start an online game in PSO.
If you use this method, you'll have to run the script every time you start PSO in Flycast, but you won't have to run it again if you start another online game without restarting emulation.
If using JPv1, JPv2, or USv2, it is also necessary to remove the Hunter Licence server check, either with a disc patch or codebreaker code. Patching the disc or creating a codebreaker code is beyond the scope of this document.
### PSO PC
PSO PC has its connection addresses in `pso.exe`. Hex edit the executable with the connection address you want to connect to. Common server addresses to search for to replace are:
- pso20.sonic.isao.net
- sg207634.sonicteam.com
- pso-mp01.sonic.isao.net
- gsproduc.ath.cx
- sylverant.net
The version of PSO PC I have has the server addresses starting at offset 0x29CB34 in pso.exe. Change those addresses to "localhost" (without quotes) if you just want to connect to a locally-running newserv instance. Alternatively, you can add an entry to the Windows hosts file (C:\Windows\System32\drivers\etc\hosts) to redirect the connection to 127.0.0.1 (localhost) or any other IP address.
### PSO GC on a real GameCube
You can make PSO connect to newserv by setting the default gateway and DNS server addresses in the game's network settings to newserv's address. newserv's DNS server must be running on port 53 and must be accessible to the GameCube. If you're not playing PSO Plus or Episode III, this should be all you need to do, assuming you already set LocalAddress in config.json to your PC's private IP address.
If you have PSO Plus or Episode III, it won't want to connect to a server on the same local network as the GameCube itself, as determined by the GameCube's IP address and subnet mask. There are a couple of ways to get around this.
Sodaboy described a fairly easy method, which is to forward the PSO and DNS ports in your router's configuration to your PC's private IP address (the PSO ports are in config.json, and are all TCP; the DNS port is 53 and is UDP). Then, set LocalAddress and ExternalAddress in config.json to your external IP address (from e.g. whatismyip.com). Most routers will let you connect to your public IP address even from within the local network, but the GameCube will think it's connecting to a different network, so it won't reject the connection. If you're concerned about security and don't want your server to be publicly accessible, you can use Windows Firewall or UFW on Linux block incoming connections on the ports you opened, except for connections from the IP addresses you specify.
Another method is to use two network interfaces on the same PC, and tell the GameCube to connect to the one that appears to be on a different network. For example, if your GameCube is on the 10.0.0.x subnet and your PC's address is 10.0.0.5, you can create a fake network adapter on your PC (or use an existing real one) that has an IP address on a different subnet than the GameCube, such as 192.168.0.8. Then, in PSO's network config, set the default gateway and DNS server addresses to 192.168.0.8, and set LocalAddress in config.json to 192.168.0.8, and PSO should connect. This is what I did back in the old days when I primarily developed software on Windows, but I haven't tried it in many years.
### PSO GC on a Wii or Wii U
Using a Wii or Wii U to connect to newserv requires the Wii or vWii to be softmodded. How to do this is beyond the scope of this document.
Nintendont includes BBA emulation and is compatible with all PSO GameCube versions except Episodes I&II Trial Edition. To use Nintendont, enable BBA emulation in Nintendont's settings and follow the instructions in the above section (PSO GC on a real GameCube).
Devolution includes modem emulation and is compatible with all PSO GameCube versions including Episodes I&II Trial Edition. newserv can act as a PPP server, which Devolution can directly connect to. To do this:
1. Enable the PPPRawListen option according to the comments in config.json.
2. Start newserv.
3. In the game's network settings, set the username and password to anything (they cannot be blank), and set the phone number to the number that newserv outputs to the console during startup. (It will be near the end of all the startup log messages.) If your Wii is on the same network as newserv, use the local number; otherwise, use the external number.
### PSO GC on Dolphin
If you're using the HLE BBA type, set the BBA's DNS server address to newserv's IP address and it should work. (If newserv is on the same machine as Dolphin, you will need to use an Action Replay code directed at 127.0.0.1 to connect, as PSO rejects DNS queries from the same IP address.) Set PSO's network settings the same as listed below.
If you're using the TAP (not tapserver) BBA type, you'll have to set PSO's network settings appropriately for your tap interface. Set the DNS server address in PSO's network settings to newserv's IP address.
If you're using the tapserver BBA or modem type, you can make it connect to a newserv instance running on the same machine via the tapserver interface. To do this:
1. In the GameCube pane of the Config window, set the SP1 device to Broadband Adapter (tapserver) or Modem Adapter (tapserver).
2. Click the "..." button next to the SP1 menu. If you're using the tapserver BBA, enter `127.0.0.1:5059` in the box. If you're using the tapserver modem, enter `127.0.0.1:5058` in the box. (If newserv isn't running on the same machine as Dolphin, replace 127.0.0.1 with newserv's IP address.)
3. In PSO's network settings, enable DHCP ("Automatically obtain an IP address"), set DNS server address to "Automatic", and leave DHCP Hostname as "Not set". Leave the proxy server settings blank.
4. Start an online game.
### PSO Xbox
Unfortunately, you can't easily host a private server for PSO Xbox because the Xbox version of the game tunnels its connections through Xbox Live. There is a modern replacement for Xbox Live named [Insignia](https://insignia.live/), which supports the three main PSO Xbox servers, but as of now does not support other private PSO servers.
### PSO BB
The PSO BB client has been modified and distributed in many different forms. newserv supports most, but not all, of the common distributions. Unlike other versions, it's common for various BB clients to have different map files. It's important that the client and server have the same map files, so make sure to set up the patch directory based on the client you'll be using with newserv. (See the [client patch directories](#client-patch-directories) section for instructions on setting this up.)
The original Japanese and US versions of PSO BB work with newserv (the last Japanese release can be found [here](https://archive.org/details/psobb_jp_setup_12511_20240109/)). To get them to connect to your server, do one of the following:
* Use a drop-in patcher like [AzureFlare](https://github.com/Repflez/AzureFlare).
* Edit your hosts file to redirect the client's destination address to localhost or your server's address.
* Edit psobb.exe to point to your newserv instance. The original clients are packed with various versions of ASProtect, so this is a more involved process than simply opening the executable in a hex editor and finding/replacing some strings.
Alternatively, you can use the Tethealla client ([English](https://web.archive.org/web/20240402011115/https://ragol.org/files/bb/TethVer12513_English.zip) or [Japanese](https://web.archive.org/web/20240402013127/https://ragol.org/files/bb/TethVer12513_Japanese.zip)). If the server is on the same PC as the client and you don't plan to have any external players, these Tethealla clients will automatically connect to the server without any modifications. This version of the client is not packed, and you can find the connection addresses starting at offset 0x56D724 in psobb.exe. Overwrite these addresses with your server's hostname or IP address, and you should be able to connect.
### Allowing external players to connect
If you want to accept connections from outside your local network, you'll need to set ExternalAddress to your public IP address in the configuration file, and you'll likely need to open some ports in your router's NAT configuration - specifically, all the TCP ports listed in PortConfiguration in config.json.
For GC clients, you'll have to use newserv's built-in DNS server or set up your own DNS server as well. If you want external clients to be able to use your DNS server, you'll have to forward UDP port 53 to your newserv instance. Remote players can then connect to your server by entering your DNS server's IP address in their client's network configuration.
# Server feature configuration
## User accounts
By default, newserv does not require users to pre-register before playing; the server will instead automatically create an account the first time each player connects. These accounts have no special permissions. You can view, create, edit, and delete user accounts in the server's shell (run `help` in the shell to see how to do this).
A license is a set of credentials that a player can use to log in. There are six types of licenses:
* *DC NTE licenses* consist of a 16-character serial number and 16-character access key.
* *DC licenses* consist of an 8-character hex serial number and an 8-character access key.
* *PC licenses* are the same format as DC licenses, but are used for PC v2.
* *GC licenses* consist of a 10-digit decimal serial number, a 12-character access key, and a password of up to 8 characters.
* *XB licenses* consist of a gamertag of up to 16 characters, a 16-character hex user ID, and a 16-character hex account ID.
* *BB licenses* consist of a username of up to 16 characters and a password of up to 16 characters.
Each account may have multiple licenses. To add a license to an existing account, use `add-license` in the shell.
On BB, character data is scoped to the license, but system and Guild Card data is scoped to the account. That is, an account with multiple BB licenses can have more than 4 characters (up to 4 per license), but they will all share the same team membership and Guild Card lists.
You may want to give your account elevated privileges. To do so, run `update-account ACCOUNT-ID flags=root` (replacing ACCOUNT-ID with your actual account-id). You can also use update-account to edit other parts of the account; see the help text for more information.
## Installing quests
newserv automatically finds quests in the subdirectories of the system/quests/ directory. To install your own quests, or to use quests you've saved using the proxy's Save Files option, just put them in one of the subdirectories there and name them appropriately. The subdirectories and their behaviors (e.g. in which game modes they should appear and for which PSO versions) is defined in the QuestCategories field in config.json.
Within the category directories, quest files should be named like `q###-VERSION-LANGUAGE.EXT` (although the `q` is ignored, and can be any letter). The fields in each filename are:
- `###`: quest number (this doesn't really matter; it should just be unique across the PSO version)
- `VERSION`: dn = Dreamcast NTE, dp = Dreamcast 11/2000 prototype, d1 = Dreamcast v1, dc = Dreamcast v2, pcn = PC NTE, pc = PC, gcn = GameCube NTE, gc = GameCube Episodes 1 & 2, gc3 = Episode 3 (see below), xb = Xbox, bb = Blue Burst
- `LANGUAGE`: j = Japanese, e = English, g = German, f = French, s = Spanish
- `EXT`: file extension (see table below)
For .dat files, the `LANGUAGE` token may be omitted. If it's present, then that .dat file will only be used for that language of the quest; if omitted, then that .dat file will be used for all languages of the quest.
For example, the GameCube version of Lost HEAT SWORD is in two files named `q058-gc-e.bin` and `q058-gc.dat`. newserv knows these files are quests because they're in the system/quests/ directory, it knows they're for PSO GC because the filenames contain `-gc`, it knows this is the English version of the quest because the .bin filename ends with `-e` (even though the .dat filename does not), and it puts them in the Retrieval category because the files are within the retrieval/ directory within system/quests/.
Some quests have additional JSON metadata files that describe how the server should handle them. These metadata files are generally named similarly to their .bin and .dat counterparts, except the `VERSION` token may also be omitted if the metadata applies to all languages of the quest on all PSO versions. See the comments in system/quests/retrieval/q058.json for all of the available options and how to use them. Some of the options are:
- Disable or hide the quest if certain preceding quests aren't cleared or other conditions aren't met
- Enable the quest to be joined while in progress
- Override the common and/or rare item tables and set the allowed drop modes
Some quests may also include a .pvr file, which contains an image used in the quest. These files are named similarly to their .bin and .dat counterparts.
The GameCube and Xbox quest formats are very similar, but newserv treats them as different. If you want to use the same quest file for GameCube and Xbox clients, you can make one a symbolic link to the other.
There are multiple PSO quest formats out there; newserv supports all of them. It can also decode any known format to standard .bin/.dat format. Specifically:
| Format | Extension | Supported | Decode action |
|------------------|-----------------------|------------|------------------|
| Compressed | .bin and .dat | Yes | None (1) |
| Compressed Ep3 | .bin or .mnm | Yes (4) | None (1) |
| Uncompressed | .bind and .datd | Yes | compress-prs (2) |
| Uncompressed Ep3 | .bind or .mnmd | Yes (4) | compress-prs (2) |
| Source | .bin.txt and .dat | Yes | None (5) |
| VMS (DCv1) | .bin.vms and .dat.vms | Yes | decode-vms |
| VMS (DCv2) | .bin.vms and .dat.vms | Decode (3) | decode-vms (3) |
| GCI (decrypted) | .bin.gci and .dat.gci | Yes | decode-gci |
| GCI (with key) | .bin.gci and .dat.gci | Yes | decode-gci |
| GCI (no key) | .bin.gci and .dat.gci | Decode (3) | decode-gci (3) |
| GCI (Ep3 NTE) | .bin.gci or .mnm.gci | Decode (3) | decode-gci (3) |
| GCI (Ep3) | .bin.gci or .mnm.gci | Yes | decode-gci |
| DLQ | .bin.dlq and .dat.dlq | Yes | decode-dlq |
| DLQ (Ep3) | .bin.dlq or .mnm.dlq | Yes | decode-dlq |
| QST (online) | .qst | Yes | decode-qst |
| QST (download) | .qst | Yes | decode-qst |
*Notes:*
1. *This is the default format. You can convert these to uncompressed format by running `newserv decompress-prs FILENAME.bin FILENAME.bind` (and similarly for .dat -> .datd)*
2. *Similar to (1), to compress an uncompressed quest file: `newserv compress-prs FILENAME.bind FILENAME.bin` (and likewise for .datd -> .dat)*
3. *Use the decode action to convert these quests to .bin/.dat format before putting them into the server's quests directory. If you know the encryption seed (serial number), pass it in as a hex string with the `--seed=` option. If you don't know the encryption seed, newserv will find it for you, which will likely take a long time.*
4. *Episode 3 quests don't go in the system/quests directory. See the [Episode 3 section](#episode-3-features) section below.*
5. *Quest source can be assembled into a .bin or .bind file with `newserv assemble-quest-script FILENAME.txt`. See system/quests/retrieval/q058-gc-e.bin.txt for an annotated example; this is the English GameCube version of Lost HEAT SWORD.*
Episode 3 download quests consist only of a .bin file - there is no corresponding .dat file. Episode 3 download quest files may be named with the .mnm extension instead of .bin, since the format is the same as the standard map files (in system/ep3/maps/). These files can be encoded in any of the formats described above, except .qst.
When newserv indexes the quests during startup, it will warn (but not fail) if any quests are corrupt or in unrecognized formats.
Quest contents are cached in memory, but if you've changed the contents of the quests directory, you can re-index the quests without restarting the server by running `reload quest-index` in the interactive shell. The new quests will be available immediately, but any games with quests already in progress will continue using the old versions of the quests until those quests end.
## Item tables and drop modes
newserv supports server-side item generation on all game versions, except for the earliest DC prototypes (NTE and 11/2000). By default, the game behaves as it did on the original servers - on all versions except BB, item drops are controlled by the leader client in each game, and on BB, item drops are controlled by the server.
There are five different available behaviors for item drops:
* `disabled` (or `none`): No items will drop from boxes or enemies.
* `client`: The game leader generates items, all items are visible to all players, and any player may pick up any item. This is the default mode for all game versions, except this mode cannot be used if the game leader is on BB.
* `shared`: The server generates items, all items are visible to all players, and any player may pick up any item. This is the default mode if the game leader is on BB.
* `private`: The server generates items, but each player may get a different item from any box or enemy. If a player isn't in the same area as an enemy at the time it's defeated, they won't get any item from it. Items dropped by players are visible to everyone.
* `duplicate`: The server generates items, and each player will get the same item from any box or enemy, but there is one copy of each item for each player (and each player only sees their own copy of the item). If a player isn't in the same area as an enemy at the time it's defeated, they won't get any item from it. Items dropped by players are not duplicated and are visible to everyone.
In the `private` and `duplicate` modes, there is no incentive to pick up items before another player, since other players cannot pick up the items you see dropped from boxes and enemies. However, if you pick up an item and drop it later, it can then be seen and picked up by any player.
The drop mode can be changed at any time during a game with the `$dropmode` chat command. If the mode is changed after some items have already been dropped, the existing items retain their visibility (that is, items dropped in private mode still can't be picked up by other players since they were dropped before the mode was changed). You can configure which drop modes are used by default, and which modes players are allowed to choose, in config.json. See the comments above the AllowedDropModes and DefaultDropMode keys.
In the server drop modes, the item tables used to generate common items are in the `system/item-tables/ItemPT-*` files. (The V2 files are used for V1 as well.) The rare item tables are in the `rare-table-*.json` files. Unlike the original formats, it's possible to make each enemy drop multiple different rare items at different rates, though the default tables never do this.
## Cross-version play
All versions of PSO can see and interact with each other in the lobby. By default, newserv allows V1 and V2 players to play in games together, and allows GC and Xbox players to play in games together. You can change these rules to allow all versions to play in games together, or to prevent versions from playing in games together, with the CompatibilityGroups setting in config.json.
There are several cross-version restrictions that always apply regardless of the compatibility groups setting:
* DC V1 players cannot join DC V2 games if the game creator didn't choose to allow them.
* DC V1 players cannot join games if the difficulty level is set to Ultimate or the game mode is Battle or Challenge.
* Only GC, Xbox, and BB players can join games in Episode 2.
* Only BB players can join games in Episode 4.
* Episode 3 players cannot join non-Episode 3 games, and vice versa.
V1/V2 compatibility and GC/Xbox compatibility are well-tested, but other situations are not. Not much attention has been given yet to how items should be handled across major versions; if you enable V2/GC compatibility, for example, there will likely be bugs. Please report such bugs as GitHub issues.
In cross-version play, when any of the server drop modes are used, the server uses the drop tables corresponding to the leader's version and section ID. (For example, if a DC V1 player is the game leader, rare-table-v1.json will be used, even after V2 players join.) If a BB player is the leader and the `client` drop mode is used, the server generates items as if it were in `shared` mode.
## Server-side saves
newserv has the ability to save character data on the server side. For PSO BB, this is required of course, but this feature can also be used on other PSO versions.
Each account has 4 BB character slots and 16 non-BB character file slots. The non-BB slots are independent of the BB slots, and can be accessed with the `$savechar <slot>` and `$loadchar <slot>` commands (slots are numbered 1 through 16). `$savechar` copies the character you're currently playing as and saves the data on the server, and `$loadchar` does the reverse, overwriting your current character with the data saved on the server. Note that you can load a character that was saved from a different version of PSO, which allows you to easily transfer characters between games. On v1 and v2, changes done by `$loadchar` will be undone if you join a game; to permanently save your changes, disconnect from the lobby after using the command.
You can see basic information about a character saved on the server (without affecting your current character) by using `$checkchar <slot>`. You can delete a previously-saved character with `$deletechar <slot>`.
There is also the command `$bbchar <username> <password> <slot>`, which behaves similarly to `$savechar` but writes the character data to a BB character slot in a different account instead (slots are numbered 1 through 4). This can be used to "upgrade" a character to BB from an earlier version.
Exactly which data is saved and loaded depends on the game version:
| Game | Inventory | Character | Options/chats | Quest flags | Bank | Battle/Challenge |
|----------------------|-----------|-----------|---------------|-------------|------|------------------|
| PSO DC v1 prototypes | Yes | Yes | No | No | No | N/A |
| PSO DC v1 | Yes | Yes | No | No | No | N/A |
| PSO DC v2 | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO PC (v2) | Yes | Yes | No | No | No | Save only |
| PSO GC NTE | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO GC (not Plus) | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO GC Plus (1) | Save only | Save only | No | No | No | Save only |
| PSO GC Ep3 (1) | No | Save only | No | No | No | Save only |
| PSO Xbox | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO BB | Yes | Yes | Yes | Yes | Yes | Yes |
*Notes*:
1. *If EnableSendFunctionCallQuestNumber is enabled in config.json, then $savechar and $loadchar can save and restore all character data on these versions, just like on GC non-Plus. Episode 3 characters exist in a separate namespace; that is, you can't use $savechar and $loadchar to convert an Ep3 character to non-Ep3, or vice versa.*
## Episode 3 features
newserv supports many features unique to Episode 3:
* CARD battles. Not every combination of abilities has been tested yet, so if you find a feature or card ability that doesn't work like it's supposed to, please make a GitHub issue and describe the situation (the attacking card(s), defending card(s), and ability or condition that didn't work).
* Spectator teams.
* Tournaments. (But they work differently than Sega's tournaments did - see below)
* Downloading quests.
* Trading cards.
* Participating in card auctions. (The auction contents must be configured in config.json.)
* Decorations in lobbies. Currently only images are supported; the game also supports loading custom 3D models in lobbies, but newserv does not implement this (yet).
### Battle records
After playing a battle, you can save the record of the battle with the `$saverec` command. You can then replay the battle later by using the `$playrec` command in a lobby - this will create a spectator team and play the recording of the battle as if it were happening in realtime. Note that there is a bug in older versions of Dolphin that seems to be frequently triggered when playing battle records, which causes the emulator to crash with the message `QObject::~QObject: Timers cannot be stopped from another thread`. To avoid this, use the latest version of Dolphin.
### Tournaments
Tournaments work differently than they did on Sega's servers. Tournaments can be created with the `create-tournament` shell command, which enables players to register for them. (Use `help` to see all the arguments - there are many!) The `start-tournament` shell command starts the tournament (and prevents further registrations), but this doesn't schedule any matches. Instead, players who are ready to play their next match can all stand at the 4-player battle table near the lobby warp in the same CARD lobby, and the tournament match will start automatically.
These tournament semantics mean that there can be multiple matches in the same tournament in play simultaneously, and not all matches in a round must be complete before the next round can begin - only the matches preceding each individual match must be complete for that match to be playable.
The Meseta rewards for winning tournament matches can be configured in config.json.
### Episode 3 files
Episode 3 state and game data is stored in the system/ep3 directory. The files in there are:
* card-definitions.mnr: Compressed card definition list, sent to Episode 3 clients at connect time. Card stats and abilities can be changed by editing this file.
* card-definitions.mnrd: Decompressed version of the above. If present, newserv will use this instead of the compressed version, since this is easier to edit.
* card-text.mnr: Compressed card text archive. Generally only used for debugging.
* card-text.mnrd: Decompressed card text archive; same format as TextCardE.bin. Generally only used for debugging.
* com-decks.json: COM decks used in tournaments. The default decks in this file come from logs from Sega's servers, so the file doesn't include every COM deck Sega ever made - the rest are probably lost to time.
* maps/: Online free battle and quest maps (.mnm/.bin/.mnmd/.bind files). newserv comes with the default online maps, as well as some fan-made variations and quests to help new players get up to speed. Within the maps/ directory, each subdirectory is treated as a separate category and may be optionally downloadable or available at the battle setup counter. The category.json file in each subdirectory specifies the category's behavior; see system/ep3/maps/online/category.json for a documented example.
* tournament-state.json: State of all active tournaments. This file is automatically written when any tournament changes state for any reason (e.g. a tournament is created/started/deleted or a match is resolved).
There is no public editor for Episode 3 maps and quests, but the format is described fairly thoroughly in src/Episode3/DataIndexes.hh (see the MapDefinition structure). You'll need to use `newserv decompress-prs ...` to decompress a .bin or .mnm file before editing it, but you don't need to compress it again to use it - just put the .bind or .mnmd file in the maps directory and newserv will make it available.
Like quests, Episode 3 card definitions, maps, and quests are cached in memory. If you've changed any of these files, you can run `reload ep3-cards` or `reload ep3-maps` in the interactive shell to make the changes take effect without restarting the server.
## Memory patches and client functions
You can put assembly files in the system/client-functions directory with filenames like PatchName.VERS.patch.s and they will appear in the Patches menu for clients that support client functions. Client functions are written in SH-4, PowerPC, or x86 assembly and are compiled when newserv is started. The assembly system's features are documented in the comments in system/client-functions/System/WriteMemoryGC.ppc.s.
The VERS token in client function filenames refers to the specific version of the game that the client function applies to. Some versions do not support receiving client functions at all. *Note: newserv uses the shorter GameCube versioning convention, where discs labeled DOL-XXXX-0-0Y are version 1.Y. The PSO community seems to use the convention 1.0Y in some places instead, but these are the same version. For example, the version that newserv calls v1.4 is the same as v1.04, and is labeled DOL-GPOJ-0-04 on the underside of the disc.*
The specific versions are:
| Game | VERS | CPU architecture |
|------------------------------|------|--------------------------------|
| PSO DC Network Trial Edition | 1OJ1 | Client functions not supported |
| PSO DC 11/2000 prototype | 1OJ2 | Client functions not supported |
| PSO DC 12/2000 prototype | 1OJ3 | Client functions not supported |
| PSO DC 01/2001 prototype | 1OJ4 | Client functions not supported |
| PSO DC v1 JP | 1OJF | Client functions not supported |
| PSO DC v1 US | 1OEF | Client functions not supported |
| PSO DC v1 EU | 1OPF | Client functions not supported |
| PSO DC 08/2001 prototype | 2OJ5 | SH-4 |
| PSO DC v2 JP | 2OJF | SH-4 |
| PSO DC v2 US | 2OEF | SH-4 |
| PSO DC v2 EU | 2OPF | SH-4 |
| PSO PC (v2) Trial Edition | 2OJT | Client functions not supported |
| PSO PC (v2) 04/2002 | 2OJW | Client functions not supported |
| PSO PC (v2) 02/2003 | 2OJZ | Client functions not supported |
| PSO GC Trial Edition | 3OJT | PowerPC |
| PSO GC v1.2 JP | 3OJ2 | PowerPC |
| PSO GC v1.3 JP | 3OJ3 | PowerPC |
| PSO GC v1.4 (Plus) JP | 3OJ4 | PowerPC |
| PSO GC v1.5 (Plus) JP | 3OJ5 | PowerPC (1) |
| PSO GC v1.0 US | 3OE0 | PowerPC |
| PSO GC v1.1 US | 3OE1 | PowerPC |
| PSO GC v1.2 (Plus) US | 3OE2 | PowerPC (1) |
| PSO GC v1.0 EU | 3OP0 | PowerPC |
| PSO GC Ep3 Trial Edition | 3SJT | PowerPC |
| PSO GC Ep3 JP | 3SJ0 | PowerPC |
| PSO GC Ep3 US | 3SE0 | PowerPC (1) |
| PSO GC Ep3 EU | 3SP0 | PowerPC (1) |
| PSO Xbox Beta | 4OJB | x86 |
| PSO Xbox JP Disc | 4OJD | x86 |
| PSO Xbox JP TU | 4OJU | x86 |
| PSO Xbox US Disc | 4OED | x86 |
| PSO Xbox US TU | 4OEU | x86 |
| PSO Xbox EU Disc | 4OPD | x86 |
| PSO Xbox EU TU | 4OPU | x86 |
| PSO BB JP 1.25.11 | 59NJ | x86 |
| PSO BB JP 1.25.13 | 59NL | x86 |
| PSO BB Tethealla | 59NL | x86 |
*Notes:*
1. *Client functions are only supported on these versions if EnableSendFunctionCallQuestNumbers is set in config.json. See the comments there for more information.*
newserv comes with a set of patches for many of the above versions. These are organized in subdirectories within system/client-functions/.
### DOL loader
You can put DOL files in the system/dol directory, and they will appear in the Programs menu for GC clients. Selecting a DOL file there will load the file into the GameCube's memory and run it, just like the old homebrew loaders (PSUL and PSOload) did. For this to work, ReadMemoryWordGC.ppc.s, WriteMemoryGC.ppc.s, and RunDOL.ppc.s must be present in the system/client-functions/System directory. This has been tested on Dolphin but not on a real GameCube, so results may vary.
Like other kinds of data, functions and DOL files are cached in memory. If you've changed any of these files, you can run `reload functions` or `reload dol-files` in the interactive shell to make the changes take effect without restarting the server.
I mainly built the DOL loading functionality for documentation purposes. By now, there are many better ways to load homebrew code on an unmodified GameCube, but to my knowledge there isn't another open-source implementation of this method in existence.
## Using newserv as a proxy
If you want to play online on remote servers rather than running your own server, newserv also includes a PSO proxy. Currently this works with PSO GC and may work with PC and DC; it also works with some BB clients in specific situations.
To use the proxy for PSO DC, PC, or GC, add an entry to the corresponding ProxyDestinations dictionary in config.json, then run newserv and connect to it as normal (see below). You'll see a "Proxy server" option in the main menu, and you can pick which remote server to connect to.
To use the proxy for PSO BB, set the ProxyDestination-BB entry in config.json. If this option is set, it essentially disables the game server for all BB clients - all BB clients will be proxied to the specified destination instead. Unfortunately, because PSO BB uses a different set of handlers for the data server phase and character selection, there's no in-game way to present the player with a list of options, like there is on PSO PC and PSO GC.
When you're on PSO DC, PC, GC, or Xbox and are connected to a remote server through newserv's proxy, choosing the Change Ship or Change Block action from the lobby counter will send you back to newserv's main menu instead of the remote server's ship or block select menu. You can go back to the server you were just on by choosing it from the proxy server menu again.
There are many options available when starting a proxy session. All options are off by default unless otherwise noted. The options are:
* **Chat commands**: enables chat commands in the proxy session (on by default).
* **Chat filter**: enables escape sequences in chat messages and info board (on by default).
* **Player notifications**: shows a message when any player joins or leaves the game or lobby you're in.
* **Block pings**: blocks automatic pings sent by the client, and responds to ping commands from the server automatically.
* **Infinite HP**: automatically heals you whenever you get hit. An attack that kills you in one hit will still kill you, however.
* **Infinite TP**: automatically restores your TP whenever you use any technique.
* **Switch assist**: unlocks doors that require two or four players in a one-player game, when you step on one of the switches.
* **Infinite Meseta** (Episode 3 only): gives you 1,000,000 Meseta, regardless of the value sent by the remote server.
* **Block events**: disables holiday events sent by the remote server.
* **Block patches**: prevents any B2 (patch) commands from reaching the client.
* **Save files**: saves copies of several kinds of files when they're sent by the remote server. The files are written to the current directory (which is usually the directory containing the system/ directory). Saved files can then be used with newserv by just moving the file into the appropriate place in the system/ directory and renaming it appropriately. These kinds of files can be saved:
* Online quests and download quests (saved as .bin/.dat files)
* GBA games (saved as .gba files)
* Patches (saved as .bin files and disassembled as .txt files)
* Player data from BB sessions (saved as .psochar files)
* Episode 3 online quests and maps (saved as .mnmd files)
* Episode 3 download quests (saved as .mnm files)
* Episode 3 card definitions (saved as .mnr files)
* Episode 3 media updates (saved as .gvm, .bml, or .bin files)
The remote server will probably try to assign you a Guild Card number that doesn't match the one you have on newserv. The proxy rewrites the commands in transit to make it look like the remote server assigned you the same Guild Card number as you have on newserv, but if the remote server has some external integrations (e.g. forum or Discord bots), they will use the Guild Card number that the remote server believes it has assigned to you. The number assigned by the remote server is shown to you when you first connect to the remote server, and you can retrieve it in lobbies or during games with the `$li` command.
Some chat commands (see below) have the same basic function on the proxy but have different effects or conditions. In addition, there are some server shell commands that affect clients on the proxy (run `help` in the shell to see what they are). If there's only one proxy session open, the shell's proxy commands will affect that session. Otherwise, you'll have to specify which session to affect with the `on` prefix - to send a chat message in C-17's session, for example, you would run `on C-17 chat ...`.
## Chat commands
newserv supports a variety of commands players can use by chatting in-game. Any chat message that begins with `$` is treated as a chat command. (If you actually want to send a chat message starting with `$`, type `$$` instead.) On the DC 11/2000 prototype, `@` is used instead of `$` for all chat commands, since `$` does not appear on the English virtual keyboard.
Some commands only work for clients not in proxy sessions. The chat commands are:
* Information commands
* `$li`: Show basic information about the lobby or game you're in. If you're on the proxy, show information about your connection instead (remote Guild Card number, client ID, etc.).
* `$si`: Show basic information about the server.
* `$ping`: Show round-trip ping time from the server to you. On the proxy, show the ping time from you to the proxy and from the proxy to the server.
* `$matcount` (non-proxy only): Show how many of each type of material you've used.
* `$killcount` (non-proxy only): Show the kill count on your currently-equipped weapon. If you're in a game and not on BB, the value is only accurate at the time the item enters the game.
* `$itemnotifs <mode>`: Enable item drop notification messages. If the game has private drops enabled, you will only see a notification if the dropped item is visible to you; you won't be notified of other players' drops. The modes are:
* `off`: No notifications are shown.
* `rare`: You are notified when a rare item drops.
* `on`: You are notified when any item drops, except Meseta.
* `every`: You are notified when any item drops, including Meseta.
* `$announcerares`: Enable or disable announcements for your rare item finds. This determines whether rare items you find will be announced to the game and server, not whether you will see announcements for others finding rare items.
* `$what` (non-proxy only): Show the type, name, and stats of the nearest item on the ground.
* `$where`: Show your current floor number and coordinates. Mainly useful for debugging.
* `$qfread <field-name>` (non-proxy only): Show the value of a quest counter in your player data. The field names are defined in config.json.
* Basic debugging commands (special permissions not required)
* `$whatobj` and `$whatene` (non-proxy only): Tells you what the closest object or enemy spawn point is to your position, along with its coordinates and object or enemy ID. The full definition is also printed to the server's log.
* `$qcheck <flag-num>` (non-proxy only): Show the value of a quest flag. If you're in a game, show the value of the flag in that game; if you're in the lobby, show the saved value of that quest flag for your character (BB only).
* `$qgread <flag-num>` (non-proxy only): Show the value of a quest counter ("global flag").
* `$sound <sound-id>`: Play the given sound (GC only).
* Restricted debugging commands (`$debug` permission required)
* `$debug`: Enable debug mode. You need the DEBUG flag in your user account to use this command. Enabling debug does several things:
* You'll be able to use the rest of the commands in this section.
* You'll see in-game messages from the server when you take some actions, like killing enemies, opening boxes, or flipping switches.
* You'll see the rare seed value and floor variations when you join a game.
* You'll be placed into the last available slot in lobbies and games instead of the first, unless you're joining a BB solo-mode game.
* You'll be able to join games with any PSO version, not only those for which cross-version play is normally enabled. See the "Cross-version play" section above for details on this.
* `$readmem <address>`: Read 4 bytes from the given address and show you the values.
* `$writemem <address> <data>`: Write data to the given address. Data is not required to be any specific size.
* `$nativecall <address> [arg1 ...]` (GC only): Call a native function on your client. Only arguments passed in registers are supported; calling functions that take many arguments is not supported.
* `$quest <number>` (non-proxy only): Load a quest by quest number. Can be used to load battle or challenge quests with only one player present. `$debug` is not required for this command if the specified quest has the AllowStartFromChatCommand field set in its metadata file.
* `$qcall <function-id>`: Call a quest function on your client.
* `$qset <flag-num>` or `$qclear <flag-num>`: Set or clear a quest flag for everyone in the game. If you're in the lobby and on BB, set or clear the saved value of a quest flag in your character file.
* `$qgwrite <flag-num> <value>` (non-proxy only): Set the value of a quest counter ("global flag") for yourself.
* `$qsync <reg-num> <value>`: Set a quest register's value for yourself only. `<reg-num>` should be either rXX (e.g. r60) or fXX (e.g. f60); if the latter, `<value>` is parsed as a floating-point value instead of as an integer.
* `$qsyncall <reg-num> <value>`: Set a quest register's value for everyone in the game. `<reg-num>` should be either rXX (e.g. r60) or fXX (e.g. f60); if the latter, `<value>` is parsed as a floating-point value instead of as an integer.
* `$swset [floor] <flag-num>` and `$swclear [floor] <flag-num>`: Set or clear a switch flag. If floor is not given, sets or clears the flag on your current floor.
* `$swsetall`: Set all switch flags on your current floor. This unlocks all doors, disables all laser fences, triggers all light/poison switches, etc.
* `$gc` (non-proxy only): Send your own Guild Card to yourself.
* `$sc <data>`: Send a command to yourself.
* `$ss <data>`: Send a command to the remote server (if in a proxy session) or to the game server.
* `$sb <data>`: Send a command to yourself, and to the remote server or game server.
* `$auction` (Episode 3 only): Bring up the CARD Auction menu, even if there are fewer than 4 players are in the game or you don't have a VIP card.
* `$makeobj <type> [coords...] [angles...] [params...]`: Create a map object. This is only implemented for a few specific client versions. The type is an integer like `273` or `0x0107`. Coordinates are specified as e.g. `x:30 y:0 z:-25.5`; if coordinates are not specified, the object is created at the player's coordinates. Angles are specified as e.g. `r:0 p:0x1000 w:-0x400` (for roll, pitch, and yaw, respectively). Parameters are specified as e.g. `1:2.0 2:0.0 5:0x4000`; any unspecified parameters are set to zero. The object is only created for the calling player and is not added to the server's map state; if the object ever sends update commands (e.g. 6x0B), it will likely result in a disconnection.
* Personal state commands
* `$arrow <color-id>`: Change your lobby arrow color. The color may be specified by number (0-12) or by name (red, blue, green, yellow, purple, cyan, orange, pink, white, white2, white3, or black).
* `$secid <section-id>`: Set your override section ID. After running this command, any games you create will use your override section ID for rare drops instead of your character's actual section ID. If you're in a game and you are the leader of the game, this also immediately changes the item tables used by the server when creating items. To revert to your actual section id, run `$secid` with no name after it. On the proxy, this will not work if the remote server controls item drops. If the server does not allow cheat mode anywhere (that is, "CheatModeBehavior" is "Off" in config.json), this command does nothing.
* `$rand <seed>`: Set your override random seed (specified as a 32-bit hex value). This will make any games you create use the given seed for rare enemies and item drops. On the proxy, this command can cause desyncs with other players in the same game, since they will not see the overridden random seed. To remove the override, run `$rand` with no arguments. If the server does not allow cheat mode anywhere (that is, "CheatModeBehavior" is "Off" in config.json), this command does nothing.
* `$ln [name-or-type]`: Set the lobby number. Visible only to you. This command exists because some non-lobby maps can be loaded as lobbies with invalid lobby numbers. See the "GC lobby types" and "Ep3 lobby types" entries in the information menu for acceptable values here. Note that non-lobby maps do not have a lobby counter, so there's no way to exit the lobby without using either `$ln` again or `$exit`. On the game server, `$ln` reloads the lobby immediately; on the proxy, it doesn't take effect until you load another lobby yourself (which means you'll like have to use `$exit` to escape). Run this command with no argument to return to the default lobby.
* `$swa`: Enable or disable switch assist. When enabled, the server will unlock two-player and four-player doors in non-quest games when you step on any of the required switches.
* `$exit`: If you're in a lobby, send you to the main menu (which ends your proxy session, if you're in one). If you're in a game or spectator team, send you to the lobby (but does not end your proxy session if you're in one). Does nothing if you're in a non-Episode 3 game and no quest is in progress.
* `$patch <name>`: Run a patch on your client. `<name>` must exactly match the name of a patch on the server.
* Character data commands (non-proxy only)
* `$switchchar <slot>` (BB only): Switch to a different character from your account without logging out.
* `$savechar <slot>`: Save your current character data on the server in the specified slot. See the [server-side saves section](#server-side-saves) for more details.
* `$loadchar <slot>`: Load character data from the specified slot on the server, and replace your current character with it. See the [server-side saves section](#server-side-saves) for more details.
* `$bbchar <username> <password> <slot>`: Save your current character data on the server in a different account's BB character slots. See the [server-side saves section](#server-side-saves) for more details.
* `$checkchar [slot]`: Tells you basic information about a server-side character previously saved using `$savechar`. If `slot` is not given, tells you which slots are used and which are free.
* `$deletechar <slot>`: Deletes a server-side character previously saved using `$savechar`.
* `$edit <stat> <value>`: Modify your character data. See the [using $edit](#using-edit) section for details.
* Blue Burst player commands (non-proxy only)
* `$bank [number]`: Switch your current bank, so you can access your other character's banks (if `number` is 1-4) or your shared account bank (if `number` is 0). If `number` is not given, switch back to your current character's bank.
* `$save`: Save your character, system, and Guild Card data immediately. (By default, your character is saved every 60 seconds while online, and your account and Guild Card data are saved whenever they change.)
* Game state commands (non-proxy only)
* `$maxlevel <level>`: Set the maximum level for players to join the current game. (This only applies when joining; if a player joins and then levels up past this level during the game, they are not kicked out, but won't be able to rejoin if they leave.)
* `$minlevel <level>`: Set the minimum level for players to join the current game.
* `$password <password>`: Set the game's join password. To unlock the game, run `$password` with nothing after it.
* `$dropmode [mode]`: Change the way item drops behave in the current game. `mode` can be `none`, `client`, `shared`, `private`, or `duplicate`. If `mode` is not given, tells you the current drop mode without changing it. See the [item tables and drop modes section](#item-tables-and-drop-modes) for more information.
* `$persist`: Enable or disable persistence for the current game. When persistence is on, the game will not be deleted when the last player leaves. The states of enemies, objects, and switches will be saved, and items left on the floor will not be deleted. (But if you're in the private or duplicate drop mode, items dropped by enemies are deleted - to make sure a certain item won't be deleted, you can pick it up and drop it again.) If the game is empty for too long (15 minutes by default), it is then deleted.
* Episode 3 commands (non-proxy only)
* `$spec`: Toggle the allow spectators flag for Episode 3 games. If any players are spectating when this flag is disabled, they are sent back to the lobby.
* `$inftime`: Toggle infinite-time mode. Must be used before starting a battle. If infinite-time mode is on, the overall and per-phase time limits will be disabled regardless of the values chosen during battle rules setup. After completing a battle, infinite-time mode is reset to the server's default value (which can be set in Episode3BehaviorFlags in config.json).
* `$dicerange [d:L-H] [1:L-H] [a1:L-H] [d1:L-H]`: Set override dice ranges for the next battle. The min and max dice values from the rules setup menu always apply to the ATK dice, but you can specify a different range for the DEF dice with `d:2-4` (for example). The `1:` override applies to the 1-player team in a 2v1 game (so you would set the 2-player team's desired dice range in the rules menu). You can also specify the 1-player team's ATK and DEF ranges separately with the `a1:` and `d1:` overrides. Note that these ranges will only be used if the chosen map or quest does not override them.
* `$stat <what>`: Show a statistic about your player or team in the current battle. `<what>` can be `duration`, `fcs-destroyed`, `cards-destroyed`, `damage-given`, `damage-taken`, `opp-cards-destroyed`, `own-cards-destroyed`, `move-distance`, `cards-set`, `fcs-set`, `attack-actions-set`, `techs-set`, `assists-set`, `defenses-self`, `defenses-ally`, `cards-drawn`, `max-attack-damage`, `max-combo`, `attacks-given`, `attacks-taken`, `sc-damage`, `damage-defended`, or `rank`.
* `$surrender`: Cause your team to immediately lose the current battle. If your story character is already defeated, you can't surrender - only your teammate can.
* `$saverec <name>`: Save the recording of the last battle.
* `$playrec <name>`: Play a battle recording. This command creates a spectator team and plays the specified recording as if it were happening in real time. By default, playback will start immediately when the spectator team is ready; you can delay this to allow others to join by prepending a `!` to the recording name. In that case, using `$playrec` again (with no argument) within the spectator team will start playback.
* Cheat mode commands
* `$cheat` (non-proxy only): Enable or disable cheat mode for the current game. All other cheat mode commands do nothing if cheat mode is disabled. By default, cheat mode is off in new games but can be enabled; there is an option in config.json that allows you to disable cheat mode entirely, or set it to on by default in new games. Cheat mode is always enabled on the proxy, unless cheat mode is disabled on the entire server.
* `$infhp`: Enable or disable infinite HP mode. Applies to only you; does not affect other players. When enabled, one-hit KO attacks will still kill you, but on most versions of the game, the server will automatically revive you if you die. Infinite HP also automatically cures status ailments.
* `$inftp`: Enable or disable infinite TP mode. Applies to only you; does not affect other players. Does not work on DCv1 or earlier versions.
* `$warpme <floor-id>` (or `$warp <floor-id>`): Warp yourself to the given floor.
* `$warpall <floor-id>`: Warp everyone in the game to the given floor. You must be the leader to use this command, unless you're on the proxy.
* `$next`: Warp yourself to the next floor.
* `$item <desc>` (or `$i <desc>`): Create an item. `desc` may be a description of the item or a string of hex data specifying the item code. Item codes are 16 hex bytes; at least 2 bytes must be specified, and all unspecified bytes are zeroes. If you are on the proxy, you must not be using Blue Burst for this command to work. On the game server, this command works for all versions. Here are some examples to illustrate the syntax (nothing is case-sensitive, and everything except the item name itself is optional):
* `$item Saber +5 0/10/25/0/10` (weapon with special, grind and attributes)
* `$item ???? Draw Autogun` (untekked weapon with special; can have grind/attributes too, as above)
* `$item SEALED J-SWORD K:2000` (weapon with kill count)
* `$item ES APHEX ZALURE TWIN +200` (ES weapon must be prefixed with "ES"; name comes before special)
* `$item DF FIELD +10DEF +20EVP +4` (armor with DFP bonus, EVP bonus, and slot count)
* `$item RED MERGE +10DFP +20EVP` (shield; same as armor except without slot count)
* `$item Knight/Power +9` (unit with specific modifier)
* `$item Knight/Power++` (unit with normal modifier; ++/-- are +4/-4 and +/- are +2/-2)
* `$item LIMITER K:1000` (sealed unit with kill count)
* `$item Tapas PB:F,G,M&Y 120% 200IQ 5/195/0/0 green` (mag with PBs, synchro, IO, stats, and color)
* `$item Trimate x10` (tool with stack size)
* `$item Disk:Reverser` (technique disk without level)
* `$item Disk:Razonde Lv.30` (technique disk with level)
* `$item 1000 Meseta`
* `$unset <index>` (non-proxy only): In an Episode 3 battle, removes one of your set cards from the field. `<index>` is the index of the set card as it appears on your screen - 1 is the card next to your SC's icon, 2 is the card to the right of 1, etc. This does not cause a Hunters-side SC to lose HP, as they normally do when their items are destroyed. You can also destroy the assist card set on yourself with `$unset 0`.
* `$dropmode [mode]` (proxy only): Change the way item drops behave in the current game, if you are not on BB. Unlike the game server version of this command, using this on the proxy requires cheats to be enabled. This works by intercepting the drop requests sent to and from the leader. (So, if you are the leader and not using server drop mode on the remote server, it affects the entire game; otherwise, it affects only items generated by your actions.) `mode` can be `none` (no drops), `default` (normal drops), or `proxy` (use newserv's drop tables instead of the remote server's). If `mode` is not given, tells you the current drop mode without changing it.
* Aesthetic commands
* `$event <event>`: Set the current holiday event in the current lobby. Holiday events are documented in the "Using $event" item in the information menu. If you're on the proxy, this applies to all lobbies and games you join, but only you will see the new event - other players will not.
* `$allevent <event>` (non-proxy only): Set the current holiday event in all lobbies.
* `$song <song-id>` (Episode 3 only): Play a specific song in the current lobby.
* Administration commands (non-proxy only)
* `$ann <message>`: Send an announcement message. The message is sent as temporary on-screen text to all players in all games and lobbies. On BB, the message appears in the scrolling top bar.
* `$ann!`, `$ann?`, `$ann?!`: Same as `$ann`, but with `?`, omits the sender's name, and with `!`, sends the message as a Simple Mail message instead of on-screen text.
* `$silence <identifier>`: Silence a player (remove their ability to chat) or unsilence a player. The identifier may be the player's name or Guild Card number.
* `$kick <identifier>`: Disconnect a player. The identifier may be the player's name or Guild Card number.
* `$ban <duration> <identifier>`: Ban a player. The duration should be of the form `10m` (minutes), `10h` (hours), `10d` (days), `10w` (weeks), `10M` (months), or `10y` (years). (Numbers other than 10 may be used, of course.) As with `$kick`, the identifier may be the player's name or Guild Card number.
### Using $edit
The $edit command modifies your character data. This command doesn't work on V3 (GameCube/Xbox). If you are on V1 or V2 (DC or PC, not BB), your changes will be undone if you join a game - to save your changes, disconnect from the lobby.
Some subcommands are always available. They are:
* `$edit mat reset power`: Clear your usage of power materials (BB only)
* `$edit mat reset mind`: Clear your usage of mind materials (BB only)
* `$edit mat reset evade`: Clear your usage of evade materials (BB only)
* `$edit mat reset def`: Clear your usage of def materials (BB only)
* `$edit mat reset luck`: Clear your usage of luck materials (BB only)
* `$edit mat reset hp`: Clear your usage of HP materials (BB only)
* `$edit mat reset tp`: Clear your usage of TP materials (BB only)
* `$edit mat reset all`: Clear your usage of all materials except HP and TP (BB only)
* `$edit mat reset every`: Clear your usage of all materials including HP and TP (BB only)
* `$edit namecolor AARRGGBB`: Set your name color (AARRGGBB specified in hex)
* `$edit language L`: Set your language (Generally only useful on BB; values for L: J = Japanese, E = English, G = German, F = French, S = Spanish, B = Simplified Chinese, T = Traditional Chinese, K = Korean)
* `$edit name NAME`: Set your character name
* `$edit npc NPC-NAME`: Set or remove an NPC skin on your character (use `none` to remove a skin). The NPC names are:
* On all versions except DCv1 and early prototypes: `ninja`, `rico`, `sonic`, `knuckles`, `tails`
* On GC, Xbox, and BB: `flowen`, `elly`
* On BB only: `momoka`, `irene`, `guild`, `nurse`
* `$edit secid SECID-NAME`: Set your section ID (cheat mode is required unless your character is Level 1)
The remaining subcommands are only available if cheat mode is enabled on the server. They are:
* `$edit atp N`: Set your ATP to N until stats are updated (e.g. by leveling up)
* `$edit mst N`: Set your MST to N until stats are updated
* `$edit evp N`: Set your EVP to N until stats are updated
* `$edit dfp N`: Set your DFP to N until stats are updated
* `$edit ata N`: Set your ATA to N until stats are updated
* `$edit lck N`: Set your LCK to N until stats are updated
* `$edit hp N`: Set your HP to N until stats are updated
* `$edit meseta N`: Set the amount of Meseta in your inventory
* `$edit exp N`: Set your total amount of EXP (does not affect level)
* `$edit level N`: Set your current level (recomputes stats, but does not affect EXP)
* `$edit tech TECH-NAME LEVEL`: Set the level of one of your techniques
## REST API
newserv has an optional HTTP server that provides a way to programmatically get data from the server in realtime. This is intended for use with external integrations; for example, a web site could query this API to get the current player count to display on the home page.
The HTTP server is disabled by default, and you have to explicitly enable it in config.json if you want this functionality. **If you enable it, make sure that the HTTP port can't be accessed from the public Internet.** The API provides a lot of internal data about players and games, and it should only be accessed by programs that you've written or that you trust.
To enable the HTTP server, add a port number in the HTTPListen list in config.json. The HTTP server will listen on that port.
All returned data is JSON-encoded, and all request data (for POST requests) must also be JSON-encoded with the `Content-Type: application/json` header.
The HTTP server has the following endpoints:
* `GET /`: Returns the server's build date and revision.
* `GET /y/data/ep3-cards`: Returns the Episode 3 card definitions.
* `GET /y/data/ep3-cards-trial`: Returns the Episode 3 Trial Edition card definitions.
* `GET /y/data/common-tables`: Returns the parameters for generating common items (ItemPT files). This endpoint returns a lot of data and can be slow!
* `GET /y/data/rare-tables`: Returns a list of rare table names.
* `GET /y/data/rare-tables/<TABLE-NAME>` (for example, `/y/data/rare-tables/rare-table-v4`): Returns the contents of a rare item table.
* `GET /y/data/quests`: Returns metadata about all available quests and quest categories.
* `GET /y/data/config`: Returns the server's configuration file.
* `GET /y/accounts`: Returns information about all registered accounts.
* `GET /y/clients`: Returns information about all connected clients on the game server.
* `GET /y/proxy-clients`: Returns information about all connected clients on the proxy.
* `GET /y/lobbies`: Returns information about all lobbies and games.
* `GET /y/server`: Returns information about the server.
* `GET /y/summary`: Returns a summary of the server's state, connected clients, active games, and proxy sessions.
* `WS /y/rare-drops/stream`: WebSocket endpoint that sends messages whenever an announceable rare item is dropped in any game. See below.
* `POST /y/shell-exec`: Runs a server shell command. Input should be a JSON dict of e.g. `{"command": "announce hello"}`; response will be a JSON dict of `{"result": "<result text>"}` or an HTTP error.
### Rare drop stream endpoint
The `/y/rare-drops/stream` endpoint provides a way to implement a drop log in e.g. Discord. For every announceable rare item, a message is sent to all connected clients on this endpoint. (Announceable rare items are items for which an in-game or server-wide text message is sent announcing the find.)
Upon connecting, you'll get the message `{"ServerType": "newserv"}`. After that, when a rare item announcement is sent, you'll get a message like this:
```
{
"PlayerAccountID", 12345,
"PlayerName", "SONIC",
"PlayerVersion", "GC_V3",
"GameName", "ttf",
"GameDropMode", "SERVER_PRIVATE",
"ItemData", "03000000 00010000 00000000 (0021002C) 00000000",
"ItemDescription", "Monomate x1",
"NotifyGame", true,
"NotifyServer", false,
}
```
# Non-server features
newserv has many CLI options, which can be used to access functionality other than the game server and proxy. Run `newserv help` to see a full list of the options and how to use each one.
The data formats that newserv can convert to/from are:
| Format | Encode/compress action | Decode/extract action |
|-------------------------------------|---------------------------|------------------------------|
| PRS compression | `compress-prs` | `decompress-prs` |
| PR2/PRC compression | `compress-pr2` | `decompress-pr2` |
| BC0 compression | `compress-bc0` | `decompress-bc0` |
| Raw encrypted data | `encrypt-data` | `decrypt-data` |
| Episode 3 command mask | `encrypt-trivial-data` | `decrypt-trivial-data` |
| Challenge Mode rank text | `encrypt-challenge-data` | `decrypt-challenge-data` |
| PSO DC quest file (.vms) | None | `decode-vms` |
| PSO GC quest file (.gci) | None | `decode-gci` |
| Download quest file (.dlq) | None | `decode-dlq` |
| Server quest file (.qst) | `encode-qst` | `decode-qst` |
| PSO DC save file (.vms) | `encrypt-vms-save` | `decrypt-vms-save` |
| PSO PC save file | `encrypt-pc-save` | `decrypt-pc-save` |
| PSO GC save file (.gci) | `encrypt-gci-save` | `decrypt-gci-save` |
| PSO Xbox save file | None | `decrypt-xbox-save` |
| PSO GC snapshot file | None | `decode-gci-snapshot` |
| Quest script (.bin) | `assemble-quest-script` | `disassemble-quest-script` |
| Quest map (.dat) | None | `disassemble-quest-map` |
| AFS archive (.afs) | None | `extract-afs` |
| BML archive (.bml) | None | `extract-bml` |
| PPK archive (.ppk) | None | `extract-ppk` |
| GSL archive (.gsl) | `generate-gsl` | `extract-gsl` |
| GVM texture (.gvm) | `encode-gvm` | None |
| Bitmap font (.fon) | `encode-bitmap-font` | `decode-bitmap-font` |
| Text archive | `encode-text-archive` | `decode-text-archive` |
| Unicode text set | `encode-unicode-text-set` | `decode-unicode-text-set` |
| Word Select data set | None | `decode-word-select-set` |
| Set data table | None | `disassemble-set-data-table` |
| Rare item table (AFS/GSL/JSON/HTML) | `convert-rare-item-set` | `convert-rare-item-set` |
There are several actions that don't fit well into the table above, which let you do other things:
* Compute the decompressed size of compressed PRS data without decompressing it (`prs-size`)
* Find the likely round1 or round2 seed for a corrupt save file (`salvage-gci`)
* Run a brute-force search for a decryption seed (`find-decryption-seed`)
* Format Episode 3 game data in a human-readable manner (`show-ep3-maps`, `show-ep3-cards`, `generate-ep3-cards-html`)
* Format Blue Burst battle parameter files in a human-readable manner (`show-battle-params`)
* Convert item data to a human-readable description, or vice versa (`describe-item`)
* Show the server's item and level tables (`show-item-tables`, `show-level-tables`)
* Connect to another PSO server and pretend to be a client (`cat-client`)
* Generate or describe DC serial numbers (`generate-dc-serial-number`, `inspect-dc-serial-number`)
# Docker
Docker is new and mostly unsupported at this time. However, here are some best-effort steps to build and run in a docker container on Ubuntu Linux.
Tested on Ubuntu 22.04.4 LTS.
Note: You cannot have anything except this docker container using port 53 (DNS) on your server.
Install prerequisites
```
sudo apt install -y git
sudo apt install -y cmake. ## minimum version is 3.10. Check installed version with "cmake --version"
```
Clone repository
```
cd ~
git clone https://github.com/fuzziqersoftware/newserv/
cd ~/newserv
```
Build newserv. This will take a while. Don't forget the period at the end!
```
sudo docker build -t newserv .
```
Create persistent directories. Assuming you want to store the persistent data in your home directory
```
mkdir ~/newservPersist
mkdir ~/newservPersist/players
mkdir ~/newservPersist/teams
mkdir ~/newservPersist/licenses
```
Copy config file to config dir
```
cp ~/newserv/system/config.example.json ~/newservPersist/config.json
```
Edit config.json
```
nano ~/newservPersist/config.json
```
Pro tip:
Set "LocalAddress" to the static, LAN IP address of your server. If your server LAN IP is "192.168.0.10":
"LocalAddress": "192.168.0.10",
Set "ExternalAddress" to the WAN IP address of your network. If your WAN IP is "8.8.8.8":
"ExternalAddress": "8.8.8.8",
For Dolphin > Settings. Set SP1 to "Broadband Adapter (HLE)" Click [...] next to this, and set the DNS to the IP address of your server. Then start the game. Changes will not take affect if the game is running.
Docker run. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
docker run --name newserv -p 53:53/udp -p 5100:5100 -p 5110:5110 -p 5111:5111 -p 5112:5112 -p 9064:9064 -p 9100:9100 -p 9103:9103 -p 9300:9300 -p 11000:11000 -p 12000:12000 -p 12004:12004 -p 12005:12005 -v /etc/localtime:/etc/localtime:ro -v /home/changeme/newservPersist/config.json:/newserv/system/config.json -v /home/changeme/newservPersist/players:/newserv/system/players -v /home/changeme/newservPersist/teams:/newserv/system/teams -v /home/changeme/newservPersist/licenses:/newserv/system/licenses --restart no newserv:latest
```
Docker run host network mode. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
docker run --net host --name newserv -v /etc/localtime:/etc/localtime:ro -v /home/changeme/newservPersist/config.json:/newserv/system/config.json -v /home/changeme/newservPersist/players:/newserv/system/players -v /home/changeme/newservPersist/teams:/newserv/system/teams -v /home/changeme/newservPersist/licenses:/newserv/system/licenses --restart no newserv:latest
```
Docker compose. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
name: psonewserv
services:
newserv:
container_name: newserv
ports:
- 53:53/udp
- 5100:5100
- 5110:5110
- 5111:5111
- 5112:5112
- 9064:9064
- 9100:9100
- 9103:9103
- 9300:9300
- 11000:11000
- 12000:12000
- 12004:12004
- 12005:12005
volumes:
- /etc/localtime:/etc/localtime:ro
- /home/changeme/newservPersist/config.json:/newserv/system/config.json
- /home/changeme/newservPersist/players:/newserv/system/players
- /home/changeme/newservPersist/teams:/newserv/system/teams
- /home/changeme/newservPersist/licenses:/newserv/system/licenses
restart: no ## Set to whatever you want.
image: newserv:latest
```
Docker compose host network mode. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
name: psonewserv
services:
newserv:
container_name: newserv
volumes:
- /etc/localtime:/etc/localtime:ro
- /home/changeme/newservPersist/config.json:/newserv/system/config.json
- /home/changeme/newservPersist/players:/newserv/system/players
- /home/changeme/newservPersist/teams:/newserv/system/teams
- /home/changeme/newservPersist/licenses:/newserv/system/licenses
restart: no ## Set to whatever you want.
network_mode: host
image: newserv:latest
```
See `LICENSE` for license details. Any copied or modified upstream code retains the original license attribution.
-2
View File
@@ -30,8 +30,6 @@
## PSOBB
- Figure out why Pouilly Slime EXP doesn't work
- Make server-specified rare enemies work with maps loaded by the proxy
- Implement serialization for various table types (ItemPMT, ItemPT, etc.)
- Record some BB tests
- Add all necessary Guild Card number rewrites in BB commands on the proxy
+926
View File
@@ -0,0 +1,926 @@
# newserv <img align="right" src="static/s-newserv.png" />
newserv is a game server, proxy, and reverse-engineering tool for Phantasy Star Online (PSO). **To quickly get started using newserv, just read the [server setup](#server-setup) and [how to connect](#how-to-connect) sections.**
This project includes code that was reverse-engineered by the community in ages long past, and has been included in many projects since then. It also includes some game data from Phantasy Star Online itself, which was originally created by Sega.
Feel free to submit GitHub issues if you find bugs or have feature requests. I'd like to make the server as stable and complete as possible, but I can't promise that I'll respond to issues in a timely manner, because this is a personal project undertaken primarily for the fun of reverse-engineering. If you want to contribute to newserv yourself, pull requests are welcome as well.
See TODO.md for a list of known issues and future work I've curated, or go to the GitHub issue tracker for issues and requests submitted by the community.
**Table of contents**
* Background
* [History](#history)
* [Other server projects](#other-server-projects)
* [Using newserv in other projects](#using-newserv-in-other-projects)
* [Contributing to newserv](#contributing-to-newserv)
* [Compatibility](#compatibility)
* Setup
* [Server setup](#server-setup)
* [Client patch directories for PC and BB](#client-patch-directories)
* [How to connect](#how-to-connect)
* Features and configuration
* [User accounts](#user-accounts)
* [Installing quests](#installing-quests)
* [Item tables and drop modes](#item-tables-and-drop-modes)
* [Cross-version play](#cross-version-play)
* [Server-side saves](#server-side-saves)
* [Episode 3 features](#episode-3-features)
* [Memory patches, client functions, and DOL files](#memory-patches-and-client-functions)
* [Using newserv as a proxy](#using-newserv-as-a-proxy)
* [Chat commands](#chat-commands)
* [REST API](#rest-api)
* [Non-server features](#non-server-features)
# History
The history of this project essentially mirrors my development as a software engineer from the beginning of my hobby until now. If you don't care about the story, skip to the "Compatibility" or "Setup" sections below.
I originally purchased PSO GC when I heard about PSUL, and wanted to play around with running homebrew on my GameCube. This pathway eventually led to [GCARS-CS](https://github.com/fuzziqersoftware/gcars-cs), but that's another story.
<img align="left" src="static/s-khyps.png" /> After playing PSO for a while, both offline and online, I wrote a proxy called Khyps sometime in 2003. This was back in the days of the official Sega servers, where vulnerabilities weren't addressed in a timely manner or at all. It was common for malicious players using their own proxies or Action Replay codes (a story for another time) to send invalid commands that the servers would blindly forward, and cause the receiving clients to crash. These crashes were more than simply inconvenient; they could also corrupt your save data, destroying the hours of work you may have put into hunting items and leveling up your character.
For a while it was essentially necessary to use a proxy to go online at all, so the proxy could block these invalid commands. Khyps was designed primarily with this function in mind, though it also implemented some convenient cheats, like the ability to give yourself or other players infinite HP and allow you to teleport to different places without using an in-game teleporter.
<img align="left" src="static/s-khyller.png" /> After Khyps I took on the larger challenge of writing a server, which resulted in Khyller sometime in 2005. This was the first server of any type I had ever written. This project eventually evolved into a full-featured environment supporting all versions of the game that I had access to - at the time, PC, GC, and BB. (However, I suspect from reading the ancient source files that Khyller's BB support was very buggy.) As Khyller evolved, the code became increasingly cumbersome, littered with debugging filth that I never cleaned up and odd coding patterns I had picked up over the years. My understanding of the C++ language was woefully incomplete as well (as opposed to now, when it is still incomplete but not woefully so), which resulted in Khyller being essentially a C project that had a couple of classes in it.
<img align="left" src="static/s-aeon.png" /> Sometime in 2006 or 2007, I abandoned Khyller and rebuilt the entire thing from scratch, resulting in Aeon. Aeon was substantially cleaner in code than Khyller but still fairly hard to work with, and it lacked a few of the more arcane features I had originally written (for example, the ability to convert any quest into a download quest). In addition, the code still had some stability problems... it turns out that Aeon's concurrency primitives were simply incorrect. I had derived the concept of a mutex myself, before taking any real computer engineering classes, but had implemented it incorrectly. I made the race window as small as possible, but Aeon would still randomly crash after running seemingly fine for a few days.
At the time of its inception, Aeon was also called newserv, and you may find some beta releases floating around the Internet with filenames like `newserv-b3.zip`. I had released betas 1, 2, and 3 before I released the entire source of beta 5 and stopped working on the project when I went to college. This was around the time when I switched from writing software primarily on Windows to primarily on macOS and Linux, so Aeon beta 5 was the last server I wrote that specifically targeted Windows. (newserv, which you're looking at now, is difficult to compile on Windows but does work.)
<img align="left" src="static/s-newserv.png" /> After a long hiatus from PSO and much professional and personal development in my technical abilities, I was reminiscing sometime in October 2018 by reading my old code archives. Somehow inspired when I came across Aeon, I spent a weekend and a couple more evenings rewriting the entire project again, cleaning up ancient patterns I had used eleven years ago, replacing entire modules with simple STL containers, and eliminating even more support files in favor of configuration autodetection. The code is now suitably modern and stable, and I'm not embarrassed by its existence, as I am by Aeon beta 5's source code and my archive of Khyller (which, thankfully, no one else ever saw).
## Other server projects
Independently of this project, there are many other PSO servers out there. Those that I know of that are (or were) public are listed here in approximate chronological order:
* (Early 2000s) **[Schtserv](https://schtserv.com/)**: The first public-access PSO server, written in Delphi by Schthack. Schtserv is the only other unofficial server to support Episode 3, their implementation of which is based on newserv's (which is based on Sega's).
* (2005) **Khyller**: An early attempt of mine to support PSO PC, GC, and BB. See above for more details.
* (2006) **Aeon**: My second attempt. Better than Khyller, but still unreliable.
* (2008) **Tethealla**: A fairly extensive implementation of PSOBB, written in C by Sodaboy. The public version of Tethealla has been [officially disowned](https://www.pioneer2.net/community/threads/tethealla-server-forums-removal.26365/) as it is now more than 15 years old, but closed-source development continues. [Ephinea](https://ephinea.pioneer2.net/) is the continuation of this project. Several other modern PSOBB servers are forks of the initial public version of Tethealla as well.
* (2008) **[Sylverant](https://sylverant.net/)** [(source)](https://sourceforge.net/projects/sylverant/): The second public-access PSO server, written in C by BlueCrab.
* (2015) **[Archon](https://github.com/dcrodman/archon)**: A PSOBB server written in Go by Drew Rodman.
* (2015) **[Idola](https://github.com/HybridEidolon/idolapsoserv)**: A PSOBB server written in Rust by HybridEidolon. Functionality status unknown; the project has been archived.
* (2017) **[Aselia](https://github.com/Solybum/Aselia)**: A PSOBB server written in C# by Soly. It seems this was planned to be open-source at some point, but that has not (yet) happened.
* (2018) **newserv**: This project right here.
* (2019) **[Mechonis](https://gitlab.com/sora3087/mechonis)**: A PSOBB server with a microservice architecture written in TypeScript by TrueVision.
* (2020) **[Booma.Server](https://github.com/HelloKitty/Booma.Server)**: A PSOBB server written in C# by Glader, with Soly's help.
* (2021) **[Phantasmal World](https://github.com/DaanVandenBosch/phantasmal-world)**: A set of PSO tools, including a web-based model viewer and quest builder, and a PSO server, written by Daan Vanden Bosch.
* (2021) **[Elseware](http://git.sharnoth.com/jake/elseware)**: A PSOBB server written in Rust by Jake.
## Using newserv in other projects
You are free to use code from newserv in your own open-source projects; the only condition is that the contents of the LICENSE file must be included in your project if you use code from newserv. Your project does not also have to use the MIT license; you can use any license you want.
If you want to use parts of newserv in your project, there are two easy ways to do so with proper licensing:
* If you're using a lot of code from newserv, you can put a copy of newserv's LICENSE file in your repository alongside your own license file, or include the contents of newserv's license in your own license file.
* If you're only using a few files from newserv, you can copy and paste the contents of the LICENSE file into a comment at the beginning of each copied file.
Some of the more likely useful files are:
* **src/CommandFormats.hh**: Complete listing of all network commands used in all known versions of the game, and their formats
* **src/CommonItemSet.hh/cc**: Format of ItemPT files, shop definition files, and tekker adjustment tables
* **src/DCSerialNumbers.hh/cc**: PSO DC serial number validation algorithm and serial number generator
* **src/ItemData.hh**: Item format reference
* **src/ItemCreator.hh/cc**: Reverse-engineered item generator from Episodes 1&2 (used for all versions)
* **src/ItemParameterTable.hh**: Format of many structures in ItemPMT.prs
* **src/Map.hh/cc**: Map file (.dat/.evt) structure, listing of object/enemy types and parameters, and reverse-engineered Challenge Mode random enemy generation algorithm
* **src/QuestScript.cc**: Complete listing of all quest opcodes on all versions, along with their arguments and behavior
* **src/RareItemSet.hh/cc**: Format of ItemRT files (rare item drop tables)
* **src/SaveFileFormats.hh**: Definitions of save file structures for all versions
* **src/Episode3/DataIndexes.hh**: Episode 3 file structures, including card definition format and map/quest format
* **system/item-tables/names-v4.json**: Names of all items, indexed by the first 3 bytes of data1
## Contributing to newserv
The goals of this project are:
* Build stable, extensible PSO server software that includes all vanilla functionality as well as optional modern conveniences, features, and cheats.
* Document the internals of PSO's network protocol, file formats, and game mechanics. This is mainly done through comments in the code.
This is a personal project; there is no official development team, official website, or official instance of newserv. Issues and pull requests are certainly welcome, but please only add content (e.g. quests or patches) that you've created, is already public, or you have permission to release publicly.
# Compatibility
newserv supports all known versions of PSO, including various development prototypes. This table lists all versions that newserv supports. (NTE stands for Network Trial Edition; the GameCube beta versions were called Trial Edition instead, but we use the NTE abbreviation anyway for consistency.)
| Version | Lobbies | Games | Proxy |
|-----------------|----------|----------|----------|
| DC NTE | Yes | Yes | Yes |
| DC 11/2000 | Yes | Yes | Yes |
| DC 12/2000 | Yes | Yes | Yes |
| DC 01/2001 | Yes | Yes | Yes |
| DC V1 | Yes | Yes | Yes |
| DC 08/2001 | Yes | Yes | Yes |
| DC V2 | Yes | Yes | Yes |
| PC NTE | Yes (1) | Yes | Yes |
| PC | Yes | Yes | Yes |
| GC Ep1&2 NTE | Yes | Yes | Yes |
| GC Ep1&2 | Yes | Yes | Yes |
| GC Ep1&2 Plus | Yes | Yes | Yes |
| GC Ep3 NTE | Yes | Yes (2) | Yes |
| GC Ep3 | Yes | Yes | Yes |
| Xbox Ep1&2 Beta | Yes (3) | Yes (3) | Yes (3) |
| Xbox Ep1&2 | Yes (3) | Yes (3) | Yes (3) |
| BB (vanilla) | Yes | Yes | Yes |
| BB (Tethealla) | Yes | Yes | Yes |
*Notes:*
1. *This is the only version of PSO that doesn't have any way to identify the player's account - there is no serial number or username. For this reason, AllowUnregisteredUsers must be enabled in config.json to support PC NTE, and PC NTE players receive a random Guild Card number every time they connect. To prevent abuse, PC NTE support can be disabled in config.json.*
2. *Episode 3 NTE battles are not well-tested; some things may not work. See notes/ep3-nte-differences.txt for a list of known differences between NTE and the final version. NTE and non-NTE players cannot battle each other.*
3. *PSO Xbox connects through Xbox Live, so you can't easily host a private server for this version of the game. See the [How to connect](#pso-xbox) section.*
# Setup
## Server setup
Currently newserv works on macOS, Windows, and Ubuntu Linux. It will likely work on other Linux flavors too.
### Windows/macOS
1. Download the latest release.zip file from the [releases page](https://github.com/fuzziqersoftware/newserv/releases).
2. Extract the contents of the archive to some location on your computer.
3. Go into the system/ folder, open config.json in a text editor, and edit it to your liking. There are comments in the file that describe what all the options do. Most of the options can be left alone if you want default behavior, but on Windows, you must change LocalAddress and ExternalAddress.
4. (Optional) If you plan to play Blue Burst on newserv, set up the patch directory. See [client patch directories](#client-patch-directories) for details.
5. Run the newserv executable.
### Linux
There are currently no precompiled releases for Linux. To run newserv on Linux, you'll have to build it from source - see the section below.
### Building from source (macOS/Linux)
To build on macOS or Linux:
1. Install the dependencies needed for your platform:
* macOS: `brew install cmake asio libiconv`
* Linux: `sudo apt-get install cmake libasio-dev` (or use your Linux distribution's package manager)
2. Build and install [phosg](https://github.com/fuzziqersoftware/phosg) and [resource_dasm](https://github.com/fuzziqersoftware/resource_dasm).
3. Run `cmake . && make` in the newserv directory.
After building newserv, edit system/config.example.json as needed **and rename it to system/config.json** (note that this step is not necessary for the precompiled releases), set up [client patch directories](#client-patch-directories) if you're planning to play Blue Burst, then run `./newserv` in newserv's directory.
The server has an interactive shell which can be used to make changes, such as managing user accounts, updating the server's configuration, managing Episode 3 tournaments, and more. Type `help` and press Enter to see all the commands.
On Linux and macOS, the server also responds to SIGUSR1 and SIGUSR2. SIGUSR1 does the equivalent of the shell's `reload config` command, which reloads config.json but not any dependent files (so quests, Episode 3 maps, etc. will not be reloaded). SIGUSR2 does the equivalent of the shell's `reload all` command, which reloads everything.
To use newserv in other ways (e.g. for translating data), see the end of this document.
### Building from source (Windows)
The current version of newserv is cross-compiled using mingw-w64 on a macOS build machine, with the necessary libraries manually installed. Setting up such a build environment is tedious and not recommended; it's recommended to just use a release version instead.
Here is a rough outline of the Windows build process. You should only attempt this yourself if you're familiar with setting up build environments and can deal with issues you may encounter along the way.
1. Install recent versions of MinGW and CMake.
2. Build and install zlib, libiconv, asio, phosg, and resource_dasm into your MinGW environment.
3. Clone the newserv repository with symlinks enabled: `git clone -c core.symlinks=true https://github.com/fuzziqersoftware/newserv.git`
4. Build newserv via CMake.
## Client patch directories
newserv implements a patch server for PSO PC and PSO BB game data. Any file or directory you put in the system/patch-bb or system/patch-pc directories will be synced to clients when they connect to the patch server.
For Blue Burst set up, the below is mandatory for a smooth experience:
1. Browse to your chosen client's data directory.
2. Copy all the `map_*.dat` files, `map_*.evt`, `unitxt_*` files, and the `data.gsl` file and place them in `system/patch-bb/data`.
3. If you're using game files from the Tethealla client, make a copy of `unitxt_j.prs` inside system/patch-bb/data and name it `unitxt_e.prs`. (If `unitxt_e.prs` already exists, replace it with the copied file.)
If you don't have a BB client, or if you're using a Tethealla client from another source, Tethealla clients that are compatible with newserv can be found here: [English](https://web.archive.org/web/20240402011115/https://ragol.org/files/bb/TethVer12513_English.zip) / [Japanese](https://web.archive.org/web/20240402013127/https://ragol.org/files/bb/TethVer12513_Japanese.zip). These clients connect to 127.0.0.1 (localhost) automatically.
For BB clients, newserv reads some files out of the patch data to implement game logic, so it's important that certain game files are synchronized between the server and the client. newserv contains defaults for these files in the system/maps/bb-v4 directory, but if these don't match the client's copies of the files, odd behavior will occur in games.
To make server startup faster, newserv caches the modification times, sizes, and checksums of the files in the patch directories. If the patch server appears to be misbehaving, try deleting the .metadata-cache.json file in the relevant patch directory to force newserv to recompute all the checksums. Also, in the case when checksums are cached, newserv may not actually load the data for a patch file until it's needed by a client. Therefore, modifying any part of the patch tree while newserv is running can cause clients to see an inconsistent view of it.
Patch directory contents are cached in memory. If you've changed any of these files, you can run `reload patch-indexes` in the interactive shell to make the changes take effect without restarting the server.
## How to connect
### PSO DC
Depending on the version of PSO DC that you have, the instructions to connect to a newserv instance will vary.
If you have NTE, USv1, EUv1, or EUv2 and a Broadband Adapter, edit the broadband DNS address to newserv's IP address with newserv's DNS server running. Otherwise, it is necessary to patch the disc or use a codebreaker code to remove the Hunter License server check and/or redirect PSO to the newserv instance. Patching the disc or creating a codebreaker code is beyond the scope of this document.
### PSO DC on Flycast
If you're emulating PSO DC, the NTE, USv1, EUv1, and EUv2 versions will connect to newserv by setting the following options in Flycast's `emu.cfg` file under `[network]`:
- DNS = Your newserv's server address (newserv's DNS server must be running on port 53)
- EmulateBBA = yes
- Enable = yes
It is also necessary to save any DNS information to the flash memory of the Dreamcast to use the BBA - the easiest way to do this is to use the website option in USv2 and then choose the save to flash option.
If the server is running on the same machine as Flycast, this might not work, even if you point Flycast's DNS queries at your local IP address (instead of 127.0.0.1). In this case, you can modify the loaded executable in memory to make it connect anywhere you want. There is a script included with newserv that can do this on macOS; a similar technique could be done manually using scanmem on Linux or Cheat Engine on Windows. To use the script, do this:
1. Build and install [memwatch](https://github.com/fuzziqersoftware/memwatch).
2. Start Flycast and run PSO. (You must start PSO before running the script; it won't work if you run the script before loading the game.)
3. Run `sudo patch_flycast_memory.py <original-destination>`. Replace `<original-destination>` with the hostname that PSO wants to connect to (you can find this out by using Wireshark and looking for DNS queries). The script may take up to a minute; you can continue using Flycast while it runs, but don't start an online game until the script is done.
4. Run newserv and start an online game in PSO.
If you use this method, you'll have to run the script every time you start PSO in Flycast, but you won't have to run it again if you start another online game without restarting emulation.
If using JPv1, JPv2, or USv2, it is also necessary to remove the Hunter Licence server check, either with a disc patch or codebreaker code. Patching the disc or creating a codebreaker code is beyond the scope of this document.
### PSO PC
PSO PC has its connection addresses in `pso.exe`. Hex edit the executable with the connection address you want to connect to. Common server addresses to search for to replace are:
- pso20.sonic.isao.net
- sg207634.sonicteam.com
- pso-mp01.sonic.isao.net
- gsproduc.ath.cx
- sylverant.net
The version of PSO PC I have has the server addresses starting at offset 0x29CB34 in pso.exe. Change those addresses to "localhost" (without quotes) if you just want to connect to a locally-running newserv instance. Alternatively, you can add an entry to the Windows hosts file (C:\Windows\System32\drivers\etc\hosts) to redirect the connection to 127.0.0.1 (localhost) or any other IP address.
### PSO GC on a real GameCube
You can make PSO connect to newserv by setting the default gateway and DNS server addresses in the game's network settings to newserv's address. newserv's DNS server must be running on port 53 and must be accessible to the GameCube. If you're not playing PSO Plus or Episode III, this should be all you need to do, assuming you already set LocalAddress in config.json to your PC's private IP address.
If you have PSO Plus or Episode III, it won't want to connect to a server on the same local network as the GameCube itself, as determined by the GameCube's IP address and subnet mask. There are a couple of ways to get around this.
Sodaboy described a fairly easy method, which is to forward the PSO and DNS ports in your router's configuration to your PC's private IP address (the PSO ports are in config.json, and are all TCP; the DNS port is 53 and is UDP). Then, set LocalAddress and ExternalAddress in config.json to your external IP address (from e.g. whatismyip.com). Most routers will let you connect to your public IP address even from within the local network, but the GameCube will think it's connecting to a different network, so it won't reject the connection. If you're concerned about security and don't want your server to be publicly accessible, you can use Windows Firewall or UFW on Linux block incoming connections on the ports you opened, except for connections from the IP addresses you specify.
Another method is to use two network interfaces on the same PC, and tell the GameCube to connect to the one that appears to be on a different network. For example, if your GameCube is on the 10.0.0.x subnet and your PC's address is 10.0.0.5, you can create a fake network adapter on your PC (or use an existing real one) that has an IP address on a different subnet than the GameCube, such as 192.168.0.8. Then, in PSO's network config, set the default gateway and DNS server addresses to 192.168.0.8, and set LocalAddress in config.json to 192.168.0.8, and PSO should connect. This is what I did back in the old days when I primarily developed software on Windows, but I haven't tried it in many years.
### PSO GC on a Wii or Wii U
Using a Wii or Wii U to connect to newserv requires the Wii or vWii to be softmodded. How to do this is beyond the scope of this document.
Nintendont includes BBA emulation and is compatible with all PSO GameCube versions except Episodes I&II Trial Edition. To use Nintendont, enable BBA emulation in Nintendont's settings and follow the instructions in the above section (PSO GC on a real GameCube).
Devolution includes modem emulation and is compatible with all PSO GameCube versions including Episodes I&II Trial Edition. newserv can act as a PPP server, which Devolution can directly connect to. To do this:
1. Enable the PPPRawListen option according to the comments in config.json.
2. Start newserv.
3. In the game's network settings, set the username and password to anything (they cannot be blank), and set the phone number to the number that newserv outputs to the console during startup. (It will be near the end of all the startup log messages.) If your Wii is on the same network as newserv, use the local number; otherwise, use the external number.
### PSO GC on Dolphin
If you're using the HLE BBA type, set the BBA's DNS server address to newserv's IP address and it should work. (If newserv is on the same machine as Dolphin, you will need to use an Action Replay code directed at 127.0.0.1 to connect, as PSO rejects DNS queries from the same IP address.) Set PSO's network settings the same as listed below.
If you're using the TAP (not tapserver) BBA type, you'll have to set PSO's network settings appropriately for your tap interface. Set the DNS server address in PSO's network settings to newserv's IP address.
If you're using the tapserver BBA or modem type, you can make it connect to a newserv instance running on the same machine via the tapserver interface. To do this:
1. In the GameCube pane of the Config window, set the SP1 device to Broadband Adapter (tapserver) or Modem Adapter (tapserver).
2. Click the "..." button next to the SP1 menu. If you're using the tapserver BBA, enter `127.0.0.1:5059` in the box. If you're using the tapserver modem, enter `127.0.0.1:5058` in the box. (If newserv isn't running on the same machine as Dolphin, replace 127.0.0.1 with newserv's IP address.)
3. In PSO's network settings, enable DHCP ("Automatically obtain an IP address"), set DNS server address to "Automatic", and leave DHCP Hostname as "Not set". Leave the proxy server settings blank.
4. Start an online game.
### PSO Xbox
Unfortunately, you can't easily host a private server for PSO Xbox because the Xbox version of the game tunnels its connections through Xbox Live. There is a modern replacement for Xbox Live named [Insignia](https://insignia.live/), which supports the three main PSO Xbox servers, but as of now does not support other private PSO servers.
### PSO BB
The PSO BB client has been modified and distributed in many different forms. newserv supports most, but not all, of the common distributions. Unlike other versions, it's common for various BB clients to have different map files. It's important that the client and server have the same map files, so make sure to set up the patch directory based on the client you'll be using with newserv. (See the [client patch directories](#client-patch-directories) section for instructions on setting this up.)
The original Japanese and US versions of PSO BB work with newserv (the last Japanese release can be found [here](https://archive.org/details/psobb_jp_setup_12511_20240109/)). To get them to connect to your server, do one of the following:
* Use a drop-in patcher like [AzureFlare](https://github.com/Repflez/AzureFlare).
* Edit your hosts file to redirect the client's destination address to localhost or your server's address.
* Edit psobb.exe to point to your newserv instance. The original clients are packed with various versions of ASProtect, so this is a more involved process than simply opening the executable in a hex editor and finding/replacing some strings.
Alternatively, you can use the Tethealla client ([English](https://web.archive.org/web/20240402011115/https://ragol.org/files/bb/TethVer12513_English.zip) or [Japanese](https://web.archive.org/web/20240402013127/https://ragol.org/files/bb/TethVer12513_Japanese.zip)). If the server is on the same PC as the client and you don't plan to have any external players, these Tethealla clients will automatically connect to the server without any modifications. This version of the client is not packed, and you can find the connection addresses starting at offset 0x56D724 in psobb.exe. Overwrite these addresses with your server's hostname or IP address, and you should be able to connect.
### Allowing external players to connect
If you want to accept connections from outside your local network, you'll need to set ExternalAddress to your public IP address in the configuration file, and you'll likely need to open some ports in your router's NAT configuration - specifically, all the TCP ports listed in PortConfiguration in config.json.
For GC clients, you'll have to use newserv's built-in DNS server or set up your own DNS server as well. If you want external clients to be able to use your DNS server, you'll have to forward UDP port 53 to your newserv instance. Remote players can then connect to your server by entering your DNS server's IP address in their client's network configuration.
# Server feature configuration
## User accounts
By default, newserv does not require users to pre-register before playing; the server will instead automatically create an account the first time each player connects. These accounts have no special permissions. You can view, create, edit, and delete user accounts in the server's shell (run `help` in the shell to see how to do this).
A license is a set of credentials that a player can use to log in. There are six types of licenses:
* *DC NTE licenses* consist of a 16-character serial number and 16-character access key.
* *DC licenses* consist of an 8-character hex serial number and an 8-character access key.
* *PC licenses* are the same format as DC licenses, but are used for PC v2.
* *GC licenses* consist of a 10-digit decimal serial number, a 12-character access key, and a password of up to 8 characters.
* *XB licenses* consist of a gamertag of up to 16 characters, a 16-character hex user ID, and a 16-character hex account ID.
* *BB licenses* consist of a username of up to 16 characters and a password of up to 16 characters.
Each account may have multiple licenses. To add a license to an existing account, use `add-license` in the shell.
On BB, character data is scoped to the license, but system and Guild Card data is scoped to the account. That is, an account with multiple BB licenses can have more than 4 characters (up to 4 per license), but they will all share the same team membership and Guild Card lists.
You may want to give your account elevated privileges. To do so, run `update-account ACCOUNT-ID flags=root` (replacing ACCOUNT-ID with your actual account-id). You can also use update-account to edit other parts of the account; see the help text for more information.
## Installing quests
newserv automatically finds quests in the subdirectories of the system/quests/ directory. To install your own quests, or to use quests you've saved using the proxy's Save Files option, just put them in one of the subdirectories there and name them appropriately. The subdirectories and their behaviors (e.g. in which game modes they should appear and for which PSO versions) is defined in the QuestCategories field in config.json.
Within the category directories, quest files should be named like `q###-VERSION-LANGUAGE.EXT` (although the `q` is ignored, and can be any letter). The fields in each filename are:
- `###`: quest number (this doesn't really matter; it should just be unique across the PSO version)
- `VERSION`: dn = Dreamcast NTE, dp = Dreamcast 11/2000 prototype, d1 = Dreamcast v1, dc = Dreamcast v2, pcn = PC NTE, pc = PC, gcn = GameCube NTE, gc = GameCube Episodes 1 & 2, gc3 = Episode 3 (see below), xb = Xbox, bb = Blue Burst
- `LANGUAGE`: j = Japanese, e = English, g = German, f = French, s = Spanish
- `EXT`: file extension (see table below)
For .dat files, the `LANGUAGE` token may be omitted. If it's present, then that .dat file will only be used for that language of the quest; if omitted, then that .dat file will be used for all languages of the quest.
For example, the GameCube version of Lost HEAT SWORD is in two files named `q058-gc-e.bin` and `q058-gc.dat`. newserv knows these files are quests because they're in the system/quests/ directory, it knows they're for PSO GC because the filenames contain `-gc`, it knows this is the English version of the quest because the .bin filename ends with `-e` (even though the .dat filename does not), and it puts them in the Retrieval category because the files are within the retrieval/ directory within system/quests/.
Some quests have additional JSON metadata files that describe how the server should handle them. These metadata files are generally named similarly to their .bin and .dat counterparts, except the `VERSION` token may also be omitted if the metadata applies to all languages of the quest on all PSO versions. See the comments in system/quests/retrieval/q058.json for all of the available options and how to use them. Some of the options are:
- Disable or hide the quest if certain preceding quests aren't cleared or other conditions aren't met
- Enable the quest to be joined while in progress
- Override the common and/or rare item tables and set the allowed drop modes
Some quests may also include a .pvr file, which contains an image used in the quest. These files are named similarly to their .bin and .dat counterparts.
The GameCube and Xbox quest formats are very similar, but newserv treats them as different. If you want to use the same quest file for GameCube and Xbox clients, you can make one a symbolic link to the other.
There are multiple PSO quest formats out there; newserv supports all of them. It can also decode any known format to standard .bin/.dat format. Specifically:
| Format | Extension | Supported | Decode action |
|------------------|-----------------------|------------|------------------|
| Compressed | .bin and .dat | Yes | None (1) |
| Compressed Ep3 | .bin or .mnm | Yes (4) | None (1) |
| Uncompressed | .bind and .datd | Yes | compress-prs (2) |
| Uncompressed Ep3 | .bind or .mnmd | Yes (4) | compress-prs (2) |
| Source | .bin.txt and .dat | Yes | None (5) |
| VMS (DCv1) | .bin.vms and .dat.vms | Yes | decode-vms |
| VMS (DCv2) | .bin.vms and .dat.vms | Decode (3) | decode-vms (3) |
| GCI (decrypted) | .bin.gci and .dat.gci | Yes | decode-gci |
| GCI (with key) | .bin.gci and .dat.gci | Yes | decode-gci |
| GCI (no key) | .bin.gci and .dat.gci | Decode (3) | decode-gci (3) |
| GCI (Ep3 NTE) | .bin.gci or .mnm.gci | Decode (3) | decode-gci (3) |
| GCI (Ep3) | .bin.gci or .mnm.gci | Yes | decode-gci |
| DLQ | .bin.dlq and .dat.dlq | Yes | decode-dlq |
| DLQ (Ep3) | .bin.dlq or .mnm.dlq | Yes | decode-dlq |
| QST (online) | .qst | Yes | decode-qst |
| QST (download) | .qst | Yes | decode-qst |
*Notes:*
1. *This is the default format. You can convert these to uncompressed format by running `newserv decompress-prs FILENAME.bin FILENAME.bind` (and similarly for .dat -> .datd)*
2. *Similar to (1), to compress an uncompressed quest file: `newserv compress-prs FILENAME.bind FILENAME.bin` (and likewise for .datd -> .dat)*
3. *Use the decode action to convert these quests to .bin/.dat format before putting them into the server's quests directory. If you know the encryption seed (serial number), pass it in as a hex string with the `--seed=` option. If you don't know the encryption seed, newserv will find it for you, which will likely take a long time.*
4. *Episode 3 quests don't go in the system/quests directory. See the [Episode 3 section](#episode-3-features) section below.*
5. *Quest source can be assembled into a .bin or .bind file with `newserv assemble-quest-script FILENAME.txt`. See system/quests/retrieval/q058-gc-e.bin.txt for an annotated example; this is the English GameCube version of Lost HEAT SWORD.*
Episode 3 download quests consist only of a .bin file - there is no corresponding .dat file. Episode 3 download quest files may be named with the .mnm extension instead of .bin, since the format is the same as the standard map files (in system/ep3/maps/). These files can be encoded in any of the formats described above, except .qst.
When newserv indexes the quests during startup, it will warn (but not fail) if any quests are corrupt or in unrecognized formats.
Quest contents are cached in memory, but if you've changed the contents of the quests directory, you can re-index the quests without restarting the server by running `reload quest-index` in the interactive shell. The new quests will be available immediately, but any games with quests already in progress will continue using the old versions of the quests until those quests end.
## Item tables and drop modes
newserv supports server-side item generation on all game versions, except for the earliest DC prototypes (NTE and 11/2000). By default, the game behaves as it did on the original servers - on all versions except BB, item drops are controlled by the leader client in each game, and on BB, item drops are controlled by the server.
There are five different available behaviors for item drops:
* `disabled` (or `none`): No items will drop from boxes or enemies.
* `client`: The game leader generates items, all items are visible to all players, and any player may pick up any item. This is the default mode for all game versions, except this mode cannot be used if the game leader is on BB.
* `shared`: The server generates items, all items are visible to all players, and any player may pick up any item. This is the default mode if the game leader is on BB.
* `private`: The server generates items, but each player may get a different item from any box or enemy. If a player isn't in the same area as an enemy at the time it's defeated, they won't get any item from it. Items dropped by players are visible to everyone.
* `duplicate`: The server generates items, and each player will get the same item from any box or enemy, but there is one copy of each item for each player (and each player only sees their own copy of the item). If a player isn't in the same area as an enemy at the time it's defeated, they won't get any item from it. Items dropped by players are not duplicated and are visible to everyone.
In the `private` and `duplicate` modes, there is no incentive to pick up items before another player, since other players cannot pick up the items you see dropped from boxes and enemies. However, if you pick up an item and drop it later, it can then be seen and picked up by any player.
The drop mode can be changed at any time during a game with the `$dropmode` chat command. If the mode is changed after some items have already been dropped, the existing items retain their visibility (that is, items dropped in private mode still can't be picked up by other players since they were dropped before the mode was changed). You can configure which drop modes are used by default, and which modes players are allowed to choose, in config.json. See the comments above the AllowedDropModes and DefaultDropMode keys.
In the server drop modes, the item tables used to generate common items are in the `system/item-tables/ItemPT-*` files. (The V2 files are used for V1 as well.) The rare item tables are in the `rare-table-*.json` files. Unlike the original formats, it's possible to make each enemy drop multiple different rare items at different rates, though the default tables never do this.
## Cross-version play
All versions of PSO can see and interact with each other in the lobby. By default, newserv allows V1 and V2 players to play in games together, and allows GC and Xbox players to play in games together. You can change these rules to allow all versions to play in games together, or to prevent versions from playing in games together, with the CompatibilityGroups setting in config.json.
There are several cross-version restrictions that always apply regardless of the compatibility groups setting:
* DC V1 players cannot join DC V2 games if the game creator didn't choose to allow them.
* DC V1 players cannot join games if the difficulty level is set to Ultimate or the game mode is Battle or Challenge.
* Only GC, Xbox, and BB players can join games in Episode 2.
* Only BB players can join games in Episode 4.
* Episode 3 players cannot join non-Episode 3 games, and vice versa.
V1/V2 compatibility and GC/Xbox compatibility are well-tested, but other situations are not. Not much attention has been given yet to how items should be handled across major versions; if you enable V2/GC compatibility, for example, there will likely be bugs. Please report such bugs as GitHub issues.
In cross-version play, when any of the server drop modes are used, the server uses the drop tables corresponding to the leader's version and section ID. (For example, if a DC V1 player is the game leader, rare-table-v1.json will be used, even after V2 players join.) If a BB player is the leader and the `client` drop mode is used, the server generates items as if it were in `shared` mode.
## Server-side saves
newserv has the ability to save character data on the server side. For PSO BB, this is required of course, but this feature can also be used on other PSO versions.
Each account has 4 BB character slots and 16 non-BB character file slots. The non-BB slots are independent of the BB slots, and can be accessed with the `$savechar <slot>` and `$loadchar <slot>` commands (slots are numbered 1 through 16). `$savechar` copies the character you're currently playing as and saves the data on the server, and `$loadchar` does the reverse, overwriting your current character with the data saved on the server. Note that you can load a character that was saved from a different version of PSO, which allows you to easily transfer characters between games. On v1 and v2, changes done by `$loadchar` will be undone if you join a game; to permanently save your changes, disconnect from the lobby after using the command.
You can see basic information about a character saved on the server (without affecting your current character) by using `$checkchar <slot>`. You can delete a previously-saved character with `$deletechar <slot>`.
There is also the command `$bbchar <username> <password> <slot>`, which behaves similarly to `$savechar` but writes the character data to a BB character slot in a different account instead (slots are numbered 1 through 4). This can be used to "upgrade" a character to BB from an earlier version.
Exactly which data is saved and loaded depends on the game version:
| Game | Inventory | Character | Options/chats | Quest flags | Bank | Battle/Challenge |
|----------------------|-----------|-----------|---------------|-------------|------|------------------|
| PSO DC v1 prototypes | Yes | Yes | No | No | No | N/A |
| PSO DC v1 | Yes | Yes | No | No | No | N/A |
| PSO DC v2 | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO PC (v2) | Yes | Yes | No | No | No | Save only |
| PSO GC NTE | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO GC (not Plus) | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO GC Plus (1) | Save only | Save only | No | No | No | Save only |
| PSO GC Ep3 (1) | No | Save only | No | No | No | Save only |
| PSO Xbox | Yes | Yes | Yes | Yes | Yes | Yes |
| PSO BB | Yes | Yes | Yes | Yes | Yes | Yes |
*Notes*:
1. *If EnableSendFunctionCallQuestNumber is enabled in config.json, then $savechar and $loadchar can save and restore all character data on these versions, just like on GC non-Plus. Episode 3 characters exist in a separate namespace; that is, you can't use $savechar and $loadchar to convert an Ep3 character to non-Ep3, or vice versa.*
## Episode 3 features
newserv supports many features unique to Episode 3:
* CARD battles. Not every combination of abilities has been tested yet, so if you find a feature or card ability that doesn't work like it's supposed to, please make a GitHub issue and describe the situation (the attacking card(s), defending card(s), and ability or condition that didn't work).
* Spectator teams.
* Tournaments. (But they work differently than Sega's tournaments did - see below)
* Downloading quests.
* Trading cards.
* Participating in card auctions. (The auction contents must be configured in config.json.)
* Decorations in lobbies. Currently only images are supported; the game also supports loading custom 3D models in lobbies, but newserv does not implement this (yet).
### Battle records
After playing a battle, you can save the record of the battle with the `$saverec` command. You can then replay the battle later by using the `$playrec` command in a lobby - this will create a spectator team and play the recording of the battle as if it were happening in realtime. Note that there is a bug in older versions of Dolphin that seems to be frequently triggered when playing battle records, which causes the emulator to crash with the message `QObject::~QObject: Timers cannot be stopped from another thread`. To avoid this, use the latest version of Dolphin.
### Tournaments
Tournaments work differently than they did on Sega's servers. Tournaments can be created with the `create-tournament` shell command, which enables players to register for them. (Use `help` to see all the arguments - there are many!) The `start-tournament` shell command starts the tournament (and prevents further registrations), but this doesn't schedule any matches. Instead, players who are ready to play their next match can all stand at the 4-player battle table near the lobby warp in the same CARD lobby, and the tournament match will start automatically.
These tournament semantics mean that there can be multiple matches in the same tournament in play simultaneously, and not all matches in a round must be complete before the next round can begin - only the matches preceding each individual match must be complete for that match to be playable.
The Meseta rewards for winning tournament matches can be configured in config.json.
### Episode 3 files
Episode 3 state and game data is stored in the system/ep3 directory. The files in there are:
* card-definitions.mnr: Compressed card definition list, sent to Episode 3 clients at connect time. Card stats and abilities can be changed by editing this file.
* card-definitions.mnrd: Decompressed version of the above. If present, newserv will use this instead of the compressed version, since this is easier to edit.
* card-text.mnr: Compressed card text archive. Generally only used for debugging.
* card-text.mnrd: Decompressed card text archive; same format as TextCardE.bin. Generally only used for debugging.
* com-decks.json: COM decks used in tournaments. The default decks in this file come from logs from Sega's servers, so the file doesn't include every COM deck Sega ever made - the rest are probably lost to time.
* maps/: Online free battle and quest maps (.mnm/.bin/.mnmd/.bind files). newserv comes with the default online maps, as well as some fan-made variations and quests to help new players get up to speed. Within the maps/ directory, each subdirectory is treated as a separate category and may be optionally downloadable or available at the battle setup counter. The category.json file in each subdirectory specifies the category's behavior; see system/ep3/maps/online/category.json for a documented example.
* tournament-state.json: State of all active tournaments. This file is automatically written when any tournament changes state for any reason (e.g. a tournament is created/started/deleted or a match is resolved).
There is no public editor for Episode 3 maps and quests, but the format is described fairly thoroughly in src/Episode3/DataIndexes.hh (see the MapDefinition structure). You'll need to use `newserv decompress-prs ...` to decompress a .bin or .mnm file before editing it, but you don't need to compress it again to use it - just put the .bind or .mnmd file in the maps directory and newserv will make it available.
Like quests, Episode 3 card definitions, maps, and quests are cached in memory. If you've changed any of these files, you can run `reload ep3-cards` or `reload ep3-maps` in the interactive shell to make the changes take effect without restarting the server.
## Memory patches and client functions
You can put assembly files in the system/client-functions directory with filenames like PatchName.VERS.patch.s and they will appear in the Patches menu for clients that support client functions. Client functions are written in SH-4, PowerPC, or x86 assembly and are compiled when newserv is started. The assembly system's features are documented in the comments in system/client-functions/System/WriteMemoryGC.ppc.s.
The VERS token in client function filenames refers to the specific version of the game that the client function applies to. Some versions do not support receiving client functions at all. *Note: newserv uses the shorter GameCube versioning convention, where discs labeled DOL-XXXX-0-0Y are version 1.Y. The PSO community seems to use the convention 1.0Y in some places instead, but these are the same version. For example, the version that newserv calls v1.4 is the same as v1.04, and is labeled DOL-GPOJ-0-04 on the underside of the disc.*
The specific versions are:
| Game | VERS | CPU architecture |
|------------------------------|------|--------------------------------|
| PSO DC Network Trial Edition | 1OJ1 | Client functions not supported |
| PSO DC 11/2000 prototype | 1OJ2 | Client functions not supported |
| PSO DC 12/2000 prototype | 1OJ3 | Client functions not supported |
| PSO DC 01/2001 prototype | 1OJ4 | Client functions not supported |
| PSO DC v1 JP | 1OJF | Client functions not supported |
| PSO DC v1 US | 1OEF | Client functions not supported |
| PSO DC v1 EU | 1OPF | Client functions not supported |
| PSO DC 08/06/2001 prototype | 2OJ4 | SH-4 |
| PSO DC 08/22/2001 prototype | 2OJ5 | SH-4 |
| PSO DC v2 JP | 2OJF | SH-4 |
| PSO DC v2 US | 2OEF | SH-4 |
| PSO DC v2 EU | 2OPF | SH-4 |
| PSO PC (v2) Trial Edition | 2OJT | Client functions not supported |
| PSO PC (v2) 04/2002 | 2OJW | Client functions not supported |
| PSO PC (v2) 02/2003 | 2OJZ | Client functions not supported |
| PSO GC Trial Edition | 3OJT | PowerPC |
| PSO GC v1.2 JP | 3OJ2 | PowerPC |
| PSO GC v1.3 JP | 3OJ3 | PowerPC |
| PSO GC v1.4 (Plus) JP | 3OJ4 | PowerPC |
| PSO GC v1.5 (Plus) JP | 3OJ5 | PowerPC (1) |
| PSO GC v1.0 US | 3OE0 | PowerPC |
| PSO GC v1.1 US | 3OE1 | PowerPC |
| PSO GC v1.2 (Plus) US | 3OE2 | PowerPC (1) |
| PSO GC v1.0 EU | 3OP0 | PowerPC |
| PSO GC Ep3 Trial Edition | 3SJT | PowerPC |
| PSO GC Ep3 JP | 3SJ0 | PowerPC |
| PSO GC Ep3 US | 3SE0 | PowerPC (1) |
| PSO GC Ep3 EU | 3SP0 | PowerPC (1) |
| PSO Xbox Beta | 4OJB | x86 |
| PSO Xbox JP Disc | 4OJD | x86 |
| PSO Xbox JP TU | 4OJU | x86 |
| PSO Xbox US Disc | 4OED | x86 |
| PSO Xbox US TU | 4OEU | x86 |
| PSO Xbox EU Disc | 4OPD | x86 |
| PSO Xbox EU TU | 4OPU | x86 |
| PSO BB JP 1.25.11 | 59NJ | x86 |
| PSO BB JP 1.25.13 | 59NL | x86 |
| PSO BB Tethealla | 59NL | x86 |
*Notes:*
1. *Client functions are only supported on these versions if EnableSendFunctionCallQuestNumbers is set in config.json. See the comments there for more information.*
newserv comes with a set of patches for many of the above versions. These are organized in subdirectories within system/client-functions/.
### DOL loader
You can put DOL files in the system/dol directory, and they will appear in the Programs menu for GC clients. Selecting a DOL file there will load the file into the GameCube's memory and run it, just like the old homebrew loaders (PSUL and PSOload) did. For this to work, ReadMemoryWordGC.ppc.s, WriteMemoryGC.ppc.s, and RunDOL.ppc.s must be present in the system/client-functions/System directory. This has been tested on Dolphin but not on a real GameCube, so results may vary.
Like other kinds of data, functions and DOL files are cached in memory. If you've changed any of these files, you can run `reload functions` or `reload dol-files` in the interactive shell to make the changes take effect without restarting the server.
I mainly built the DOL loading functionality for documentation purposes. By now, there are many better ways to load homebrew code on an unmodified GameCube, but to my knowledge there isn't another open-source implementation of this method in existence.
## Using newserv as a proxy
If you want to play online on remote servers rather than running your own server, newserv also includes a PSO proxy. Currently this works with PSO GC and may work with PC and DC; it also works with some BB clients in specific situations.
To use the proxy for PSO DC, PC, or GC, add an entry to the corresponding ProxyDestinations dictionary in config.json, then run newserv and connect to it as normal (see below). You'll see a "Proxy server" option in the main menu, and you can pick which remote server to connect to.
To use the proxy for PSO BB, set the ProxyDestination-BB entry in config.json. If this option is set, it essentially disables the game server for all BB clients - all BB clients will be proxied to the specified destination instead. Unfortunately, because PSO BB uses a different set of handlers for the data server phase and character selection, there's no in-game way to present the player with a list of options, like there is on PSO PC and PSO GC.
When you're on PSO DC, PC, GC, or Xbox and are connected to a remote server through newserv's proxy, choosing the Change Ship or Change Block action from the lobby counter will send you back to newserv's main menu instead of the remote server's ship or block select menu. You can go back to the server you were just on by choosing it from the proxy server menu again.
There are many options available when starting a proxy session. All options are off by default unless otherwise noted. The options are:
* **Chat commands**: enables chat commands in the proxy session (on by default).
* **Chat filter**: enables escape sequences in chat messages and info board (on by default).
* **Player notifications**: shows a message when any player joins or leaves the game or lobby you're in.
* **Block pings**: blocks automatic pings sent by the client, and responds to ping commands from the server automatically.
* **Infinite HP**: automatically heals you whenever you get hit. An attack that kills you in one hit will still kill you, however.
* **Infinite TP**: automatically restores your TP whenever you use any technique.
* **Switch assist**: unlocks doors that require two or four players in a one-player game, when you step on one of the switches.
* **Infinite Meseta** (Episode 3 only): gives you 1,000,000 Meseta, regardless of the value sent by the remote server.
* **Block events**: disables holiday events sent by the remote server.
* **Block patches**: prevents any B2 (patch) commands from reaching the client.
* **Save files**: saves copies of several kinds of files when they're sent by the remote server. The files are written to the current directory (which is usually the directory containing the system/ directory). Saved files can then be used with newserv by just moving the file into the appropriate place in the system/ directory and renaming it appropriately. These kinds of files can be saved:
* Online quests and download quests (saved as .bin/.dat files)
* GBA games (saved as .gba files)
* Patches (saved as .bin files and disassembled as .txt files)
* Player, system, and Guild Card data from BB sessions (saved as .psochar, .psosys, .psosysteam, and .psocard files)
* Stream file data from BB sessions (saved as ItemPMT, BattleParamEntry, ItemMagEdit, and PlyLevelTbl files)
* Episode 3 online quests and maps (saved as .mnmd files)
* Episode 3 download quests (saved as .mnm files)
* Episode 3 card definitions (saved as .mnr files)
* Episode 3 media updates (saved as .gvm, .bml, or .bin files)
The remote server will probably try to assign you a Guild Card number that doesn't match the one you have on newserv. The proxy rewrites the commands in transit to make it look like the remote server assigned you the same Guild Card number as you have on newserv, but if the remote server has some external integrations (e.g. forum or Discord bots), they will use the Guild Card number that the remote server believes it has assigned to you. The number assigned by the remote server is shown to you when you first connect to the remote server, and you can retrieve it in lobbies or during games with the `$li` command.
Some chat commands (see below) have the same basic function on the proxy but have different effects or conditions. In addition, there are some server shell commands that affect clients on the proxy (run `help` in the shell to see what they are). If there's only one proxy session open, the shell's proxy commands will affect that session. Otherwise, you'll have to specify which session to affect with the `on` prefix - to send a chat message in C-17's session, for example, you would run `on C-17 chat ...`.
## Chat commands
newserv supports a variety of commands players can use by chatting in-game. Any chat message that begins with `$` is treated as a chat command. (If you actually want to send a chat message starting with `$`, type `$$` instead.) On the DC 11/2000 prototype, `@` is used instead of `$` for all chat commands, since `$` does not appear on the English virtual keyboard.
Some commands only work for clients not in proxy sessions. The chat commands are:
* Information commands
* `$li`: Show basic information about the lobby or game you're in. If you're on the proxy, show information about your connection instead (remote Guild Card number, client ID, etc.).
* `$si`: Show basic information about the server.
* `$ping`: Show round-trip ping time from the server to you. On the proxy, show the ping time from you to the proxy and from the proxy to the server.
* `$matcount` (non-proxy only): Show how many of each type of material you've used.
* `$killcount` (non-proxy only): Show the kill count on your currently-equipped weapon. If you're in a game and not on BB, the value is only accurate at the time the item enters the game.
* `$itemnotifs <mode>`: Enable item drop notification messages. If the game has private drops enabled, you will only see a notification if the dropped item is visible to you; you won't be notified of other players' drops. The modes are:
* `off`: No notifications are shown.
* `rare`: You are notified when a rare item drops.
* `on`: You are notified when any item drops, except Meseta.
* `every`: You are notified when any item drops, including Meseta.
* `$announcerares`: Enable or disable announcements for your rare item finds. This determines whether rare items you find will be announced to the game and server, not whether you will see announcements for others finding rare items.
* `$what` (non-proxy only): Show the type, name, and stats of the nearest item on the ground.
* `$where`: Show your current floor number and coordinates. Mainly useful for debugging.
* `$qfread <field-name>` (non-proxy only): Show the value of a quest counter in your player data. The field names are defined in config.json.
* Basic debugging commands (special permissions not required)
* `$whatobj` and `$whatene` (non-proxy only): Tells you what the closest object or enemy spawn point is to your position, along with its coordinates and object or enemy ID. The full definition is also printed to the server's log.
* `$qcheck <flag-num>` (non-proxy only): Show the value of a quest flag. If you're in a game, show the value of the flag in that game; if you're in the lobby, show the saved value of that quest flag for your character (BB only).
* `$qgread <flag-num>` (non-proxy only): Show the value of a quest counter ("global flag").
* `$sound <sound-id>`: Play the given sound (GC only).
* Restricted debugging commands (`$debug` permission required)
* `$debug`: Enable debug mode. You need the DEBUG flag in your user account to use this command. Enabling debug does several things:
* You'll be able to use the rest of the commands in this section.
* You'll see in-game messages from the server when you take some actions, like killing enemies, opening boxes, or flipping switches.
* You'll see the rare seed value and floor variations when you join a game.
* You'll be placed into the last available slot in lobbies and games instead of the first, unless you're joining a BB solo-mode game.
* You'll be able to join games with any PSO version, not only those for which cross-version play is normally enabled. See the "Cross-version play" section above for details on this.
* `$readmem <address>`: Read 4 bytes from the given address and show you the values.
* `$writemem <address> <data>`: Write data to the given address. Data is not required to be any specific size.
* `$nativecall <address> [arg1 ...]` (GC only): Call a native function on your client. Only arguments passed in registers are supported; calling functions that take many arguments is not supported.
* `$quest <number>` (non-proxy only): Load a quest by quest number. Can be used to load battle or challenge quests with only one player present. `$debug` is not required for this command if the specified quest has the AllowStartFromChatCommand field set in its metadata file.
* `$qcall <function-id>`: Call a quest function on your client.
* `$qset <flag-num>` or `$qclear <flag-num>`: Set or clear a quest flag for everyone in the game. If you're in the lobby and on BB, set or clear the saved value of a quest flag in your character file.
* `$qgwrite <flag-num> <value>` (non-proxy only): Set the value of a quest counter ("global flag") for yourself.
* `$qsync <reg-num> <value>`: Set a quest register's value for yourself only. `<reg-num>` should be either rXX (e.g. r60) or fXX (e.g. f60); if the latter, `<value>` is parsed as a floating-point value instead of as an integer.
* `$qsyncall <reg-num> <value>`: Set a quest register's value for everyone in the game. `<reg-num>` should be either rXX (e.g. r60) or fXX (e.g. f60); if the latter, `<value>` is parsed as a floating-point value instead of as an integer.
* `$swset [floor] <flag-num>` and `$swclear [floor] <flag-num>`: Set or clear a switch flag. If floor is not given, sets or clears the flag on your current floor.
* `$swsetall`: Set all switch flags on your current floor. This unlocks all doors, disables all laser fences, triggers all light/poison switches, etc.
* `$allrare`: Make all enemies and boxes drop their rare items every time.
* `$gc` (non-proxy only): Send your own Guild Card to yourself.
* `$sc <data>`: Send a command to yourself.
* `$scp <data>`: Send a protected command to yourself.
* `$ss <data>`: Send a command to the remote server (if in a proxy session) or to the game server.
* `$sb <data>`: Send a command to yourself, and to the remote server or game server.
* `$auction` (Episode 3 only): Bring up the CARD Auction menu, even if there are fewer than 4 players are in the game or you don't have a VIP card.
* `$makeobj <type> [coords...] [angles...] [params...]`: Create a map object. This is only implemented for a few specific client versions. The type is an integer like `273` or `0x0107`. Coordinates are specified as e.g. `x:30 y:0 z:-25.5`; if coordinates are not specified, the object is created at the player's coordinates. Angles are specified as e.g. `r:0 p:0x1000 w:-0x400` (for roll, pitch, and yaw, respectively). Parameters are specified as e.g. `1:2.0 2:0.0 5:0x4000`; any unspecified parameters are set to zero. The object is only created for the calling player and is not added to the server's map state; if the object ever sends update commands (e.g. 6x0B), it will likely result in a disconnection.
* Personal state commands
* `$arrow <color-id>`: Change your lobby arrow color. The color may be specified by number (0-12) or by name (red, blue, green, yellow, purple, cyan, orange, pink, white, white2, white3, or black).
* `$secid <section-id>`: Set your override section ID. After running this command, any games you create will use your override section ID for rare drops instead of your character's actual section ID. If you're in a game and you are the leader of the game, this also immediately changes the item tables used by the server when creating items. To revert to your actual section id, run `$secid` with no name after it. On the proxy, this will not work if the remote server controls item drops. If the server does not allow cheat mode anywhere (that is, "CheatModeBehavior" is "Off" in config.json), this command does nothing.
* `$rand <seed>`: Set your override random seed (specified as a 32-bit hex value). This will make any games you create use the given seed for rare enemies and item drops. On the proxy, this command can cause desyncs with other players in the same game, since they will not see the overridden random seed. To remove the override, run `$rand` with no arguments. If the server does not allow cheat mode anywhere (that is, "CheatModeBehavior" is "Off" in config.json), this command does nothing.
* `$ln [name-or-type]`: Set the lobby number. Visible only to you. This command exists because some non-lobby maps can be loaded as lobbies with invalid lobby numbers. See the "GC lobby types" and "Ep3 lobby types" entries in the information menu for acceptable values here. Note that non-lobby maps do not have a lobby counter, so there's no way to exit the lobby without using either `$ln` again or `$exit`. On the game server, `$ln` reloads the lobby immediately; on the proxy, it doesn't take effect until you load another lobby yourself (which means you'll like have to use `$exit` to escape). Run this command with no argument to return to the default lobby.
* `$swa`: Enable or disable switch assist. When enabled, the server will unlock two-player and four-player doors in non-quest games when you step on any of the required switches.
* `$exit`: If you're in a lobby, send you to the main menu (which ends your proxy session, if you're in one). If you're in a game or spectator team, send you to the lobby (but does not end your proxy session if you're in one). Does nothing if you're in a non-Episode 3 game and no quest is in progress.
* `$patch <name>`: Run a patch on your client. `<name>` must exactly match the name of a patch on the server.
* Character data commands (non-proxy only)
* `$switchchar <slot>` (BB only): Switch to a different character from your account without logging out.
* `$savechar <slot>`: Save your current character data on the server in the specified slot. See the [server-side saves section](#server-side-saves) for more details.
* `$loadchar <slot>`: Load character data from the specified slot on the server, and replace your current character with it. See the [server-side saves section](#server-side-saves) for more details.
* `$bbchar <username> <password> <slot>`: Save your current character data on the server in a different account's BB character slots. See the [server-side saves section](#server-side-saves) for more details.
* `$checkchar [slot]`: Tells you basic information about a server-side character previously saved using `$savechar`. If `slot` is not given, tells you which slots are used and which are free.
* `$deletechar <slot>`: Deletes a server-side character previously saved using `$savechar`.
* `$edit <stat> <value>`: Modify your character data. See the [using $edit](#using-edit) section for details.
* Blue Burst player commands (non-proxy only)
* `$bank [number]`: Switch your current bank, so you can access your other character's banks (if `number` is 1-4) or your shared account bank (if `number` is 0). If `number` is not given, switch back to your current character's bank.
* `$save`: Save your character, system, and Guild Card data immediately. (By default, your character is saved every 60 seconds while online, and your account and Guild Card data are saved whenever they change.)
* Game state commands (non-proxy only)
* `$maxlevel <level>`: Set the maximum level for players to join the current game. (This only applies when joining; if a player joins and then levels up past this level during the game, they are not kicked out, but won't be able to rejoin if they leave.)
* `$minlevel <level>`: Set the minimum level for players to join the current game.
* `$password <password>`: Set the game's join password. To unlock the game, run `$password` with nothing after it.
* `$dropmode [mode]`: Change the way item drops behave in the current game. `mode` can be `none`, `client`, `shared`, `private`, or `duplicate`. If `mode` is not given, tells you the current drop mode without changing it. See the [item tables and drop modes section](#item-tables-and-drop-modes) for more information.
* `$persist`: Enable or disable persistence for the current game. When persistence is on, the game will not be deleted when the last player leaves. The states of enemies, objects, and switches will be saved, and items left on the floor will not be deleted. (But if you're in the private or duplicate drop mode, items dropped by enemies are deleted - to make sure a certain item won't be deleted, you can pick it up and drop it again.) If the game is empty for too long (15 minutes by default), it is then deleted.
* Episode 3 commands (non-proxy only)
* `$spec`: Toggle the allow spectators flag for Episode 3 games. If any players are spectating when this flag is disabled, they are sent back to the lobby.
* `$inftime`: Toggle infinite-time mode. Must be used before starting a battle. If infinite-time mode is on, the overall and per-phase time limits will be disabled regardless of the values chosen during battle rules setup. After completing a battle, infinite-time mode is reset to the server's default value (which can be set in Episode3BehaviorFlags in config.json).
* `$dicerange [d:L-H] [1:L-H] [a1:L-H] [d1:L-H]`: Set override dice ranges for the next battle. The min and max dice values from the rules setup menu always apply to the ATK dice, but you can specify a different range for the DEF dice with `d:2-4` (for example). The `1:` override applies to the 1-player team in a 2v1 game (so you would set the 2-player team's desired dice range in the rules menu). You can also specify the 1-player team's ATK and DEF ranges separately with the `a1:` and `d1:` overrides. Note that these ranges will only be used if the chosen map or quest does not override them.
* `$stat <what>`: Show a statistic about your player or team in the current battle. `<what>` can be `duration`, `fcs-destroyed`, `cards-destroyed`, `damage-given`, `damage-taken`, `opp-cards-destroyed`, `own-cards-destroyed`, `move-distance`, `cards-set`, `fcs-set`, `attack-actions-set`, `techs-set`, `assists-set`, `defenses-self`, `defenses-ally`, `cards-drawn`, `max-attack-damage`, `max-combo`, `attacks-given`, `attacks-taken`, `sc-damage`, `damage-defended`, or `rank`.
* `$surrender`: Cause your team to immediately lose the current battle. If your story character is already defeated, you can't surrender - only your teammate can.
* `$saverec <name>`: Save the recording of the last battle.
* `$playrec <name>`: Play a battle recording. This command creates a spectator team and plays the specified recording as if it were happening in real time. By default, playback will start immediately when the spectator team is ready; you can delay this to allow others to join by prepending a `!` to the recording name. In that case, using `$playrec` again (with no argument) within the spectator team will start playback.
* Cheat mode commands
* `$cheat` (non-proxy only): Enable or disable cheat mode for the current game. All other cheat mode commands do nothing if cheat mode is disabled. By default, cheat mode is off in new games but can be enabled; there is an option in config.json that allows you to disable cheat mode entirely, or set it to on by default in new games. Cheat mode is always enabled on the proxy, unless cheat mode is disabled on the entire server.
* `$infhp`: Enable or disable infinite HP mode. Applies to only you; does not affect other players. When enabled, one-hit KO attacks will still kill you, but on most versions of the game, the server will automatically revive you if you die. Infinite HP also automatically cures status ailments.
* `$inftp`: Enable or disable infinite TP mode. Applies to only you; does not affect other players. Does not work on DCv1 or earlier versions.
* `$fastkill`: Enable or disable fast kills. Applies to only you; does not affect other players. When enabled, the server will kill any enemy after you hit it once. Bosses are not affected by fast kills.
* `$warpme <floor-id>` (or `$warp <floor-id>`): Warp yourself to the given floor.
* `$warpall <floor-id>`: Warp everyone in the game to the given floor. You must be the leader to use this command, unless you're on the proxy.
* `$next`: Warp yourself to the next floor.
* `$item <desc>` (or `$i <desc>`): Create an item. `desc` may be a description of the item or a string of hex data specifying the item code. Item codes are 16 hex bytes; at least 2 bytes must be specified, and all unspecified bytes are zeroes. If you are on the proxy, you must not be using Blue Burst for this command to work. On the game server, this command works for all versions. Here are some examples to illustrate the syntax (nothing is case-sensitive, and everything except the item name itself is optional):
* `$item Saber +5 0/10/25/0/10` (weapon with special, grind and attributes)
* `$item ???? Draw Autogun` (untekked weapon with special; can have grind/attributes too, as above)
* `$item SEALED J-SWORD K:2000` (weapon with kill count)
* `$item ES APHEX ZALURE TWIN +200` (ES weapon must be prefixed with "ES"; name comes before special)
* `$item DF FIELD +10DEF +20EVP +4` (armor with DFP bonus, EVP bonus, and slot count)
* `$item RED MERGE +10DFP +20EVP` (shield; same as armor except without slot count)
* `$item Knight/Power +9` (unit with specific modifier)
* `$item Knight/Power++` (unit with normal modifier; ++/-- are +4/-4 and +/- are +2/-2)
* `$item LIMITER K:1000` (sealed unit with kill count)
* `$item Tapas PB:F,G,M&Y 120% 200IQ 5/195/0/0 green` (mag with PBs, synchro, IO, stats, and color)
* `$item Trimate x10` (tool with stack size)
* `$item Disk:Reverser` (technique disk without level)
* `$item Disk:Razonde Lv.30` (technique disk with level)
* `$item 1000 Meseta`
* `$unset <index>` (non-proxy only): In an Episode 3 battle, removes one of your set cards from the field. `<index>` is the index of the set card as it appears on your screen - 1 is the card next to your SC's icon, 2 is the card to the right of 1, etc. This does not cause a Hunters-side SC to lose HP, as they normally do when their items are destroyed. You can also destroy the assist card set on yourself with `$unset 0`.
* `$dropmode [mode]` (proxy only): Change the way item drops behave in the current game, if you are not on BB. Unlike the game server version of this command, using this on the proxy requires cheats to be enabled. This works by intercepting the drop requests sent to and from the leader. (So, if you are the leader and not using server drop mode on the remote server, it affects the entire game; otherwise, it affects only items generated by your actions.) `mode` can be `none` (no drops), `default` (normal drops), or `proxy` (use newserv's drop tables instead of the remote server's). If `mode` is not given, tells you the current drop mode without changing it.
* Aesthetic commands
* `$event <event>`: Set the current holiday event in the current lobby. Holiday events are documented in the "Using $event" item in the information menu. If you're on the proxy, this applies to all lobbies and games you join, but only you will see the new event - other players will not.
* `$allevent <event>` (non-proxy only): Set the current holiday event in all lobbies.
* `$song <song-id>` (Episode 3 only): Play a specific song in the current lobby.
* Administration commands (non-proxy only)
* `$ann <message>`: Send an announcement message. The message is sent as temporary on-screen text to all players in all games and lobbies. On BB, the message appears in the scrolling top bar.
* `$ann!`, `$ann?`, `$ann?!`: Same as `$ann`, but with `?`, omits the sender's name, and with `!`, sends the message as a Simple Mail message instead of on-screen text.
* `$silence <identifier>`: Silence a player (remove their ability to chat) or unsilence a player. The identifier may be the player's name or Guild Card number.
* `$kick <identifier>`: Disconnect a player. The identifier may be the player's name or Guild Card number.
* `$ban <duration> <identifier>`: Ban a player. The duration should be of the form `10m` (minutes), `10h` (hours), `10d` (days), `10w` (weeks), `10M` (months), or `10y` (years). (Numbers other than 10 may be used, of course.) As with `$kick`, the identifier may be the player's name or Guild Card number.
### Using $edit
The $edit command modifies your character data. This command doesn't work on V3 (GameCube/Xbox). If you are on V1 or V2 (DC or PC, not BB), your changes will be undone if you join a game - to save your changes, disconnect from the lobby.
Some subcommands are always available. They are:
* `$edit mat reset power`: Clear your usage of power materials (BB only)
* `$edit mat reset mind`: Clear your usage of mind materials (BB only)
* `$edit mat reset evade`: Clear your usage of evade materials (BB only)
* `$edit mat reset def`: Clear your usage of def materials (BB only)
* `$edit mat reset luck`: Clear your usage of luck materials (BB only)
* `$edit mat reset hp`: Clear your usage of HP materials (BB only)
* `$edit mat reset tp`: Clear your usage of TP materials (BB only)
* `$edit mat reset all`: Clear your usage of all materials except HP and TP (BB only)
* `$edit mat reset every`: Clear your usage of all materials including HP and TP (BB only)
* `$edit namecolor AARRGGBB`: Set your name color (AARRGGBB specified in hex)
* `$edit language L`: Set your language (Generally only useful on BB; values for L: J = Japanese, E = English, G = German, F = French, S = Spanish, B = Simplified Chinese, T = Traditional Chinese, K = Korean)
* `$edit name NAME`: Set your character name
* `$edit npc NPC-NAME`: Set or remove an NPC skin on your character (use `none` to remove a skin). The NPC names are:
* On all versions except DCv1 and early prototypes: `ninja`, `rico`, `sonic`, `knuckles`, `tails`
* On GC, Xbox, and BB: `flowen`, `elly`
* On BB only: `momoka`, `irene`, `guild`, `nurse`
* `$edit secid SECID-NAME`: Set your section ID (cheat mode is required unless your character is Level 1)
The remaining subcommands are only available if cheat mode is enabled on the server. They are:
* `$edit atp N`: Set your ATP to N until stats are updated (e.g. by leveling up)
* `$edit mst N`: Set your MST to N until stats are updated
* `$edit evp N`: Set your EVP to N until stats are updated
* `$edit dfp N`: Set your DFP to N until stats are updated
* `$edit ata N`: Set your ATA to N until stats are updated
* `$edit lck N`: Set your LCK to N until stats are updated
* `$edit hp N`: Set your HP to N until stats are updated
* `$edit meseta N`: Set the amount of Meseta in your inventory
* `$edit exp N`: Set your total amount of EXP (does not affect level)
* `$edit level N`: Set your current level (recomputes stats, but does not affect EXP)
* `$edit tech TECH-NAME LEVEL`: Set the level of one of your techniques
## REST API
newserv has an optional HTTP server that provides a way to programmatically get data from the server in realtime. This is intended for use with external integrations; for example, a web site could query this API to get the current player count to display on the home page.
The HTTP server is disabled by default, and you have to explicitly enable it in config.json if you want this functionality. **If you enable it, make sure that the HTTP port can't be accessed from the public Internet.** The API provides a lot of internal data about players and games, and it should only be accessed by programs that you've written or that you trust.
To enable the HTTP server, add a port number in the HTTPListen list in config.json. The HTTP server will listen on that port.
All returned data is JSON-encoded, and all request data (for POST requests) must also be JSON-encoded with the `Content-Type: application/json` header.
The HTTP server has the following endpoints:
* `GET /`: Returns the server's build date and revision.
* `GET /y/data/ep3-cards`: Returns the Episode 3 card definitions.
* `GET /y/data/ep3-cards-trial`: Returns the Episode 3 Trial Edition card definitions.
* `GET /y/data/common-tables`: Returns the parameters for generating common items (ItemPT files). This endpoint returns a lot of data and can be slow!
* `GET /y/data/rare-tables`: Returns a list of rare table names.
* `GET /y/data/rare-tables/<TABLE-NAME>` (for example, `/y/data/rare-tables/rare-table-v4`): Returns the contents of a rare item table.
* `GET /y/data/quests`: Returns metadata about all available quests and quest categories.
* `GET /y/data/config`: Returns the server's configuration file.
* `GET /y/accounts`: Returns information about all registered accounts.
* `GET /y/clients`: Returns information about all connected clients on the game server.
* `GET /y/proxy-clients`: Returns information about all connected clients on the proxy.
* `GET /y/lobbies`: Returns information about all lobbies and games.
* `GET /y/server`: Returns information about the server.
* `GET /y/summary`: Returns a summary of the server's state, connected clients, active games, and proxy sessions.
* `WS /y/rare-drops/stream`: WebSocket endpoint that sends messages whenever an announceable rare item is dropped in any game. See below.
* `POST /y/shell-exec`: Runs a server shell command. Input should be a JSON dict of e.g. `{"command": "announce hello"}`; response will be a JSON dict of `{"result": "<result text>"}` or an HTTP error.
### Rare drop stream endpoint
The `/y/rare-drops/stream` endpoint provides a way to implement a drop log in e.g. Discord. For every announceable rare item, a message is sent to all connected clients on this endpoint. (Announceable rare items are items for which an in-game or server-wide text message is sent announcing the find.)
Upon connecting, you'll get the message `{"ServerType": "newserv"}`. After that, when a rare item announcement is sent, you'll get a message like this:
```
{
"PlayerAccountID", 12345,
"PlayerName", "SONIC",
"PlayerVersion", "GC_V3",
"GameName", "ttf",
"GameDropMode", "SERVER_PRIVATE",
"ItemData", "03000000 00010000 00000000 (0021002C) 00000000",
"ItemDescription", "Monomate x1",
"NotifyGame", true,
"NotifyServer", false,
}
```
# Non-server features
newserv has many CLI options, which can be used to access functionality other than the game server and proxy. Run `newserv help` to see a full list of the options and how to use each one.
The data formats that newserv can convert to/from are:
| Format | Encode/compress action | Decode/extract action |
|-------------------------------------|---------------------------|------------------------------|
| PRS compression | `compress-prs` | `decompress-prs` |
| PR2/PRC compression | `compress-pr2` | `decompress-pr2` |
| BC0 compression | `compress-bc0` | `decompress-bc0` |
| Raw encrypted data | `encrypt-data` | `decrypt-data` |
| Episode 3 command mask | `encrypt-trivial-data` | `decrypt-trivial-data` |
| Challenge Mode rank text | `encrypt-challenge-data` | `decrypt-challenge-data` |
| PSO DC quest file (.vms) | None | `decode-vms` |
| PSO GC quest file (.gci) | None | `decode-gci` |
| Download quest file (.dlq) | None | `decode-dlq` |
| Server quest file (.qst) | `encode-qst` | `decode-qst` |
| PSO DC save file (.vms) | `encrypt-vms-save` | `decrypt-vms-save` |
| PSO PC save file | `encrypt-pc-save` | `decrypt-pc-save` |
| PSO GC save file (.gci) | `encrypt-gci-save` | `decrypt-gci-save` |
| PSO Xbox save file | None | `decrypt-xbox-save` |
| PSO GC snapshot file | None | `decode-gci-snapshot` |
| Quest script (.bin) | `assemble-quest-script` | `disassemble-quest-script` |
| Quest map (.dat) | None | `disassemble-quest-map` |
| AFS archive (.afs) | None | `extract-afs` |
| BML archive (.bml) | None | `extract-bml` |
| PPK archive (.ppk) | None | `extract-ppk` |
| GSL archive (.gsl) | `generate-gsl` | `extract-gsl` |
| GVM texture (.gvm) | `encode-gvm` | None |
| Bitmap font (.fon) | `encode-bitmap-font` | `decode-bitmap-font` |
| Text archive | `encode-text-archive` | `decode-text-archive` |
| Unicode text set | `encode-unicode-text-set` | `decode-unicode-text-set` |
| Word Select data set | None | `decode-word-select-set` |
| Set data table | None | `disassemble-set-data-table` |
| Rare item table (AFS/GSL/JSON/HTML) | `convert-rare-item-set` | `convert-rare-item-set` |
There are several actions that don't fit well into the table above, which let you do other things:
* Compute the decompressed size of compressed PRS data without decompressing it (`prs-size`)
* Find the likely round1 or round2 seed for a corrupt save file (`salvage-gci`)
* Run a brute-force search for a decryption seed (`find-decryption-seed`)
* Format Episode 3 game data in a human-readable manner (`show-ep3-maps`, `show-ep3-cards`, `generate-ep3-cards-html`)
* Format Blue Burst battle parameter files in a human-readable manner (`show-battle-params`)
* Convert item data to a human-readable description, or vice versa (`describe-item`)
* Show the server's item and level tables (`show-item-tables`, `show-level-tables`)
* Connect to another PSO server and pretend to be a client (`cat-client`)
* Generate or describe DC serial numbers (`generate-dc-serial-number`, `inspect-dc-serial-number`)
# Docker
Docker is new and mostly unsupported at this time. However, here are some best-effort steps to build and run in a docker container on Ubuntu Linux.
Tested on Ubuntu 22.04.4 LTS.
Note: You cannot have anything except this docker container using port 53 (DNS) on your server.
Install prerequisites
```
sudo apt install -y git
sudo apt install -y cmake. ## minimum version is 3.10. Check installed version with "cmake --version"
```
Clone repository
```
cd ~
git clone https://github.com/fuzziqersoftware/newserv/
cd ~/newserv
```
Build newserv. This will take a while. Don't forget the period at the end!
```
sudo docker build -t newserv .
```
Create persistent directories. Assuming you want to store the persistent data in your home directory
```
mkdir ~/newservPersist
mkdir ~/newservPersist/players
mkdir ~/newservPersist/teams
mkdir ~/newservPersist/licenses
```
Copy config file to config dir
```
cp ~/newserv/system/config.example.json ~/newservPersist/config.json
```
Edit config.json
```
nano ~/newservPersist/config.json
```
Pro tip:
Set "LocalAddress" to the static, LAN IP address of your server. If your server LAN IP is "192.168.0.10":
"LocalAddress": "192.168.0.10",
Set "ExternalAddress" to the WAN IP address of your network. If your WAN IP is "8.8.8.8":
"ExternalAddress": "8.8.8.8",
For Dolphin > Settings. Set SP1 to "Broadband Adapter (HLE)" Click [...] next to this, and set the DNS to the IP address of your server. Then start the game. Changes will not take affect if the game is running.
Docker run. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
docker run --name newserv -p 53:53/udp -p 5100:5100 -p 5110:5110 -p 5111:5111 -p 5112:5112 -p 9064:9064 -p 9100:9100 -p 9103:9103 -p 9300:9300 -p 11000:11000 -p 12000:12000 -p 12004:12004 -p 12005:12005 -v /etc/localtime:/etc/localtime:ro -v /home/changeme/newservPersist/config.json:/newserv/system/config.json -v /home/changeme/newservPersist/players:/newserv/system/players -v /home/changeme/newservPersist/teams:/newserv/system/teams -v /home/changeme/newservPersist/licenses:/newserv/system/licenses --restart no newserv:latest
```
Docker run host network mode. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
docker run --net host --name newserv -v /etc/localtime:/etc/localtime:ro -v /home/changeme/newservPersist/config.json:/newserv/system/config.json -v /home/changeme/newservPersist/players:/newserv/system/players -v /home/changeme/newservPersist/teams:/newserv/system/teams -v /home/changeme/newservPersist/licenses:/newserv/system/licenses --restart no newserv:latest
```
Docker compose. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
name: psonewserv
services:
newserv:
container_name: newserv
ports:
- 53:53/udp
- 5100:5100
- 5110:5110
- 5111:5111
- 5112:5112
- 9064:9064
- 9100:9100
- 9103:9103
- 9300:9300
- 11000:11000
- 12000:12000
- 12004:12004
- 12005:12005
volumes:
- /etc/localtime:/etc/localtime:ro
- /home/changeme/newservPersist/config.json:/newserv/system/config.json
- /home/changeme/newservPersist/players:/newserv/system/players
- /home/changeme/newservPersist/teams:/newserv/system/teams
- /home/changeme/newservPersist/licenses:/newserv/system/licenses
restart: no ## Set to whatever you want.
image: newserv:latest
```
Docker compose host network mode. Remember to change /home/changeme/newservPersist to your persistent directory. Do not use aliases such as '~'
```
name: psonewserv
services:
newserv:
container_name: newserv
volumes:
- /etc/localtime:/etc/localtime:ro
- /home/changeme/newservPersist/config.json:/newserv/system/config.json
- /home/changeme/newservPersist/players:/newserv/system/players
- /home/changeme/newservPersist/teams:/newserv/system/teams
- /home/changeme/newservPersist/licenses:/newserv/system/licenses
restart: no ## Set to whatever you want.
network_mode: host
image: newserv:latest
```
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
import os
import shutil
import subprocess
import sys
from typing import Callable
def filter_directory(dir: str, predicate: Callable[[str], bool]):
for filename in os.listdir(dir):
if not predicate(filename):
path = os.path.join(dir, filename)
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
def main():
print("Deleting existing release directory")
if os.path.exists("release"):
shutil.rmtree("release")
if os.path.exists("release.zip"):
os.remove("release.zip")
os.mkdir("release")
print("Adding executables")
shutil.copy("newserv", "release/newserv-macos")
shutil.copy("newserv.exe", "release/newserv-windows.exe")
shutil.copy("README.md", "release/README.md")
print("Adding system directory")
shutil.copytree("system", "release/system")
print("Removing instance-based and temporary files")
filter_directory(
"release/system",
lambda filename: (not filename.endswith(".json"))
or filename == "config.example.json",
)
filter_directory(
"release/system/ep3", lambda filename: not filename.startswith("cardtex")
)
filter_directory(
"release/system/client-functions",
lambda filename: filename not in ("Debug-Private", "FastLoading", "notes.txt"),
)
filter_directory("release/system/dol", lambda filename: False)
filter_directory("release/system/ep3/banners", lambda filename: False)
filter_directory("release/system/ep3/battle-records", lambda filename: False)
filter_directory("release/system/licenses", lambda filename: False)
filter_directory("release/system/players", lambda filename: False)
filter_directory(
"release/system/quests",
lambda filename: filename not in ("private", "includes"),
)
filter_directory("release/system/teams", lambda filename: filename == "base.json")
subprocess.check_call(["find", "release", "-name", ".DS_Store", "-delete"])
subprocess.check_call(["find", "release", "-name", "*.WIP-s", "-delete"])
print("Setting up configuration")
os.rename("release/system/config.example.json", "release/system/config.json")
if __name__ == "__main__":
sys.exit(main())
+206 -10
View File
@@ -13,6 +13,7 @@ Version codes (from README.md):
1OJF: PSO DC v1 JP
1OEF: PSO DC v1 US
1OPF: PSO DC v1 EU
2OJ4: PSO DC 08/2001 prototype
2OJ5: PSO DC 08/2001 prototype
2OJF: PSO DC v2 JP
2OEF: PSO DC v2 US
@@ -80,12 +81,14 @@ Disable item equip restrictions ("God of equip")
3OJ5 => 041050D4 38000005
3OJT => 0415BF50 38000005
3OP0 => 041052D4 38000005
59NJ => 005C9F35 E9A7000000
59NL => 005C9F31 E9A7000000
All items visible in Pioneer 2
3OE1 => 04102D88 38600000
Mags visible in Pioneer 2
59NJ => 005D8F27 EB04
59NL => 005D8F4B EB04
Disable pause menu background + offset
@@ -93,6 +96,9 @@ Disable pause menu background + offset
0428735C 4800000C
3OE2 => 0424CED8 48000370
042887D8 4800000C
59NJ => 00719C58 9090
00733C57 9090
00733ABE 90E9
59NL => 00719B54 9090
00733BA7 9090
00733A0E 90E9
@@ -212,6 +218,9 @@ Auto-press A as fast as possible during loading screens
3SJT => 040C2C48 60000000
3SJ0 => 042F8B74 60000000
CARD lobby battle tables react immediately
3SE0 => 042C04D4 60000000
Change type of all loading screens
Values for X: 0 = lobby/game join, 1 = quest load, 3 = pipe up, 4 = pipe down, anything else = silent black screen
3OE1 => 0401CA04 3BE0000X
@@ -251,16 +260,6 @@ Unlock all COM decks
3SP0 => 042CB414 38600001
3SE0 => 042CA908 38600001
Enable marker color menu in all lobbies
3OJ2 => 04138200 3800000E
3OJ3 => 04138508 3800000E
3OJ4 => 041390AC 3800000E
3OJ5 => 041385B0 3800000E
3OE0 => 041384BC 3800000E
3OE1 => 041384BC 3800000E
3OE2 => 041385C0 3800000E
3OP0 => 04138840 3800000E
Enable all lobby counter options in non-CARD lobbies
3SE0 => 04096A8C 480000C0
04096B4C 38800007
@@ -276,6 +275,21 @@ Enable Change Marker option in all lobbies
3OE2 => 041385C8 4800004C
3OP0 => 04138848 4800004C
Lobby arrows rotation speed modifier
3OE1 => 041C6B64 3804XXXX (default 0800)
Change lobby arrow colors
Note: All values as floats in [0, 1]
3OE1 => 04443780 AAAAAAAA (slot 0)
04443784 RRRRRRRR (slot 0)
04443788 GGGGGGGG (slot 0)
0444378C BBBBBBBB (slot 0)
04443790 AAAAAAAA (slot 1)
04443794 RRRRRRRR (slot 1)
04443798 GGGGGGGG (slot 1)
0444379C BBBBBBBB (slot 1)
...
Change HUD color mask
3SE0 => 0438CA8C 3C00RRGG
0438CA90 6000BBAA
@@ -628,6 +642,8 @@ Fast tekker (skips wind-up jingle)
0023EF77 jmp +0x0A
4OPU => 0023F14C mov dword [ebp + 0x14C], 1
0023F167 jmp +0x0A
59NJ => 006DA14B mov dword [edi + 0x14C], 1
006DA168 jmp +0x0B
59NL => 006DA113 mov dword [edi + 0x14C], 1
006DA130 jmp +0x0B
@@ -921,3 +937,183 @@ Change particle colors in quest loading screen
Floor warp loading screen speed modifier
// XXXX = speed; default is 01B4; 0800 = very fast/wobbly; 0020 = very slow
3OE1 => 0434A350 3863XXXX
Slow Gibbles fix
3OJ2 => 042D6A48 C022FD98
042D6A6C C022FD98
3OJ3 => 042D7A00 C022FDA0
042D7A24 C022FDA0
3OJ4 => 042D8B34 C022FDA0
042D8B58 C022FDA0
3OJ5 => 042D88E0 C022FDA0
042D8904 C022FDA0
3OE0 => 042D7428 C022FDA8
042D744C C022FDA8
3OE1 => 042D746C C022FDA8
042D7490 C022FDA8
3OE2 => 042D8A94 C022FDA8
042D8AB8 C022FDA8
3OP0 => 042D8228 C022FDA8
042D824C C022FDA8
Override Challenge mode random enemy location tables limit
2OJ5 => 8C2501B2 XXE5 (count as byte)
2OJF => 8C24E98E XXE5 (count as byte)
2OEF => 8C2501A2 XXE5 (count as byte)
2OPF => 8C244C7E XXE5 (count as byte)
2OJW => 005AA2FE XXXXXXXX (count * 4 as little-endian dword)
005AA30C XXXXXXXX (count as little-endian dword)
2OJZ => 005A908E XXXXXXXX (count * 4 as little-endian dword)
005A909D XXXXXXXX (count as little-endian dword)
3OE0 => 04209448 3880XXXX (count as big-endian word)
3OE1 => 04209448 3880XXXX (count as big-endian word)
3OE2 => 0420A330 3880XXXX (count as big-endian word)
3OJ2 => 04208C4C 3880XXXX (count as big-endian word)
3OJ3 => 042094C0 3880XXXX (count as big-endian word)
3OJ4 => 0420A5A8 3880XXXX (count as big-endian word)
3OJ5 => 04209FFC 3880XXXX (count as big-endian word)
3OP0 => 04209D2C 3880XXXX (count as big-endian word)
4OJB => 002E527C XXXXXXXX (count as little-endian dword)
4OJD => 002E5DFC XXXXXXXX (count as little-endian dword)
4OJU => 002E740C XXXXXXXX (count as little-endian dword)
4OED => 002E71DC XXXXXXXX (count as little-endian dword)
4OEU => 002E742C XXXXXXXX (count as little-endian dword)
4OPD => 002E720C XXXXXXXX (count as little-endian dword)
4OPU => 002E745C XXXXXXXX (count as little-endian dword)
59NJ => 0080FA3F XXXXXXXX (count * 4 as little-endian dword)
0080FA58 XXXXXXXX (count as little-endian dword)
59NL => 0080ECB7 XXXXXXXX (count * 4 as little-endian dword)
0080ECD0 XXXXXXXX (count as little-endian dword)
Disable dust effect in CCA
3OJT => 042F4EE8 48000010
3OJ2 => 04297ECC 48000010
3OJ3 => 04298C94 48000010
3OJ4 => 04299DAC 48000010
3OJ5 => 04299B60 48000010
3OE0 => 042987EC 48000010
3OE1 => 04298830 48000010
3OE2 => 04299D14 48000010
3OP0 => 042994BC 48000010
Inventory debugging code
(makes a copy of player 1's inventory at 8000A04C, updated every frame)
3OE2 => 0400A000 9421FFE0 // stwu [r1 - 0x20], r1
0400A004 7C0802A6 // mflr r0
0400A008 90010024 // stw [r1 + 0x24], r0
0400A00C 3C608051 // lis r3, 0x8051
0400A010 8063EA10 // lwz r3, [r3 - 0x15F0] // r3 = TObjPlayer_objs[0]
0400A014 3C808000 // lis r4, 0x8000
0400A018 6084A050 // ori r4, r4, 0xA050
0400A01C 9064FFFC // stw [r4 - 4], r3 // 8000A04C = 0 (in case player is null)
0400A020 28030000 // cmplwi r3, 0
0400A024 41820014 // beq +0x10
0400A028 481AE2E9 // bl TObjPlayer_export_inventory // (TObjPlayer_objs[0], 0x8000A050)
0400A02C 3C808000 // lis r4, 0x8000
0400A030 6084A04C // ori r4, r4, 0xA04C
0400A034 90640000 // stw [r4], r3 // 8000A04C = inventory item count
0400A038 80010024 // lwz r0, [r1 + 0x24]
0400A03C 7C0803A6 // mtlr r0
0400A040 38210020 // addi r1, r1, 0x20
0400A044 4E800020 // blr
041A39B8 4BE66648 // b 8000A000 // main_phase_0E_exec_frame return - chain to hook at 8000A000
Load qdefault.bin quest script from disk in offline free play
(Don't use this on a disc image where qdefault.bin doesn't exist; there is a bug in the quest script environment constructor that will leave the current directory set incorrectly if the file doesn't exist, and the game will softlock)
3OE1 => 041A3A30 4BE6656D
041A3088 4BE66F1D
04009F9C 38600002
04009FA0 48000008
04009FA4 38600000
04009FA8 7C0802A6
04009FAC 9421FFE0
04009FB0 90010024
04009FB4 90610008
04009FB8 386001A4
04009FBC 4821F581
04009FC0 28030000
04009FC4 41820018
04009FC8 808DBD20
04009FCC 3CA08000
04009FD0 60A59FF0
04009FD4 38C00000
04009FD8 481EC171
04009FDC 80610008
04009FE0 80010024
04009FE4 38210020
04009FE8 7C0803A6
04009FEC 4E800020
04009FF0 71646566
04009FF4 61756C74
04009FF8 2E62696E
04009FFC 00000000
3OE2 => 041A3B5C 4BE66441
041A31B0 4BE66DF5
04009F9C 38600002
04009FA0 48000008
04009FA4 38600000
04009FA8 7C0802A6
04009FAC 9421FFE0
04009FB0 90010024
04009FB4 90610008
04009FB8 386001A4
04009FBC 48220635
04009FC0 28030000
04009FC4 41820018
04009FC8 808DBD40
04009FCC 3CA08000
04009FD0 60A59FF0
04009FD4 38C00000
04009FD8 481EC309
04009FDC 80610008
04009FE0 80010024
04009FE4 38210020
04009FE8 7C0803A6
04009FEC 4E800020
04009FF0 71646566
04009FF4 61756C74
04009FF8 2E62696E
04009FFC 00000000
Enable quest board menu in free play (for use with the above code)
3OE0 => 04262B44 38600001
3OE1 => 04262B44 38600001
3OE2 => 04263F04 38600001
3OJ2 => 0426226C 38600001
3OJ3 => 04262E44 38600001
3OJ4 => 04263EB8 38600001
3OP0 => 0426374C 38600001
All classes' footsteps sound like RAcast's
(Change the 2 in 38600002 to 0 for human/Newman, 1 for lighter androids, or 3 if you want to be annoyed)
3OE0 => 041B3ED0 38600002
041B3ED4 4E800020
3OE1 => 041B3ED0 38600002
041B3ED4 4E800020
3OE2 => 041B4068 38600002
041B406C 4E800020
3OJ2 => 041B3AE4 38600002
041B3AE8 4E800020
3OJ3 => 041B3F38 38600002
041B3F3C 4E800020
3OJ4 => 041B552C 38600002
041B5530 4E800020
3OJ5 => 041B4004 38600002
041B4008 4E800020
3OJT => 0420A120 38600002
0420A124 4E800020
3OP0 => 041B4524 38600002
041B4528 4E800020
3SE0 => 040D0378 38600002
040D037C 4E800020
3SJ0 => 040D0394 38600002
040D0398 4E800020
3SJT => 040D431C 38600002
040D4320 4E800020
3SP0 => 040D07BC 38600002
040D07C0 4E800020
Rappy size modifier
3OE1 => 040C1E24 48000020 // Disable flag check in render
045D0718 40800000 // X/Z scale as float (here, 4.0)
045D071C 40800000 // Y scale as float (here, 4.0)
+2 -1
View File
@@ -2,4 +2,5 @@
1OJ2 (11/2000): test1.st-pso.games.sega.net
1OJ3 (12/2000): sg107634.csrd.sega.co.jp OR master.pso.dream-key.com
1OJ4 (01/2001): master.pso.dream-key.com
2OJ5 (08/2001; v2): game01.st-pso.games.sega.net
2OJ4 (08/06/2001; v2): game01.st-pso.games.sega.net
2OJ5 (08/22/2001; v2): game01.st-pso.games.sega.net
+586
View File
@@ -0,0 +1,586 @@
NOTE: The NNF descriptions are from Kayak's movement data notes: https://qedit.info/index.php?title=Get_movement_data
MOVEMENT DATA 00 (BOOTA)
MOVEMENT DATA 01 (ZE_BOOTA)
MOVEMENT DATA 03 (BA_BOOTA)
MOVEMENT DATA 11 (GORAN)
MOVEMENT DATA 12 (PYRO_GORAN)
MOVEMENT DATA 13 (GORAN_DETONATOR)
MOVEMENT DATA 4A (BOOMA, MERILLIA)
MOVEMENT DATA 4B (GOBOOMA, MERILTAS)
MOVEMENT DATA 4C (GIGOBOOMA)
MOVEMENT DATA 4E (EVIL_SHARK, DOLMOLM)
MOVEMENT DATA 4F (PAL_SHARK, DOLMDARL)
MOVEMENT DATA 50 (GUIL_SHARK)
MOVEMENT DATA 52 (DIMENIAN)
MOVEMENT DATA 53 (LA_DIMENIAN)
MOVEMENT DATA 54 (SO_DIMENIAN)
fparam1 = idle move speed (when returning to initial position)
fparam2 = idle walking animation speed
fparam3 = engaged move speed (when approaching a player)
fparam4 = engaged animation speed
fparam5 = MERILLIA, MERILTAS; TODO: 3OE1:800D5750; poison cloud damage
fparam5 = DOLMOLM, DOLMDARL; TODO: 3OE1:802FFA70; max distance to notice player?; NNF: Possibly frames before getting trapped
fparam5 = BOOTA, ZE_BOOTA, BA_BOOTA; TODO: 59NL:005A56B5, 59NL:005A5361
fparam5 = GORAN, PYRO_GORAN, GORAN_DETONATOR; TODO: 59NL:005ACDD2
fparam6 = MERILLIA, MERILTAS; TODO: 3OE1:800D7074; NNF: run away speed
fparam6 = GORAN, PYRO_GORAN, GORAN_DETONATOR; TODO: 59NL:005AD31E, 59NL:005ACC23, 59NL:005ACB4A; length of a vector (speed?)
iparam1 = MERILLIA, MERILTAS; low HP threshold percentage (0-100); controls how often it runs away
iparam1 = DOLMOLM, DOLMDARL; TODO: 3OE1:802FFFBC; NNF: Angle to use Trap (Cannot exceed Attack data angle)
iparam1 = BOOTA, ZE_BOOTA, BA_BOOTA; TODO: 59NL:005A53D7, 59NL:005A531C, 59NL:005A5092 (special case for 01 only apparently?)
iparam1 = GORAN, PYRO_GORAN, GORAN_DETONATOR; TODO: 59NL:005AD0CF, 59NL:005ACE95; looks like an angle in degrees (range [0, 359])
iparam2 = DOLMOLM, DOLMDARL; TODO: 3OE1:80300154; NNF: Length of time in seconds Dolmolm trap lasts
iparam2 = BOOTA, ZE_BOOTA, BA_BOOTA; TODO: 59NL:005A5580
iparam2 = GORAN, PYRO_GORAN, GORAN_DETONATOR; TODO: 59NL:005ACD0F
MOVEMENT DATA 00 (MOTHMANT)
fparam1 = speed when low to the ground (chase mode)
iparam2 = delay before attack (applies when in chase mode and reached target, or between attacks when near target)
MOVEMENT DATA 01 (MONEST)
(loaded with assets but not used)
MOVEMENT DATA 02 (SAVAGE_WOLF)
MOVEMENT DATA 03 (BARBAROUS_WOLF)
(loaded with assets but not used)
MOVEMENT DATA 04 (POISON_LILY)
MOVEMENT DATA 05 (NAR_LILY)
MOVEMENT DATA 25 (DEL_LILY)
fparam1 = DEL_LILY; TODO: 3OE1:800C25C8; damage for some kind of attack
iparam1 = POISON_LILY, NAR_LILY; Megid level, only used in Ultimate
MOVEMENT DATA 05 (SAND_RAPPY_CRATER)
MOVEMENT DATA 06 (DEL_RAPPY_CRATER)
MOVEMENT DATA 17 (SAND_RAPPY_DESERT)
MOVEMENT DATA 18 (RAG_RAPPY, DEL_RAPPY_DESERT)
MOVEMENT DATA 19 (AL_RAPPY, LOVE_RAPPY, SAINT_RAPPY, EGG_RAPPY, HALLO_RAPPY)
fparam1 = hitbox radius
fparam2 = TODO: 3OE1:TObjEneLappy_set_params_from_movement_data, 59NL:FUN_00526A7C; NNF: Flinch time (higher number is less flinch time)
fparam3 = TODO: 3OE1:TObjEneLappy_set_params_from_movement_data, 59NL:FUN_00526A7C; NNF: Animation speed at which their legs move after getting hit once they fake die (negative values make them run underground, 0 makes it so their legs don't move along and they just slide across the ground lol.)
MOVEMENT DATA 06 (SINOW_BEAT, SINOW_BERILL)
MOVEMENT DATA 10 (SINOW_GOLD, SINOW_SPIGELL)
fparam1 = TODO: 3OE1:800E63F0, 3OE1:800F38D8; NNF: Movement speed
fparam2 = SINOW_BEAT, SINOW_GOLD; TODO: 3OE1:800E6410; NNF: Clone movement speed (invisible flag must be set to 0 to get clones)
fparam3 = TODO: 3OE1:800E5D0C, 3OE1:800F3234; NNF: The speed (and amount) it moves forward right when it is about to attack you
fparam4 = TODO: 3OE1:800E7BA0, 3OE1:800E7DA8, 3OE1:800F53E4
fparam5 = TODO: 3OE1:800E7BA8, 3OE1:800F53EC
fparam6 = SINOW_BERILL, SINOW_SPIGELL; TODO: 3OE1:800F21D4, 3OE1:800F2E84; probability of something (0-1)
iparam1 = Shifta/Deband/Resta level
iparam2 = TODO: 3OE1:800E5200, 3OE1:800F2B8C
iparam3 = TODO: 3OE1:800E5D78, 3OE1:800F32A0; NNF: Amount of time (in frames) that the sinow pauses after it attacks
iparam4 = SINOW_BERILL, SINOW_SPIGELL; attack tech level (Rafoie in Ultimate, Gifoie otherwise)
MOVEMENT DATA 07 (CANADINE)
MOVEMENT DATA 08 (CANADINE_RING)
MOVEMENT DATA 09 (CANANE)
fparam1 = TODO: 3OE1:8009CEF4; NNF: Movement speed of animation perfomed just before melee attack
fparam2 = electrical attack damage
fparam3 = explosion damage
iparam1 = TODO: 3OE1:8009D4AC; NNF: Zonde attack charge time (higher is longer)
iparam2 = TODO: 3OE1:8009D508; NNF: Delay after laser targetting ends before shooting Zonde
iparam3 = TODO: 3OE1:8009D59C; NNF: Delay after casting Zonde
iparam4 = TODO: 3OE1:8009D5B8; NNF: Number of times Zonde is cast before they go to the next cycle
iparam5 = TODO: 3OE1:8009C5C8; NNF: stun frames after being hit
iparam6 = CANANE; TODO: 3OE1:8009B148; number of out-fighters (see CANADINE description in Map.cc); NNF: How many of the 8 ring Canadines will cast Zonde (numbers greater than 8 are treated as 8). The remaining number out of 8 will perform melee attacks instead. Value of 0 causes FSOD.
MOVEMENT DATA 07 (GEE)
iparam5 = TODO: 3OE1:800C9778; probably same as CANADINE (movement data 07 iparam5)
MOVEMENT DATA 07 (ZU_CRATER)
MOVEMENT DATA 08 (PAZUZU_CRATER)
MOVEMENT DATA 1B (ZU_CRATER)
MOVEMENT DATA 1C (PAZUZU_CRATER)
fparam1 = TODO: 59NL:005B4A3C
MOVEMENT DATA 08 (PIG_RAY)
MOVEMENT DATA 09 (UL_RAY)
fparam1 = TODO: 3OE1:803072B0, 3OE1:80307354; speed?
iparam1 = TODO: 3OE1:803075FC; frame count for something
MOVEMENT DATA 09 (ASTARK)
fparam1 = TODO: 59NL:005A2B8F
fparam2 = TODO: 59NL:005A2E1E
fparam3 = TODO: 59NL:005A31D1
fparam4 = TODO: 59NL:005A3124
fparam5 = TODO: 59NL:005A4992
fparam6 = TODO: 59NL:005A2B79
iparam1 = TODO: 59NL:005A4947
iparam2 = TODO: 59NL:005A499D
MOVEMENT DATA 0A (CHAOS_SORCERER)
iparam1 = attack tech 1 level (Grants in Ultimate, Gizonde in non-Ultimate Ep2, Rafoie in non-Ultimate Ep1)
iparam2 = attack teck 2 level (Megid in Ultimate, Gibarta otherwise)
iparam3 = Resta level
MOVEMENT DATA 0B (BEE_R)
MOVEMENT DATA 0C (BEE_L)
(loaded with assets but not used)
MOVEMENT DATA 0D (SATELLITE_LIZARD_CRATER)
MOVEMENT DATA 0E (YOWIE_CRATER)
MOVEMENT DATA 1D (SATELLITE_LIZARD_DESERT)
MOVEMENT DATA 1E (YOWIE_DESERT)
fparam1 = TODO: 59NL:005AEBC5; looks like an angle in degrees (range [0, 359])
fparam2 = TODO: 59NL:005AEBEE
MOVEMENT DATA 0D (DARK_BRINGER)
fparam1 = TODO: 3OE1:FUN_80097F98; NNF: charge speed
fparam2 = TODO: 3OE1:FUN_800983F8; NNF: movement speed
fparam6 = TODO: 3OE1:80097F3C; NNF: Regular attack cooldown. Delay between going red and shooting.
iparam2 = TODO: 3OE1:FUN_80097F98; NNF: cooldown time after shooting
iparam3 = damage for charge attack; 3OE1:80099128
iparam4 = TODO: 3OE1:80097A30; NNF: laser attack damage
iparam5 = TODO: 3OE1:FUN_800983F8; NNF: swing attack radius
iparam6 = TODO: 3OE1:FUN_800983F8; NNF: charge attack radius (if player is outside this range)
MOVEMENT DATA 0D (DELBITER)
fparam1 = TODO: 3OE1:80302D1C, 3OE1:80302B38, 3OE1:803033C8, 3OE1:8030344C; NNF: Charge speed
fparam2 = TODO: 3OE1:80303124; NNF: Walking speed
fparam3 = TODO: 3OE1:80304F00
fparam4 = TODO: 3OE1:80304F10
fparam5 = TODO: 3OE1:80302E34
fparam6 = TODO: 3OE1:80302FD8; NNF: Charge radius (how far away you have to be before it charges).
iparam1 = TODO: 3OE1:80302A6C
iparam2 = TODO: 3OE1:803042F8
iparam3 = TODO: 3OE1:80304368; NNF: Charge damage.
iparam4 = TODO: 3OE1:80302414; related to TP absorption; NNF: Laser damage.
iparam5 = TODO: 3OE1:803030A4; NNF: Radius at which Delbiter attempts foot stomp attack (the range at which that attack can hit you, however, is not modified).
iparam6 = TODO: 3OE1:8030267C
MOVEMENT DATA 0E (DARK_BELRA)
(loaded with assets but not used)
MOVEMENT DATA 0F (DE_ROL_LE, BARBA_RAY)
fparam1 = DE_ROL_LE; TODO: damage amount; 3OE1:800304A4
fparam1 = BARBA_RAY; TODO: 3OE1:802E7980; damage for some attack; NNF: laser damage
fparam2 = DE_ROL_LE; TODO: TObjectV8047ec78 which has no constructor, so this is unused?; 3OE1:80038FD8
fparam2 = BARBA_RAY; TODO: 3OE1:802EDA38; TBoss7PhotonBullet_update; NNF: missile damage
fparam3 = DE_ROL_LE; TODO: TBoss2Mine, appears to be mine explosion damage; 3OE1:800385E4; NNF: Missile damage
fparam4 = DE_ROL_LE; TODO: multiplied by a random number in range [-1, 1] and added to pos.x; only happens if param5 passes
fparam5 = DE_ROL_LE; TODO: probability of some kind (range [0, 1]); 3OE1:80030C80
iparam1 = total HP
iparam2 = HP until armor on joints falls off
iparam3 = HP until mask falls off
iparam4 = DE_ROL_LE; TODO: only used in Ultimate, in other difficulties 180 is used instead
iparam5 = DE_ROL_LE; TODO: only used in Ultimate, in other difficulties 120 is used instead
MOVEMENT DATA 0F (DORPHON)
MOVEMENT DATA 10 (DORPHON_ECLAIR)
fparam1 = TODO: 59NL:005A832F, 59NL:005A8364, 59NL:005A8388, 59NL:005A8A9A, 59NL:005A9643, 59NL:005A96E5
fparam2 = TODO: 59NL:005A8EC2, 59NL:005A903D
fparam3 = TODO: 59NL:FUN_005A9ADC; minimum 0.1
fparam4 = TODO: 59NL:FUN_005A9ADC; minimum 0.1
fparam5 = TODO: 59NL:005A85AB
fparam6 = TODO: 59NL:005A8F2D
iparam1 = TODO: 59NL:005A8082
iparam2 = TODO: 59NL:005A89C6 and many others
iparam3 = TODO: 59NL:005A8477 and many others
iparam4 = TODO: 59NL:005A79E6; looks like same as for DELBITER
iparam5 = TODO: 59NL:005A8E4D
iparam6 = TODO: 59NL:005A71DA; multiplied by 30
MOVEMENT DATA 11 (DRAGON, GOL_DRAGON)
fparam1 = DRAGON; TODO: TBoss1DragonEffBreath
fparam1 = GOL_DRAGON; TODO: 3OE1:802F98EC; damage for some attack
fparam2 = DRAGON; TODO: TObjBoss1Crater_update, multiplied by 0.666 internally; TBoss1Dragon @ 3OE1:800276E0
fparam2 = GOL_DRAGON; TODO: 3OE1:802F987C; damage for some attack
fparam3 = DRAGON; TODO: 3OE1:8002787C
fparam3 = GOL_DRAGON; TODO: 3OE1:802F9810; damage for some attack
fparam4 = DRAGON; TODO: hitbox radius for something
fparam4 = GOL_DRAGON; TODO: 3OE1:802F9DBC; range for some attack
fparam5 = DRAGON; TODO: only used in Ultimate, in other difficulties 0.8 is used instead
fparam5 = GOL_DRAGON; TODO: 3OE1:802F2FDC, 3OE1:802F38A8, 3OE1:802F3AFC, 3OE1:802F8800
fparam6 = DRAGON; TODO: only used in Ultimate, in other difficulties 2.0 is used instead
fparam6 = GOL_DRAGON; TODO: 3OE1:802F7BBC, 3OE1:802F7C34
iparam1 = TODO: 3OE1:TBoss8Dragon_v58; damage amount for 1 hitbox
iparam2 = TODO: 3OE1:TBoss8Dragon_v58; damage amount for 2 hitboxes
iparam3 = TODO: 3OE1:TBoss8Dragon_v58; damage amount for 4 hitboxes
iparam4 = GOL_DRAGON; clone HP
iparam5 = GOL_DRAGON; TODO: 3OE1:802F32C8; which clone to create? (should be in range [0, 5])
MOVEMENT DATA 12 (GOL_DRAGON)
fparam1 = TODO: 3OE1:FUN_802FC22C
fparam2 = TODO: 3OE1:FUN_802FC22C
fparam3 = TODO: 3OE1:FUN_802FC22C
fparam4 = TODO: 3OE1:FUN_802FC22C
fparam5 = TODO: 3OE1:FUN_802FC22C; same function as fparam1 but used when no clones exist?
fparam6 = TODO: 3OE1:FUN_802FC22C; same function as fparam2 but used when no clones exist?
MOVEMENT DATA 13 (GOL_DRAGON)
fparam1 = TODO: 3OE1:FUN_802FC22C; same function as movement data 12 fparam3 but used when no clones exist?
fparam2 = TODO: 3OE1:FUN_802FC22C; same function as movement data 12 fparam4 but used when no clones exist?
fparam3 = TODO: 3OE1:802FBDBC; HP for phase 2 to begin?
fparam4 = TODO: 3OE1:802F6F24; scaling factor for a vector (speed/range?)
MOVEMENT DATA 19 (MERISSA_A)
MOVEMENT DATA 1A (MERISSA_AA)
fparam1 = TODO: 59NL:005B70AC
fparam2 = TODO: 59NL:005B70AC
fparam3 = TODO: 59NL:005B70AC
fparam4 = TODO: 59NL:005B5750, 59NL:005B6101
iparam1 = TODO: 59NL:005B56F8, 59NL:005B61DE; looks like an angle in degrees (range [0, 359])
iparam2 = TODO: 59NL:005B5824; looks like an angle in degrees (range [0, 359])
MOVEMENT DATA 1A (NANO_DRAGON)
fparam1 = horizontal flight speed
fparam2 = straight laser speed
fparam3 = homing laser speed (if set too low, it will go backwards)
fparam4 = TODO: 3OE1:800D9C70; NNF: Homing laser projectile count (projectile number = number given).
fparam5 = TODO: 3OE1:800D9C70; NNF: Homing laser arc.
iparam1 = straight laser damage
iparam2 = homing laser damage
MOVEMENT DATA 1A (GI_GUE)
fparam1 = TODO: 3OE1:802CA8F4, 3OE1:802CAA04; looks like a scape factor; NNF: Speed when flying away.
fparam2 = TODO: 3OE1:TObjEneMe1GiGue_FUN_802C98FC; NNF: missile speed
fparam3 = TODO: 3OE1:TObjEneMe1GiGue_FUN_802C98FC; NNF: confuse projectile speed
fparam4 = TODO: 3OE1:802CCA18
fparam5 = TODO: 3OE1:802CC640
fparam6 = TODO: 3OE1:802CA274; probability in range [0, 1]
iparam1 = TODO: 3OE1:TObjEneMe1GiGue_FUN_802C98FC; minimum value 40; NNF: Rafoie bomb attack damage
iparam2 = TODO: 3OE1:TObjEneMe1GiGue_FUN_802C98FC; NNF: Confusion projectile damage (affected by EFR).
iparam3 = Jellen/Zalure level
iparam4 = TODO: 3OE1:TObjEneMe1GiGue_FUN_802C98FC
iparam5 = TODO: 3OE1:TObjEneMe1GiGue_FUN_802C98FC; minimum value 20 in one scenario, 40 in another
MOVEMENT DATA 1B (DUBCHIC)
MOVEMENT DATA 1C (GILLCHIC)
fparam1 = TODO: 3OE1:FUN_800A89D4; NNF: Punch speed. Higher values means faster punches.
fparam2 = punch attack range when not damaged
fparam3 = TODO: 3OE1:800A8B64, 3OE1:800A9E98; only used when damaged, values when not damaged are 0.37037036 for DUBCHIC, 0.57037038 for GILLCHIC (unused since GILLCHIC dies instead of being damaged)
fparam4 = TODO: 3OE1:FUN_800A89D4
fparam5 = TODO: 3OE1:FUN_800A89D4; NNF: Punch speed and movement speed when damaged
fparam6 = punch attack range when damaged
iparam1 = number of frames after kill before revive sequence starts (Dubchic only)
iparam2 = TODO: 3OE1:800A8F9C; NNF: Laser charge time
iparam3 = TODO: 3OE1:800A9B40; NNF: Number of invicibility frames after knockdown
iparam4 = laser damage
MOVEMENT DATA 1D (GARANZ)
fparam1 = TODO: 3OE1:800D320C; NNF: Distance travelled every movement phase. Speed is unaffected, so it can take a long time before it stops to shoot.
fparam2 = TODO: 3OE1:TObjEneGyaranzo_set_movement_params; NNF: Movement speed. This not only makes the Garanz faster, but ends the movement phase sooner, so it gets around to shooting missiles faster too. Doesn't work well without a value in fparam1.
fparam3 = TODO: 3OE1:TObjEneGyaranzo_set_movement_params; NNF: TODO
fparam4 = missile speed
fparam5 = TODO: 3OE1:TObjEneGyaranzo_set_movement_params; NNF: Missile launch arc. Defines how tight the downward curve of the missile (once launched) towards the player is. Set to 0, missiles travel straight into the ceiling and cannot hit the player.
iparam1 = TODO: 3OE1:800D2C4C; NNF: Number of frames waited after shooting before commencing movement again. Garanz does have a lower limit and will not wait 0 frames before starting again.
iparam2 = TODO: 3OE1:800D2254; NNF: Missile launch cooldown
iparam3 = TODO: 3OE1:800D46A8; missile damage
iparam4 = TODO: 3OE1:800D40FC; NNF: Mine Damage
MOVEMENT DATA 1E (DARK_GUNNER)
fparam1 = TODO: 3OE1:800A0F44, 3OE1:800A11D0
fparam2 = TODO: 3OE1:800A24F8
fparam3 = TODO: 3OE1:800A1C4C; seems to be a distance limit / radius of some sort
fparam4 = TODO: 3OE1:800A1104; NNF: laser speed
iparam1 = charge time after windup sound and before laser shot
iparam2 = TODO: 3OE1:800A12A4; NNF: Length of time vulnerability remains after being damaged (lower=shorter)
iparam3 = TODO: 3OE1:800A3190; NNF: Duration of invincibility (close to 0 will be no invincibility).
iparam4 = laser shot damage
MOVEMENT DATA 1E (GAL_GRYPHON)
fparam1 = TODO: 3OE1:80065DEC; NNF: Y Value Camera adjustment when Gal lands
fparam2 = TODO: 3OE1:80065DEC; NNF: X Value Camera adjustment when Gal lands
fparam3 = TODO: 3OE1:80065DEC; NNF: Y Value Camera adjustment when Gal lands (cam location)
fparam4 = TODO: 3OE1:80065DEC; NNF: Adjusts Camera near or far to player
fparam5 = TODO: 3OE1:80065DEC; same as fparam1 but for a different situation (A); NNF: Lowers/Raises the Camera when Gal is flying
fparam6 = TODO: 3OE1:80065DEC; same as fparam2 but for a different situation (A)
MOVEMENT DATA 1F (BULCLAW)
iparam1 = TODO: 3OE1:8008F8C8; percentage (0-100) of max HP; NNF: % chance it does it's suicide attack once split into a Bulk, you need to attack it once
MOVEMENT DATA 1F (GAL_GRYPHON)
fparam1 = TODO: 3OE1:80065DEC; same as data 1E fparam3 but for a different situation (A); NNF: (BULCLAW) Aggro Range?
fparam2 = TODO: 3OE1:80065DEC; same as data 1E fparam4 but for a different situation (A)
fparam3 = TODO: 3OE1:80065DEC; same as data 1E fparam1 but for a different situation (B)
fparam4 = TODO: 3OE1:80065DEC; same as data 1E fparam2 but for a different situation (B)
fparam5 = TODO: 3OE1:80065DEC; same as data 1E fparam3 but for a different situation (B)
fparam6 = TODO: 3OE1:80065DEC; same as data 1E fparam4 but for a different situation (B)
MOVEMENT DATA 1F (GIRTABLULU)
fparam1 = TODO: 59NL:005ABDBD
fparam2 = TODO: 59NL:005ABDB1
fparam4 = TODO: 59NL:005ABD3C
fparam5 = TODO: 59NL:005ABD45
fparam6 = TODO: 59NL:005ABD08; looks like an angle in degrees (range [0, 359])
iparam1 = TODO: 59NL:005AAB66, 59NL:005AAD18
iparam3 = TODO: 59NL:005AA9FA
iparam4 = TODO: 59NL:005AA85B
iparam5 = TODO: 59NL:005AAF20; length of time in frames?
iparam6 = TODO: 59NL:005AA5FD
MOVEMENT DATA 20 (BULCLAW)
(loaded with assets but not used)
MOVEMENT DATA 20 (GAL_GRYPHON)
fparam1 = TODO: 3OE1:FUN_80064064; damage scaling factor for some attack (TBoss5GryphonSnarl)
fparam2 = TODO: 3OE1:80064130; damage amount for shock wave attack (TBoss5GryphonShockWave)
fparam3 = TODO: 3OE1:80064130; damage amount for tornado attack (TBoss5GryphonTornado)
fparam4 = TODO: 3OE1:80064044; damage amount for some attack
fparam5 = TODO: 3OE1:8006475C; hitbox radius for some attack?
iparam1 = TODO: 3OE1:TBoss5Gryphon_V58; damage amount for 1 hitbox
iparam2 = TODO: 3OE1:TBoss5Gryphon_V58; damage amount for 4 hitboxes
iparam3 = TODO: 3OE1:TBoss5Gryphon_V58; damage amount for 1 hitbox
iparam4 = TODO: 3OE1:TBoss5Gryphon_V58; damage amount for 4 hitboxes
iparam5 = TODO: 3OE1:TBoss5Gryphon_FUN_8005F0F0, 3OE1:800609D0
MOVEMENT DATA 20 (SAINT_MILLION_1)
MOVEMENT DATA 22 (SAINT_MILLION_2)
MOVEMENT DATA 24 (SHAMBERTIN_1)
MOVEMENT DATA 26 (SHAMBERTIN_2)
MOVEMENT DATA 28 (KONDRIEU_1)
MOVEMENT DATA 2A (KONDRIEU_2)
iparam1 = TODO: 59NL:00768990, 59NL:00768A84
iparam2 = TODO: 59NL:00768990, 59NL:00768A84
iparam3 = TODO: 59NL:00768990, 59NL:00768A84
iparam4 = TODO: 59NL:00768990, 59NL:00768A84
iparam5 = TODO: 59NL:00768990, 59NL:00768A84
MOVEMENT DATA 21 (SAINT_MILION_SPINNER, 0/4/8/12)
MOVEMENT DATA 23 (SAINT_MILION_SPINNER, other indexes)
MOVEMENT DATA 25 (SHAMBERTIN_SPINNER, 0/4/8/12)
MOVEMENT DATA 27 (SHAMBERTIN_SPINNER, other indexes)
MOVEMENT DATA 29 (KONDRIEU_SPINNER, 0/4/8/12)
MOVEMENT DATA 2B (KONDRIEU_SPINNER, other indexes)
iparam1 = TODO: 59NL:0076D40D
MOVEMENT DATA 21 (VOL_OPT_1)
iparam1 = speed of moving around in the screens
MOVEMENT DATA 22 (VOL_OPT_1)
iparam1 = damage for electrical attack
MOVEMENT DATA 23 (VOL_OPT_1)
iparam1 = large monitors' HP
iparam2 = small monitors' HP
MOVEMENT DATA 23 (EPSILON)
fparam2 = TODO: 3OE1:8035FDB4; scale factor for vector; NNF: Laser tracking speed.
fparam3 = TODO: 3OE1:8035FF08; NNF: Rafoie damage (based on MST).
iparam1 = TODO: 3OE1:8035FD60; NNF: Controls how long the laser tracks players before casting Rafoie (number of Rafoies shot is tied to this - shorter tracking time means more Rafoies).
iparam2 = TODO: 3OE1:8035FE40; NNF: Delay between when Rafoie stops and next laser begins.
iparam3 = TODO: 3OE1:8035E44C, 3OE1:803608C0; NNF: Cooldown on Epsigard tech activation.
iparam4 = TODO: 3OE1:8035F850; NNF: Epsigard attack radius.
MOVEMENT DATA 24 (VOL_OPT)
(loaded with assets but not used)
MOVEMENT DATA 24 (EPSIGARD)
fparam1 = TODO: 3OE1:8035CB58, 3OE1:8035CD1C, 3OE1:8035D3B4; NNF: Epsigard circle radius.
fparam2 = TODO: 3OE1:8035CD20; NNF: Speed at which Epsigards eject from Epsilon. Epsigards always eject for a second, so fast eject speeds will project them far. They will then spin come back in to fparam1 radius.
fparam3 = TODO: 3OE1:8035CB50, 3OE1:8035CBFC; NNF: Epsigard rotation speed.
fparam4 = TODO: 3OE1:8035D0CC; NNF: Damage dealt per Epsigard hit.
iparam1 = TODO: 3OE1:8035CF28; NNF: Seems to affect Epsigard damage radius. At 120, can't get hit from the front, can only gt hit from a specific position from the back and to the side.
MOVEMENT DATA 25 (VOL_OPT_2)
fparam1 = TODO: specifies length of a vector; NNF: missile speed; 3OE1:80049CB0
fparam2 = TODO: specifies length of a vector; 3OE1:80049C94
fparam3 = TODO: NNF: knockback distance when hit by pillar; player gets rotated in a random direction, and then moved backwards from that direction
fparam4 = TODO: 3OE1:80049FE0; NNF: Homing pillar stomp: Affects cooldown of third pillar ('fast' pillar variants only).
fparam5 = TODO: add param for random generation for pillar stomp; NNF: Homing pillar stomp: Affects cooldown of second pillar ('fast' pillar variants only).
fparam6 = TODO: mult param for random generation for pillar stomp; final value is (random(0, 1) * fparam5) + fparam4; 3 values generated in total; NNF: Homing pillar stomp: Affects cooldown of first pillar ('fast' pillar variants only).
iparam1 = TODO: NNF: missile damage
iparam2 = TODO: NNF: pillar damage
iparam3 = TODO: NNF: trap laser damage
iparam4 = HP recovery amount * 5 (so e.g. 2500 here means 500HP)
iparam5 = TODO: NNF: Charge time of trap laser attack; value used is max(10, iparam5 + 120); but used in multiple places! which is which? 3OE1:800490D0 3OE1:8004661C
iparam6 = TODO: related to TObjVoloptPillar; 3OE1:80044ACC, 3OE1:80047110, 3OE1:8004A24C; NNF: Homing pillar stomp: Cooldown for each pillar drop. Longer is higher.
MOVEMENT DATA 26 (VOL_OPT_2)
fparam1 = TODO: specifies length of a vector; 3OE1:80049778, 3OE1:800499E8; NNF: Ball speed for laser floor trap
fparam2 = TODO: specifies length of a vector; 3OE1:8004975C
iparam1 = TODO: looks like lifetime in frames for a subordinate; 3OE1:80049A14; NNF: Ball chase duration
iparam2 = TODO: 3OE1:8004490C; looks like an angular velocity?; NNF: Amount of wait time taken for rotating pillars to first attack
MOVEMENT DATA 26 (ILL_GILL)
fparam1 = TODO: 3OE1:803642E8, 3OE1:80363DBC, 3OE1:80363FCC; NNF: Affects charge speed and cooldown time.
fparam2 = TODO: 3OE1:80364F3C; NNF: Scythe attack speed.
iparam1 = TODO: 3OE1:80365324, 3OE1:803652CC; weapon special amount; NNF: Seems to affect how much damage the lightning scythe attack does, and how effective the megid scythe attack is (lower is less effective)
iparam2 = TODO: 3OE1:8036537C; weapon special amount; NNF: Seems to affect how much damage the lightning scythe attack does, and how effective the megid scythe attack is (lower is less effective)
MOVEMENT DATA 27 (VOL_OPT; used in Vol Opt phase 1?)
MOVEMENT DATA 28 (VOL_OPT; used when no player is caught by the Vol Opt cage)
MOVEMENT DATA 29 (VOL_OPT; used when any player is caught by the Vol Opt cage)
fparam1 = TODO: param to some camera logic
fparam2 = TODO: param to some camera logic
fparam3 = TODO: param to some camera logic
fparam4 = TODO: param to some camera logic
iparam1 = TODO: entire movement data is unused if this is zero; 3OE1:TBoss3Volopt_FUN_8003EB6C
MOVEMENT DATA 2A (VOL_OPT_2)
iparam1 = TODO: only has effect if nonzero; 3OE1:80048074
MOVEMENT DATA 2B (OLGA_FLOW_1)
fparam1 = TODO: 3OE1:802B6190, 3OE1:803547F4; must be >0, default 20; NNF: sword damage
fparam2 = TODO: 3OE1:80320F84; NNF: Olga Flow 1 shot (ball) damage
fparam3 = TODO: 3OE1:802B5DD0; must be >0, default 20; NNF: tail swipe damage
fparam4 = TODO: 3OE1:802B5980; must be >0, default 20; NNF: shot (beam) damage
fparam5 = TODO: 3OE1:802B5668; must be >0, default 20; NNF: gravity trap attack damage
fparam6 = TODO: 3OE1:802B2620; must be >0, default 7; NNF: delay between attacks (lower is faster)
iparam1 = TODO: 3OE1:802B4970; looks like damage threshold; must be >0, default 200; NNF: Docile Mode HP Threshold
iparam2 = TODO: 3OE1:802B4A50; looks like damage threshold; must be >0, default 200; NNF: Sky/Floor Sword HP to trigger
iparam3 = TODO: 3OE1:802B49C0; must be >0, default 200; NNF: Sky/Floor Sword HP to cancel
iparam4 = TODO: 3OE1:802B4924; must be >0, default 200; NNF: Gravity Trap Attack HP Threshold
iparam5 = TODO: 3OE1:802B694C; seems to not be read - missing label?; must be >0, default 90; NNF: Shot charge-up duration (lower is shorter)
iparam6 = TODO: 3OE1:TBoss6Type1_FUN_802B1CA8; must be >0, default 180; NNF: Movement speed and duration during charge-up shot (lower is faster/shorter)
MOVEMENT DATA 2C (OLGA_FLOW_2)
fparam1 = TODO: 3OE1:80354FBC; NNF: Olga Flow 2 sword damage (lower is less)
fparam2 = TODO: 3OE1:802BB218; must be >0, default is 20; NNF: Foot damage
fparam5 = TODO: 3OE1:802BB218; must be >0, default is 20; NNF: Wrong attribute damage dealt during soul steal (physical - lower is less)
fparam3 = TODO: 3OE1:80354FEC, 3OE1:8035BF80; NNF: Olga Flow 2 Divine Punishment damage (lower is less)
fparam4 = rock damage; must be > 0; default 20
fparam6 = TODO: 3OE1:802BB218; must be >0, default is 60; NNF: Rock fall duration during soul steal (lower is less)
iparam1 = TODO: 3OE1:802BB218; must be >0, default is 200; NNF: Amount of damage to trigger Divine Punishment
iparam2 = TODO: 3OE1:802BB218; must be >0, default is 200; NNF: Amount of damage it takes to go into soul steal state
iparam3 = TODO: 3OE1:802BB218; must be >0, default is 200; NNF: Amount of damage to knock Olga Flow out of soul steal state
iparam4 = TODO: 3OE1:802BB218; must be >0, default is 60; NNF: Delay between attacks (lower is faster)
iparam5 = TODO: 3OE1:802BB218; must be in range [0, 100] with iparam5 + iparam6 <= 100, default is 25, used as a probability along with iparam6; NNF: Form 1's Total HP% Trigger to halve Attack delays
iparam6 = TODO: 3OE1:802BB218; must be in range [0, 100] with iparam5 + iparam6 <= 100, default is 10, used as a probability along with iparam5
MOVEMENT DATA 2D (OLGA_FLOW_1, OLGA_FLOW_2)
fparam1 = OLGA_FLOW_1; TODO: 3OE1:80323128; TBoss6Mine; default 20; NNF: Trap damage Form 1
fparam2 = OLGA_FLOW_2; TODO: 3OE1:8036773C; TBoss6MagMine; must be >0, default 20; NNF: Trap damage Form 2
fparam3 = OLGA_FLOW_2; TODO: 3OE1:8036778C; TBoss6MagMine; must be in range [0, 100], default 0
MOVEMENT DATA 2E (OLGA_FLOW_2)
fparam1 = TODO: 3OE1:8032EE24; TBoss6Mag; NNF: Amount of time Gael/Giel stays dead (lower is shorter)
fparam2 = TODO: 3OE1:8032EE74; TBoss6Mag; NNF: Gael/Giel Chase speed during Divine Punishment
fparam3 = TODO: 3OE1:802BB218; must be >0, default 1; used instead of movement data 2F fparam1 if a certain flag is set; NNF: Olga Flow's normal movement speed after some threshold
fparam4 = TODO: 3OE1:802BB218; must be >0, default 1; used instead of movement data 2F fparam2 if a certain flag is set; NNF: Olga Flow's movement speed during soul steal after some threshold
MOVEMENT DATA 2F (OLGA_FLOW_1, OLGA_FLOW_2)
fparam1 = OLGA_FLOW_2; TODO: 3OE1:802BB218; must be >0, default 1
fparam2 = OLGA_FLOW_2; TODO: 3OE1:802BB218; must be >0, default 1
fparam3 = OLGA_FLOW_2; TODO: 3OE1:802BB218, 3OE1:8035BFB0; must be >0, default 1; damage reduction for movement data 2C fparam2?, only applies if a certain flag is set
fparam4 = OLGA_FLOW_2; TODO: 3OE1:802BB218; must be >0, default 120; looks like duration for something
fparam5 = OLGA_FLOW_1; TODO: 3OE1:80320FB4; also related to shot/ball attack
fparam6 = OLGA_FLOW_1; TODO: 3OE1:802B694C; must be >0, default 7; same as movement data 2B fparam6 but used when a certain flag is enabled
MOVEMENT DATA 30 (POFUILLY_SLIME)
MOVEMENT DATA 34 (POUILLY_SLIME)
fparam1 = spit attack damage * 5 (so e.g. 1000 here means 200 damange)
MOVEMENT DATA 30 (DELDEPTH)
fparam1 = TODO: 3OE1:80312E04; NNF: Movement speed (Disk form).
fparam2 = TODO: 3OE1:80312E1C; NNF: Distance travelled per movement (Disk form).
iparam1 = attack tech level (Megid in Ultimate; Barta in other difficulties); also bomb power? (TODO: 3OE1:80312490)
iparam2 = TODO: 3OE1:80312AE0; NNF: Rotation speed (Unfolded form) - lower is slower.
MOVEMENT DATA 31 (PAN_ARMS)
fparam1 = TODO: 3OE1:800DF31C
fparam2 = TODO: 3OE1:800E36DC; NNF: Blue laser damage
fparam3 = TODO: 3OE1:800E36DC; NNF: Red laser damage
iparam1 = TODO: 3OE1:800DF32C; value is max(iparam1, 5); NNF: spawn radius
iparam2 = TODO: 3OE1:800DF350; value is max(iparam2, 0); NNF: spawn speed in frames
MOVEMENT DATA 32 (HIDOOM)
MOVEMENT DATA 33 (MIGIUM)
fparam1 = TODO: 3OE1:800E2640
fparam2 = TODO: 3OE1:800E2650; NNF: stab damage
fparam3 = MIGIUM; TODO: 3OE1:800E26AC
iparam1 = MIGIUM; Resta level, must be in range [0, 14]; NNF: Jellen level
iparam2 = MIGIUM; Jellen level, must be in range [0, 14]; NNF: Zalure level
iparam3 = MIGIUM; Zalure level, must be in range [0, 14]; NNF: Resta level
MOVEMENT DATA 35 (DARVANT)
fparam1 = TODO: must be in range [0.33333334, 5.833333]; 3OE1:8005D5E0; NNF: Attack speed
iparam1 = number of Darvants that must be killed before phase ends (actual value is player count * iparam1); must be in range [1, 19]
MOVEMENT DATA 36 (DARK_FALZ_1)
fparam1 = NNF: movement speed; must be in range [1, 60]; used as reciprocal (see 3OE1:80052F60) so lower is faster
iparam1 = Rafoie level, expected to be in range [0, 14]
iparam2 = Rabarta level, expected to be in range [0, 14]
iparam3 = TODO: 3OE1:FUN_80054DE0; NNF: Dark Falz 1 Divine Punishment strength (Also based on MST)
MOVEMENT DATA 37 (DARK_FALZ_2)
fparam1 = TODO: 3OE1:80057BE4; value used is clamp(floor(fparam1), 1, 25) * 75 - 7; appears angle-related; 3OE1:8005653C; NNF: Movement speed (backwards, lower is faster).
iparam1 = TODO: must be in range [1, 4], chooses between 4 different actions in a certain situation, named MD_STOP1 through MD_STOP4; 3OE1:80056358
iparam2 = TODO: Resta level; 3OE1:80056994
MOVEMENT DATA 38 (DARK_FALZ_3)
fparam1 = TODO: 3OE1:80050CA4
iparam1 = Grants level
iparam2 = Megid level
iparam3 = number of pairs of homing attacks (TObjDFHorming) to launch at once; must be in range [1, 8]
iparam4 = TODO: 3OE1:8005B14C; NNF: HP threshold to soul steal
iparam5 = TODO: 3OE1:80050C94; NNF: Ball attack damage. (with 3000/10 MST, does 700 Damage)
MOVEMENT DATA 39 (DARVANT, DARK_FALZ_1)
fparam1 = DARVANT; TODO: must be in range [0.33333334, 10.208332]; 3OE1:8005D618; NNF: Attack speed
iparam1 = DARK_FALZ_1; TODO: number of Darvants to spawn at a time?; clamped to [1, 6]; 3OE1:80054CF0
MOVEMENT DATA 3A (MERICAROL)
MOVEMENT DATA 45 (MERIKLE)
MOVEMENT DATA 46 (MERICUS)
fparam1 = TODO: 3OE1:802CE110; NNF: rush damage
fparam2 = poison cloud damage
fparam3 = TODO: 3OE1:802CEAA8; NNF: Spit 'attack capability'. Set to 1, attack does nothing and does not register as a hit.
fparam4 = TODO: 3OE1:802CEAB0; NNF: Projectile speed; also affects the cooldown time between each shot.
fparam5 = poison cloud radius
fparam6 = TODO: 3OE1:802CD890; probability in range [0, 1]; NNF: Level of 'Megidness'. Value of 1 treats the attack as megid, despite fparam3.
iparam3 = TODO: 3OE1:802CED14; NNF: Projectile fire rate.
iparam4 = TODO: 3OE1:802CD7FC; NNF: Charge up time for poison cloud attack.
iparam5 = TODO: 3OE1:802CE850; NNF: Melee attack cooldown time.
iparam6 = TODO: 3OE1:802CEA30
MOVEMENT DATA 3B (UL_GIBBON)
MOVEMENT DATA 3C (ZOL_GIBBON)
(loaded with assets but not used)
MOVEMENT DATA 3D (GIBBLES)
fparam2 = TODO: 3OE1:802D7F5C; NNF: Triple-punch attack cooldown.
fparam3 = TODO: 3OE1:802D8BC0; NNF: Movement speed.
fparam4 = TODO: 3OE1:802D7490; NNF: Jump cooldown time (Higher value = less waiting time).
iparam1 = TODO: 3OE1:802D7484
MOVEMENT DATA 40 (MORFOS)
fparam1 = laser speed; hitbox radius is fparam1 * 1.5
fparam2 = laser damage
iparam1 = TODO: 3OE1:80332298, 3OE1:803321C4; NNF: Firing rate of regular laser attack. Laser attack when aggressive (charging) is unaffected.
iparam2 = TODO: 3OE1:8033161C, 3OE1:8033192C, 3OE1:80331B4C, 3OE1:80331D00, 3OE1:80331FA0; NNF: Speed at which Morphos spins after firing laser.
iparam3 = TODO: 3OE1:80331F04; NNF: Interval in frames of attacks
iparam4 = TODO: 3OE1:803318EC; NNF: Charge frames before attacking without hitstun.
iparam5 = TODO: 3OE1:803318CC; NNF: Affects charge laser tracking. Too high and doesnt lock-on. Need Research
MOVEMENT DATA 41 (RECOBOX)
(loaded with assets but not used)
MOVEMENT DATA 42 (RECON)
fparam1 = TODO: 3OE1:8031C31C; NNF: Chase speed for buzzsaw attack
fparam2 = bomb explosion radius
fparam3 = bomb damage
fparam4 = TODO: 3OE1:8031A144; NNF: bomb throw distance
iparam1 = TODO: 3OE1:80319DCC; bomb frames until explosion?; NNF: Speed recon comes out of the recobox. As it always takes the same amount of 'time' to come out, higher values make it go high up as well as fast.
iparam2 = TODO: 3OE1:8031B68C; NNF: Frame delay from when Recon gets in position to when it activates buzzsaw.
MOVEMENT DATA 43 (SINOW_ZOA)
MOVEMENT DATA 44 (SINOW_ZELE)
fparam1 = TODO: 3OE1:80317B7C; NNF: Movement speed
fparam3 = TODO: 3OE1:803173F4; NNF: Speed at which Sinow Zoa/Zele reappears after warping.
fparam4 = TODO: 3OE1:80319960; NNF: Attack speed
fparam5 = TODO: 3OE1:80319968
fparam6 = TODO: 3OE1:80316F84
iparam1 = Resta/Shifta/Deband/Jellen/Zalure level
iparam2 = TODO: 3OE1:80316BE8
iparam3 = TODO: 3OE1:80317458; NNF: Cooldown time for all attacks.
iparam4 = attack tech level (Rabarta in Ultimate, Gibarta otherwise)
MOVEMENT DATA 48 (HILDEBEAR)
MOVEMENT DATA 49 (HILDEBLUE)
fparam1 = punch attack speed
fparam2 = TODO: 3OE1:800ADBE0; NNF: tech range
fparam3 = movement speed (does not affect animation speed)
fparam4 = walking animation speed
MOVEMENT DATA 4D (GRASS_ASSASSIN)
(loaded with assets but not used)
MOVEMENT DATA 51 (DELSABER)
fparam1 = TODO: 3OE1:800A5454
fparam2 = TODO: 3OE1:800A5708
fparam3 = TODO: 3OE1:800A5CA4
fparam4 = TODO: 3OE1:800A5D04
+2 -2
View File
@@ -67,8 +67,8 @@ string AFSArchive::generate_t(const vector<string>& files) {
w.put_u32b(0x41465300); // 'AFS\0'
w.put<U32T<BE>>(files.size());
// It seems entries are aligned to 0x800-byte boundaries, and the file's
// header is always 0x80000 (!) bytes, most of which is unused
// It seems entries are aligned to 0x800-byte boundaries, and the file's header is always 0x80000 (!) bytes, most of
// which is unused
uint32_t data_offset = 0x80000;
for (const auto& file : files) {
w.put<U32T<BE>>(data_offset);
+16 -20
View File
@@ -32,10 +32,7 @@ shared_ptr<DCNTELicense> DCNTELicense::from_json(const phosg::JSON& json) {
}
phosg::JSON DCNTELicense::json() const {
return phosg::JSON::dict({
{"SerialNumber", this->serial_number},
{"AccessKey", this->access_key},
});
return phosg::JSON::dict({{"SerialNumber", this->serial_number}, {"AccessKey", this->access_key}});
}
shared_ptr<V1V2License> V1V2License::from_json(const phosg::JSON& json) {
@@ -52,10 +49,7 @@ shared_ptr<V1V2License> V1V2License::from_json(const phosg::JSON& json) {
}
phosg::JSON V1V2License::json() const {
return phosg::JSON::dict({
{"SerialNumber", this->serial_number},
{"AccessKey", this->access_key},
});
return phosg::JSON::dict({{"SerialNumber", this->serial_number}, {"AccessKey", this->access_key}});
}
shared_ptr<GCLicense> GCLicense::from_json(const phosg::JSON& json) {
@@ -101,11 +95,7 @@ shared_ptr<XBLicense> XBLicense::from_json(const phosg::JSON& json) {
}
phosg::JSON XBLicense::json() const {
return phosg::JSON::dict({
{"GamerTag", this->gamertag},
{"UserID", this->user_id},
{"AccountID", this->account_id},
});
return phosg::JSON::dict({{"GamerTag", this->gamertag}, {"UserID", this->user_id}, {"AccountID", this->account_id}});
}
shared_ptr<BBLicense> BBLicense::from_json(const phosg::JSON& json) {
@@ -128,10 +118,7 @@ shared_ptr<BBLicense> BBLicense::from_json(const phosg::JSON& json) {
}
phosg::JSON BBLicense::json() const {
return phosg::JSON::dict({
{"UserName", this->username},
{"Password", this->password},
});
return phosg::JSON::dict({{"UserName", this->username}, {"Password", this->password}});
}
Account::Account(const phosg::JSON& json)
@@ -329,6 +316,9 @@ string Account::str() const {
flags_str += "CHEAT_ANYWHERE,";
}
if (this->check_flag(Flag::DISABLE_QUEST_REQUIREMENTS)) {
flags_str += "DISABLE_QUEST_REQUIREMENTS,";
}
if (this->check_flag(Flag::ALWAYS_ENABLE_CHAT_COMMANDS)) {
flags_str += "ALWAYS_ENABLE_CHAT_COMMANDS,";
}
if (this->check_flag(Flag::IS_SHARED_ACCOUNT)) {
@@ -409,7 +399,8 @@ string Account::str() const {
void Account::save() const {
if (!this->is_temporary) {
auto json = this->json();
string json_data = json.serialize(phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::HEX_INTEGERS);
string json_data = json.serialize(
phosg::JSON::SerializeOption::FORMAT | phosg::JSON::SerializeOption::HEX_INTEGERS);
string filename = std::format("system/licenses/{:010}.json", this->account_id);
phosg::save_file(filename, json_data);
}
@@ -653,7 +644,11 @@ shared_ptr<Login> AccountIndex::from_gc_credentials_locked(
}
shared_ptr<Login> AccountIndex::from_gc_credentials(
uint32_t serial_number, const string& access_key, const string* password, const string& character_name, bool allow_create) {
uint32_t serial_number,
const string& access_key,
const string* password,
const string& character_name,
bool allow_create) {
if (serial_number == 0) {
throw no_username();
}
@@ -747,7 +742,8 @@ shared_ptr<Login> AccountIndex::from_bb_credentials_locked(const string& usernam
return login;
}
shared_ptr<Login> AccountIndex::from_bb_credentials(const string& username, const string* password, bool allow_create) {
shared_ptr<Login> AccountIndex::from_bb_credentials(
const string& username, const string* password, bool allow_create) {
if (username.empty() || (password && password->empty())) {
throw no_username();
}
+12 -38
View File
@@ -72,8 +72,7 @@ struct Account {
ADMINISTRATOR = 0x000000FF,
ROOT = 0x7FFFFFFF,
IS_SHARED_ACCOUNT = 0x80000000,
// NOTE: When adding or changing license flags, don't forget to change the
// documentation in the shell's help text.
// NOTE: When adding or changing license flags, don't forget to change the documentation in the shell's help text.
UNUSED_BITS = 0x70FFFF00,
// clang-format on
};
@@ -149,8 +148,7 @@ struct Login {
bool account_was_created = false;
// This field will never be null
std::shared_ptr<Account> account;
// Exactly one of the following will be non-null, representing the license
// that the client logged in with
// Exactly one of the following will be non-null, representing the license that the client logged in with
std::shared_ptr<DCNTELicense> dc_nte_license;
std::shared_ptr<V1V2License> dc_license;
std::shared_ptr<V1V2License> pc_license;
@@ -210,22 +208,12 @@ public:
std::shared_ptr<Account> from_account_id(uint32_t account_id) const;
std::shared_ptr<Login> from_dc_nte_credentials(
const std::string& serial_number,
const std::string& access_key,
bool allow_create);
const std::string& serial_number, const std::string& access_key, bool allow_create);
std::shared_ptr<Login> from_dc_credentials(
uint32_t serial_number,
const std::string& access_key,
const std::string& character_name,
bool allow_create);
std::shared_ptr<Login> from_pc_nte_credentials(
uint32_t guild_card_number,
bool allow_create);
uint32_t serial_number, const std::string& access_key, const std::string& character_name, bool allow_create);
std::shared_ptr<Login> from_pc_nte_credentials(uint32_t guild_card_number, bool allow_create);
std::shared_ptr<Login> from_pc_credentials(
uint32_t serial_number,
const std::string& access_key,
const std::string& character_name,
bool allow_create);
uint32_t serial_number, const std::string& access_key, const std::string& character_name, bool allow_create);
std::shared_ptr<Login> from_gc_credentials(
uint32_t serial_number,
const std::string& access_key,
@@ -233,14 +221,9 @@ public:
const std::string& character_name,
bool allow_create);
std::shared_ptr<Login> from_xb_credentials(
const std::string& gamertag,
uint64_t user_id,
uint64_t account_id,
bool allow_create);
const std::string& gamertag, uint64_t user_id, uint64_t account_id, bool allow_create);
std::shared_ptr<Login> from_bb_credentials(
const std::string& username,
const std::string* password,
bool allow_create);
const std::string& username, const std::string* password, bool allow_create);
std::shared_ptr<Account> create_temporary_account_for_shared_account(
std::shared_ptr<const Account> src_a, const std::string& variation_data) const;
@@ -248,8 +231,6 @@ public:
protected:
bool force_all_temporary;
// This class must be thread-safe because it's used by both the patch server
// and game server threads
mutable std::shared_mutex lock;
std::unordered_map<uint32_t, std::shared_ptr<Account>> by_account_id;
std::unordered_map<std::string, std::shared_ptr<Account>> by_dc_nte_serial_number;
@@ -262,23 +243,16 @@ protected:
void add_locked(std::shared_ptr<Account> a);
std::shared_ptr<Login> from_dc_nte_credentials_locked(
const std::string& serial_number,
const std::string& access_key);
const std::string& serial_number, const std::string& access_key);
std::shared_ptr<Login> from_dc_credentials_locked(
uint32_t serial_number,
const std::string& access_key,
const std::string& character_name);
uint32_t serial_number, const std::string& access_key, const std::string& character_name);
std::shared_ptr<Login> from_pc_credentials_locked(
uint32_t serial_number,
const std::string& access_key,
const std::string& character_name);
uint32_t serial_number, const std::string& access_key, const std::string& character_name);
std::shared_ptr<Login> from_gc_credentials_locked(
uint32_t serial_number,
const std::string& access_key,
const std::string* password,
const std::string& character_name);
std::shared_ptr<Login> from_xb_credentials_locked(uint64_t user_id);
std::shared_ptr<Login> from_bb_credentials_locked(
const std::string& username,
const std::string* password);
std::shared_ptr<Login> from_bb_credentials_locked(const std::string& username, const std::string* password);
};
+17 -16
View File
@@ -267,20 +267,16 @@ public:
// Returns {type: {constructor_addr: [(start_area, end_area), ...]}}
template <typename EntryT>
map<uint32_t, map<uint32_t, vector<pair<size_t, size_t>>>>
parse_dat_constructor_table_t(
shared_ptr<const ResourceDASM::MemoryContext>& mem,
const ParseDATConstructorTableSpec& spec) {
map<uint32_t, map<uint32_t, vector<pair<size_t, size_t>>>> parse_dat_constructor_table_t(
shared_ptr<const ResourceDASM::MemoryContext>& mem, const ParseDATConstructorTableSpec& spec) {
if (!mem) {
throw runtime_error("no file selected");
}
// On some of the x86 builds of the game (PCv2 and Xbox), the constructor
// tables aren't entirely static in the data sections - some parts are
// written during static initialization instead. To handle this, we make a
// copy of the immutable MemoryContext and run the static initialization
// functions using resource_dasm's emulator before parsing the constructor
// table.
// On some of the x86 builds of the game (PCv2 and Xbox), the constructor tables aren't entirely static in the data
// sections - some parts are written during static initialization instead. To handle this, we make a copy of the
// immutable MemoryContext and run the static initialization functions using resource_dasm's emulator before
// parsing the constructor table.
shared_ptr<const ResourceDASM::MemoryContext> effective_mem = mem;
if (!spec.x86_constructor_calls.empty()) {
auto constructed_mem = make_shared<ResourceDASM::MemoryContext>(mem->duplicate());
@@ -455,9 +451,7 @@ public:
}
}
line.push_back(' ');
line += is_enemies
? MapFile::name_for_enemy_type(type)
: MapFile::name_for_object_type(type);
line += is_enemies ? MapFile::name_for_enemy_type(type) : MapFile::name_for_object_type(type);
if ((formatted_lines.size() % 40) == 0) {
formatted_lines.emplace_back(header_line);
@@ -732,9 +726,7 @@ public:
}
uint32_t find_be_to_le_data_match(
shared_ptr<const ResourceDASM::MemoryContext> dest_mem,
uint32_t src_addr,
uint32_t src_size) const {
shared_ptr<const ResourceDASM::MemoryContext> dest_mem, uint32_t src_addr, uint32_t src_size) const {
if (src_size == 0) {
src_size = 4;
}
@@ -863,6 +855,15 @@ public:
this->set_source_file(tokens.at(1));
} else if (tokens[0] == "find") {
this->find_data(phosg::parse_data_string(tokens.at(1)));
} else if (tokens[0] == "only") {
unordered_set<string> to_keep{tokens.begin() + 1, tokens.end()};
for (auto it = this->mems.begin(); it != this->mems.end();) {
if (to_keep.count(it->first)) {
it++;
} else {
it = this->mems.erase(it);
}
}
} else if (tokens[0] == "match") {
this->find_all_matches(
stoul(tokens.at(1), nullptr, 16),
+7 -8
View File
@@ -324,8 +324,8 @@ asio::awaitable<WebSocketMessage> HTTPClient::recv_websocket_message(size_t max_
this->last_communication_time = phosg::now();
// If the current message is a control message, respond appropriately
// (these can be sent in the middle of fragmented messages)
// If the current message is a control message, respond appropriately (these can be sent in the middle of
// fragmented messages)
uint8_t opcode = msg.header[0] & 0x0F;
if (opcode & 0x08) {
if (opcode == 0x0A) {
@@ -347,8 +347,8 @@ asio::awaitable<WebSocketMessage> HTTPClient::recv_websocket_message(size_t max_
continue;
}
// If there's an existing fragment, the current message's opcode should be
// zero; if there's no pending message, it must not be zero
// If there's an existing fragment, the current message's opcode should be zero; if there's no pending message, it
// must not be zero
if (prev_msg_present == (opcode != 0)) {
this->r.close();
continue;
@@ -372,10 +372,9 @@ asio::awaitable<WebSocketMessage> HTTPClient::recv_websocket_message(size_t max_
prev_msg.data += msg.data;
}
// If the FIN bit is set, then the frame is complete - append the payload
// to any pending payloads and call the message handler. If the FIN bit
// isn't set, we need to receive at least one continuation frame to
// complete the message.
// If the FIN bit is set, then the frame is complete - append the payload to any pending payloads and call the
// message handler. If the FIN bit isn't set, we need to receive at least one continuation frame to complete the
// message.
if (prev_msg.header[0] & 0x80) {
co_return prev_msg;
}
+9 -15
View File
@@ -38,9 +38,8 @@ struct HTTPRequest {
std::unordered_multimap<std::string, std::string> query_params;
std::string data;
// Header name should be entirely lowercase for this function. Returns
// nullptr if the header doesn't exist; throws http_error(400) if multiple
// instances of it exist.
// Header name should be entirely lowercase for this function. Returns nullptr if the header doesn't exist; throws
// http_error(400) if multiple instances of it exist.
const std::string* get_header(const std::string& name) const;
const std::string* get_query_param(const std::string& name) const;
@@ -49,8 +48,7 @@ struct HTTPRequest {
struct HTTPResponse {
std::string http_version;
int response_code = 200;
// Content-Length should NOT be specified in headers; it is automatically
// added in async_write() if data is not blank.
// Content-Length should NOT be specified in headers; it is automatically added in async_write() if data isn't blank.
std::unordered_multimap<std::string, std::string> headers;
std::string data;
};
@@ -244,9 +242,8 @@ protected:
}
}
// Attempts to switch the client to WebSockets. Returns true if this is done
// successfully (and the caller should then receive/send WebSocket messages),
// or false if this failed (and the caller should send an HTTP response).
// Attempts to switch the client to WebSockets. Returns true if this is done successfully (and the caller should then
// receive/send WebSocket messages), or false if this failed (and the caller should send an HTTP response).
asio::awaitable<bool> enable_websockets(std::shared_ptr<ClientT> c, const HTTPRequest& req) {
if (req.method != HTTPRequest::Method::GET) {
co_return false;
@@ -287,13 +284,10 @@ protected:
// handle_request must do one of the following three things:
// 1. Return an HTTP response.
// 2. Call enable_websockets, and if it returns true, return nullptr. After
// this point, handle_request will not be called again for this client;
// handle_websocket_message will be called instead when any WebSocket
// messages are received. If enable_websockets returns false,
// handle_request must still return an HTTP response.
// 3. Throw an exception. In this case, the client receives an HTTP 500
// response.
// 2. Call enable_websockets, and if it returns true, return nullptr. After this point, handle_request will not be
// called again for this client; handle_websocket_message will be called instead when any WebSocket messages are
// received. If enable_websockets returns false, handle_request must still return an HTTP response.
// 3. Throw an exception. In this case, the client receives an HTTP 500 response.
virtual asio::awaitable<std::unique_ptr<HTTPResponse>> handle_request(std::shared_ptr<ClientT> c, HTTPRequest&& req) = 0;
virtual asio::awaitable<void> handle_websocket_message(std::shared_ptr<ClientT>, WebSocketMessage&&) {
co_return;
+1 -2
View File
@@ -73,8 +73,7 @@ asio::awaitable<string> AsyncSocketReader::read_line(const char* delimiter, size
throw runtime_error("line exceeds max length");
}
// TODO: It's not great that we copy the data here. There's probably a more
// idiomatic and efficient way to do this.
// TODO: It's not great that we copy the data here. There's probably a more idiomatic and efficient way to do this.
string ret = this->pending_data.substr(0, delimiter_pos);
this->pending_data = this->pending_data.substr(delimiter_pos + delimiter_size);
co_return ret;
+8 -10
View File
@@ -175,16 +175,15 @@ public:
AsyncSocketReader& operator=(AsyncSocketReader&&) = delete;
~AsyncSocketReader() = default;
// Reads one line from the socket, buffering any extra data read. The
// delimiter is not included in the returned line. max_length = 0 means no
// maximum length is enforced.
// Reads one line from the socket, buffering any extra data read. The delimiter is not included in the returned line.
// max_length = 0 means no maximum length is enforced.
asio::awaitable<std::string> read_line(
const char* delimiter = "\n", size_t max_length = 0);
asio::awaitable<std::string> read_data(size_t size);
asio::awaitable<void> read_data_into(void* data, size_t size);
// The caller cannot know what the socket's read state is, so this should
// only be used when the caller intends to write to the socket, not read
// The caller cannot know what the socket's read state is, so this should only be used when the caller intends to
// write to the socket, not read
inline asio::ip::tcp::socket& get_socket() {
return this->sock;
}
@@ -215,8 +214,8 @@ public:
void add(std::string&& data);
// When using add_reference, it is the caller's responsibility to ensure that
// the buffer is valid until *this is destroyed or write() returns.
// When using add_reference, it is the caller's responsibility to ensure that the buffer is valid until *this is
// destroyed or write() returns.
void add_reference(const void* data, size_t size);
asio::awaitable<void> write(asio::ip::tcp::socket& sock);
@@ -260,9 +259,8 @@ asio::awaitable<std::invoke_result_t<FnT, ArgTs...>> call_on_thread_pool(asio::t
using ReturnT = std::invoke_result_t<FnT, ArgTs...>;
auto bound = std::bind(std::forward<FnT>(f), std::forward<ArgTs>(args)...);
// We have to use a shared_ptr here in case call_on_thread_pool is canceled
// (in that case, the posted callback will try to use promise after the
// call_on_thread_pool coroutine has been destroyed)
// We have to use a shared_ptr here in case call_on_thread_pool is canceled (in that case, the posted callback will
// try to use promise after the call_on_thread_pool coroutine has been destroyed)
auto promise = std::make_shared<AsyncPromise<ReturnT>>();
asio::post(pool, [bound = std::move(bound), promise]() mutable {
try {
+2 -8
View File
@@ -14,12 +14,9 @@ struct BMLHeaderT {
parray<uint8_t, 0x04> unknown_a1;
U32T<BE> num_entries;
parray<uint8_t, 0x38> unknown_a2;
} __attribute__((packed));
} __packed_ws_be__(BMLHeaderT, 0x40);
using BMLHeader = BMLHeaderT<false>;
using BMLHeaderBE = BMLHeaderT<true>;
check_struct_size(BMLHeader, 0x40);
check_struct_size(BMLHeaderBE, 0x40);
template <bool BE>
struct BMLHeaderEntryT {
@@ -30,12 +27,9 @@ struct BMLHeaderEntryT {
U32T<BE> compressed_gvm_size;
U32T<BE> decompressed_gvm_size;
parray<uint8_t, 0x0C> unknown_a2;
} __attribute__((packed));
} __packed_ws_be__(BMLHeaderEntryT, 0x40);
using BMLHeaderEntry = BMLHeaderEntryT<false>;
using BMLHeaderEntryBE = BMLHeaderEntryT<true>;
check_struct_size(BMLHeaderEntry, 0x40);
check_struct_size(BMLHeaderEntryBE, 0x40);
template <bool BE>
void BMLArchive::load_t() {
+56 -24
View File
@@ -10,35 +10,67 @@
using namespace std;
void BattleParamsIndex::Table::print(FILE* stream, Episode episode) const {
auto print_entry = [stream, episode](const PlayerStats& e, size_t z) {
string names_str;
for (auto type : enemy_types_for_battle_param_index(episode, z)) {
if (!names_str.empty()) {
names_str += ", ";
}
names_str += phosg::name_for_enum(type);
}
phosg::fwrite_fmt(stream,
"{:5} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {}",
e.char_stats.atp,
e.char_stats.mst,
e.char_stats.evp,
e.char_stats.hp,
e.char_stats.dfp,
e.char_stats.ata,
e.char_stats.lck,
e.esp,
e.experience,
e.meseta,
names_str);
};
phosg::fwrite_fmt(stream, "========== STATS\n");
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
phosg::fwrite_fmt(stream, "{} ZZ ATP PSV EVP HP DFP ATA LCK ESP EXP DIFF NAMES\n",
abbreviation_for_difficulty(difficulty));
for (size_t z = 0; z < 0x60; z++) {
const auto& e = this->stats[static_cast<size_t>(difficulty)][z];
phosg::fwrite_fmt(stream, " {:02X} ", z);
print_entry(this->stats[static_cast<size_t>(difficulty)][z], z);
string names_str;
for (auto type : enemy_types_for_battle_param_stats_index(episode, z)) {
if (!names_str.empty()) {
names_str += ", ";
}
names_str += phosg::name_for_enum(type);
}
phosg::fwrite_fmt(stream,
"{:5} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {}",
e.char_stats.atp, e.char_stats.mst, e.char_stats.evp, e.char_stats.hp, e.char_stats.dfp, e.char_stats.ata,
e.char_stats.lck, e.esp, e.experience, e.meseta, names_str);
fputc('\n', stream);
}
}
phosg::fwrite_fmt(stream, "========== ATTACK DATA\n");
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
phosg::fwrite_fmt(stream, "{} ZZ ATP- ATP+ ATA- ATA+ -DIST-X- -ANGLE-- -DIST-Y- -A8- -A9- A10- A11- --A12--- --A13--- --A14--- --A15--- --A16---\n",
abbreviation_for_difficulty(difficulty));
for (size_t z = 0; z < 0x60; z++) {
const auto& e = this->attack_data[static_cast<size_t>(difficulty)][z];
phosg::fwrite_fmt(stream,
" {:02X} {:04X} {:04X} {:04X} {:04X} {:8.3f} {:08X} {:8.3f} {:04X} {:04X} {:04X} {:04X} {:08X} {:08X} {:08X} {:08X} {:08X}",
z, e.min_atp, e.max_atp, e.min_ata, e.max_ata, e.distance_x, e.angle, e.distance_y, e.unknown_a8,
e.unknown_a9, e.unknown_a10, e.unknown_a11, e.unknown_a12, e.unknown_a13, e.unknown_a14, e.unknown_a15,
e.unknown_a16);
fputc('\n', stream);
}
}
phosg::fwrite_fmt(stream, "========== RESIST DATA\n");
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
phosg::fwrite_fmt(stream, "{} ZZ EVP- EFR- EIC- ETH- ELT- EDK- ---A6--- ---A7--- ---A8--- ---A9--- --DFP---\n",
abbreviation_for_difficulty(difficulty));
for (size_t z = 0; z < 0x60; z++) {
const auto& e = this->resist_data[static_cast<size_t>(difficulty)][z];
phosg::fwrite_fmt(stream,
" {:02X} {:04X} {:04X} {:04X} {:04X} {:04X} {:04X} {:08X} {:08X} {:08X} {:08X} {:08X}",
z, e.evp_bonus, e.efr, e.eic, e.eth, e.elt, e.edk, e.unknown_a6, e.unknown_a7, e.unknown_a8, e.unknown_a9,
e.dfp_bonus);
fputc('\n', stream);
}
}
phosg::fwrite_fmt(stream, "========== MOVEMENT DATA\n");
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
phosg::fwrite_fmt(stream, "{} ZZ FPARAM-1 FPARAM-2 FPARAM-3 FPARAM-4 FPARAM-5 FPARAM-6 IPARAM-1 IPARAM-2 IPARAM-3 IPARAM-4 IPARAM-5 IPARAM-6\n",
abbreviation_for_difficulty(difficulty));
for (size_t z = 0; z < 0x60; z++) {
const auto& e = this->movement_data[static_cast<size_t>(difficulty)][z];
phosg::fwrite_fmt(stream,
" {:02X} {:8.3f} {:8.3f} {:8.3f} {:8.3f} {:8.3f} {:8.3f} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X}",
z, e.fparam1, e.fparam2, e.fparam3, e.fparam4, e.fparam5, e.fparam6,
e.iparam1, e.iparam2, e.iparam3, e.iparam4, e.iparam5, e.iparam6);
fputc('\n', stream);
}
}
+17 -17
View File
@@ -19,12 +19,12 @@ public:
// These files are little-endian, even on PSO GC.
struct AttackData {
/* 00 */ le_int16_t unknown_a1;
/* 02 */ le_int16_t atp;
/* 04 */ le_int16_t ata_bonus;
/* 06 */ le_uint16_t unknown_a4;
/* 00 */ le_int16_t min_atp;
/* 02 */ le_int16_t max_atp;
/* 04 */ le_int16_t min_ata;
/* 06 */ le_int16_t max_ata;
/* 08 */ le_float distance_x;
/* 0C */ le_uint32_t angle_x; // Out of 0x10000 (high 16 bits are unused)
/* 0C */ le_uint32_t angle; // Out of 0x10000 (high 16 bits are unused)
/* 10 */ le_float distance_y;
/* 14 */ le_uint16_t unknown_a8;
/* 16 */ le_uint16_t unknown_a9;
@@ -54,18 +54,18 @@ public:
} __packed_ws__(ResistData, 0x20);
struct MovementData {
/* 00 */ le_float idle_move_speed;
/* 04 */ le_float idle_animation_speed;
/* 08 */ le_float move_speed;
/* 0C */ le_float animation_speed;
/* 10 */ le_float unknown_a1;
/* 14 */ le_float unknown_a2;
/* 18 */ le_uint32_t unknown_a3;
/* 1C */ le_uint32_t unknown_a4;
/* 20 */ le_uint32_t unknown_a5;
/* 24 */ le_uint32_t unknown_a6;
/* 28 */ le_uint32_t unknown_a7;
/* 2C */ le_uint32_t unknown_a8;
/* 00 */ le_float fparam1;
/* 04 */ le_float fparam2;
/* 03 */ le_float fparam3;
/* 0C */ le_float fparam4;
/* 10 */ le_float fparam5;
/* 14 */ le_float fparam6;
/* 18 */ le_uint32_t iparam1;
/* 1C */ le_uint32_t iparam2;
/* 20 */ le_uint32_t iparam3;
/* 24 */ le_uint32_t iparam4;
/* 28 */ le_uint32_t iparam5;
/* 2C */ le_uint32_t iparam6;
/* 30 */
} __packed_ws__(MovementData, 0x30);
+15 -23
View File
@@ -32,7 +32,8 @@ void Channel::send(uint16_t cmd, uint32_t flag, bool silent) {
this->send(cmd, flag, nullptr, 0, silent);
}
void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<const void*, size_t>> blocks, bool silent) {
void Channel::send(
uint16_t cmd, uint32_t flag, const std::vector<std::pair<const void*, size_t>> blocks, bool silent) {
if (!this->connected()) {
channel_exceptions_log.warning_f("Attempted to send command on closed channel; dropping data");
return;
@@ -57,10 +58,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
case Version::GC_EP3:
case Version::XB_V3: {
PSOCommandHeaderDCV3 header;
if (this->crypt_out.get() &&
(this->version != Version::DC_NTE) &&
(this->version != Version::DC_11_2000) &&
(this->version != Version::DC_V1)) {
if (this->crypt_out.get() && !is_v1(this->version)) {
send_data_size = (sizeof(header) + size + 3) & ~3;
} else {
send_data_size = (sizeof(header) + size);
@@ -90,13 +88,11 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
break;
}
case Version::BB_V4: {
// BB has an annoying behavior here: command lengths must be multiples of
// 4, but the actual data length must be a multiple of 8. If the size
// field is not divisible by 8, 4 extra bytes are sent anyway. This
// behavior only applies when encryption is enabled - any commands sent
// before encryption is enabled have no size restrictions (except they
// must include a full header and must fit in the client's receive
// buffer), and no implicit extra bytes are sent.
// BB has an annoying behavior here: command lengths must be multiples of 4, but the actual data length must be a
// multiple of 8. If the size field is not divisible by 8, 4 extra bytes are sent anyway. This behavior only
// applies when encryption is enabled - any commands sent before encryption is enabled have no size restrictions
// (except they must include a full header and must fit in the client's receive buffer), and no implicit extra
// bytes are sent.
PSOCommandHeaderBB header;
if (this->crypt_out.get()) {
send_data_size = (sizeof(header) + size + 7) & ~7;
@@ -115,8 +111,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
throw logic_error("unimplemented game version in send_command");
}
// All versions of PSO I've seen (so far) have a receive buffer 0x7C00
// bytes in size
// All versions of PSO I've seen (so far) have a receive buffer 0x7C00 bytes in size
if (send_data_size > 0x7C00) {
throw runtime_error("outbound command too large");
}
@@ -132,8 +127,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
print_color_escape(stderr, phosg::TerminalFormat::FG_YELLOW, phosg::TerminalFormat::BOLD, phosg::TerminalFormat::END);
}
if (version == Version::BB_V4) {
command_data_log.info_f("Sending to {} (version=BB command={:04X} flag={:08X})",
this->name, cmd, flag);
command_data_log.info_f("Sending to {} (version=BB command={:04X} flag={:08X})", this->name, cmd, flag);
} else {
command_data_log.info_f("Sending to {} (version={} command={:02X} flag={:02X})",
this->name, phosg::name_for_enum(version), cmd, flag);
@@ -187,9 +181,8 @@ asio::awaitable<Channel::Message> Channel::recv() {
throw runtime_error("header size field is smaller than header");
}
// If encryption is enabled, BB pads commands to 8-byte boundaries, and this
// is not reflected in the size field. This logic does not occur if encryption
// is not yet enabled.
// If encryption is enabled, BB pads commands to 8-byte boundaries, and this is not reflected in the size field. This
// logic does not occur if encryption is not yet enabled.
size_t command_physical_size = (this->crypt_in.get() && (version == Version::BB_V4))
? ((command_logical_size + 7) & ~7)
: command_logical_size;
@@ -198,10 +191,9 @@ asio::awaitable<Channel::Message> Channel::recv() {
co_await this->recv_raw(command_data.data(), command_data.size());
if (this->crypt_in.get()) {
// Some versions of PSO DC can send commands whose sizes are not a multiple
// of 4, but the server is expected to always use a multiple of 4 bytes when
// decrypting (the extra cipher bytes are lost). To emulate this behavior,
// we have to round up the size for DC commands here.
// Some versions of PSO DC can send commands whose sizes are not a multiple of 4, but the server is expected to
// always use a multiple of 4 bytes when decrypting (the extra cipher bytes are lost). To emulate this behavior, we
// have to round up the size for DC commands here.
size_t orig_size = command_data.size();
command_data.resize((orig_size + 3) & (~3), 0);
this->crypt_in->decrypt(command_data.data(), command_data.size());
+9 -16
View File
@@ -60,9 +60,8 @@ public:
// Returns whether the channel is connected or not.
virtual bool connected() const = 0;
// Disconnects the channel. Any pending data will still be sent before the
// underlying transport (e.g. socket) is closed, but further send calls will
// do nothing.
// Disconnects the channel. Any pending data will still be sent before the underlying transport (e.g. socket) is
// closed, but further send calls will do nothing.
virtual void disconnect() = 0;
// Sends a message with an automatically-constructed header.
@@ -76,8 +75,7 @@ public:
this->send(cmd, flag, &data, sizeof(data), silent);
}
// Sends a message with a pre-existing header (as the first few bytes in the
// data)
// Sends a message with a pre-existing header (as the first few bytes in the data)
void send(const void* data, size_t size, bool silent = false);
void send(const std::string& data, bool silent = false);
@@ -96,27 +94,22 @@ protected:
Channel& operator=(const Channel& other) = delete;
Channel& operator=(Channel&& other) = delete;
// Sends raw data on the underlying transport. If the channel is already
// disconnected, silently drops the data.
// Sends raw data on the underlying transport. If the channel is already disconnected, silently drops the data.
virtual void send_raw(std::string&& data) = 0;
// Receives raw data on the underlying transport. Raises when the channel is
// disconnected.
// Receives raw data on the underlying transport. Raises when the channel is disconnected.
virtual asio::awaitable<void> recv_raw(void* data, size_t size) = 0;
};
// Standard channel type, used for most PSO clients. Represents an open TCP
// socket.
// Standard channel type, used for most PSO clients. Represents an open TCP socket.
class SocketChannel : public Channel, public std::enable_shared_from_this<SocketChannel> {
public:
std::unique_ptr<asio::ip::tcp::socket> sock;
asio::ip::tcp::endpoint local_addr;
asio::ip::tcp::endpoint remote_addr;
// SocketChannel has a static constructor because it has an internal task,
// which is necessary to support flushing before disconnection (for example)
// and also to make send_raw not a coroutine, which keeps the rest of the
// code cleaner. The task needs to hold a shared_ptr to the SocketChannel
// whilc it's open
// SocketChannel has a static constructor because it has an internal task, which is necessary to support flushing
// before disconnection (for example) and also to make send_raw not a coroutine, which keeps the rest of the code
// cleaner.
static std::shared_ptr<SocketChannel> create(std::shared_ptr<asio::io_context> io_context,
std::unique_ptr<asio::ip::tcp::socket>&& sock,
Version version,
+199 -109
View File
@@ -25,7 +25,7 @@
using namespace std;
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tools
string str_for_flag_ranges(const vector<bool>& flags) {
@@ -60,7 +60,7 @@ string str_for_flag_ranges(const vector<bool>& flags) {
return ret;
}
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Checks
class precondition_failed {
@@ -165,7 +165,7 @@ struct Args {
}
};
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Command definitions
struct ChatCommandDefinition {
@@ -188,7 +188,7 @@ struct ChatCommandDefinition {
unordered_map<string, const ChatCommandDefinition*> ChatCommandDefinition::all_defs;
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// All commands (in alphabetical order)
ChatCommandDefinition cc_allevent(
@@ -265,8 +265,8 @@ ChatCommandDefinition cc_announce_rares(
a.c->login->account->toggle_user_flag(Account::UserFlag::DISABLE_DROP_NOTIFICATION_BROADCAST);
a.c->login->account->save();
send_text_message_fmt(a.c, "$C6Rare announcements\n{} for your\nitems",
a.c->login->account->check_user_flag(Account::UserFlag::DISABLE_DROP_NOTIFICATION_BROADCAST) ? "disabled" : "enabled");
bool enabled = a.c->login->account->check_user_flag(Account::UserFlag::DISABLE_DROP_NOTIFICATION_BROADCAST);
send_text_message_fmt(a.c, "$C6Rare announcements\n{} for your\nitems", enabled ? "disabled" : "enabled");
co_return;
});
@@ -370,9 +370,8 @@ ChatCommandDefinition cc_ban(
throw precondition_failed("$C6You do not have\nsufficient privileges.");
}
if (a.c == target) {
// This shouldn't be possible because you need BAN_USER to get here,
// but the target can't have BAN_USER if we get here, so if a.c and
// target are the same, one of the preceding conditions must be false.
// This shouldn't be possible because you need BAN_USER to get here, but the target can't have BAN_USER if we
// get here, so if a.c and target are the same, one of the preceding conditions must be false.
throw logic_error("client attempts to ban themself");
}
@@ -440,12 +439,14 @@ ChatCommandDefinition cc_bank(
});
static asio::awaitable<void> server_command_bbchar_savechar(const Args& a, bool is_bb_conversion) {
// TODO: We could support this in proxy sessions; we'd just have to handle the 61/30 correctly
a.check_is_proxy(false);
// Allow $savechar in proxy sessions for character migration/testing.
// Keep $bbchar blocked in proxy sessions because it writes to BB account slots.
if (is_bb_conversion) {
a.check_is_proxy(false);
}
a.check_is_game(false);
auto s = a.c->require_server_state();
auto l = a.c->require_lobby();
if (is_bb_conversion && is_ep3(a.c->version())) {
throw precondition_failed("$C6Episode 3 players\ncannot be converted\nto BB format");
@@ -482,10 +483,14 @@ static asio::awaitable<void> server_command_bbchar_savechar(const Args& a, bool
dest_account = a.c->login->account;
}
// If the client isn't BB, request the player info. (If they are BB, the
// server already has it)
// In direct sessions, request player info from the client.
// In proxy sessions, don't use the 61/30 request path; use the server-side
// character state already tracked for the proxied client.
GetPlayerInfoResult ch;
if (a.c->version() == Version::BB_V4) {
if ((a.c->version() == Version::BB_V4) || a.c->proxy_session) {
if (is_ep3(a.c->version())) {
throw precondition_failed("$C6Proxy savechar for\nEpisode 3 is not\nimplemented yet");
}
ch.character = a.c->character_file();
ch.is_full_info = true;
} else {
@@ -516,8 +521,7 @@ static asio::awaitable<void> server_command_bbchar_savechar(const Args& a, bool
}
} else {
// Client sent 61; generate a BB-format player from the information we have
// and save that instead
// Client sent 61; generate a BB-format player from the information we have and save that instead
if (ch.character) {
auto bb_player = PSOBBCharacterFile::create_from_config(
a.c->login->account->account_id,
@@ -528,9 +532,8 @@ static asio::awaitable<void> server_command_bbchar_savechar(const Args& a, bool
bb_player->disp.visual.version = 4;
bb_player->disp.visual.name_color_checksum = 0x00000000;
bb_player->inventory = ch.character->inventory;
// Before V3, player stats can't be correctly computed from other fields
// because material usage isn't stored anywhere. For these versions, we
// have to trust the stats field from the player's data.
// Before V3, player stats can't be correctly computed from other fields because material usage isn't stored
// anywhere. For these versions, we have to trust the stats field from the player's data.
auto level_table = s->level_table(a.c->version());
if (is_v1_or_v2(a.c->version())) {
bb_player->disp.stats = ch.character->disp.stats;
@@ -1074,9 +1077,7 @@ ChatCommandDefinition cc_event(
ChatCommandDefinition cc_exit(
{"$exit"},
+[](const Args& a) -> asio::awaitable<void> {
if (!(a.c->proxy_session
? a.c->proxy_session->is_in_game
: a.c->require_lobby()->is_game())) {
if (!(a.c->proxy_session ? a.c->proxy_session->is_in_game : a.c->require_lobby()->is_game())) {
// Client is in the lobby; send them to the login server (main menu)
if (a.c->proxy_session) {
if (is_v4(a.c->version())) {
@@ -1181,8 +1182,6 @@ ChatCommandDefinition cc_infhp(
ChatCommandDefinition cc_inftime(
{"$inftime"},
+[](const Args& a) -> asio::awaitable<void> {
// TODO: We could implement this in proxy sessions by rewriting the rules
// struct from the server in various 6xB4 commands.
a.check_is_proxy(false);
a.check_is_game(true);
a.check_is_ep3(true);
@@ -1232,17 +1231,25 @@ ChatCommandDefinition cc_item(
a.check_cheats_enabled_or_allowed(s->cheat_flags.create_items);
ItemData item;
bool was_enqueued = false;
if (a.c->proxy_session) {
if (a.c->version() == Version::BB_V4) {
throw precondition_failed("$C6This command cannot\nbe used in proxy\nsessions in BB games");
}
a.check_is_leader();
item = s->parse_item_description(a.c->version(), a.text);
item.id = phosg::random_object<uint32_t>() | 0x80000000;
if (a.text.starts_with("!")) {
item = s->parse_item_description(a.c->version(), a.text.substr(1));
a.c->proxy_session->next_drop_item = item;
was_enqueued = true;
send_drop_stacked_item_to_channel(s, a.c->channel, item, a.c->floor, a.c->pos);
send_drop_stacked_item_to_channel(s, a.c->proxy_session->server_channel, item, a.c->floor, a.c->pos);
} else {
item = s->parse_item_description(a.c->version(), a.text);
item.id = phosg::random_object<uint32_t>() | 0x80000000;
send_drop_stacked_item_to_channel(s, a.c->channel, item, a.c->floor, a.c->pos);
send_drop_stacked_item_to_channel(s, a.c->proxy_session->server_channel, item, a.c->floor, a.c->pos);
}
} else {
auto l = a.c->require_lobby();
@@ -1259,7 +1266,11 @@ ChatCommandDefinition cc_item(
}
string name = s->describe_item(a.c->version(), item, ItemNameIndex::Flag::INCLUDE_PSO_COLOR_ESCAPES);
send_text_message(a.c, "$C7Item created:\n" + name);
if (was_enqueued) {
send_text_message(a.c, "$C7Next item:\n" + name);
} else {
send_text_message(a.c, "$C7Item created:\n" + name);
}
co_return;
});
@@ -1301,9 +1312,8 @@ ChatCommandDefinition cc_kick(
throw precondition_failed("$C6You do not have\nsufficient privileges.");
}
if (a.c == target) {
// This shouldn't be possible because you need KICK_USER to get here,
// but the target can't have KICK_USER if we get here, so if a.c and
// target are the same, one of the preceding conditions must be false.
// This shouldn't be possible because you need KICK_USER to get here, but the target can't have KICK_USER if we
// get here, so if a.c and target are the same, one of the preceding conditions must be false.
throw logic_error("client attempts to kick themself off");
}
@@ -1332,13 +1342,10 @@ ChatCommandDefinition cc_killcount(
throw precondition_failed("No equipped items\nhave kill counts");
} else {
// Kill counts are only accurate on the server side at all times on BB.
// On other versions, we update the server's view of the client's
// inventory during games, but we can't track kills because the client
// doesn't inform the server whether it counted a kill for any
// individual enemy. So, on non-BB versions, the kill count is accurate
// at all times in the lobby (since kills can't occur there), or at the
// beginning of a game.
// Kill counts are only accurate on the server side at all times on BB. On other versions, we update the
// server's view of the client's inventory during games, but we can't track kills because the client doesn't
// inform the server whether it counted a kill for any individual enemy. So, on non-BB versions, the kill count
// is accurate at all times in the lobby (since kills can't occur there), or at the beginning of a game.
if ((a.c->version() == Version::BB_V4) || !a.c->require_lobby()->is_game()) {
send_text_message(a.c, "As of now:");
} else {
@@ -1361,9 +1368,8 @@ ChatCommandDefinition cc_lobby_info(
+[](const Args& a) -> asio::awaitable<void> {
if (a.c->proxy_session) {
string msg;
// On non-masked-GC sessions (BB), there is no remote Guild Card number, so we
// don't show it. (The user can see it in the pause menu, unlike in masked-GC
// sessions like GC.)
// On non-masked-GC sessions (BB), there is no remote Guild Card number, so we don't show it. (The user can see
// it in the pause menu, unlike in masked-GC sessions like GC.)
if (a.c->proxy_session->remote_guild_card_number >= 0) {
msg = std::format("$C7GC: $C6{}$C7\n", a.c->proxy_session->remote_guild_card_number);
}
@@ -1529,14 +1535,32 @@ ChatCommandDefinition cc_ln(
ChatCommandDefinition cc_loadchar(
{"$loadchar"},
+[](const Args& a) -> asio::awaitable<void> {
a.check_is_proxy(false);
if (a.c->proxy_session && (a.c->version() == Version::BB_V4)) {
throw precondition_failed("$C6This command cannot\nbe used in proxy\nsessions in BB games");
}
a.check_is_game(false);
if (a.check_permissions && a.c->login->account->check_flag(Account::Flag::IS_SHARED_ACCOUNT)) {
throw precondition_failed("$C7This command cannot\nbe used on a shared\naccount");
}
auto s = a.c->require_server_state();
auto l = a.c->require_lobby();
shared_ptr<Lobby> l;
if (a.c->proxy_session) {
if (!a.c->proxy_session->is_in_lobby) {
throw precondition_failed("$C6This command can\nonly be used from\nthe lobby");
}
} else {
l = a.c->require_lobby();
}
auto send_proxy_lobby_refresh = [&]() {
auto temp_l = make_shared<Lobby>(s, 0xFFFFFFFF, false);
temp_l->block = 1;
temp_l->event = a.c->proxy_session ? a.c->proxy_session->lobby_event : 0;
temp_l->leader_id = a.c->lobby_client_id;
temp_l->clients.at(a.c->lobby_client_id) = a.c;
send_join_lobby(a.c, temp_l);
};
size_t index = stoull(a.text, nullptr, 0) - 1;
if (index >= s->num_backup_character_slots) {
@@ -1569,7 +1593,7 @@ ChatCommandDefinition cc_loadchar(
throw precondition_failed("Can\'t load character\ndata on this game\nversion");
}
auto send_set_extended_player_info = [&a, &s]<typename CharT>(const CharT& char_file) -> asio::awaitable<void> {
auto send_set_extended_player_info = [&a, &s, &send_proxy_lobby_refresh]<typename CharT>(const CharT& char_file) -> asio::awaitable<void> {
co_await prepare_client_for_patches(a.c);
try {
auto fn = s->function_code_index->get_patch("SetExtendedPlayerInfo", a.c->specific_version);
@@ -1578,6 +1602,8 @@ ChatCommandDefinition cc_loadchar(
if (l) {
send_player_leave_notification(l, a.c->lobby_client_id);
s->send_lobby_join_notifications(l, a.c);
} else if (a.c->proxy_session) {
send_proxy_lobby_refresh();
}
} catch (const exception& e) {
a.c->log.warning_f("Failed to set extended player info: {}", e.what());
@@ -1612,11 +1638,15 @@ ChatCommandDefinition cc_loadchar(
}
} else {
// On v1 and v2, the client will assign its character data from the lobby
// join command, so it suffices to just resend the join notification.
auto s = a.c->require_server_state();
send_player_leave_notification(l, a.c->lobby_client_id);
s->send_lobby_join_notifications(l, a.c);
// On PC V2 and older DC versions, the client will assign its character data
// from the lobby join command, so resend a lobby join notification.
if (a.c->proxy_session) {
send_proxy_lobby_refresh();
} else {
auto s = a.c->require_server_state();
send_player_leave_notification(l, a.c->lobby_client_id);
s->send_lobby_join_notifications(l, a.c);
}
}
co_return;
});
@@ -1788,9 +1818,7 @@ ChatCommandDefinition cc_next(
auto s = a.c->require_server_state();
a.check_cheats_enabled_or_allowed(s->cheat_flags.warp);
auto episode = a.c->proxy_session
? a.c->proxy_session->lobby_episode
: a.c->require_lobby()->episode;
auto episode = a.c->proxy_session ? a.c->proxy_session->lobby_episode : a.c->require_lobby()->episode;
size_t limit = FloorDefinition::limit_for_episode(episode);
if (limit > 0) {
send_warp(a.c, (a.c->floor + 1) % limit, true);
@@ -1829,16 +1857,33 @@ ChatCommandDefinition cc_patch(
string patch_name = std::move(tokens[0]);
unordered_map<string, uint32_t> label_writes;
for (size_t z = 0; z < tokens.size() - 1; z++) {
label_writes.emplace(std::format("arg{}", z), stoul(tokens[z + 1], nullptr, 0));
const auto& token = tokens[z + 1];
size_t equals_pos = token.find('=');
string key, value;
if (equals_pos == std::string::npos) {
key = std::format("arg{}", z);
value = token;
} else {
key = token.substr(0, equals_pos);
value = token.substr(equals_pos + 1);
}
if (value.contains('.')) { // float
label_writes.emplace(std::move(key), std::bit_cast<uint32_t>(stof(value, nullptr)));
} else { // int
label_writes.emplace(std::move(key), stoul(value, nullptr, 0));
}
}
co_await prepare_client_for_patches(a.c);
try {
auto s = a.c->require_server_state();
// Note: We can't look this up before prepare_client_for_patches
// because specific_version may not be set at that point
// Note: We can't look this up before prepare_client_for_patches because specific_version may not be set
auto fn = s->function_code_index->get_patch(patch_name, a.c->specific_version);
co_await send_function_call(a.c, fn, label_writes);
auto ret = co_await send_function_call(a.c, fn, label_writes);
if (fn->show_return_value) {
send_text_message_fmt(a.c, "$C6Return value:$C7\nInt: {}\nHex: {:08X}\nFloat: {:g}",
ret.return_value.load(), ret.return_value.load(), std::bit_cast<float>(ret.return_value.load()));
}
} catch (const out_of_range&) {
send_text_message(a.c, "$C6Invalid patch name");
}
@@ -1874,9 +1919,7 @@ ChatCommandDefinition cc_ping(
if (a.c->proxy_session) {
a.c->proxy_session->server_ping_start_time = a.c->ping_start_time;
C_GuildCardSearch_40 cmd = {
0x00010000,
a.c->proxy_session->remote_guild_card_number,
a.c->proxy_session->remote_guild_card_number};
0x00010000, a.c->proxy_session->remote_guild_card_number, a.c->proxy_session->remote_guild_card_number};
a.c->proxy_session->server_channel->send(0x40, 0x00, &cmd, sizeof(cmd));
}
co_return;
@@ -1914,7 +1957,8 @@ ChatCommandDefinition cc_playrec(
data = phosg::load_file(file_path_for_recording(filename, a.c->login->account->account_id, false));
} catch (const phosg::cannot_open_file&) {
try {
data = prs_decompress(phosg::load_file(file_path_for_recording(filename, a.c->login->account->account_id, true)));
data = prs_decompress(phosg::load_file(file_path_for_recording(
filename, a.c->login->account->account_id, true)));
} catch (const phosg::cannot_open_file&) {
throw precondition_failed("$C4The recording does\nnot exist");
}
@@ -2196,6 +2240,34 @@ ChatCommandDefinition cc_quest(
co_return;
});
ChatCommandDefinition cc_fastkill(
{"$fastkill"},
+[](const Args& a) -> asio::awaitable<void> {
if (!a.c->proxy_session) {
a.check_is_game(true);
}
if (a.c->check_flag(Client::Flag::FAST_KILLS_ENABLED)) {
a.c->clear_flag(Client::Flag::FAST_KILLS_ENABLED);
send_text_message(a.c, "$C6Fast kills disabled");
} else {
auto s = a.c->require_server_state();
a.check_cheats_enabled_or_allowed(s->cheat_flags.fast_kills);
a.c->set_flag(Client::Flag::FAST_KILLS_ENABLED);
send_text_message(a.c, "$C6Fast kills enabled");
}
co_return;
});
ChatCommandDefinition cc_allrare(
{"$allrare"},
+[](const Args& a) -> asio::awaitable<void> {
a.check_debug_enabled();
a.c->toggle_flag(Client::Flag::ALL_RARES_ENABLED);
send_text_message_fmt(
a.c, "$C6All-rares {}", a.c->check_flag(Client::Flag::ALL_RARES_ENABLED) ? "enabled" : "disabled");
co_return;
});
ChatCommandDefinition cc_rand(
{"$rand"},
+[](const Args& a) -> asio::awaitable<void> {
@@ -2282,11 +2354,29 @@ ChatCommandDefinition cc_savechar(
co_return;
});
ChatCommandDefinition cc_savefiles(
{"$savefiles"},
+[](const Args& a) -> asio::awaitable<void> {
a.check_is_proxy(true);
auto s = a.c->require_server_state();
if (!s->proxy_allow_save_files) {
send_text_message(a.c, "$C6Save files is not\nallowed");
} else if (a.c->check_flag(Client::Flag::PROXY_SAVE_FILES)) {
a.c->clear_flag(Client::Flag::PROXY_SAVE_FILES);
send_text_message(a.c, "$C6Save files disabled");
} else {
auto s = a.c->require_server_state();
a.c->set_flag(Client::Flag::PROXY_SAVE_FILES);
send_text_message(a.c, "$C6Save files enabled");
}
co_return;
});
ChatCommandDefinition cc_saverec(
{"$saverec"},
+[](const Args& a) -> asio::awaitable<void> {
// TODO: We can probably support this on the proxy server, but it would
// only include CA commands from the local player
// TODO: We can support this on the proxy server, but it would only include CA commands from the local player
a.check_is_proxy(false);
if (!a.c->ep3_prev_battle_record) {
throw precondition_failed("$C4No finished\nrecording is\npresent");
@@ -2299,14 +2389,18 @@ ChatCommandDefinition cc_saverec(
co_return;
});
static asio::awaitable<void> command_send_command(const Args& a, bool to_client, bool to_server) {
static asio::awaitable<void> command_send_command(const Args& a, bool to_client, bool to_server, bool send_protected) {
if (!a.c->proxy_session) {
a.check_debug_enabled();
}
string data = phosg::parse_data_string(a.text);
data.resize((data.size() + 3) & (~3));
if (to_client) {
a.c->channel->send(data);
if (send_protected) {
co_await send_protected_command(a.c, data.data(), data.size(), false);
} else {
a.c->channel->send(data);
}
}
if (to_server) {
if (a.c->proxy_session) {
@@ -2321,13 +2415,19 @@ static asio::awaitable<void> command_send_command(const Args& a, bool to_client,
ChatCommandDefinition cc_sb(
{"$sb"},
+[](const Args& a) -> asio::awaitable<void> {
return command_send_command(a, true, true);
return command_send_command(a, true, true, false);
});
ChatCommandDefinition cc_sc(
{"$sc"},
+[](const Args& a) -> asio::awaitable<void> {
return command_send_command(a, true, false);
return command_send_command(a, true, false, false);
});
ChatCommandDefinition cc_scp(
{"$scp"},
+[](const Args& a) -> asio::awaitable<void> {
return command_send_command(a, true, false, true);
});
ChatCommandDefinition cc_secid(
@@ -2433,7 +2533,7 @@ ChatCommandDefinition cc_silence(
auto s = a.c->require_server_state();
auto target = s->find_client(&a.text);
if (!target->login) {
// this should be impossible, but I'll bet it's not actually
// This should be impossible, but I'll bet it's not actually
throw precondition_failed("$C6Client not logged in");
}
@@ -2493,9 +2593,8 @@ ChatCommandDefinition cc_spec(
throw logic_error("Episode 3 client in non-Episode 3 game");
}
// In non-tournament games, only the leader can do this; in a tournament
// match, the players don't have control over who the leader is, so we allow
// all players to use this command
// In non-tournament games, only the leader can do this; in a tournament match, the players don't have control
// over who the leader is, so we allow all players to use this command
if (!l->tournament_match) {
a.check_is_leader();
}
@@ -2522,7 +2621,7 @@ ChatCommandDefinition cc_spec(
ChatCommandDefinition cc_ss(
{"$ss"},
+[](const Args& a) -> asio::awaitable<void> {
return command_send_command(a, false, true);
return command_send_command(a, false, true, false);
});
ChatCommandDefinition cc_stat(
@@ -2643,8 +2742,8 @@ ChatCommandDefinition cc_swa(
a.check_is_game(true);
a.c->toggle_flag(Client::Flag::SWITCH_ASSIST_ENABLED);
send_text_message_fmt(a.c, "$C6Switch assist {}",
a.c->check_flag(Client::Flag::SWITCH_ASSIST_ENABLED) ? "enabled" : "disabled");
bool enabled = a.c->check_flag(Client::Flag::SWITCH_ASSIST_ENABLED);
send_text_message_fmt(a.c, "$C6Switch assist {}", enabled ? "enabled" : "disabled");
co_return;
});
@@ -2756,15 +2855,12 @@ ChatCommandDefinition cc_switchchar(
a.c->bb_character_index = index;
a.c->bb_bank_character_index = index;
// TODO: This can trigger a client bug where the previous character's
// name label object isn't deleted if the leave and join notifications
// are received on the same frame. This results in the receiving player
// seeing both labels over the new character, with the latest one
// appearing on top. We could fix this by requiring each recipient to
// reply to a ping between the two commands, similar to how the 64 and
// 6x6D commands are split during game joining, but implementing that
// here seems not worth the effort given the low likelihood and impact of
// this bug.
// TODO: This can trigger a client bug where the previous character's name label object isn't deleted if the
// leave and join notifications are received on the same frame. This results in the receiving player seeing both
// labels over the new character, with the latest one appearing on top. We could fix this by requiring each
// recipient to reply to a ping between the two commands, similar to how the 64 and 6x6D commands are split
// during game joining, but implementing that here seems not worth the effort given the low likelihood and impact
// of this bug.
send_complete_player_bb(a.c);
send_player_leave_notification(l, a.c->lobby_client_id);
s->send_lobby_join_notifications(l, a.c);
@@ -2803,9 +2899,7 @@ ChatCommandDefinition cc_unset(
ChatCommandDefinition cc_variations(
{"$variations"},
+[](const Args& a) -> asio::awaitable<void> {
// Note: This command is intentionally undocumented, since it's primarily used
// for testing. If we ever make it public, we should add some kind of user
// feedback (currently it sends no message when it runs).
// Note: This command is intentionally undocumented, since it's primarily used for testing
a.check_is_proxy(false);
a.check_is_game(false);
auto s = a.c->require_server_state();
@@ -2835,9 +2929,7 @@ static void command_warp(const Args& a, bool is_warpall) {
return;
}
Episode episode = a.c->proxy_session
? a.c->proxy_session->lobby_episode
: a.c->require_lobby()->episode;
Episode episode = a.c->proxy_session ? a.c->proxy_session->lobby_episode : a.c->require_lobby()->episode;
size_t limit = FloorDefinition::limit_for_episode(episode);
if (limit == 0) {
return;
@@ -2903,15 +2995,16 @@ ChatCommandDefinition cc_what(
throw precondition_failed("$C4No items are near you");
} else {
auto s = a.c->require_server_state();
string name = s->describe_item(a.c->version(), nearest_fi->data, ItemNameIndex::Flag::INCLUDE_PSO_COLOR_ESCAPES);
string name = s->describe_item(
a.c->version(), nearest_fi->data, ItemNameIndex::Flag::INCLUDE_PSO_COLOR_ESCAPES);
send_text_message(a.c, name);
}
co_return;
});
static void whatobj_whatene_fn(const Args& a, bool include_objs, bool include_enes) {
// TODO: This probably wouldn't be too hard to implement for proxy sessions.
// We already have the map and most of the lobby metadata (episode, etc.)
// TODO: This probably wouldn't be too hard to implement for proxy sessions. We already have the map and most of the
// lobby metadata (episode, etc.)
a.check_is_proxy(false);
a.check_is_game(true);
auto l = a.c->require_lobby();
@@ -2978,14 +3071,14 @@ static void whatobj_whatene_fn(const Args& a, bool include_objs, bool include_en
}
}
// Since we check all objects first, nearest_ene will only be set if
// there is an enemy closer than all objects. So, we print that if it's
// set, and print the object if not.
// Since we check all objects first, nearest_ene will only be set if there is an enemy closer than all objects. So,
// we print that if it's set, and print the object if not.
if (nearest_ene) {
const auto* set_entry = nearest_ene->super_ene->version(a.c->version()).set_entry;
string type_name = MapFile::name_for_enemy_type(set_entry->base_type, a.c->version(), area);
uint8_t area = l->area_for_floor(a.c->version(), a.c->floor);
send_text_message_fmt(a.c, "$C5E-{:03X}\n$C6{}\n$C2{}\n$C7X:{:.2f} Z:{:.2f}",
nearest_ene->e_id, phosg::name_for_enum(nearest_ene->type(a.c->version(), l->episode, l->difficulty, l->event)),
nearest_ene->e_id, phosg::name_for_enum(nearest_ene->type(a.c->version(), area, l->difficulty, l->event)),
type_name, nearest_worldspace_pos.x, nearest_worldspace_pos.z);
auto set_str = set_entry->str(a.c->version(), area);
a.c->log.info_f("Enemy found via $whatobj: E-{:03X} {} at x={:g} y={:g} z={:g}",
@@ -3096,10 +3189,9 @@ ChatCommandDefinition cc_nativecall(
+[](const Args& a) -> asio::awaitable<void> {
a.check_debug_enabled();
// TODO: $nativecall is not implemented on x86 (yet) because there are
// multiple calling conventions used within the executable (at least on
// Xbox and BB), so we would need a way to specify which calling
// convention to use, which would be annoying
// TODO: $nativecall is not implemented on x86 (yet) because there are multiple calling conventions used within
// the executable (at least on Xbox and BB), so we would need a way to specify which calling convention to use,
// which would be annoying
if (is_x86(a.c->version())) {
throw precondition_failed("Command not supported\non x86 clients");
}
@@ -3136,7 +3228,7 @@ ChatCommandDefinition cc_nativecall(
co_return;
});
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dispatch methods
struct SplitCommand {
@@ -3154,16 +3246,14 @@ struct SplitCommand {
}
};
// This function is called every time any player sends a chat beginning with a
// dollar sign. It is this function's responsibility to see if the chat is a
// command, and to execute the command and block the chat if it is.
// This function is called every time any player sends a chat message beginning with $. It is this function's
// responsibility to see if the chat is a command, and to execute the command and block the chat if it is.
asio::awaitable<void> on_chat_command(std::shared_ptr<Client> c, const std::string& text, bool check_permissions) {
SplitCommand cmd(text);
// This function is only called by on_06 if it looks like a chat command
// (starts with $, or @ on 11/2000), so we just normalize all commands to $
// here
if (!cmd.name.empty() && cmd.name[0] == '@') {
// This function is only called by on_06 if it looks like a chat command (starts with $, or @ on 11/2000, or
// s->chat_command_sentinel if overridden), so we just normalize all commands to $ here
if (!cmd.name.empty()) {
cmd.name[0] = '$';
}
+1 -4
View File
@@ -40,12 +40,9 @@ struct ChoiceSearchConfigT {
}
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(ChoiceSearchConfigT, 0x18);
using ChoiceSearchConfig = ChoiceSearchConfigT<false>;
using ChoiceSearchConfigBE = ChoiceSearchConfigT<true>;
check_struct_size(ChoiceSearchConfig, 0x18);
check_struct_size(ChoiceSearchConfigBE, 0x18);
struct ChoiceSearchCategory {
struct Choice {
+58 -42
View File
@@ -25,8 +25,7 @@ static atomic<uint64_t> next_id(1);
void Client::set_flags_for_version(Version version, int64_t sub_version) {
this->set_flag(Flag::PROXY_CHAT_COMMANDS_ENABLED);
// BB shares some sub_version values with GC Episode 3, so we handle it
// separately first.
// BB shares some sub_version values with GC Episode 3, so we handle it separately first.
if (version == Version::BB_V4) {
this->set_flag(Flag::NO_D6);
this->set_flag(Flag::SAVE_ENABLED);
@@ -72,8 +71,8 @@ void Client::set_flags_for_version(Version version, int64_t sub_version) {
break;
case Version::GC_V3:
case Version::GC_EP3:
// Some of these versions have send_function_call and some don't; we
// have to set these flags later when we get sub_version
// Some of these versions have send_function_call and some don't; we have to set these flags later when we
// get sub_version
break;
case Version::XB_V3:
// TODO: Do all versions of XB need this flag? US does, at least.
@@ -142,8 +141,8 @@ void Client::set_flags_for_version(Version version, int64_t sub_version) {
this->set_flag(Flag::SEND_FUNCTION_CALL_ACTUALLY_RUNS_CODE);
this->set_flag(Flag::ENCRYPTED_SEND_FUNCTION_CALL);
this->set_flag(Flag::SEND_FUNCTION_CALL_NO_CACHE_PATCH);
// sub_version can't be used to tell JP final and Trial Edition apart; we
// instead look at header.flag in the 61 command and set the version then.
// sub_version can't be used to tell JP final and Trial Edition apart; we instead look at header.flag in the 61
// command and set the version then.
break;
case 0x41: // GC Ep3 US (and BB, but BB is handled above)
case 0x42: // GC Ep3 EU 50Hz
@@ -191,9 +190,8 @@ Client::Client(
should_update_play_time(false) {
this->update_channel_name();
// Don't print data sent to patch clients to the logs. The patch server
// protocol is fully understood and data logs for patch clients are generally
// more annoying than helpful at this point.
// Don't print data sent to patch clients to the logs. The patch server protocol is fully understood and data logs
// for patch clients are generally more annoying than helpful at this point.
auto s = server->get_state();
if (is_patch(this->version()) && s->hide_download_commands) {
this->channel->terminal_recv_color = phosg::TerminalFormat::END;
@@ -212,9 +210,8 @@ Client::Client(
this->reschedule_save_game_data_timer();
this->reschedule_ping_and_timeout_timers();
// Don't print data sent to patch clients to the logs. The patch server
// protocol is fully understood and data logs for patch clients are generally
// more annoying than helpful at this point.
// Don't print data sent to patch clients to the logs. The patch server protocol is fully understood and data logs
// for patch clients are generally more annoying than helpful at this point.
if ((s->hide_download_commands) &&
((this->version() == Version::PC_PATCH) || (this->version() == Version::BB_PATCH))) {
this->channel->terminal_recv_color = phosg::TerminalFormat::END;
@@ -262,7 +259,7 @@ void Client::reschedule_save_game_data_timer() {
this->save_game_data_timer.expires_after(std::chrono::seconds(60));
this->save_game_data_timer.async_wait([this](std::error_code ec) {
if (!ec) {
if (this->character_file(false)) {
if (this->login && this->character_file(false)) {
this->save_all();
}
this->reschedule_save_game_data_timer();
@@ -298,9 +295,8 @@ void Client::reschedule_ping_and_timeout_timers() {
}
void Client::convert_account_to_temporary_if_nte() {
// If the session is a prototype version and the account was created and we
// should use a temporary account instead, delete the permanent account and
// replace it with a temporary account.
// If the session is a prototype version and the account was created and we should use a temporary account instead,
// delete the permanent account and replace it with a temporary account.
auto s = this->require_server_state();
if (s->use_temp_accounts_for_prototypes && this->login->account_was_created && is_any_nte(this->version())) {
this->log.info_f("Client is a prototype version and the account was created during this session; converting permanent account to temporary account");
@@ -353,8 +349,7 @@ shared_ptr<const TeamIndex::Team> Client::team() const {
return nullptr;
}
// The team membership is valid, but the player name may be different; update
// the team membership if needed
// The team membership is valid, but the player name may be different; update the team membership if needed
if (p) {
auto& m = member_it->second;
string name = p->disp.name.decode(this->language());
@@ -424,7 +419,7 @@ bool Client::can_play_quest(
if (!q->has_version_any_language(this->version())) {
return false;
}
if (num_players > q->meta.max_players) {
if ((q->meta.max_players > 0) && (num_players > q->meta.max_players)) {
return false;
}
return this->evaluate_quest_availability_expression(
@@ -601,8 +596,8 @@ void Client::save_character_file() {
throw logic_error("no character file loaded");
}
if (this->should_update_play_time) {
// This is slightly inaccurate, since fractions of a second are truncated
// off each time we save. I'm lazy, so insert shrug emoji here.
// This is slightly inaccurate, since fractions of a second are truncated off each time we save. I'm lazy, so
// insert shrug emoji here
uint64_t t = phosg::now();
uint64_t seconds = (t - this->last_play_time_update) / 1000000;
this->character_data->play_time_seconds += seconds;
@@ -624,8 +619,12 @@ void Client::create_character_file(
Language language,
const PlayerDispDataBBPreview& preview,
shared_ptr<const LevelTable> level_table) {
this->log.info_f("Creating new character file");
this->character_data = PSOBBCharacterFile::create_from_preview(guild_card_number, language, preview, level_table);
this->save_character_file();
this->log.info_f("Deleting bank file");
this->bank_data.reset();
std::filesystem::remove(this->bank_filename());
}
void Client::create_battle_overlay(shared_ptr<const BattleRules> rules, shared_ptr<const LevelTable> level_table) {
@@ -642,8 +641,7 @@ void Client::create_battle_overlay(shared_ptr<const BattleRules> rules, shared_p
this->overlay_character_data->inventory.remove_all_items_of_type(3);
}
if (rules->replace_char) {
// TODO: Shouldn't we clear other material usage here? It looks like the
// original code doesn't, but that seems wrong.
// TODO: Shouldn't we clear other material usage here? Looks like the original code doesn't, but that seems wrong.
this->overlay_character_data->inventory.hp_from_materials = 0;
this->overlay_character_data->inventory.tp_from_materials = 0;
@@ -678,7 +676,8 @@ void Client::create_battle_overlay(shared_ptr<const BattleRules> rules, shared_p
}
}
void Client::create_challenge_overlay(Version version, size_t template_index, shared_ptr<const LevelTable> level_table) {
void Client::create_challenge_overlay(
Version version, size_t template_index, shared_ptr<const LevelTable> level_table) {
auto p = this->character_file(true, false);
const auto& tpl = get_challenge_template_definition(version, p->disp.visual.class_flags, template_index);
@@ -700,9 +699,11 @@ void Client::create_challenge_overlay(Version version, size_t template_index, sh
level_table->reset_to_base(overlay->disp.stats, overlay->disp.visual.char_class);
level_table->advance_to_level(overlay->disp.stats, tpl.level, overlay->disp.visual.char_class);
const auto& stats_delta = level_table->stats_delta_for_level(
overlay->disp.visual.char_class, overlay->disp.stats.level);
overlay->disp.stats.esp = 40;
overlay->disp.stats.unknown_a3 = 10.0;
overlay->disp.stats.experience = level_table->stats_delta_for_level(overlay->disp.visual.char_class, overlay->disp.stats.level).experience;
overlay->disp.stats.attack_range = 10.0;
overlay->disp.stats.experience = stats_delta.experience;
overlay->disp.stats.meseta = 0;
overlay->clear_all_material_usage();
for (size_t z = 0; z < 0x13; z++) {
@@ -762,10 +763,9 @@ std::shared_ptr<PlayerBank> Client::bank_file(bool allow_load) {
this->bank_data->load(f.get());
this->log.info_f("Loaded bank data from {}", filename);
} catch (const phosg::cannot_open_file&) {
// If there isn't a psobank file, use the loaded character data if the
// bank character index matches the current character index (that is, we
// should use the current character's bank); otherwise, load the
// corresponding character and parse the bank from that character file
// If there isn't a psobank file, use the loaded character data if the bank character index matches the current
// character index (that is, we should use the current character's bank); otherwise, load the corresponding
// character and parse the bank from that character file
if (this->bb_bank_character_index == this->bb_character_index) {
this->bank_data = std::make_shared<PlayerBank>(this->character_file(true, false)->bank);
this->log.info_f("Using bank data from loaded character");
@@ -787,6 +787,7 @@ std::shared_ptr<PlayerBank> Client::bank_file(bool allow_load) {
auto s = this->require_server_state();
this->bank_data->max_items = s->bb_max_bank_items;
this->bank_data->max_meseta = s->bb_max_bank_meseta;
this->update_bank_data_after_load(this->bank_data);
}
return this->bank_data;
}
@@ -891,8 +892,7 @@ void Client::load_all_files() {
this->character_data = psochar.character_file;
this->log.info_f("Loaded character data from {}", char_filename);
// If there was no .psosys file, use the system file from the .psochar
// file instead
// If there was no .psosys file, use the system file from the .psochar file instead
if (!this->system_data) {
if (!psochar.system_file) {
throw logic_error("account system data not present, and also not loaded from psochar file");
@@ -913,14 +913,14 @@ void Client::load_all_files() {
string card_filename = this->guild_card_filename();
if (std::filesystem::is_regular_file(card_filename)) {
this->guild_card_data = make_shared<PSOBBGuildCardFile>(phosg::load_object_file<PSOBBGuildCardFile>(card_filename));
this->guild_card_data->delete_duplicates();
this->log.info_f("Loaded Guild Card data from {}", card_filename);
} else {
this->log.info_f("Guild Card file is missing: {}", card_filename);
}
}
// If any of the above files are still missing, try to load from .nsa/.nsc
// files instead
// If any of the above files are still missing, try to load from .nsa/.nsc files instead
if (!this->system_data || (!this->character_data && (this->bb_character_index >= 0)) || !this->guild_card_data) {
string nsa_filename = this->legacy_account_filename();
shared_ptr<LegacySavedAccountDataBB> nsa_data;
@@ -986,9 +986,8 @@ void Client::load_all_files() {
}
}
// The system and Guild Card files can be auto-created if they can't be
// loaded. After this, system_data and guild_card_data are always non-null,
// but character_data may still be null
// The system and Guild Card files can be auto-created if they can't be loaded. After this, system_data and
// guild_card_data are always non-null, but character_data may still be null
if (!this->system_data) {
this->system_data = make_shared<PSOBBBaseSystemFile>();
auto s = this->require_server_state();
@@ -1009,9 +1008,9 @@ void Client::load_all_files() {
auto stack_limits = s->item_stack_limits(this->version());
this->blocked_senders.clear();
for (size_t z = 0; z < this->guild_card_data->blocked.size(); z++) {
if (this->guild_card_data->blocked[z].present) {
this->blocked_senders.emplace(this->guild_card_data->blocked[z].guild_card_number);
for (size_t z = 0; z < this->guild_card_data->blocked_senders.size(); z++) {
if (this->guild_card_data->blocked_senders[z].present) {
this->blocked_senders.emplace(this->guild_card_data->blocked_senders[z].guild_card_number);
}
}
@@ -1023,8 +1022,8 @@ void Client::load_all_files() {
this->login->account->save();
this->last_play_time_update = phosg::now();
if (this->bb_character_index >= 0) {
// Note that bank_file() can't recur infinitely here because
// character_file is already set; it will not call load_all_files() again
// Note that bank_file() can't recur infinitely here because character_file is already set; it will not call
// load_all_files() again
this->bank_file()->enforce_stack_limits(stack_limits);
}
}
@@ -1039,6 +1038,23 @@ void Client::update_character_data_after_load(shared_ptr<PSOBBCharacterFile> cha
charfile->guild_card.language = lang;
}
void Client::update_bank_data_after_load(shared_ptr<PlayerBank> bank) {
auto s = this->require_server_state();
auto limits = s->item_stack_limits(this->version());
for (auto& item : bank->items) {
if (item.data.is_stackable(*limits)) {
if (item.data.data1[5] != item.amount) {
this->log.info_f("Updating item data stack count from bank stack count ({} -> {}) for {}",
item.data.data1[5], item.amount, item.data.hex());
item.data.data1[5] = item.amount;
}
} else if (item.amount != 1) {
this->log.info_f("Clearing bank stack count ({}) for {}", item.amount, item.data.hex());
item.amount = 1;
}
}
}
void Client::save_all() {
if (this->system_data) {
this->save_system_file();
+60 -62
View File
@@ -39,57 +39,60 @@ public:
// clang-format off
// Version-related flags
CHECKED_FOR_DC_V1_PROTOTYPE = 0x0000000000000002,
NO_D6_AFTER_LOBBY = 0x0000000000000100,
NO_D6 = 0x0000000000000200,
FORCE_ENGLISH_LANGUAGE_BB = 0x0000000000000400,
CHECKED_FOR_DC_V1_PROTOTYPE = 0x0000000000000001,
NO_D6_AFTER_LOBBY = 0x0000000000000002,
NO_D6 = 0x0000000000000004,
FORCE_ENGLISH_LANGUAGE_BB = 0x0000000000000008,
// Flags describing the behavior for send_function_call
HAS_SEND_FUNCTION_CALL = 0x0000000000001000,
ENCRYPTED_SEND_FUNCTION_CALL = 0x0000000000002000,
SEND_FUNCTION_CALL_ACTUALLY_RUNS_CODE = 0x0000000000004000,
SEND_FUNCTION_CALL_NO_CACHE_PATCH = 0x0000000000008000,
CAN_RECEIVE_ENABLE_B2_QUEST = 0x0000000000020000,
AWAITING_ENABLE_B2_QUEST = 0x0000000000040000,
HAS_SEND_FUNCTION_CALL = 0x0000000000000010,
ENCRYPTED_SEND_FUNCTION_CALL = 0x0000000000000020,
SEND_FUNCTION_CALL_ACTUALLY_RUNS_CODE = 0x0000000000000040,
SEND_FUNCTION_CALL_NO_CACHE_PATCH = 0x0000000000000080,
CAN_RECEIVE_ENABLE_B2_QUEST = 0x0000000000000100,
AWAITING_ENABLE_B2_QUEST = 0x0000000000000200,
// State flags
LOADING = 0x0000000000100000,
LOADING_QUEST = 0x0000000000200000,
LOADING_RUNNING_JOINABLE_QUEST = 0x0000000000400000,
LOADING_TOURNAMENT = 0x0000000000800000,
IN_INFORMATION_MENU = 0x0000000001000000,
AT_WELCOME_MESSAGE = 0x0000000002000000,
SAVE_ENABLED = 0x0000000004000000,
HAS_EP3_CARD_DEFS = 0x0000000008000000,
HAS_EP3_MEDIA_UPDATES = 0x0000000010000000,
HAS_AUTO_PATCHES = 0x0000004000000000,
AT_BANK_COUNTER = 0x0000000080000000,
SHOULD_SEND_ARTIFICIAL_ITEM_STATE = 0x0001000000000000,
SHOULD_SEND_ARTIFICIAL_ENEMY_AND_SET_STATE = 0x0040000000000000,
SHOULD_SEND_ARTIFICIAL_OBJECT_STATE = 0x0080000000000000,
SHOULD_SEND_ARTIFICIAL_FLAG_STATE = 0x0002000000000000,
SHOULD_SEND_ARTIFICIAL_PLAYER_STATES = 0x0200000000000000,
SHOULD_SEND_ENABLE_SAVE = 0x0004000000000000,
SWITCH_ASSIST_ENABLED = 0x0000000100000000,
IS_CLIENT_CUSTOMIZATION = 0x0100000000000000,
EP3_ALLOW_6xBC = 0x1000000000000000,
LOADING = 0x0000000000000400,
LOADING_QUEST = 0x0000000000000800,
LOADING_RUNNING_JOINABLE_QUEST = 0x0000000000001000,
LOADING_TOURNAMENT = 0x0000000000002000,
IN_INFORMATION_MENU = 0x0000000000004000,
AT_WELCOME_MESSAGE = 0x0000000000008000,
SAVE_ENABLED = 0x0000000000010000,
HAS_EP3_CARD_DEFS = 0x0000000000020000,
HAS_EP3_MEDIA_UPDATES = 0x0000000000040000,
HAS_AUTO_PATCHES = 0x0000000000080000,
AT_BANK_COUNTER = 0x0000000000100000,
SHOULD_SEND_ARTIFICIAL_ITEM_STATE = 0x0000000000200000,
SHOULD_SEND_ARTIFICIAL_ENEMY_AND_SET_STATE = 0x0000000000400000,
SHOULD_SEND_ARTIFICIAL_OBJECT_STATE = 0x0000000000800000,
SHOULD_SEND_ARTIFICIAL_FLAG_STATE = 0x0000000001000000,
SHOULD_SEND_ARTIFICIAL_PLAYER_STATES = 0x0000000002000000,
SHOULD_SEND_ENABLE_SAVE = 0x0000000004000000,
SWITCH_ASSIST_ENABLED = 0x0000000008000000,
IS_CLIENT_CUSTOMIZATION = 0x0000000010000000,
EP3_ALLOW_6xBC = 0x0000000020000000,
// Cheat mode and option flags
INFINITE_HP_ENABLED = 0x0000000200000000,
INFINITE_TP_ENABLED = 0x0000000400000000,
DEBUG_ENABLED = 0x0000000800000000,
ITEM_DROP_NOTIFICATIONS_1 = 0x0010000000000000,
ITEM_DROP_NOTIFICATIONS_2 = 0x0020000000000000,
HAS_ENEMY_DAMAGE_SYNC_PATCH = 0x2000000000000000, // Must be same as in EnemyDamageSync*.s
INFINITE_HP_ENABLED = 0x0000000040000000,
INFINITE_TP_ENABLED = 0x0000000080000000,
FAST_KILLS_ENABLED = 0x0000000100000000,
ALL_RARES_ENABLED = 0x0000100000000000,
DEBUG_ENABLED = 0x0000000200000000,
ITEM_DROP_NOTIFICATIONS_1 = 0x0000000400000000,
ITEM_DROP_NOTIFICATIONS_2 = 0x0000000800000000,
HAS_ENEMY_DAMAGE_SYNC_PATCH = 0x0000001000000000, // Must be same as in EnemyDamageSync*.s
HAS_PSO_PEEPS_XP_PATCH = 0x0000200000000000, // Must be same as in PSO Peeps XP patches
// Proxy option flags
PROXY_SAVE_FILES = 0x0000001000000000,
PROXY_CHAT_COMMANDS_ENABLED = 0x0000002000000000,
PROXY_SAVE_FILES = 0x0000002000000000,
PROXY_CHAT_COMMANDS_ENABLED = 0x0000004000000000,
PROXY_PLAYER_NOTIFICATIONS_ENABLED = 0x0000008000000000,
PROXY_EP3_INFINITE_MESETA_ENABLED = 0x0000080000000000,
PROXY_EP3_INFINITE_TIME_ENABLED = 0x0000100000000000,
PROXY_BLOCK_FUNCTION_CALLS = 0x0000800000000000,
PROXY_EP3_UNMASK_WHISPERS = 0x0008000000000000,
PROXY_EP3_INFINITE_MESETA_ENABLED = 0x0000010000000000,
PROXY_EP3_INFINITE_TIME_ENABLED = 0x0000020000000000,
PROXY_BLOCK_FUNCTION_CALLS = 0x0000040000000000,
PROXY_EP3_UNMASK_WHISPERS = 0x0000080000000000,
// clang-format on
};
enum class ItemDropNotificationMode {
@@ -138,6 +141,7 @@ public:
std::shared_ptr<Channel> channel;
std::shared_ptr<PSOBBMultiKeyDetectorEncryption> bb_detector_crypt;
ServerBehavior server_behavior;
uint16_t listener_port = 0;
std::unordered_map<std::string, std::function<void()>> disconnect_hooks;
uint64_t ping_start_time = 0;
@@ -148,13 +152,14 @@ public:
uint8_t override_lobby_event = 0xFF; // FF = no override
uint8_t override_lobby_number = 0x80; // 80 = no override
int64_t override_random_seed = -1;
int8_t selected_blueballz_tier = -1; // -1 = normal lobby/game; 0..10 = requested Blueballz tier
std::unique_ptr<Variations> override_variations;
VectorXYZF pos;
uint32_t floor = 0x0F;
std::weak_ptr<Lobby> lobby;
uint8_t lobby_client_id = 0;
uint8_t lobby_arrow_color = 0;
int64_t preferred_lobby_id = -1; // <0 = no preference
int64_t preferred_lobby_id = -1; // <0 = none chosen
asio::steady_timer save_game_data_timer;
asio::steady_timer send_ping_timer;
@@ -188,8 +193,7 @@ public:
std::unordered_set<uint32_t> blocked_senders;
std::unique_ptr<PlayerDispDataDCPCV3> v1_v2_last_reported_disp;
std::shared_ptr<Parsed6x70Data> last_reported_6x70;
// These are null unless the client is within the trade sequence (D0-D4 or EE
// commands)
// These are null unless the client is within the trade sequence (D0-D4 or EE commands)
std::unique_ptr<PendingItemTrade> pending_item_trade;
std::unique_ptr<PendingCardTrade> pending_card_trade;
uint32_t telepipe_lobby_id = 0;
@@ -198,15 +202,14 @@ public:
ItemData bb_identify_result;
std::array<std::vector<ItemData>, 3> bb_shop_contents;
// Miscellaneous (used by chat commands)
uint32_t next_exp_value = 0; // next EXP value to give
// Miscellaneous (used by chat commands / quest opcodes)
uint8_t schtserv_response_register = 0;
uint32_t next_exp_value = 0;
bool can_chat = true;
// NOTE: If you add any new optional promises here, make sure to also add
// them to cancel_pending_promises.
// NOTE: Entries in this queue can be nullptr; that represents a B2 command
// sent by the remote server during a proxy session. We can't just omit those
// from the queue entirely, because if we did, we could end up sending the
// wrong B3 response back.
// NOTE: If you add any new optional promises here, make sure to also add them to cancel_pending_promises.
// NOTE: Entries in this queue can be nullptr; that represents a B2 command sent by the remote server during a proxy
// session. We can't just omit those from the queue entirely, because if we did, we could end up sending the wrong B3
// response back.
std::deque<std::shared_ptr<AsyncPromise<C_ExecuteCodeResult_B3>>> function_call_response_queue;
std::shared_ptr<AsyncPromise<GetPlayerInfoResult>> character_data_ready_promise;
std::shared_ptr<AsyncPromise<void>> enable_save_promise;
@@ -214,10 +217,7 @@ public:
// File loading state
std::unordered_map<std::string, std::shared_ptr<const std::string>> sending_files;
Client(
std::shared_ptr<GameServer> server,
std::shared_ptr<Channel> channel,
ServerBehavior server_behavior);
Client(std::shared_ptr<GameServer> server, std::shared_ptr<Channel> channel, ServerBehavior server_behavior);
~Client();
void update_channel_name();
@@ -256,8 +256,6 @@ public:
void convert_account_to_temporary_if_nte();
void sync_config();
std::shared_ptr<ServerState> require_server_state() const;
std::shared_ptr<Lobby> require_lobby() const;
@@ -351,9 +349,8 @@ public:
void cancel_pending_promises();
private:
// The overlay character data is used in battle and challenge modes, when
// character data is temporarily replaced in-game. In other play modes and in
// lobbies, overlay_character_data is null.
// The overlay character data is used in battle and challenge modes, when character data is temporarily replaced
// in-game. In other play modes and in lobbies, overlay_character_data is null.
std::shared_ptr<PSOBBBaseSystemFile> system_data;
std::shared_ptr<PSOBBCharacterFile> overlay_character_data;
std::shared_ptr<PSOBBCharacterFile> character_data;
@@ -363,4 +360,5 @@ private:
void load_all_files();
void update_character_data_after_load(std::shared_ptr<PSOBBCharacterFile> character_data);
void update_bank_data_after_load(std::shared_ptr<PlayerBank> bank_data);
};
+1647 -2164
View File
File diff suppressed because it is too large Load Diff
+24 -32
View File
@@ -37,6 +37,14 @@ struct VectorXZF {
inline double norm2() const {
return ((this->x * this->x) + (this->z * this->z));
}
inline double dist(const VectorXZF& other) const {
return sqrt(this->dist2(other));
}
inline double dist2(const VectorXZF& other) const {
double x = this->x - other.x;
double z = this->z - other.z;
return ((x * x) + (z * z));
}
inline VectorXZF rotate_y(double angle) const {
double s = sin(angle);
@@ -86,26 +94,17 @@ struct VectorXYZF {
inline VectorXYZF rotate_x(double angle) const {
double s = sin(angle);
double c = cos(angle);
return VectorXYZF{
this->x,
this->y * c - this->z * s,
this->y * s + this->z * c};
return VectorXYZF{this->x, this->y * c - this->z * s, this->y * s + this->z * c};
}
inline VectorXYZF rotate_y(double angle) const {
double s = sin(angle);
double c = cos(angle);
return VectorXYZF{
this->x * c + this->z * s,
this->y,
-this->x * s + this->z * c};
return VectorXYZF{this->x * c + this->z * s, this->y, -this->x * s + this->z * c};
}
inline VectorXYZF rotate_z(double angle) const {
double s = sin(angle);
double c = cos(angle);
return VectorXYZF{
this->x * c - this->y * s,
this->x * s + this->y * c,
this->z};
return VectorXYZF{this->x * c - this->y * s, this->x * s + this->y * c, this->z};
}
inline std::string str() const {
@@ -132,39 +131,32 @@ struct ArrayRefT {
/* 00 */ U32T<BE> count;
/* 04 */ U32T<BE> offset;
/* 08 */
} __attribute__((packed));
} __packed_ws_be__(ArrayRefT, 8);
using ArrayRef = ArrayRefT<false>;
using ArrayRefBE = ArrayRefT<true>;
check_struct_size(ArrayRef, 8);
check_struct_size(ArrayRefBE, 8);
template <bool BE>
struct RELFileFooterT {
static constexpr bool IsBE = BE;
// Relocations is a list of words (le_uint16_t on DC/PC/XB/BB, be_uint16_t on
// GC) containing the number of doublewords (uint32_t) to skip for each
// relocation. The relocation pointer starts at the beginning of the file
// data, and advances by the value of one relocation word (times 4) before
// each relocation. At each relocated doubleword, the address of the first
// byte of the file is added to the existing value.
// For example, if the file data contains the following data (where R
// specifies doublewords to relocate):
// Relocations is a list of words (le_uint16_t on DC/PC/XB/BB, be_uint16_t on GC) containing the number of
// doublewords (uint32_t) to skip for each relocation. The relocation pointer starts at the beginning of the file
// data, and advances by the value of one relocation word (times 4) before each relocation. At each relocated
// doubleword, the address of the first byte of the file is added to the existing value.
//
// For example, if the file data contains the following data (where R specifies doublewords to relocate):
// RR RR RR RR ?? ?? ?? ?? ?? ?? ?? ?? RR RR RR RR
// RR RR RR RR ?? ?? ?? ?? RR RR RR RR
// then the relocation words should be 0000, 0003, 0001, and 0002.
// If there is a small number of relocations, they may be placed in the unused
// fields of this structure to save space and/or confuse reverse engineers.
// The game never accesses the last 12 bytes of this structure unless
// relocations_offset points there, so those 12 bytes may also be omitted
// entirely in situations (e.g. in the B2 command, without changing code_size,
// so code_size would technically extend beyond the end of the B2 command).
//
// If there is a small number of relocations, they may be placed in the unused fields of this structure to save space
// and/or confuse reverse engineers. The game never accesses the last 12 bytes of this structure unless
// relocations_offset points there, so those 12 bytes may also be omitted entirely in some situations (e.g. in the B2
// command, without changing code_size, so code_size would technically extend beyond the end of the B2 command).
U32T<BE> relocations_offset = 0;
U32T<BE> num_relocations = 0;
parray<U32T<BE>, 2> unused1;
U32T<BE> root_offset = 0;
parray<U32T<BE>, 3> unused2;
} __attribute__((packed));
} __packed_ws_be__(RELFileFooterT, 0x20);
using RELFileFooter = RELFileFooterT<false>;
using RELFileFooterBE = RELFileFooterT<true>;
check_struct_size(RELFileFooter, 0x20);
check_struct_size(RELFileFooterBE, 0x20);
+349 -212
View File
@@ -96,63 +96,95 @@ void from_json_into(const phosg::JSON& json, parray<parray<CommonItemSet::Table:
}
}
CommonItemSet::Table::Table(const phosg::JSON& json, Episode episode)
CommonItemSet::Table::Table(std::shared_ptr<const Table> prev_table, const phosg::JSON& json, Episode episode)
: episode(episode) {
from_json_into(json.at("BaseWeaponTypeProbTable"), this->base_weapon_type_prob_table);
from_json_into(json.at("SubtypeBaseTable"), this->subtype_base_table);
from_json_into(json.at("SubtypeAreaLengthTable"), this->subtype_area_length_table);
from_json_into(json.at("GrindProbTable"), this->grind_prob_table);
from_json_into(json.at("ArmorShieldTypeIndexProbTable"), this->armor_shield_type_index_prob_table);
from_json_into(json.at("ArmorSlotCountProbTable"), this->armor_slot_count_prob_table);
from_json_into(json.at("BoxMesetaRanges"), this->box_meseta_ranges);
this->has_rare_bonus_value_prob_table = json.at("HasRareBonusValueProbTable").as_bool();
from_json_into(json.at("BonusValueProbTable"), this->bonus_value_prob_table);
from_json_into(json.at("NonRareBonusProbSpec"), this->nonrare_bonus_prob_spec);
from_json_into(json.at("BonusTypeProbTable"), this->bonus_type_prob_table);
from_json_into(json.at("SpecialMult"), this->special_mult);
from_json_into(json.at("SpecialPercent"), this->special_percent);
from_json_into(json.at("ToolClassProbTable"), this->tool_class_prob_table);
from_json_into(json.at("TechniqueIndexProbTable"), this->technique_index_prob_table);
from_json_into(json.at("TechniqueLevelRanges"), this->technique_level_ranges);
this->armor_or_shield_type_bias = json.at("ArmorOrShieldTypeBias").as_int();
from_json_into(json.at("UnitMaxStarsTable"), this->unit_max_stars_table);
from_json_into(json.at("BoxItemClassProbTable"), this->box_item_class_prob_table);
auto parse_field = [&]<typename T>(const std::string& key, T& field, const T* prev_field) {
if (json.count(key)) {
from_json_into(json.at(key), field);
} else if (prev_field) {
field = *prev_field;
}
};
const auto& enemy_meseta_ranges_json = json.at("EnemyMesetaRanges").as_dict();
const auto& enemy_type_drop_probs_json = json.at("EnemyTypeDropProbs").as_dict();
const auto& enemy_item_classes_json = json.at("EnemyItemClasses").as_dict();
for (size_t z = 0; z < 0x64; z++) {
auto types = enemy_types_for_rare_table_index(episode, z);
vector<string> names;
if (types.empty()) {
names.emplace_back(std::format("{}:!{:02X}", abbreviation_for_episode(episode), z));
} else {
for (auto type : types) {
names.emplace_back(std::format("{}:{}", abbreviation_for_episode(episode), phosg::name_for_enum(type)));
parse_field("BaseWeaponTypeProbTable", this->base_weapon_type_prob_table, prev_table ? &prev_table->base_weapon_type_prob_table : nullptr);
parse_field("SubtypeBaseTable", this->subtype_base_table, prev_table ? &prev_table->subtype_base_table : nullptr);
parse_field("SubtypeAreaLengthTable", this->subtype_area_length_table, prev_table ? &prev_table->subtype_area_length_table : nullptr);
parse_field("GrindProbTable", this->grind_prob_table, prev_table ? &prev_table->grind_prob_table : nullptr);
parse_field("ArmorShieldTypeIndexProbTable", this->armor_shield_type_index_prob_table, prev_table ? &prev_table->armor_shield_type_index_prob_table : nullptr);
parse_field("ArmorSlotCountProbTable", this->armor_slot_count_prob_table, prev_table ? &prev_table->armor_slot_count_prob_table : nullptr);
parse_field("BoxMesetaRanges", this->box_meseta_ranges, prev_table ? &prev_table->box_meseta_ranges : nullptr);
if (json.count("HasRareBonusValueProbTable")) {
this->has_rare_bonus_value_prob_table = json.at("HasRareBonusValueProbTable").as_bool();
} else if (prev_table) {
this->has_rare_bonus_value_prob_table = prev_table->has_rare_bonus_value_prob_table;
}
parse_field("BonusValueProbTable", this->bonus_value_prob_table, prev_table ? &prev_table->bonus_value_prob_table : nullptr);
parse_field("NonRareBonusProbSpec", this->nonrare_bonus_prob_spec, prev_table ? &prev_table->nonrare_bonus_prob_spec : nullptr);
parse_field("BonusTypeProbTable", this->bonus_type_prob_table, prev_table ? &prev_table->bonus_type_prob_table : nullptr);
parse_field("SpecialMult", this->special_mult, prev_table ? &prev_table->special_mult : nullptr);
parse_field("SpecialPercent", this->special_percent, prev_table ? &prev_table->special_percent : nullptr);
parse_field("ToolClassProbTable", this->tool_class_prob_table, prev_table ? &prev_table->tool_class_prob_table : nullptr);
parse_field("TechniqueIndexProbTable", this->technique_index_prob_table, prev_table ? &prev_table->technique_index_prob_table : nullptr);
parse_field("TechniqueLevelRanges", this->technique_level_ranges, prev_table ? &prev_table->technique_level_ranges : nullptr);
if (json.count("ArmorOrShieldTypeBias")) {
this->armor_or_shield_type_bias = json.at("ArmorOrShieldTypeBias").as_int();
} else if (prev_table) {
this->armor_or_shield_type_bias = prev_table->armor_or_shield_type_bias;
}
parse_field("UnitMaxStarsTable", this->unit_max_stars_table, prev_table ? &prev_table->unit_max_stars_table : nullptr);
parse_field("BoxItemClassProbTable", this->box_item_class_prob_table, prev_table ? &prev_table->box_item_class_prob_table : nullptr);
if (json.count("EnemyMesetaRanges")) {
const auto& dict = json.at("EnemyMesetaRanges").as_dict();
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
try {
from_json_into(*dict.at(phosg::name_for_enum(enemy_type)), this->enemy_type_meseta_ranges[enemy_type]);
} catch (const out_of_range&) {
}
}
for (const auto& name : names) {
from_json_into(*enemy_meseta_ranges_json.at(name), this->enemy_meseta_ranges[z]);
this->enemy_type_drop_probs[z] = enemy_type_drop_probs_json.at(name)->as_int();
this->enemy_item_classes[z] = enemy_item_classes_json.at(name)->as_int();
} else {
this->enemy_type_meseta_ranges = prev_table->enemy_type_meseta_ranges;
}
if (json.count("EnemyTypeDropProbs")) {
const auto& dict = json.at("EnemyTypeDropProbs").as_dict();
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
try {
this->enemy_type_drop_probs[enemy_type] = dict.at(phosg::name_for_enum(enemy_type))->as_int();
} catch (const out_of_range&) {
}
}
} else {
this->enemy_type_drop_probs = prev_table->enemy_type_drop_probs;
}
if (json.count("EnemyItemClasses")) {
const auto& dict = json.at("EnemyItemClasses").as_dict();
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
try {
this->enemy_type_item_classes[enemy_type] = dict.at(phosg::name_for_enum(enemy_type))->as_int();
} catch (const out_of_range&) {
}
}
} else {
this->enemy_type_item_classes = prev_table->enemy_type_item_classes;
}
}
static const char* name_for_common_item_class(uint8_t item_class) {
switch (item_class) {
case 0x00:
return "WEAPON ";
return "WEAPON";
case 0x01:
return "ARMOR ";
return "ARMOR";
case 0x02:
return "SHIELD ";
return "SHIELD";
case 0x03:
return "UNIT ";
return "UNIT";
case 0x04:
return "TOOL ";
return "TOOL";
case 0x05:
return "MESETA ";
return "MESETA";
case 0x06:
return "NOTHING";
default:
@@ -161,42 +193,29 @@ static const char* name_for_common_item_class(uint8_t item_class) {
}
void CommonItemSet::Table::print(FILE* stream) const {
const auto& meseta_ranges = this->enemy_meseta_ranges;
const auto& meseta_ranges = this->enemy_type_meseta_ranges;
const auto& drop_probs = this->enemy_type_drop_probs;
const auto& item_classes = this->enemy_item_classes;
const auto& item_classes = this->enemy_type_item_classes;
phosg::fwrite_fmt(stream, "Enemy tables:\n");
phosg::fwrite_fmt(stream, " ## $LOW $HIGH DAR% ITEM ENEMIES\n");
for (size_t z = 0; z < 0x64; z++) {
string enemies_str;
for (EnemyType enemy_type : enemy_types_for_rare_table_index(this->episode, z)) {
if (!enemies_str.empty()) {
enemies_str += ", ";
}
enemies_str += phosg::name_for_enum(enemy_type);
}
if (drop_probs[z]) {
phosg::fwrite_fmt(stream, " {:02X} {:5} {:5} {:3}% {:02X}:{} {}\n",
z, meseta_ranges[z].min, meseta_ranges[z].max, drop_probs[z], item_classes[z],
name_for_common_item_class(item_classes[z]), enemies_str);
} else {
phosg::fwrite_fmt(stream, " {:02X} ----- ----- 0% -- {}\n", z, enemies_str);
phosg::fwrite_fmt(stream, " ##:ENEMY $LOW $HIGH DAR% ITEM\n");
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
const auto& def = type_definition_for_enemy(enemy_type);
try {
const auto& meseta_range = meseta_ranges.at(enemy_type);
const auto& drop_prob = drop_probs.at(enemy_type);
const auto& item_class = item_classes.at(enemy_type);
phosg::fwrite_fmt(stream, " {:02X}:{:<23} {:5} {:5} {:3}% {:02X}:{:<7}\n",
def.rt_index, phosg::name_for_enum(enemy_type),
meseta_range.min, meseta_range.max, drop_prob, item_class,
name_for_common_item_class(item_class));
} catch (const out_of_range&) {
phosg::fwrite_fmt(stream, " {:02X}:{:<23} ----- ----- ---- --:-------\n",
def.rt_index, phosg::name_for_enum(enemy_type));
}
}
static const array<const char*, 12> base_weapon_type_names = {
"SABER ",
"SWORD ",
"DAGGER ",
"PARTISAN",
"SLICER ",
"HANDGUN ",
"RIFLE ",
"MECHGUN ",
"SHOT ",
"CANE ",
"ROD ",
"WAND ",
};
"SABER", "SWORD", "DAGGER", "PARTISAN", "SLICER", "HANDGUN", "RIFLE", "MECHGUN", "SHOT", "CANE", "ROD", "WAND"};
phosg::fwrite_fmt(stream, "Base weapon config:\n");
phosg::fwrite_fmt(stream, " TYPE PROB [SB AL] FLOORS\n");
for (size_t z = 0; z < 12; z++) {
@@ -214,7 +233,7 @@ void CommonItemSet::Table::print(FILE* stream) const {
floor_to_class[x] = this->subtype_base_table[z] + (x / this->subtype_area_length_table[z]);
}
}
phosg::fwrite_fmt(stream, " {:02X}:{} {:3}% [{:02X} {:02X}] {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}\n",
phosg::fwrite_fmt(stream, " {:02X}:{:<8} {:3}% [{:02X} {:02X}] {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}\n",
z, base_weapon_type_names[z], this->base_weapon_type_prob_table[z],
this->subtype_base_table[z], this->subtype_area_length_table[z],
floor_to_class[0], floor_to_class[1], floor_to_class[2], floor_to_class[3], floor_to_class[4],
@@ -266,10 +285,10 @@ void CommonItemSet::Table::print(FILE* stream) const {
this->special_mult[z], this->special_percent[z]);
}
phosg::fwrite_fmt(stream, " Tool class table:\n");
phosg::fwrite_fmt(stream, " CS A1 A2 A3 A4 A5 A6 A7 A8 A9 A10\n");
phosg::fwrite_fmt(stream, "Tool class table:\n");
phosg::fwrite_fmt(stream, " CS A1 A2 A3 A4 A5 A6 A7 A8 A9 A10\n");
for (size_t tool_class = 0; tool_class < this->tool_class_prob_table.size(); tool_class++) {
phosg::fwrite_fmt(stream, " {:02X}", tool_class);
phosg::fwrite_fmt(stream, " {:02X}", tool_class);
for (size_t area_norm = 0; area_norm < 10; area_norm++) {
phosg::fwrite_fmt(stream, " {:5}", this->tool_class_prob_table[tool_class][area_norm]);
}
@@ -298,10 +317,10 @@ void CommonItemSet::Table::print(FILE* stream) const {
"MEGID ",
};
phosg::fwrite_fmt(stream, " Technique table:\n");
phosg::fwrite_fmt(stream, " TECH A1 A2 A3 A4 A5 A6 A7 A8 A9 A10\n");
phosg::fwrite_fmt(stream, "Technique table:\n");
phosg::fwrite_fmt(stream, " TECH A1 A2 A3 A4 A5 A6 A7 A8 A9 A10\n");
for (size_t tech_num = 0; tech_num < this->technique_index_prob_table.size(); tech_num++) {
phosg::fwrite_fmt(stream, " {:02X}:{}", tech_num, technique_names[tech_num]);
phosg::fwrite_fmt(stream, " {:02X}:{}", tech_num, technique_names[tech_num]);
for (size_t area_norm = 0; area_norm < 10; area_norm++) {
uint16_t prob = this->technique_index_prob_table[tech_num][area_norm];
if (prob) {
@@ -316,24 +335,24 @@ void CommonItemSet::Table::print(FILE* stream) const {
fputc('\n', stream);
}
phosg::fwrite_fmt(stream, " Armor/shield type bias: {}\n", this->armor_or_shield_type_bias);
phosg::fwrite_fmt(stream, "Armor/shield type bias: {}\n", this->armor_or_shield_type_bias);
phosg::fwrite_fmt(stream, " Armor/shield type index table:\n");
phosg::fwrite_fmt(stream, " TY PROB\n");
phosg::fwrite_fmt(stream, "Armor/shield type index table:\n");
phosg::fwrite_fmt(stream, " TY PROB\n");
for (size_t z = 0; z < 5; z++) {
phosg::fwrite_fmt(stream, " {:02X} {:3}%\n", z, this->armor_shield_type_index_prob_table[z]);
phosg::fwrite_fmt(stream, " {:02X} {:3}%\n", z, this->armor_shield_type_index_prob_table[z]);
}
phosg::fwrite_fmt(stream, " Armor/shield slot count table:\n");
phosg::fwrite_fmt(stream, " #S PROB\n");
phosg::fwrite_fmt(stream, "Armor/shield slot count table:\n");
phosg::fwrite_fmt(stream, " #S PROB\n");
for (size_t z = 0; z < 5; z++) {
phosg::fwrite_fmt(stream, " {:02X} {:3}%\n", z, this->armor_slot_count_prob_table[z]);
phosg::fwrite_fmt(stream, " {:02X} {:3}%\n", z, this->armor_slot_count_prob_table[z]);
}
phosg::fwrite_fmt(stream, " Unit maximum stars table:\n");
phosg::fwrite_fmt(stream, " AR #*\n");
phosg::fwrite_fmt(stream, "Unit maximum stars table:\n");
phosg::fwrite_fmt(stream, " AR #*\n");
for (size_t z = 0; z < 10; z++) {
phosg::fwrite_fmt(stream, " {:02X} {:3}\n", z, this->unit_max_stars_table[z]);
phosg::fwrite_fmt(stream, " {:02X} {:3}\n", z, this->unit_max_stars_table[z]);
}
}
@@ -371,20 +390,50 @@ void CommonItemSet::Table::print_diff(FILE* stream, const Table& other) const {
phosg::format_data_string(&this->armor_slot_count_prob_table, sizeof(this->armor_slot_count_prob_table)),
phosg::format_data_string(&other.armor_slot_count_prob_table, sizeof(other.armor_slot_count_prob_table)));
}
if (this->enemy_meseta_ranges != other.enemy_meseta_ranges) {
phosg::fwrite_fmt(stream, "> enemy_meseta_ranges: {} -> {}\n",
phosg::format_data_string(&this->enemy_meseta_ranges, sizeof(this->enemy_meseta_ranges)),
phosg::format_data_string(&other.enemy_meseta_ranges, sizeof(other.enemy_meseta_ranges)));
auto format_enemy_range_table = [&](const std::unordered_map<EnemyType, Range<uint16_t>>& table) -> std::string {
string ret = "";
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
try {
const auto& range = table.at(enemy_type);
if (!ret.empty()) {
ret += ",";
}
ret += std::format("{}=[{},{}]", phosg::name_for_enum(enemy_type), range.min, range.max);
} catch (const out_of_range&) {
}
}
return ret;
};
auto format_enemy_u8_table = [&](const std::unordered_map<EnemyType, uint8_t>& table) -> std::string {
string ret = "";
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
try {
uint8_t value = table.at(enemy_type);
if (!ret.empty()) {
ret += ",";
}
ret += std::format("{}={}", phosg::name_for_enum(enemy_type), value);
} catch (const out_of_range&) {
}
}
return ret;
};
if (this->enemy_type_meseta_ranges != other.enemy_type_meseta_ranges) {
phosg::fwrite_fmt(stream, "> enemy_type_meseta_ranges: {} -> {}\n",
format_enemy_range_table(this->enemy_type_meseta_ranges),
format_enemy_range_table(other.enemy_type_meseta_ranges));
}
if (this->enemy_type_drop_probs != other.enemy_type_drop_probs) {
phosg::fwrite_fmt(stream, "> enemy_type_drop_probs: {} -> {}\n",
phosg::format_data_string(&this->enemy_type_drop_probs, sizeof(this->enemy_type_drop_probs)),
phosg::format_data_string(&other.enemy_type_drop_probs, sizeof(other.enemy_type_drop_probs)));
format_enemy_u8_table(this->enemy_type_drop_probs),
format_enemy_u8_table(other.enemy_type_drop_probs));
}
if (this->enemy_item_classes != other.enemy_item_classes) {
phosg::fwrite_fmt(stream, "> enemy_item_classes: {} -> {}\n",
phosg::format_data_string(&this->enemy_item_classes, sizeof(this->enemy_item_classes)),
phosg::format_data_string(&other.enemy_item_classes, sizeof(other.enemy_item_classes)));
if (this->enemy_type_item_classes != other.enemy_type_item_classes) {
phosg::fwrite_fmt(stream, "> enemy_type_item_classes: {} -> {}\n",
format_enemy_u8_table(this->enemy_type_item_classes),
format_enemy_u8_table(other.enemy_type_item_classes));
}
if (this->box_meseta_ranges != other.box_meseta_ranges) {
phosg::fwrite_fmt(stream, "> box_meseta_ranges: {} -> {}\n",
@@ -453,88 +502,145 @@ void CommonItemSet::Table::print_diff(FILE* stream, const Table& other) const {
}
}
phosg::JSON CommonItemSet::Table::json() const {
phosg::JSON enemy_meseta_ranges_json = phosg::JSON::dict();
phosg::JSON enemy_type_drop_probs_json = phosg::JSON::dict();
phosg::JSON enemy_item_classes_json = phosg::JSON::dict();
for (size_t z = 0; z < 0x64; z++) {
for (Episode episode : ALL_EPISODES_V4) {
auto types = enemy_types_for_rare_table_index(episode, z);
vector<string> names;
if (types.empty()) {
names.emplace_back(std::format("{}:!{:02X}", abbreviation_for_episode(episode), z));
} else {
for (auto type : types) {
names.emplace_back(std::format("{}:{}", abbreviation_for_episode(episode), phosg::name_for_enum(type)));
phosg::JSON CommonItemSet::Table::json(std::shared_ptr<const Table> prev_table) const {
auto ret = phosg::JSON::dict();
if (!prev_table || (this->base_weapon_type_prob_table != prev_table->base_weapon_type_prob_table)) {
ret.emplace("BaseWeaponTypeProbTable", to_json(this->base_weapon_type_prob_table));
}
if (!prev_table || (this->subtype_base_table != prev_table->subtype_base_table)) {
ret.emplace("SubtypeBaseTable", to_json(this->subtype_base_table));
}
if (!prev_table || (this->subtype_area_length_table != prev_table->subtype_area_length_table)) {
ret.emplace("SubtypeAreaLengthTable", to_json(this->subtype_area_length_table));
}
if (!prev_table || (this->grind_prob_table != prev_table->grind_prob_table)) {
ret.emplace("GrindProbTable", to_json(this->grind_prob_table));
}
if (!prev_table || (this->armor_shield_type_index_prob_table != prev_table->armor_shield_type_index_prob_table)) {
ret.emplace("ArmorShieldTypeIndexProbTable", to_json(this->armor_shield_type_index_prob_table));
}
if (!prev_table || (this->armor_slot_count_prob_table != prev_table->armor_slot_count_prob_table)) {
ret.emplace("ArmorSlotCountProbTable", to_json(this->armor_slot_count_prob_table));
}
bool needs_enemy_type_meseta_ranges = (!prev_table ||
(this->enemy_type_meseta_ranges != prev_table->enemy_type_meseta_ranges));
bool needs_enemy_type_drop_probs = (!prev_table ||
(this->enemy_type_drop_probs != prev_table->enemy_type_drop_probs));
bool needs_enemy_type_item_classes = (!prev_table ||
(this->enemy_type_item_classes != prev_table->enemy_type_item_classes));
if (needs_enemy_type_meseta_ranges || needs_enemy_type_drop_probs || needs_enemy_type_item_classes) {
phosg::JSON enemy_type_meseta_ranges_json = phosg::JSON::dict();
phosg::JSON enemy_type_drop_probs_json = phosg::JSON::dict();
phosg::JSON enemy_type_item_classes_json = phosg::JSON::dict();
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
auto name = phosg::name_for_enum(enemy_type);
if (needs_enemy_type_meseta_ranges) {
try {
enemy_type_meseta_ranges_json.emplace(name, to_json(this->enemy_type_meseta_ranges.at(enemy_type)));
} catch (const std::out_of_range&) {
}
}
for (const auto& name : names) {
enemy_meseta_ranges_json.emplace(name, to_json(this->enemy_meseta_ranges[z]));
enemy_type_drop_probs_json.emplace(name, this->enemy_type_drop_probs[z]);
enemy_item_classes_json.emplace(name, this->enemy_item_classes[z]);
if (needs_enemy_type_drop_probs) {
try {
enemy_type_drop_probs_json.emplace(name, this->enemy_type_drop_probs.at(enemy_type));
} catch (const std::out_of_range&) {
}
}
if (needs_enemy_type_item_classes) {
try {
enemy_type_item_classes_json.emplace(name, this->enemy_type_item_classes.at(enemy_type));
} catch (const std::out_of_range&) {
}
}
}
if (needs_enemy_type_meseta_ranges) {
ret.emplace("EnemyMesetaRanges", std::move(enemy_type_meseta_ranges_json));
}
if (needs_enemy_type_drop_probs) {
ret.emplace("EnemyTypeDropProbs", std::move(enemy_type_drop_probs_json));
}
if (needs_enemy_type_item_classes) {
ret.emplace("EnemyItemClasses", std::move(enemy_type_item_classes_json));
}
}
return phosg::JSON::dict({
{"BaseWeaponTypeProbTable", to_json(this->base_weapon_type_prob_table)},
{"SubtypeBaseTable", to_json(this->subtype_base_table)},
{"SubtypeAreaLengthTable", to_json(this->subtype_area_length_table)},
{"GrindProbTable", to_json(this->grind_prob_table)},
{"ArmorShieldTypeIndexProbTable", to_json(this->armor_shield_type_index_prob_table)},
{"ArmorSlotCountProbTable", to_json(this->armor_slot_count_prob_table)},
{"EnemyMesetaRanges", std::move(enemy_meseta_ranges_json)},
{"EnemyTypeDropProbs", std::move(enemy_type_drop_probs_json)},
{"EnemyItemClasses", std::move(enemy_item_classes_json)},
{"BoxMesetaRanges", to_json(this->box_meseta_ranges)},
{"HasRareBonusValueProbTable", this->has_rare_bonus_value_prob_table},
{"BonusValueProbTable", to_json(this->bonus_value_prob_table)},
{"NonRareBonusProbSpec", to_json(this->nonrare_bonus_prob_spec)},
{"BonusTypeProbTable", to_json(this->bonus_type_prob_table)},
{"SpecialMult", to_json(this->special_mult)},
{"SpecialPercent", to_json(this->special_percent)},
{"ToolClassProbTable", to_json(this->tool_class_prob_table)},
{"TechniqueIndexProbTable", to_json(this->technique_index_prob_table)},
{"TechniqueLevelRanges", to_json(this->technique_level_ranges)},
{"ArmorOrShieldTypeBias", this->armor_or_shield_type_bias},
{"UnitMaxStarsTable", to_json(this->unit_max_stars_table)},
{"BoxItemClassProbTable", to_json(this->box_item_class_prob_table)},
});
if (!prev_table || (this->box_meseta_ranges != prev_table->box_meseta_ranges)) {
ret.emplace("BoxMesetaRanges", to_json(this->box_meseta_ranges));
}
if (!prev_table || (this->has_rare_bonus_value_prob_table != prev_table->has_rare_bonus_value_prob_table)) {
ret.emplace("HasRareBonusValueProbTable", this->has_rare_bonus_value_prob_table);
}
if (!prev_table || (this->bonus_value_prob_table != prev_table->bonus_value_prob_table)) {
ret.emplace("BonusValueProbTable", to_json(this->bonus_value_prob_table));
}
if (!prev_table || (this->nonrare_bonus_prob_spec != prev_table->nonrare_bonus_prob_spec)) {
ret.emplace("NonRareBonusProbSpec", to_json(this->nonrare_bonus_prob_spec));
}
if (!prev_table || (this->bonus_type_prob_table != prev_table->bonus_type_prob_table)) {
ret.emplace("BonusTypeProbTable", to_json(this->bonus_type_prob_table));
}
if (!prev_table || (this->special_mult != prev_table->special_mult)) {
ret.emplace("SpecialMult", to_json(this->special_mult));
}
if (!prev_table || (this->special_percent != prev_table->special_percent)) {
ret.emplace("SpecialPercent", to_json(this->special_percent));
}
if (!prev_table || (this->tool_class_prob_table != prev_table->tool_class_prob_table)) {
ret.emplace("ToolClassProbTable", to_json(this->tool_class_prob_table));
}
if (!prev_table || (this->technique_index_prob_table != prev_table->technique_index_prob_table)) {
ret.emplace("TechniqueIndexProbTable", to_json(this->technique_index_prob_table));
}
if (!prev_table || (this->technique_level_ranges != prev_table->technique_level_ranges)) {
ret.emplace("TechniqueLevelRanges", to_json(this->technique_level_ranges));
}
if (!prev_table || (this->armor_or_shield_type_bias != prev_table->armor_or_shield_type_bias)) {
ret.emplace("ArmorOrShieldTypeBias", this->armor_or_shield_type_bias);
}
if (!prev_table || (this->unit_max_stars_table != prev_table->unit_max_stars_table)) {
ret.emplace("UnitMaxStarsTable", to_json(this->unit_max_stars_table));
}
if (!prev_table || (this->box_item_class_prob_table != prev_table->box_item_class_prob_table)) {
ret.emplace("BoxItemClassProbTable", to_json(this->box_item_class_prob_table));
}
return ret;
}
phosg::JSON CommonItemSet::json() const {
auto modes_dict = phosg::JSON::dict();
for (const auto& mode : ALL_GAME_MODES_V4) {
auto episodes_dict = phosg::JSON::dict();
for (const auto& episode : ALL_EPISODES_V4) {
auto difficulty_dict = phosg::JSON::dict();
auto ret = phosg::JSON::dict();
for (const auto& episode : ALL_EPISODES_V4) {
for (const auto& mode : ALL_GAME_MODES_V4) {
for (const auto& difficulty : ALL_DIFFICULTIES_V234) {
auto section_id_dict = phosg::JSON::dict();
for (uint8_t section_id = 0; section_id < 10; section_id++) {
auto json_key = this->json_key_for_table(episode, mode, difficulty, section_id);
try {
auto prev_table = this->get_prev_table(episode, mode, difficulty, section_id);
auto table = this->get_table(episode, mode, difficulty, section_id);
section_id_dict.emplace(name_for_section_id(section_id), table->json());
ret.emplace(json_key, table->json(prev_table));
} catch (const runtime_error&) {
}
}
difficulty_dict.emplace(token_name_for_difficulty(difficulty), std::move(section_id_dict));
}
episodes_dict.emplace(token_name_for_episode(episode), std::move(difficulty_dict));
}
modes_dict.emplace(name_for_mode(mode), std::move(episodes_dict));
}
return modes_dict;
return ret;
}
void CommonItemSet::print(FILE* stream) const {
for (const auto& mode : ALL_GAME_MODES_V4) {
for (const auto& episode : ALL_EPISODES_V4) {
for (const auto& episode : ALL_EPISODES_V4) {
for (const auto& mode : ALL_GAME_MODES_V4) {
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
for (uint8_t section_id = 0; section_id < 10; section_id++) {
try {
auto table = this->get_table(episode, mode, difficulty, section_id);
phosg::fwrite_fmt(stream, "============ {} {} {} {}\n",
name_for_mode(mode), name_for_episode(episode), name_for_difficulty(difficulty), name_for_section_id(section_id));
name_for_episode(episode),
name_for_mode(mode),
name_for_difficulty(difficulty),
name_for_section_id(section_id));
table->print(stream);
} catch (const runtime_error&) {
}
@@ -545,8 +651,8 @@ void CommonItemSet::print(FILE* stream) const {
}
void CommonItemSet::print_diff(FILE* stream, const CommonItemSet& other) const {
for (const auto& mode : ALL_GAME_MODES_V4) {
for (const auto& episode : ALL_EPISODES_V4) {
for (const auto& episode : ALL_EPISODES_V4) {
for (const auto& mode : ALL_GAME_MODES_V4) {
for (const auto& difficulty : ALL_DIFFICULTIES_V234) {
for (uint8_t section_id = 0; section_id < 10; section_id++) {
shared_ptr<const Table> this_table;
@@ -564,13 +670,22 @@ void CommonItemSet::print_diff(FILE* stream, const CommonItemSet& other) const {
continue;
} else if (!this_table) {
phosg::fwrite_fmt(stream, "> Table present in other but not this: {} {} {} {}\n",
name_for_mode(mode), name_for_episode(episode), name_for_difficulty(difficulty), name_for_section_id(section_id));
name_for_episode(episode),
name_for_mode(mode),
name_for_difficulty(difficulty),
name_for_section_id(section_id));
} else if (!other_table) {
phosg::fwrite_fmt(stream, "> Table present in this but not other: {} {} {} {}\n",
name_for_mode(mode), name_for_episode(episode), name_for_difficulty(difficulty), name_for_section_id(section_id));
name_for_episode(episode),
name_for_mode(mode),
name_for_difficulty(difficulty),
name_for_section_id(section_id));
} else if (*this_table != *other_table) {
phosg::fwrite_fmt(stream, "> Tables do not match: {} {} {} {}\n",
name_for_mode(mode), name_for_episode(episode), name_for_difficulty(difficulty), name_for_section_id(section_id));
name_for_episode(episode),
name_for_mode(mode),
name_for_difficulty(difficulty),
name_for_section_id(section_id));
this_table->print_diff(stream, *other_table);
}
}
@@ -598,12 +713,27 @@ void CommonItemSet::Table::parse_itempt_t(const phosg::StringReader& r, bool is_
this->grind_prob_table = r.pget<parray<parray<uint8_t, 4>, 9>>(offsets.grind_prob_table_offset);
this->armor_shield_type_index_prob_table = r.pget<parray<uint8_t, 0x05>>(offsets.armor_shield_type_index_prob_table_offset);
this->armor_slot_count_prob_table = r.pget<parray<uint8_t, 0x05>>(offsets.armor_slot_count_prob_table_offset);
const auto& data = r.pget<parray<Range<U16T<BE>>, 0x64>>(offsets.enemy_meseta_ranges_offset);
for (size_t z = 0; z < data.size(); z++) {
this->enemy_meseta_ranges[z] = Range<uint16_t>{data[z].min, data[z].max};
const auto& enemy_rt_index_meseta_ranges = r.pget<parray<Range<U16T<BE>>, NUM_RT_INDEXES_V3>>(
offsets.enemy_rt_index_meseta_ranges_offset);
const auto& enemy_rt_index_drop_probs = r.pget<parray<uint8_t, NUM_RT_INDEXES_V3>>(
offsets.enemy_rt_index_drop_probs_offset);
const auto& enemy_rt_index_item_classes = r.pget<parray<uint8_t, NUM_RT_INDEXES_V3>>(
offsets.enemy_rt_index_item_classes_offset);
for (auto enemy_type : phosg::EnumRange<EnemyType>()) {
const auto& def = type_definition_for_enemy(enemy_type);
if (def.valid_in_episode(this->episode) && (def.rt_index < enemy_rt_index_meseta_ranges.size())) {
const auto& meseta_range = enemy_rt_index_meseta_ranges[def.rt_index];
if (meseta_range.max > 0) {
this->enemy_type_meseta_ranges.emplace(enemy_type, Range<uint16_t>{meseta_range.min, meseta_range.max});
}
if (enemy_rt_index_drop_probs[def.rt_index] > 0) {
this->enemy_type_drop_probs.emplace(enemy_type, enemy_rt_index_drop_probs[def.rt_index]);
}
if (enemy_rt_index_item_classes[def.rt_index] != 0xFF) {
this->enemy_type_item_classes.emplace(enemy_type, enemy_rt_index_item_classes[def.rt_index]);
}
}
}
this->enemy_type_drop_probs = r.pget<parray<uint8_t, 0x64>>(offsets.enemy_type_drop_probs_offset);
this->enemy_item_classes = r.pget<parray<uint8_t, 0x64>>(offsets.enemy_item_classes_offset);
{
const auto& data = r.pget<parray<Range<U16T<BE>>, 0x0A>>(offsets.box_meseta_ranges_offset);
for (size_t z = 0; z < data.size(); z++) {
@@ -653,20 +783,43 @@ uint16_t CommonItemSet::key_for_table(Episode episode, GameMode mode, Difficulty
(static_cast<uint16_t>(secid) & 0x000F));
}
std::string CommonItemSet::json_key_for_table(
Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id) {
return std::format("{}:{}:{}:{}", abbreviation_for_episode(episode), name_for_mode(mode),
token_name_for_difficulty(difficulty), name_for_section_id(section_id));
}
shared_ptr<const CommonItemSet::Table> CommonItemSet::get_table(
Episode episode, GameMode mode, Difficulty difficulty, uint8_t secid) const {
Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id) const {
try {
return this->tables.at(this->key_for_table(episode, mode, difficulty, secid));
return this->tables.at(this->key_for_table(episode, mode, difficulty, section_id));
} catch (const out_of_range&) {
throw runtime_error(std::format("common item table not available for episode={}, mode={}, difficulty={}, secid={}",
name_for_episode(episode), name_for_mode(mode), name_for_difficulty(difficulty), secid));
name_for_episode(episode), name_for_mode(mode), name_for_difficulty(difficulty), section_id));
}
}
shared_ptr<const CommonItemSet::Table> CommonItemSet::get_prev_table(
Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id) const {
if (section_id != 0) {
// All section IDs are based on the previous, except Viridia
return this->get_table(episode, mode, difficulty, section_id - 1);
} else if (difficulty != Difficulty::NORMAL) {
// All Viridia tables are based on the previous difficulty, except Normal
auto prev_difficulty = static_cast<Difficulty>(static_cast<uint8_t>(difficulty) - 1);
return this->get_table(episode, mode, prev_difficulty, 0);
} else if (mode != GameMode::NORMAL) {
// All Normal Viridia tables are based on the Normal game mode, except Normal itself
return this->get_table(episode, GameMode::NORMAL, Difficulty::NORMAL, 0);
} else {
// There's no previous table
return nullptr;
}
}
AFSV2CommonItemSet::AFSV2CommonItemSet(
std::shared_ptr<const std::string> pt_afs_data, std::shared_ptr<const std::string> ct_afs_data) {
// Each AFS file has 40 entries (30 on v1); the first 10 are for Normal, then
// Hard, etc.
// Each AFS file has 40 entries (30 on v1); the first 10 are for Normal, then Hard, etc.
{
AFSArchive pt_afs(pt_afs_data);
bool include_ultimate;
@@ -692,8 +845,7 @@ AFSV2CommonItemSet::AFSV2CommonItemSet(
}
}
// ItemCT AFS files also have 40 entries, but only the 0th, 10th, 20th, and
// 30th are used (section_id is ignored)
// ItemCT AFS files also have 40 entries, but only the 0th, 10th, 20th, and 30th are used (section_id is ignored)
if (ct_afs_data) {
AFSArchive ct_afs(ct_afs_data);
bool include_ultimate;
@@ -743,7 +895,7 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr<const std::string> gs
section_id);
};
for (Episode episode : ALL_EPISODES_V4) {
for (Episode episode : ALL_EPISODES_V3) {
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
for (size_t section_id = 0; section_id < 10; section_id++) {
phosg::StringReader r;
@@ -768,54 +920,42 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr<const std::string> gs
}
}
if (episode != Episode::EP4) {
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
try {
auto r = gsl.get_reader(filename_for_table(episode, difficulty, 0, true));
auto table = make_shared<Table>(r, is_big_endian, true, episode);
for (size_t section_id = 0; section_id < 10; section_id++) {
this->tables.emplace(this->key_for_table(episode, GameMode::CHALLENGE, difficulty, section_id), table);
}
} catch (const out_of_range&) {
// GC NTE doesn't have Ep2 challenge; just skip adding the table
for (Difficulty difficulty : ALL_DIFFICULTIES_V234) {
try {
auto r = gsl.get_reader(filename_for_table(episode, difficulty, 0, true));
auto table = make_shared<Table>(r, is_big_endian, true, episode);
for (size_t section_id = 0; section_id < 10; section_id++) {
this->tables.emplace(this->key_for_table(episode, GameMode::CHALLENGE, difficulty, section_id), table);
}
} catch (const out_of_range&) {
// GC NTE doesn't have Ep2 challenge; just skip adding the table
}
}
}
}
JSONCommonItemSet::JSONCommonItemSet(const phosg::JSON& json) {
for (const auto& mode_it : json.as_dict()) {
static const unordered_map<string, GameMode> mode_keys(
{{"Normal", GameMode::NORMAL}, {"Battle", GameMode::BATTLE}, {"Challenge", GameMode::CHALLENGE}, {"Solo", GameMode::SOLO}});
GameMode mode = mode_keys.at(mode_it.first);
for (const auto& episode_it : mode_it.second->as_dict()) {
static const unordered_map<string, Episode> episode_keys(
{{"Episode1", Episode::EP1}, {"Episode2", Episode::EP2}, {"Episode4", Episode::EP4}});
Episode episode = episode_keys.at(episode_it.first);
for (const auto& difficulty_it : episode_it.second->as_dict()) {
static const unordered_map<string, Difficulty> difficulty_keys(
{{"Normal", Difficulty::NORMAL}, {"Hard", Difficulty::HARD}, {"VeryHard", Difficulty::VERY_HARD}, {"Ultimate", Difficulty::ULTIMATE}});
Difficulty difficulty = difficulty_keys.at(difficulty_it.first);
for (const auto& section_id_it : difficulty_it.second->as_dict()) {
uint8_t section_id = section_id_for_name(section_id_it.first);
this->tables.emplace(
this->key_for_table(episode, mode, difficulty, section_id),
make_shared<Table>(*section_id_it.second, episode));
for (const auto& episode : ALL_EPISODES_V4) {
for (const auto& mode : ALL_GAME_MODES_V4) {
for (const auto& difficulty : ALL_DIFFICULTIES_V234) {
for (uint8_t section_id = 0; section_id < 10; section_id++) {
try {
auto prev_table = this->get_prev_table(episode, mode, difficulty, section_id);
auto json_key = this->json_key_for_table(episode, mode, difficulty, section_id);
auto key = this->key_for_table(episode, mode, difficulty, section_id);
this->tables.emplace(key, make_shared<Table>(prev_table, json.at(json_key), episode));
} catch (const runtime_error&) {
} catch (const out_of_range&) {
}
}
}
}
}
}
RELFileSet::RELFileSet(std::shared_ptr<const std::string> data)
: data(data), r(*this->data) {}
RELFileSet::RELFileSet(std::shared_ptr<const std::string> data) : data(data), r(*this->data) {}
ArmorRandomSet::ArmorRandomSet(std::shared_ptr<const std::string> data)
: RELFileSet(data) {
ArmorRandomSet::ArmorRandomSet(std::shared_ptr<const std::string> data) : RELFileSet(data) {
// For some reason the footer tables are doubly indirect in this file
uint32_t specs_offset_offset = this->r.pget_u32b(data->size() - 0x10);
uint32_t specs_offset = this->r.pget_u32b(specs_offset_offset);
@@ -837,8 +977,7 @@ ArmorRandomSet::get_unit_table(size_t index) const {
return this->get_table<WeightTableEntry8>(this->tables->at(2), index);
}
ToolRandomSet::ToolRandomSet(std::shared_ptr<const std::string> data)
: RELFileSet(data) {
ToolRandomSet::ToolRandomSet(std::shared_ptr<const std::string> data) : RELFileSet(data) {
uint32_t specs_offset = r.pget_u32b(data->size() - 0x10);
this->common_recovery_table_spec = &r.pget<TableSpec>(r.pget_u32b(specs_offset));
this->rare_recovery_table_spec = &r.pget<TableSpec>(r.pget_u32b(specs_offset + sizeof(uint32_t)), 2 * sizeof(TableSpec));
@@ -865,8 +1004,7 @@ ToolRandomSet::get_tech_disk_level_table(size_t index) const {
return this->get_table<TechDiskLevelEntry>(*this->tech_disk_level_table_spec, index);
}
WeaponRandomSet::WeaponRandomSet(std::shared_ptr<const std::string> data)
: RELFileSet(data) {
WeaponRandomSet::WeaponRandomSet(std::shared_ptr<const std::string> data) : RELFileSet(data) {
uint32_t offsets_offset = this->r.pget_u32b(data->size() - 0x10);
this->offsets = &this->r.pget<Offsets>(offsets_offset);
}
@@ -906,8 +1044,7 @@ WeaponRandomSet::get_favored_grind_range(size_t index) const {
return &this->r.pget<RangeTableEntry>(this->offsets->favored_grind_range_table + sizeof(RangeTableEntry) * index);
}
TekkerAdjustmentSet::TekkerAdjustmentSet(std::shared_ptr<const std::string> data)
: data(data), r(*data) {
TekkerAdjustmentSet::TekkerAdjustmentSet(std::shared_ptr<const std::string> data) : data(data), r(*data) {
this->offsets = &this->r.pget<Offsets>(this->r.pget_u32b(this->r.size() - 0x10));
}
+124 -147
View File
@@ -4,6 +4,7 @@
#include <phosg/Encoding.hh>
#include <phosg/JSON.hh>
#include "EnemyType.hh"
#include "GSLArchive.hh"
#include "PSOEncryption.hh"
#include "StaticGameData.hh"
@@ -15,7 +16,7 @@ public:
class Table {
public:
Table() = delete;
Table(const phosg::JSON& json, Episode episode);
Table(std::shared_ptr<const Table> prev_table, const phosg::JSON& json, Episode episode);
Table(const phosg::StringReader& r, bool big_endian, bool is_v3, Episode episode);
bool operator==(const Table& other) const = default;
@@ -23,11 +24,15 @@ public:
template <typename IntT>
struct Range {
IntT min;
IntT max;
IntT min = 0;
IntT max = 0;
bool operator==(const Range& other) const = default;
bool operator!=(const Range& other) const = default;
inline bool empty() const {
return ((this->min | this->max) == 0);
}
} __attribute__((packed));
Episode episode;
@@ -37,9 +42,10 @@ public:
parray<parray<uint8_t, 4>, 9> grind_prob_table;
parray<uint8_t, 0x05> armor_shield_type_index_prob_table;
parray<uint8_t, 0x05> armor_slot_count_prob_table;
parray<Range<uint16_t>, 0x64> enemy_meseta_ranges;
parray<uint8_t, 0x64> enemy_type_drop_probs;
parray<uint8_t, 0x64> enemy_item_classes;
// Note: PSO originally uses arrays indexed by rt_index here, but we index enemies by the EnemyType enum instead
std::unordered_map<EnemyType, Range<uint16_t>> enemy_type_meseta_ranges;
std::unordered_map<EnemyType, uint8_t> enemy_type_drop_probs;
std::unordered_map<EnemyType, uint8_t> enemy_type_item_classes;
parray<Range<uint16_t>, 0x0A> box_meseta_ranges;
bool has_rare_bonus_value_prob_table;
parray<parray<uint16_t, 6>, 0x17> bonus_value_prob_table;
@@ -54,7 +60,7 @@ public:
parray<uint8_t, 0x0A> unit_max_stars_table;
parray<parray<uint8_t, 10>, 7> box_item_class_prob_table;
phosg::JSON json() const;
phosg::JSON json(std::shared_ptr<const Table> prev_table) const;
void print(FILE* stream) const;
void print_diff(FILE* stream, const Table& other) const;
@@ -64,54 +70,43 @@ public:
template <bool BE>
struct OffsetsT {
// This data structure uses index probability tables in multiple places. An
// index probability table is a table where each entry holds the probability
// that that entry's index is used. For example, if the armor slot count
// probability table contains [77, 17, 5, 1, 0], this means there is a 77%
// chance of no slots, 17% chance of 1 slot, 5% chance of 2 slots, 1% chance
// of 3 slots, and no chance of 4 slots. The values in index probability
// tables do not have to add up to 100; the game sums all of them and
// chooses a random number less than that maximum.
// This data structure uses index probability tables in multiple places. An index probability table is a table
// where each entry holds the probability that that entry's index is used. For example, if the armor slot count
// probability table contains [77, 17, 5, 1, 0], this means there is a 77% chance of no slots, 17% chance of 1
// slot, 5% chance of 2 slots, 1% chance of 3 slots, and no chance of 4 slots. The values in index probability
// tables do not have to add up to 100; the game sums all of them and chooses a random number less than that
// maximum.
// The area (floor) number is used in many places as well. Unlike the normal
// area numbers, which start with Pioneer 2, the area numbers in this
// structure start with Forest 1, and boss areas are treated as the first
// area of the next section (so De Rol Le has Mines 1 drops, for example).
// Final boss areas are treated as the last non-boss area (so Dark Falz
// boxes are like Ruins 3 boxes). We refer to these adjusted area numbers as
// (area - 1).
// The area (floor) number is used in many places as well. Unlike the normal area numbers, which start with
// Pioneer 2, the area numbers in this structure start with Forest 1, and boss areas are treated as the first
// area of the next section (so De Rol Le has Mines 1 drops, for example). Final boss areas are treated as the
// last non-boss area (so Dark Falz boxes are like Ruins 3 boxes). We refer to these adjusted area numbers as
// (area - 1), or area_norm.
// This index probability table determines the types of non-rare weapons.
// The indexes in this table correspond to the non-rare weapon types 01
// through 0C (Saber through Wand).
// This index probability table determines the types of non-rare weapons. The indexes in this table correspond to
// the non-rare weapon types 01 through 0C (Saber through Wand).
// V2/V3: -> parray<uint8_t, 0x0C>
/* 00 */ U32T<BE> base_weapon_type_prob_table_offset;
// This table specifies the base subtype for each weapon type. Negative
// values here mean that the weapon cannot be found in the first N areas (so
// -2, for example, means that the weapon never appears in Forest 1 or 2 at
// all). Nonnegative values here mean the subtype can be found in all areas,
// and specify the base subtype (usually in the range [0, 4]). The subtype
// of weapon that actually appears depends on this value and a value from
// the following table.
// This table specifies the base subtype for each weapon type. Negative values here mean that the weapon cannot
// be found in the first N areas (so -2, for example, means that the weapon never appears in Forest 1 or 2 at
// all). Nonnegative values here mean the subtype can be found in all areas, and specify the base subtype
// (usually in the range [0, 4]). The subtype of weapon that actually appears depends on this value and a value
// from the following table.
// V2/V3: -> parray<int8_t, 0x0C>
/* 04 */ U32T<BE> subtype_base_table_offset;
// This table specifies how many areas each weapon subtype appears in. For
// example, if Sword (subtype 02, which is index 1 in this table and the
// table above) has a subtype base of -2 and a subtype area length of 4,
// then Sword items can be found when area - 1 is 2, 3, 4, or 5 (Cave 1
// through Mine 1), and Gigush (the next sword subtype) can be found in Mine
// 1 through Ruins 3.
// This table specifies how many areas each weapon subtype appears in. For example, if Sword (subtype 02, which
// is index 1 in this table and the table above) has a subtype base of -2 and a subtype area length of 4, then
// Sword items can be found when area - 1 is 2, 3, 4, or 5 (Cave 1 through Mine 1), and Gigush (the next sword
// subtype) can be found in Mine 1 through Ruins 3.
// V2/V3: -> parray<uint8_t, 0x0C>
/* 08 */ U32T<BE> subtype_area_length_table_offset;
// This index probability table specifies how likely each possible grind
// value is. The table is indexed as [grind][subtype_area_index], where the
// subtype area index is how many areas the player is beyond the first area
// in which the subtype can first be found (clamped to [0, 3]). To continue
// the example above, in Cave 3, subtype_area_index would be 2, since Swords
// can first be found two areas earlier in Cave 1.
// This index probability table specifies how likely each possible grind value is. The table is indexed as
// [grind][subtype_area_index], where the subtype area index is how many areas the player is beyond the first
// area in which the subtype can first be found (clamped to [0, 3]). To continue the example above, in Cave 3,
// subtype_area_index would be 2, since Swords can first be found two areas earlier in Cave 1.
// For example, this table could look like this:
// [64 1E 19 14] // Chance of getting a grind +0
// [00 1E 17 0F] // Chance of getting a grind +1
@@ -121,74 +116,66 @@ public:
// V2/V3: -> parray<parray<uint8_t, 4>, 9>
/* 0C */ U32T<BE> grind_prob_table_offset;
// TODO: Figure out exactly how this table is used. Anchor: 80106D34
// This index probability table specifies how likely each type of armor or shield is. The general formula is:
// data1[2] = max((area_norm + (result from this table) + armor_or_shield_type_bias - 3), 0)
// In this way, (armor_or_shield_type_bias + area_norm - 3) can be thought of as the "base" value for each area,
// and this table specifies how likely the armor/shield is to be "upgraded" from that value.
// V2/V3: -> parray<uint8_t, 0x05>
/* 10 */ U32T<BE> armor_shield_type_index_prob_table_offset;
// This index probability table specifies how common each possible slot
// count is for armor drops.
// This index probability table specifies how common each possible slot count is for armor drops.
// V2/V3: -> parray<uint8_t, 0x05>
/* 14 */ U32T<BE> armor_slot_count_prob_table_offset;
// This array (indexed by enemy_type) specifies the range of meseta values
// that each enemy can drop.
// V2/V3: -> parray<Range<U16T>, 0x64>
/* 18 */ U32T<BE> enemy_meseta_ranges_offset;
// This array (indexed by rt_index) specifies the range of meseta values that each enemy can drop.
// V2/V3: -> parray<Range<U16T>, NUM_RT_INDEXES_V3>
/* 18 */ U32T<BE> enemy_rt_index_meseta_ranges_offset;
// Each byte in this table (indexed by enemy_type) represents the percent
// chance that the enemy drops anything at all. (This check is done before
// the rare drop check, so the chance of getting a rare item from an enemy
// is essentially this probability multiplied by the rare drop rate.)
// V2/V3: -> parray<uint8_t, 0x64>
/* 1C */ U32T<BE> enemy_type_drop_probs_offset;
// Each byte in this table (indexed by rt_index) represents the percent chance that the enemy drops anything at
// all. (This check is done before the rare drop check, so the chance of getting a rare item from an enemy is
// essentially this probability multiplied by the rare drop rate.)
// V2/V3: -> parray<uint8_t, NUM_RT_INDEXES_V3>
/* 1C */ U32T<BE> enemy_rt_index_drop_probs_offset;
// Each byte in this table (indexed by enemy_type) represents the class of
// item that the enemy can drop. The values are:
// 00 = weapon
// 01 = armor
// 02 = shield
// 03 = unit
// 04 = tool
// 05 = meseta
// Anything else = no item
// V2/V3: -> parray<uint8_t, 0x64>
/* 20 */ U32T<BE> enemy_item_classes_offset;
// Each byte in this table (indexed by rt_index) represents the class of item that can drop. The values are:
// 00 = weapon
// 01 = armor
// 02 = shield
// 03 = unit
// 04 = tool
// 05 = meseta
// Anything else = no item
// V2/V3: -> parray<uint8_t, NUM_RT_INDEXES_V3>
/* 20 */ U32T<BE> enemy_rt_index_item_classes_offset;
// This table (indexed by area - 1) specifies the ranges of meseta values
// that can drop from boxes.
// This table (indexed by area - 1) specifies the ranges of meseta values that can drop from boxes.
// V2/V3: -> parray<Range<U16T>, 0x0A>
/* 24 */ U32T<BE> box_meseta_ranges_offset;
// This array specifies the chance that a rare weapon will have each
// possible bonus value. This is indexed as [(bonus_value - 10 / 5)][spec],
// so the first row refers the probability of getting a -10% bonus, the next
// row is the chance of getting -5%, etc., all the way up to +100%. For
// non-rare items, spec is determined randomly based on the following field;
// for rare items, spec is always 5.
// This array specifies the chance that a rare weapon will have each possible bonus value. This is indexed as
// [(bonus_value - 10 / 5)][spec], so the first row refers the probability of getting a -10% bonus, the next row
// is the chance of getting -5%, etc., all the way up to +100%. For non-rare items (or all items on v1/v2), spec
// is determined randomly based on the following field; for rare items on v3+, spec is always 5.
// V2: -> parray<parray<uint8_t, 5>, 0x17>
// V3: -> parray<parray<U16T, 6>, 0x17>
/* 28 */ U32T<BE> bonus_value_prob_table_offset;
// This array specifies the value of spec to be used in the above lookup for
// non-rare items. This is NOT an index probability table; this is a direct
// lookup with indexes [bonus_index][area - 1]. A value of 0xFF in any byte
// of this array prevents any weapon from having a bonus in that slot.
// For example, the array might look like this:
// This array specifies the value of spec to be used in the above lookup for non-rare items. This is NOT an index
// probability table; this is a direct lookup with indexes [bonus_index][area - 1]. A value of 0xFF in any byte
// of this array prevents any weapon from having a bonus in that slot. An example table might look like this:
// [00 00 00 01 01 01 01 02 02 02]
// [FF FF FF 00 00 00 01 01 01 01]
// [FF FF FF FF FF FF FF FF FF 00]
// F1 F2 C1 C2 C3 M1 M2 R1 R2 R3 // (Episode 1 areas, for reference)
// In this example, spec is 0, 1, or 2 in all cases where a weapon can have
// a bonus. In Forest 1 and 2 and Cave 1, weapons may have at most one
// bonus; in all other areas except Ruins 3, they can have at most two
// bonuses, and in Ruins 3, they can have up to three bonuses.
// In this example, spec is 0, 1, or 2 in all cases where a weapon can have a bonus. In Forest 1 and 2 and Cave
// 1, weapons may have at most one bonus; in all other areas except Ruins 3, they can have at most two bonuses,
// and in Ruins 3, they can have up to three bonuses.
// V2/V3: // -> parray<parray<uint8_t, 10>, 3>
/* 2C */ U32T<BE> nonrare_bonus_prob_spec_offset;
// This array specifies the chance that a weapon will have each bonus type.
// The table is indexed as [bonus_type][area - 1] for non-rare items; for
// rare items, a random value in the range [0, 9] is used instead of
// (area - 1).
// This array specifies the chance that a weapon will have each bonus type. The table is indexed as
// [bonus_type][area - 1] for non-rare items; for rare items, a random value in the range [0, 9] is used instead
// of (area - 1).
// For example, the table might look like this:
// [46 46 3F 3E 3E 3D 3C 3C 3A 3A] // Chance of getting no bonus
// [14 14 0A 0A 09 02 02 04 05 05] // Chance of getting Native bonus
@@ -200,54 +187,50 @@ public:
// V2/V3: -> parray<parray<uint8_t, 10>, 6>
/* 30 */ U32T<BE> bonus_type_prob_table_offset;
// This array (indexed by area - 1) specifies a multiplier of used in
// special ability determination. It seems this uses the star values from
// ItemPMT, but not yet clear exactly in what way.
// TODO: Figure out exactly what this does. Anchor: 80106FEC
// This array (indexed by area - 1) specifies a parameter used in weapon special generation. If the sampled value
// from this table is 0, no special is generated. Otherwise, a random floating-point value W in the range [0,
// special_mult] is generated and truncated to an integer. If this value is greater than 3, no special is
// generated; otherwise, a random special worth (W + 1) stars is chosen. It seems Sega only intended special_mult
// to be in the range [0, 4], but values greater than 4 will work, and will simply increase the probability of
// getting no special.
// V2/V3: -> parray<uint8_t, 0x0A>
/* 34 */ U32T<BE> special_mult_offset;
// This array (indexed by area - 1) specifies the probability that any
// non-rare weapon will have a special ability.
// This array (indexed by area - 1) specifies the probability that a non-rare weapon will have a special ability.
// V2/V3: -> parray<uint8_t, 0x0A>
/* 38 */ U32T<BE> special_percent_offset;
// This index probability table is indexed by [tool_class][area - 1]. The
// tool class refers to an entry in ItemPMT, which links it to the actual
// item code.
// This index probability table is indexed by [tool_class][area - 1]. The tool class refers to an entry in
// ItemPMT, which links it to the actual item code.
// V2/V3: -> parray<parray<U16T, 0x0A>, 0x1C>
/* 3C */ U32T<BE> tool_class_prob_table_offset;
// This index probability table determines how likely each technique is to
// appear. The table is indexed as [technique_num][area - 1].
// This index probability table determines how likely each technique is to appear. The table is indexed as
// [technique_num][area - 1].
// V2/V3: -> parray<parray<uint8_t, 0x0A>, 0x13>
/* 40 */ U32T<BE> technique_index_prob_table_offset;
// This table specifies the ranges for technique disk levels. The table is
// indexed as [technique_num][area - 1]. If either min or max in the range
// is 0xFF, or if max < min, technique disks are not dropped for that
// technique and area pair.
// This table specifies the ranges for technique disk levels. The table is indexed as [technique_num][area - 1].
// If either min or max in the range is 0xFF, or if max < min, technique disks are not dropped for that technique
// and area pair.
// V2/V3: -> parray<parray<Range<uint8_t>, 0x0A>, 0x13>
/* 44 */ U32T<BE> technique_level_ranges_offset;
// See comments on armor_shield_type_index_prob_table_offset for how this is used.
/* 48 */ uint8_t armor_or_shield_type_bias;
/* 49 */ parray<uint8_t, 3> unused1;
// These values specify the maximum number of stars any generated unit can
// have in each area. The values here are not inclusive; that is, a value
// of 7 means that only units with 1-6 stars can drop in that area. The
// game uniformly chooses a random number of stars in the acceptable
// range, then uniformly chooses a random unit with that many stars.
// These values specify the maximum number of stars any generated unit can have in each area. The values here are
// not inclusive; that is, a value of 7 means that only units with 1-6 stars can drop in that area. The game
// uniformly chooses a random number of stars in the acceptable range, then uniformly chooses a random unit with
// that many stars.
// V2/V3: -> parray<uint8_t, 0x0A>
/* 4C */ U32T<BE> unit_max_stars_offset;
// This index probability table determines which type of items drop from
// boxes. The table is indexed as [item_class][area - 1], with item_class
// as the result value (that is, in the example below, the game looks at a
// single column and sums the values going down, then the chosen item
// class is one of the row indexes based on the weight values in the
// column.) The resulting item_class value has the same meaning as in
// enemy_item_classes above.
// This index probability table determines which type of items drop from boxes. The table is indexed as
// [item_class][area - 1], with item_class as the result value (that is, in the example below, the game looks at
// a single column and sums the values going down, then the chosen item class is one of the row indexes based on
// the weight values in the column.) The resulting value has the same meaning as in enemy_rt_index_item_classes.
// For example, this array might look like the following:
// [07 07 08 08 06 07 08 09 09 0A] // Chances per area of a weapon drop
// [02 02 02 02 03 02 02 02 03 03] // Chances per area of an armor drop
@@ -261,17 +244,19 @@ public:
/* 50 */ U32T<BE> box_item_class_prob_table_offset;
// There are several unused fields here.
} __attribute__((packed));
} __packed_ws_be__(OffsetsT, 0x54);
using Offsets = OffsetsT<false>;
using OffsetsBE = OffsetsT<true>;
check_struct_size(Offsets, 0x54);
check_struct_size(OffsetsBE, 0x54);
};
bool operator==(const CommonItemSet& other) const = default;
bool operator!=(const CommonItemSet& other) const = default;
std::shared_ptr<const Table> get_table(Episode episode, GameMode mode, Difficulty difficulty, uint8_t secid) const;
std::shared_ptr<const Table> get_table(
Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id) const;
std::shared_ptr<const Table> get_prev_table(
Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id) const;
phosg::JSON json() const;
void print(FILE* stream) const;
void print_diff(FILE* stream, const CommonItemSet& other) const;
@@ -279,7 +264,8 @@ public:
protected:
CommonItemSet() = default;
static uint16_t key_for_table(Episode episode, GameMode mode, Difficulty difficulty, uint8_t secid);
static uint16_t key_for_table(Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id);
static std::string json_key_for_table(Episode episode, GameMode mode, Difficulty difficulty, uint8_t section_id);
std::unordered_map<uint16_t, std::shared_ptr<Table>> tables;
};
@@ -299,8 +285,8 @@ public:
explicit JSONCommonItemSet(const phosg::JSON& json);
};
// Note: There are clearly better ways of doing this, but this implementation
// closely follows what the original code in the client does.
// Note: There are clearly better ways of doing this, but this implementation closely follows what the original code in
// the client does.
template <typename ItemT, size_t MaxCount>
struct ProbabilityTable {
ItemT items[MaxCount];
@@ -349,7 +335,6 @@ public:
ValueT value;
WeightT weight;
} __attribute__((packed));
using WeightTableEntry8 = WeightTableEntry<uint8_t>;
using WeightTableEntry32 = WeightTableEntry<be_uint32_t>;
check_struct_size(WeightTableEntry8, 2);
@@ -368,11 +353,9 @@ protected:
RELFileSet(std::shared_ptr<const std::string> data);
template <typename T>
std::pair<const T*, size_t> get_table(
const TableSpec& spec, size_t index) const {
std::pair<const T*, size_t> get_table(const TableSpec& spec, size_t index) const {
const T* entries = &r.pget<T>(
spec.offset + index * spec.entries_per_table * sizeof(T),
spec.entries_per_table * sizeof(T));
spec.offset + index * spec.entries_per_table * sizeof(T), spec.entries_per_table * sizeof(T));
return std::make_pair(entries, spec.entries_per_table);
}
};
@@ -485,17 +468,14 @@ private:
} __packed_ws__(LuckTableEntry, 2);
struct Offsets {
// Each section ID's favored weapon class has different probabilities than
// those used for all other weapons. The tables are labeled with (D) for the
// default values and (F) for the favored-class values.
// Each section ID's favored weapon class has different probabilities than those used for all other weapons. The
// tables are labeled with (D) for the default values and (F) for the favored-class values.
// Note that the favored bonuses for Redria are all zero; these values are
// unused because Redria does not have a favored weapon type. Curiously,
// Yellowboze also does not have a favored weapon type, but the values for
// Note that the favored bonuses for Redria are all zero; these values are unused because Redria does not have a
// favored weapon type. Curiously, Yellowboze also does not have a favored weapon type, but the values for
// Yellowboze are not all zero.
// This table specifies how likely a special is to be upgraded or
// downgraded by one level.
// This table specifies how likely a special is to be upgraded or downgraded by one level.
// In PSO V3, the special upgrade table is:
// Viridia => (D) +1=10%, 0=60%, -1=30%
// Viridia => (F) +1=25%, 0=50%, -1=25%
@@ -519,9 +499,8 @@ private:
// Whitill => (F) +1=25%, 0=50%, -1=25%
be_uint32_t special_upgrade_prob_table_offset; // [{c, o -> (DeltaProbabilityEntry)[10][c]})
// This table specifies how likely a weapon's grind is to be upgraded or
// downgraded, and by how much. The final grind value is clamped to the
// range between 0 and the weapon's maximum grind from ItemPMT, inclusive.
// This table specifies how likely a weapon's grind is to be upgraded or downgraded, and by how much. The final
// grind value is clamped to the range between 0 and the weapon's maximum grind from ItemPMT, inclusive.
// In PSO V3, the grind delta table is:
// Viridia => (D) +3=3%, +2=7%, +1=13%, 0=60%, -1=10%, -2=7%, -3=0%
// Viridia => (F) +3=5%, +2=13%, +1=25%, 0=50%, -1=7%, -2=0%, -3=0%
@@ -545,9 +524,8 @@ private:
// Whitill => (F) +3=5%, +2=13%, +1=25%, 0=50%, -1=7%, -2=0%, -3=0%
be_uint32_t grind_delta_prob_table_offset; // [{c, o -> (DeltaProbabilityEntry)[10][c]})
// This table specifies how likely a weapon's bonuses are to be upgraded
// or downgraded, and by how much. The final bonuses are capped above at
// 100, but there is no lower limit (so negative results are possible).
// This table specifies how likely a weapon's bonuses are to be upgraded or downgraded, and by how much. The final
// bonuses are capped above at 100, but there is no lower limit (so negative results are possible).
// In PSO V3, the bonus delta table is:
// Viridia => (D) +10=5%, +5=15%, 0=60%, -5=15%, -10=5%
// Viridia => (F) +10=8%, +5=20%, 0=60%, -5=10%, -10=2%
@@ -571,11 +549,10 @@ private:
// Whitill => (F) +10=8%, +5=20%, 0=60%, -5=10%, -10=2%
be_uint32_t bonus_delta_prob_table_offset; // [{c, o -> (DeltaProbabilityEntry)[10][c]})
// There is a secondary computation done during weapon adjustment that
// appears to determine how "good" the resulting weapon is compared to its
// original state. If the result of this computation is positive, the game
// plays a jingle when the tekker result is accepted. These tables describe
// how much each delta affects this value, which we call luck.
// There is a secondary computation done during weapon adjustment that appears to determine how "good" the
// resulting weapon is compared to its original state. If the result of this computation is positive, the game
// plays a jingle when the tekker result is accepted. These tables describe how much each delta affects this value,
// which we call luck.
// In PSO V3, the special upgrade luck table is:
// +1 => +20, 0 => 0, -1 => -20
+89 -141
View File
@@ -63,14 +63,11 @@ struct WindowIndex {
return match_iter - match_offset;
};
// The data structure we want is a binary-searchable set of all strings
// starting at all possible offsets within the sliding window, and we need
// to be able to search lexicographically but insert and delete by offset.
// A std::map<std::string, size_t> would accomplish this, but would be
// horrendously inefficient: we'd have to copy strings far too much. We can
// solve this by instead storing the offset of each string as keys in a set
// and using a custom comparator to treat them as references to binary
// strings within the data.
// The data structure we want is a binary-searchable set of all strings starting at all possible offsets within the
// sliding window, and we need to be able to search lexicographically but insert and delete by offset. A
// std::map<std::string, size_t> would accomplish this, but would be horrendously inefficient: we'd have to copy
// strings far too much. We can solve this by instead storing the offset of each string as keys in a set and using a
// custom comparator to treat them as references to binary strings within the data.
bool set_comparator(size_t a, size_t b) const {
size_t max_length = min<size_t>(MaxMatchLength, this->size - max<size_t>(a, b));
size_t end_a = a + max_length;
@@ -87,11 +84,9 @@ struct WindowIndex {
};
pair<size_t, size_t> get_best_match() const {
// Find the best match from the index. It's unlikely that we'll get an
// exact match, so check the entry before the upper_bound result too.
// Note: We use upper_bound rather than lower_bound because in PRS, a
// backreference can be encoded with fewer bits if it's close to the
// decompression offset, and this makes us pick the latest match by
// Find the best match from the index. It's unlikely that we'll get an exact match, so check the entry before the
// upper_bound result too. Note: We use upper_bound rather than lower_bound because in PRS, a backreference can be
// encoded with fewer bits if it's close to the decompression offset, and this makes us pick the latest match by
// default.
size_t match_offset = 0;
size_t match_size = 0;
@@ -123,9 +118,7 @@ struct LZSSInterleavedWriter {
uint8_t next_control_bit;
uint8_t buf[0x19];
LZSSInterleavedWriter()
: buf_offset(1),
next_control_bit(1) {
LZSSInterleavedWriter() : buf_offset(1), next_control_bit(1) {
this->buf[0] = 0;
}
@@ -166,9 +159,7 @@ struct LZSSInterleavedWriter {
class ControlStreamReader {
public:
ControlStreamReader(phosg::StringReader& r)
: r(r),
bits(0x0000) {}
ControlStreamReader(phosg::StringReader& r) : r(r), bits(0x0000) {}
bool read() {
if (!(this->bits & 0x0100)) {
@@ -285,8 +276,7 @@ string prs_compress_optimal(const void* in_data_v, size_t in_size, ProgressCallb
long_window_thread.join();
extended_window_thread.join();
// For each node, populate the literal value, and the best ways to get to the
// following nodes
// For each node, populate the literal value, and the best ways to get to the following nodes
for (size_t z = 0; z < in_size; z++) {
if ((z & 0xFFF) == 0 && progress_fn) {
progress_fn(CompressPhase::CONSTRUCT_PATHS, z, in_size, 0);
@@ -441,9 +431,8 @@ string prs_compress_optimal(const string& data, ProgressCallback progress_fn) {
string prs_compress_pessimal(const void* vdata, size_t size) {
const uint8_t* in_data = reinterpret_cast<const uint8_t*>(vdata);
// The worst possible encoding we can do is a literal byte when no byte with
// the same value is within the window, or an extended copy if there is a byte
// with the same value in the window.
// The worst possible encoding we can do is a literal byte when no byte with the same value is within the window, or
// an extended copy if there is a byte with the same value in the window.
WindowIndex<0x1FFF, 1> window(in_data, size);
LZSSInterleavedWriter w;
for (size_t z = 0; z < size; z++) {
@@ -539,9 +528,8 @@ void PRSCompressor::advance() {
match_size++;
}
// If there are multiple matches of the longest length, use the latest one,
// since it's more likely that it can be expressed as a short copy instead
// of a long copy.
// If there are multiple matches of the longest length, use the latest one, since it's more likely that it can be
// expressed as a short copy instead of a long copy.
if (match_size >= (best_match_size + best_match_literals)) {
best_match_offset = match_offset;
best_match_size = match_size;
@@ -558,15 +546,13 @@ void PRSCompressor::advance() {
this->advance_literal();
}
// If there is a suitable match, write a backreference; otherwise, write a
// literal. The backreference should be encoded:
// If there is a match, write a backreference; otherwise, write a literal. The backreference should be encoded:
// - As a short copy if offset in [-0x100, -1] and size in [2, 5]
// - As a long copy if offset in [-0x1FFF, -1] and size in [3, 9]
// - As an extended copy if offset in [-0x1FFF, -1] and size in [10, 0x100]
// Technically an extended copy can be used for sizes 1-9 as well, but if
// size is 1 or 2, writing literals is better (since it uses fewer data
// bytes and control bits), and a long copy can cover sizes 3-9 (and also
// uses fewer data bytes and control bits).
// Technically an extended copy can be used for sizes 1-9 as well, but if size is 1 or 2, writing literals is better
// (since it uses fewer data bytes and control bits), and a long copy can cover sizes 3-9 (and also uses fewer data
// bytes and control bits).
ssize_t backreference_offset = best_match_offset - this->reverse_log.end_offset();
if (best_match_size < 2) {
// The match is too small; a literal would use fewer bits
@@ -576,8 +562,8 @@ void PRSCompressor::advance() {
this->advance_short_copy(backreference_offset, best_match_size);
} else if (best_match_size < 3) {
// We can't use a long copy for size 2, and it's not worth it to use an
// extended copy for this either (as noted above), so write a literal
// We can't use a long copy for size 2, and it's not worth it to use an extended copy for this either (as noted
// above), so write a literal
this->advance_literal();
} else if ((backreference_offset >= -0x1FFF) && (best_match_size <= 9)) {
@@ -655,14 +641,12 @@ string& PRSCompressor::close() {
void PRSCompressor::write_control(bool z) {
if (this->pending_control_bits & 0x0100) {
this->output.pput_u8(
this->control_byte_offset, this->pending_control_bits & 0xFF);
this->output.pput_u8(this->control_byte_offset, this->pending_control_bits & 0xFF);
this->control_byte_offset = this->output.size();
this->output.put_u8(0);
this->pending_control_bits = z ? 0x8080 : 0x8000;
} else {
this->pending_control_bits =
(this->pending_control_bits >> 1) | (z ? 0x8080 : 0x8000);
this->pending_control_bits = (this->pending_control_bits >> 1) | (z ? 0x8080 : 0x8000);
}
}
@@ -671,8 +655,7 @@ void PRSCompressor::flush_control() {
while (!(this->pending_control_bits & 0x0100)) {
this->pending_control_bits >>= 1;
}
this->output.pput_u8(
this->control_byte_offset, this->pending_control_bits & 0xFF);
this->output.pput_u8(this->control_byte_offset, this->pending_control_bits & 0xFF);
} else {
if (this->control_byte_offset != this->output.size() - 1) {
throw logic_error("data written without control bits");
@@ -681,25 +664,17 @@ void PRSCompressor::flush_control() {
}
}
string prs_compress(
const void* vdata,
size_t size,
ssize_t compression_level,
ProgressCallback progress_fn) {
string prs_compress(const void* vdata, size_t size, ssize_t compression_level, ProgressCallback progress_fn) {
PRSCompressor prs(compression_level, progress_fn);
prs.add(vdata, size);
return std::move(prs.close());
}
string prs_compress(
const string& data,
ssize_t compression_level,
ProgressCallback progress_fn) {
string prs_compress(const string& data, ssize_t compression_level, ProgressCallback progress_fn) {
return prs_compress(data.data(), data.size(), compression_level, progress_fn);
}
string prs_compress_indexed(
const void* in_data_v, size_t in_size, ProgressCallback progress_fn) {
string prs_compress_indexed(const void* in_data_v, size_t in_size, ProgressCallback progress_fn) {
const uint8_t* in_data = reinterpret_cast<const uint8_t*>(in_data_v);
LZSSInterleavedWriter w;
@@ -718,14 +693,11 @@ string prs_compress_indexed(
auto m_long = w_long.get_best_match();
auto m_extended = w_extended.get_best_match();
// Write the match that achieves the best ratio of output bytes to
// compressed bits used. To do this without floating-point math, we multiply
// the output byte count for each type of command by 468 / (command_bits),
// since 468 is the least common multiple of the number of bits for each
// command type. The command type with the highest score is the one we'll
// use, breaking ties by choosing the shorter command type. Note that the
// size of any copy type can be zero if no match was found; if no matches
// were found at all, then we can always write a literal.
// Write the match that achieves the best ratio of output bytes to compressed bits used. To do this without
// floating-point math, we multiply the output byte count for each type of command by 468 / (command_bits), since
// 468 is the least common multiple of the number of bits for each command type. The command type with the highest
// score is the one we'll use, breaking ties by choosing the shorter command type. Note that the size of any copy
// type can be zero if no match was found; if no matches were found at all, then we can always write a literal.
size_t score_literal = 52;
size_t score_short = m_short.second * 39;
size_t score_long = m_long.second * 26;
@@ -838,41 +810,30 @@ string prs_compress_indexed(const string& data, ProgressCallback progress_fn) {
PRSDecompressResult prs_decompress_with_meta(
const void* data, size_t size, size_t max_output_size, bool allow_unterminated) {
// PRS is an LZ77-based compression algorithm. Compressed data is split into
// two streams: a control stream and a data stream. The control stream is read
// one bit at a time, and the data stream is read one byte at a time. The
// streams are interleaved such that the decompressor never has to move
// backward in the input stream - when the decompressor needs a control bit
// and there are no unused bits from the previous byte of the control stream,
// it reads a byte from the input and treats it as the next 8 control bits.
// PRS is an LZ77-based compression algorithm. Compressed data is split into two streams: a control stream and a data
// stream. The control stream is read one bit at a time, and the data stream is read one byte at a time. The streams
// are interleaved such that the decompressor never has to move backward in the input stream - when the decompressor
// needs a control bit and there are no unused bits from the previous byte of the control stream, it reads a byte
// from the input and treats it as the next 8 control bits.
// There are 3 distinct commands in PRS, labeled here with their control bits:
// 1 - Literal byte. The decompressor copies one byte from the input data
// stream to the output.
// 00 - Short backreference. The decompressor reads two control bits and adds
// 2 to this value to determine the number of bytes to copy, then reads
// one byte from the data stream to determine how far back in the output
// to copy from. This byte is treated as an 8-bit negative number - so
// 0xF7, for example, means to start copying data from 9 bytes before the
// end of the output. The range must start before the end of the output,
// but the end of the range may be beyond the end of the output. In this
// case, the bytes between the beginning of the range and original end of
// the output are simply repeated.
// 01 - Long backreference. The decompressor reads two bytes from the data and
// byteswaps the resulting 16-bit value (that is, the low byte is read
// first). The start offset (again, as a negative number) is the top 13
// bits of this value; the size is the low 3 bits of this value, plus 2.
// If the size bits are all zero, an additional byte is read from the
// data stream and 1 is added to it to determine the backreference size
// (we call this an extended backreference). Therefore, the maximum
// backreference size is 256 bytes.
// Decompression ends when either there are no more input bytes to read, or
// when a long backreference is read with all zeroes in its offset field. The
// original implementation stops decompression successfully when any attempt
// to read from the input encounters the end of the stream, but newserv's
// implementation only allows this at the end of an opcode - if end-of-stream
// is encountered partway through an opcode, we throw instead, because it's
// likely the input has been truncated or is malformed in some way.
// 1 - Literal byte. The decompressor copies one byte from the input data stream to the output.
// 00 - Short backreference. The decompressor reads two control bits and adds 2 to this value to determine the number
// of bytes to copy, then reads one byte from the data stream to determine how far back in the output to copy
// from. This byte is treated as an 8-bit negative number - so 0xF7, for example, means to start copying data
// from 9 bytes before the end of the output. The range must start before the end of the output, but the end of
// the range may be beyond the end of the output. In this case, the bytes between the beginning of the range and
// original end of the output are simply repeated.
// 01 - Long backreference. The decompressor reads two bytes from the data and byteswaps the resulting 16-bit value
// (that is, the low byte is read first). The start offset (again, as a negative number) is the top 13 bits of
// this value; the size is the low 3 bits of this value, plus 2. If the size bits are all zero, an additional
// byte is read from the data stream and 1 is added to it to determine the backreference size (we call this an
// extended backreference). Therefore, the maximum backreference size is 256 bytes.
// Decompression ends when either there are no more input bytes to read, or when a long backreference is read with
// all zeroes in its offset field. The original implementation stops decompression successfully when any attempt to
// read from the input encounters the end of the stream, but newserv's implementation only allows this at the end of
// an opcode - if end-of-stream is encountered partway through an opcode, we throw instead, because it's likely the
// input has been truncated or is malformed in some way.
phosg::StringWriter w;
phosg::StringReader r(data, size);
@@ -894,10 +855,9 @@ PRSDecompressResult prs_decompress_with_meta(
ssize_t offset;
size_t count;
// Control 01 = long backreference
if (cr.read()) {
// The bits stored in the data stream are AAAAABBBCCCCCCCC, which we
// rearrange into offset = CCCCCCCCAAAAA and size = BBB.
// Control 01 = long backreference
// The bits from the data stream are AAAAABBBCCCCCCCC, which we rearrange as offset=CCCCCCCCAAAAA and size=BBB.
uint16_t a = r.get_u8();
a |= (r.get_u8() << 8);
offset = (a >> 3) | (~0x1FFF);
@@ -905,24 +865,21 @@ PRSDecompressResult prs_decompress_with_meta(
if (offset == ~0x1FFF) {
break;
}
// If the size field is zero, it's an extended backreference (size comes
// from another byte in the data stream)
// If the size field is zero, it's an extended backreference (size comes from another byte in the data stream)
count = (a & 7) ? ((a & 7) + 2) : (r.get_u8() + 1);
// Control 00 = short backreference
} else {
// Count comes from 2 bits in the control stream instead of from the
// data stream (and 2 is added). Importantly, the control stream bits
// are read first - this may involve reading another control stream
// byte, which happens before the offset is read from the data stream.
// Control 00 = short backreference
// Count comes from 2 bits in the control stream instead of from the data stream (and 2 is added). Importantly,
// the control stream bits are read first - this may involve reading another control stream byte, which happens
// before the offset is read from the data stream.
count = cr.read() << 1;
count = (count | cr.read()) + 2;
offset = r.get_u8() | (~0xFF);
}
// Copy bytes from the referenced location in the output. Importantly,
// copy only one byte at a time, in order to support ranges that cover the
// current end of the output.
// Copy bytes from the referenced location in the output. Importantly, copy only one byte at a time, in order to
// support ranges that cover the current end of the output.
size_t read_offset = w.size() + offset;
if (read_offset >= w.size()) {
throw runtime_error("backreference offset beyond beginning of output");
@@ -1069,11 +1026,10 @@ void prs_disassemble(FILE* stream, const std::string& data) {
return prs_disassemble(stream, data.data(), data.size());
}
// BC0 is a compression algorithm fairly similar to PRS, but with a simpler set
// of commands. Like PRS, there is a control stream, indicating when to copy a
// literal byte from the input and when to copy from a backreference; unlike
// PRS, there is only one type of backreference. Also, there is no stop opcode;
// the decompressor simply stops when there are no more input bytes to read.
// BC0 is a compression algorithm fairly similar to PRS, but with a simpler set of commands. Like PRS, there is a
// control stream, indicating when to copy a literal byte from the input and when to copy from a backreference; unlike
// PRS, there is only one type of backreference. Also, there is no stop opcode; the decompressor simply stops when
// there are no more input bytes to read.
struct BC0PathNode {
uint16_t memo_offset = 0;
@@ -1112,8 +1068,7 @@ string bc0_compress_optimal(
}
}
// For each node, populate the literal value, and the best ways to get to the
// following nodes
// For each node, populate the literal value, and the best ways to get to the following nodes
for (size_t z = 0; z < in_size; z++) {
if ((z & 0xFFF) == 0 && progress_fn) {
progress_fn(CompressPhase::CONSTRUCT_PATHS, z, in_size, 0);
@@ -1238,11 +1193,9 @@ string bc0_encode(const void* in_data_v, size_t in_size) {
return std::move(w.close());
}
// The BC0 decompression implementation in PSO GC is vulnerable to overflow
// attacks - there is no bounds checking on the output buffer. It is unlikely
// that this can be usefully exploited (e.g. for RCE) because the output pointer
// is loaded from memory before every byte is written, so we cannot change the
// output pointer to any arbitrary address.
// The BC0 decompression implementation in PSO GC is vulnerable to overflow attacks - there is no bounds checking on
// the output buffer. It is unlikely that this can be usefully exploited (e.g. for RCE) because the output pointer is
// loaded from memory before every byte is written, so we cannot change the output pointer to any arbitrary address.
string bc0_decompress(const string& data) {
return bc0_decompress(data.data(), data.size());
@@ -1252,22 +1205,18 @@ string bc0_decompress(const void* data, size_t size) {
phosg::StringReader r(data, size);
phosg::StringWriter w;
// Unlike PRS, BC0 uses a memo which "rolls over" every 0x1000 bytes. The
// boundaries of these "memo pages" are offset by -0x12 bytes for some reason,
// so the first output byte corresponds to position 0xFEE on the first memo
// page. Backreferences refer to offsets based on the start of memo pages; for
// example, if the current output offset is 0x1234, a backreference with
// offset 0x123 refers to the byte that was written at offset 0x1111 (because
// that byte is at offset 0x111 in the memo, because the memo rolls over every
// 0x1000 bytes and the first memo byte was 0x12 bytes before the beginning of
// the next page). The memo is initially zeroed from 0 to 0xFEE; it seems PSO
// GC doesn't initialize the last 0x12 bytes of the first memo page.
// Unlike PRS, BC0 uses a memo which "rolls over" every 0x1000 bytes. The boundaries of these "memo pages" are offset
// by -0x12 bytes for some reason, so the first output byte corresponds to position 0xFEE on the first memo page.
// Backreferences refer to offsets based on the start of memo pages; for example, if the current output offset is
// 0x1234, a backreference with offset 0x123 refers to the byte that was written at offset 0x1111 (because that byte
// is at offset 0x111 in the memo, because the memo rolls over every 0x1000 bytes and the first memo byte was 0x12
// bytes before the beginning of the next page). The memo is initially zeroed from 0 to 0xFEE; it seems PSO GC
// doesn't initialize the last 0x12 bytes of the first memo page.
parray<uint8_t, 0x1000> memo;
uint16_t memo_offset = 0x0FEE;
// The low byte of this value contains the control stream data; the high bits
// specify which low bits are valid. When the last 1 is shifted out of the
// high byte, we need to read a new control stream byte to get the next set of
// The low byte of this value contains the control stream data; the high bits specify which low bits are valid. When
// the last 1 is shifted out of the high byte, we need to read a new control stream byte to get the next set of
// control bits.
uint16_t control_stream_bits = 0x0000;
@@ -1282,14 +1231,13 @@ string bc0_decompress(const void* data, size_t size) {
}
if ((control_stream_bits & 1) == 0) {
// Control bit 0 means to perform a backreference copy. The offset and
// size are stored in two bytes in the input stream, laid out as follows:
// a1 = 0bBBBBBBBB
// a2 = 0bAAAACCCC
// The offset is the concatenation of bits AAAABBBBBBBB, which refers to
// a position in the memo; the number of bytes to copy is (CCCC + 3). The
// decompressor copies that many bytes from that offset in the memo, and
// writes them to the output and to the current position in the memo.
// Control bit 0 means to perform a backreference copy. The offset and size are stored in two bytes in the input
// stream, laid out as follows:
// a1 = 0bBBBBBBBB
// a2 = 0bAAAACCCC
// The offset is the concatenation of bits AAAABBBBBBBB, which refers to a position in the memo; the number of
// bytes to copy is (CCCC + 3). The decompressor copies that many bytes from that offset in the memo, and writes
// them to the output and to the current position in the memo.
uint8_t a1 = r.get_u8();
if (r.eof()) {
break;
@@ -1305,8 +1253,8 @@ string bc0_decompress(const void* data, size_t size) {
}
} else {
// Control bit 1 means to write a byte directly from the input to the
// output. As above, the byte is also written to the memo.
// Control bit 1 means to write a byte directly from the input to the output. As above, the byte is also written
// to the memo.
uint8_t v = r.get_u8();
w.put_u8(v);
memo[memo_offset] = v;
+35 -58
View File
@@ -22,39 +22,32 @@ const char* phosg::name_for_enum<CompressPhase>(CompressPhase v);
typedef std::function<void(CompressPhase phase, size_t input_progress, size_t input_size, size_t output_size)> ProgressCallback;
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PRS compression
////////////////////////////////////////////////////////////////////////////////
// Use this class if you need to compress from multiple input buffers, or need
// to compress multiple chunks and don't want to copy their contents
// unnecessarily. (For most common use cases, use prs_compress, below, instead.)
// To use this class, instantiate it, then call .add() one or more times, then
// call .close() and use the returned string as the compressed result.
// Use this class if you need to compress from multiple input buffers, or need to compress multiple chunks and don't
// want to copy their contents unnecessarily. (For most common use cases, use prs_compress, below, instead.) To use
// this class, instantiate it, then call .add() one or more times, then call .close() and use the returned string as
// the compressed result.
class PRSCompressor {
public:
// compression_level specifies how aggressively to search for alternate paths:
// -1: Don't perform any compression at all, but produce output that can be
// understood by prs_decompress. The output will be about 9/8 the size
// of the input.
// 0: Greedily search for the longest backreference at every point. Don't
// consider any alternate paths. Generally offers a good balance between
// speed and output size.
// 1: Consider two paths at each point when a backreference is found: using
// the backreference or ignoring it.
// 2+: Consider further chains of paths at each point. Using values 2 or
// greater for compression_level generally yields diminishing returns.
// -1: Don't perform any compression at all, but produce output that can be understood by prs_decompress. The
// output will be about 9/8 the size of the input.
// 0: Greedily search for the longest backreference at every point. Don't consider any alternate paths. Generally
// offers a good balance between speed and output size.
// 1: Consider two paths at each point when a backreference is found: using the backreference or ignoring it.
// 2+: Consider further chains of paths at each point. Using values 2 or greater for compression_level generally
// yields diminishing returns.
explicit PRSCompressor(ssize_t compression_level = 0, ProgressCallback progress_fn = nullptr);
~PRSCompressor() = default;
// Adds more input data to be compressed, which logically comes after all
// previous data provided via add() calls. Cannot be called after close() is
// called.
// Adds more input data to be compressed, which logically comes after all previous data provided via add() calls.
// Cannot be called after close() is called.
void add(const void* data, size_t size);
void add(const std::string& data);
// Ends compression and returns the complete compressed result. It's OK to
// std::move() from the returned string reference.
// Ends compression and returns the complete compressed result. It's OK to std::move() from the returned reference.
std::string& close();
// Returns the total number of bytes passed to add() calls so far.
@@ -149,36 +142,24 @@ private:
phosg::StringWriter output;
};
// These functions use PRSCompressor to compress a buffer of data. This is
// essentially a shortcut for constructing a PRSCompressor, calling .add() on
// it once, then calling .close().
// These functions use PRSCompressor to compress a buffer of data. This is essentially a shortcut for constructing a
// PRSCompressor, calling .add() on it once, then calling .close().
std::string prs_compress(
const void* vdata,
size_t size,
ssize_t compression_level = 0,
ProgressCallback progress_fn = nullptr);
const void* vdata, size_t size, ssize_t compression_level = 0, ProgressCallback progress_fn = nullptr);
std::string prs_compress(
const std::string& data,
ssize_t compression_level = 0,
ProgressCallback progress_fn = nullptr);
const std::string& data, ssize_t compression_level = 0, ProgressCallback progress_fn = nullptr);
// A faster form of prs_compress that doesn't have a tunable compression level.
std::string prs_compress_indexed(
const void* vdata,
size_t size,
ProgressCallback progress_fn = nullptr);
std::string prs_compress_indexed(
const std::string& data,
ProgressCallback progress_fn = nullptr);
std::string prs_compress_indexed(const void* vdata, size_t size, ProgressCallback progress_fn = nullptr);
std::string prs_compress_indexed(const std::string& data, ProgressCallback progress_fn = nullptr);
// Compresses data using PRS to the smallest possible output size. This function
// is slow, but produces results significantly smaller than even Sega's original
// compressor.
// Compresses data using PRS to the smallest possible output size. This function is slow, but produces results
// significantly smaller than even Sega's original compressor.
std::string prs_compress_optimal(const void* vdata, size_t size, ProgressCallback progress_fn = nullptr);
std::string prs_compress_optimal(const std::string& data, ProgressCallback progress_fn = nullptr);
// Compresses data using PRS to the LARGEST possible output size. There is no
// practical use for this function except for amusement.
// Compresses data using PRS to the LARGEST possible output size. There is no practical use for this function except
// for amusement.
std::string prs_compress_pessimal(const void* vdata, size_t size);
// Decompresses PRS-compressed data.
@@ -186,13 +167,14 @@ struct PRSDecompressResult {
std::string data;
size_t input_bytes_used;
};
PRSDecompressResult prs_decompress_with_meta(const void* data, size_t size, size_t max_output_size = 0, bool allow_unterminated = false);
PRSDecompressResult prs_decompress_with_meta(const std::string& data, size_t max_output_size = 0, bool allow_unterminated = false);
PRSDecompressResult prs_decompress_with_meta(
const void* data, size_t size, size_t max_output_size = 0, bool allow_unterminated = false);
PRSDecompressResult prs_decompress_with_meta(
const std::string& data, size_t max_output_size = 0, bool allow_unterminated = false);
std::string prs_decompress(const void* data, size_t size, size_t max_output_size = 0, bool allow_unterminated = false);
std::string prs_decompress(const std::string& data, size_t max_output_size = 0, bool allow_unterminated = false);
// Returns the decompressed size of PRS-compressed data, without actually
// decompressing it.
// Returns the decompressed size of PRS-compressed data, without actually decompressing it.
size_t prs_decompress_size(const void* data, size_t size, size_t max_output_size = 0, bool allow_unterminated = false);
size_t prs_decompress_size(const std::string& data, size_t max_output_size = 0, bool allow_unterminated = false);
@@ -200,21 +182,16 @@ size_t prs_decompress_size(const std::string& data, size_t max_output_size = 0,
void prs_disassemble(FILE* stream, const void* data, size_t size);
void prs_disassemble(FILE* stream, const std::string& data);
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BC0 compression
////////////////////////////////////////////////////////////////////////////////
// Compresses data using the BC0 algorithm. Like with PRS, the optimal variant
// is slow, but produces the smallest possible output.
std::string bc0_compress_optimal(
const void* in_data_v,
size_t in_size,
ProgressCallback progress_fn = nullptr);
// Compresses data using the BC0 algorithm. Like with PRS, the optimal variant is slow, but produces the smallest
// possible output.
std::string bc0_compress(const std::string& data, ProgressCallback progress_fn = nullptr);
std::string bc0_compress(const void* in_data_v, size_t in_size, ProgressCallback progress_fn = nullptr);
std::string bc0_compress_optimal(const void* in_data_v, size_t in_size, ProgressCallback progress_fn = nullptr);
// Encodes data in a BC0-compatible format without compression (similar to using
// compression_level=-1 with prs_compress).
// Encodes data in a BC0-compatible format without compression (similar to compression_level=-1 in prs_compress).
std::string bc0_encode(const void* in_data_v, size_t in_size);
// Decompresses BC0-compressed data.
+724 -1106
View File
File diff suppressed because it is too large Load Diff
+8 -12
View File
@@ -5,20 +5,16 @@
#include <string>
#include <unordered_map>
// dc_serial_number_is_valid_slow is Sega's implementation;
// dc_serial_number_is_valid_fast produces identical results but is between 3000
// and 7500 times faster, depending on the compiler's optimization level.
bool dc_serial_number_is_valid_slow(
const std::string& s, uint8_t domain, uint8_t subdomain = 0xFF);
bool dc_serial_number_is_valid_fast(
const std::string& s, uint8_t domain, uint8_t subdomain = 0xFF);
bool dc_serial_number_is_valid_fast(
uint32_t serial_number, uint8_t domain, uint8_t subdomain = 0xFF);
bool decoded_dc_serial_number_is_valid_fast(
uint32_t serial_number, uint8_t domain, uint8_t subdomain = 0xFF);
// dc_serial_number_is_valid_slow is Sega's implementation; dc_serial_number_is_valid_fast produces identical results
// but is between 3000 and 7500 times faster, depending on the compiler's optimization level.
bool dc_serial_number_is_valid_slow(const std::string& s, uint8_t domain, uint8_t subdomain = 0xFF);
bool dc_serial_number_is_valid_fast(const std::string& s, uint8_t domain, uint8_t subdomain = 0xFF);
bool dc_serial_number_is_valid_fast(uint32_t serial_number, uint8_t domain, uint8_t subdomain = 0xFF);
bool decoded_dc_serial_number_is_valid_fast(uint32_t serial_number, uint8_t domain, uint8_t subdomain = 0xFF);
std::string generate_dc_serial_number(uint8_t domain, uint8_t subdomain = 0xFF);
std::unordered_map<uint32_t, std::string> generate_all_dc_serial_numbers(uint8_t domain = 0xFF, uint8_t subdomain = 0xFF);
std::unordered_map<uint32_t, std::string> generate_all_dc_serial_numbers(
uint8_t domain = 0xFF, uint8_t subdomain = 0xFF);
struct DCSerialNumberIterator {
bool started = false;
+3 -5
View File
@@ -544,8 +544,8 @@ asio::awaitable<void> DownloadSession::on_message(Channel::Message& msg) {
}
case 0x67: {
// Technically we should assign item IDs here, but the server will never
// be able to see that we didn't, so we don't bother
// Technically we should assign item IDs here, but the server will never be able to see that we didn't, so we
// don't bother
const auto& game_config = this->game_configs[this->current_game_config_index];
if (this->version == Version::PC_V2) {
@@ -688,9 +688,7 @@ asio::awaitable<void> DownloadSession::on_message(Channel::Message& msg) {
}
auto& f = this->open_files.at(cmd.filename.decode());
size_t block_offset = msg.flag * 0x400;
size_t allowed_block_size = (block_offset < f.total_size)
? min<size_t>(f.total_size - block_offset, 0x400)
: 0;
size_t allowed_block_size = (block_offset < f.total_size) ? min<size_t>(f.total_size - block_offset, 0x400) : 0;
size_t data_size = min<size_t>(cmd.data_size, allowed_block_size);
size_t block_end_offset = block_offset + data_size;
if (block_end_offset > f.data.size()) {
+173 -174
View File
@@ -13,139 +13,145 @@ static constexpr uint8_t EP1 = EnemyTypeDefinition::Flag::VALID_EP1;
static constexpr uint8_t EP2 = EnemyTypeDefinition::Flag::VALID_EP2;
static constexpr uint8_t EP4 = EnemyTypeDefinition::Flag::VALID_EP4;
static constexpr uint8_t RARE = EnemyTypeDefinition::Flag::IS_RARE;
static constexpr uint8_t BOSS = EnemyTypeDefinition::Flag::IS_BOSS;
static constexpr uint8_t NONE = 0xFF;
static const vector<EnemyTypeDefinition> type_defs{
// clang-format off
// TYPE FLAGS RT BP ENUM NAME IN-GAME NAME ULTIMATE NAME
{EnemyType::UNKNOWN, 0, 0xFF, 0xFF, "UNKNOWN", "__UNKNOWN__", nullptr},
{EnemyType::NONE, 0, 0xFF, 0xFF, "NONE", "__NONE__", nullptr},
{EnemyType::NON_ENEMY_NPC, EP1 | EP2 | EP4, 0xFF, 0xFF, "NON_ENEMY_NPC", "__NPC__", nullptr},
{EnemyType::AL_RAPPY, EP1 | RARE, 0x06, 0x19, "AL_RAPPY", "Al Rappy", "Pal Rappy"},
{EnemyType::ASTARK, EP4, 0x41, 0x09, "ASTARK", "Astark", nullptr},
{EnemyType::BA_BOOTA, EP4, 0x4F, 0x03, "BA_BOOTA", "Ba Boota", nullptr},
{EnemyType::BARBA_RAY, EP2, 0x49, 0x0F, "BARBA_RAY", "Barba Ray", nullptr},
{EnemyType::BARBAROUS_WOLF, EP1 | EP2, 0x08, 0x03, "BARBAROUS_WOLF", "Barbarous Wolf", "Gulgus-gue"},
{EnemyType::BEE_L, EP1 | EP2, 0xFF, 0xFF, "BEE_L", "Bee L", "Gee L"},
{EnemyType::BEE_R, EP1 | EP2, 0xFF, 0xFF, "BEE_R", "Bee R", "Gee R"},
{EnemyType::BOOMA, EP1, 0x09, 0x4B, "BOOMA", "Booma", "Bartle"},
{EnemyType::BOOTA, EP4, 0x4D, 0x00, "BOOTA", "Boota", nullptr},
{EnemyType::BULCLAW, EP1, 0x28, 0x1F, "BULCLAW", "Bulclaw", nullptr},
{EnemyType::BULK, EP1, 0x27, 0x1F, "BULK", "Bulk", nullptr},
{EnemyType::CANADINE, EP1, 0x1C, 0x07, "CANADINE", "Canadine", "Canabin"},
{EnemyType::CANADINE_GROUP, EP1, 0x1C, 0x08, "CANADINE_GROUP", "Canadine (group)", "Canabin (group)"},
{EnemyType::CANANE, EP1, 0x1D, 0x09, "CANANE", "Canane", "Canune"},
{EnemyType::CHAOS_BRINGER, EP1, 0x24, 0x0D, "CHAOS_BRINGER", "Chaos Bringer", "Dark Bringer"},
{EnemyType::CHAOS_SORCERER, EP1 | EP2, 0x1F, 0x0A, "CHAOS_SORCERER", "Chaos Sorceror", "Gran Sorceror"},
{EnemyType::CLAW, EP1, 0x26, 0x20, "CLAW", "Claw", nullptr},
{EnemyType::DARK_BELRA, EP1 | EP2, 0x25, 0x0E, "DARK_BELRA", "Dark Belra", "Indi Belra"},
{EnemyType::DARK_FALZ_1, EP1, 0xFF, 0x36, "DARK_FALZ_1", "Dark Falz (phase 1)", nullptr},
{EnemyType::DARK_FALZ_2, EP1, 0x2F, 0x37, "DARK_FALZ_2", "Dark Falz (phase 2)", nullptr},
{EnemyType::DARK_FALZ_3, EP1, 0x2F, 0x38, "DARK_FALZ_3", "Dark Falz (phase 3)", nullptr},
{EnemyType::DARK_GUNNER, EP1, 0x22, 0x1E, "DARK_GUNNER", "Dark Gunner", nullptr},
{EnemyType::DARK_GUNNER_CONTROL, EP1, 0xFF, 0xFF, "DARK_GUNNER_CONTROL", "Dark Gunner (control)", nullptr},
{EnemyType::DARVANT, EP1, 0xFF, 0x35, "DARVANT", "Darvant", nullptr},
{EnemyType::DARVANT_ULTIMATE, EP1, 0xFF, 0x39, "DARVANT_ULTIMATE", "Darvant (ultimate)", nullptr},
{EnemyType::DE_ROL_LE, EP1, 0x2D, 0x0F, "DE_ROL_LE", "De Rol Le", "Dal Ral Lie"},
{EnemyType::DE_ROL_LE_BODY, EP1, 0xFF, 0xFF, "DE_ROL_LE_BODY", "De Rol Le (body)", "Dal Ral Lie (body)"},
{EnemyType::DE_ROL_LE_MINE, EP1, 0xFF, 0xFF, "DE_ROL_LE_MINE", "De Rol Le (mine)", "Dal Ral Lie (mine)"},
{EnemyType::DEATH_GUNNER, EP1, 0x23, 0x1E, "DEATH_GUNNER", "Death Gunner", nullptr},
{EnemyType::DEL_LILY, EP2, 0x53, 0x25, "DEL_LILY", "Del Lily", nullptr},
{EnemyType::DEL_RAPPY_CRATER, EP4, 0x57, 0x06, "DEL_RAPPY_CRATER", "Del Rappy (crater)", nullptr},
{EnemyType::DEL_RAPPY_DESERT, EP4, 0x58, 0x18, "DEL_RAPPY_DESERT", "Del Rappy (desert)", nullptr},
{EnemyType::DELBITER, EP2, 0x48, 0x0D, "DELBITER", "Delbiter", nullptr},
{EnemyType::DELDEPTH, EP2, 0x47, 0x30, "DELDEPTH", "Deldepth", nullptr},
{EnemyType::DELSABER, EP1 | EP2, 0x1E, 0x52, "DELSABER", "Delsaber", nullptr},
{EnemyType::DIMENIAN, EP1 | EP2, 0x29, 0x53, "DIMENIAN", "Dimenian", "Arlan"},
{EnemyType::DOLMDARL, EP2, 0x41, 0x50, "DOLMDARL", "Dolmdarl", nullptr},
{EnemyType::DOLMOLM, EP2, 0x40, 0x4F, "DOLMOLM", "Dolmolm", nullptr},
{EnemyType::DORPHON, EP4, 0x50, 0x0F, "DORPHON", "Dorphon", nullptr},
{EnemyType::DORPHON_ECLAIR, EP4 | RARE, 0x51, 0x10, "DORPHON_ECLAIR", "Dorphon Eclair", nullptr},
{EnemyType::DRAGON, EP1, 0x2C, 0x12, "DRAGON", "Dragon", "Sil Dragon"},
{EnemyType::DUBCHIC, EP1 | EP2, 0x18, 0x1B, "DUBCHIC", "Dubchic", "Dubchich"},
{EnemyType::DUBWITCH, EP1 | EP2, 0xFF, 0xFF, "DUBWITCH", "Dubwitch", "Duvuik"},
{EnemyType::EGG_RAPPY, EP2, 0x51, 0x19, "EGG_RAPPY", "Egg Rappy", nullptr},
{EnemyType::EPSIGARD, EP2, 0xFF, 0xFF, "EPSIGARD", "Episgard", nullptr},
{EnemyType::EPSILON, EP2, 0x54, 0x23, "EPSILON", "Epsilon", nullptr},
{EnemyType::EVIL_SHARK, EP1, 0x10, 0x4F, "EVIL_SHARK", "Evil Shark", "Vulmer"},
{EnemyType::GAEL_OR_GIEL, EP2, 0xFF, 0x2E, "GAEL", "Gael/Giel", nullptr},
{EnemyType::GAL_GRYPHON, EP2, 0x4D, 0x1E, "GAL_GRYPHON", "Gal Gryphon", nullptr},
{EnemyType::GARANZ, EP1 | EP2, 0x19, 0x1D, "GARANZ", "Garanz", "Baranz"},
{EnemyType::GEE, EP2, 0x36, 0x07, "GEE", "Gee", nullptr},
{EnemyType::GI_GUE, EP2, 0x37, 0x1A, "GI_GUE", "Gi Gue", nullptr},
{EnemyType::GIBBLES, EP2, 0x3D, 0x3D, "GIBBLES", "Gibbles", nullptr},
{EnemyType::GIGOBOOMA, EP1, 0x0B, 0x4D, "GIGOBOOMA", "Gigobooma", "Tollaw"},
{EnemyType::GILLCHIC, EP1 | EP2, 0x32, 0x1C, "GILLCHIC", "Gillchic", "Gillchich"},
{EnemyType::GIRTABLULU, EP4, 0x48, 0x1F, "GIRTABLULU", "Girtablulu", nullptr},
{EnemyType::GOBOOMA, EP1, 0x0A, 0x4C, "GOBOOMA", "Gobooma", "Barble"},
{EnemyType::GOL_DRAGON, EP2, 0x4C, 0x12, "GOL_DRAGON", "Gol Dragon", nullptr},
{EnemyType::GORAN, EP4, 0x52, 0x11, "GORAN", "Goran", nullptr},
{EnemyType::GORAN_DETONATOR, EP4, 0x53, 0x13, "GORAN_DETONATOR", "Goran Detonator", nullptr},
{EnemyType::GRASS_ASSASSIN, EP1 | EP2, 0x0C, 0x4E, "GRASS_ASSASSIN", "Grass Assassin", "Crimson Assassin"},
{EnemyType::GUIL_SHARK, EP1, 0x12, 0x51, "GUIL_SHARK", "Guil Shark", "Melqueek"},
{EnemyType::HALLO_RAPPY, EP2, 0x50, 0x19, "HALLO_RAPPY", "Hallo Rappy", nullptr},
{EnemyType::HIDOOM, EP1 | EP2, 0x17, 0x32, "HIDOOM", "Hidoom", nullptr},
{EnemyType::HILDEBEAR, EP1 | EP2, 0x01, 0x49, "HILDEBEAR", "Hildebear", "Hildelt"},
{EnemyType::HILDEBLUE, EP1 | EP2 | RARE, 0x02, 0x4A, "HILDEBLUE", "Hildeblue", "Hildetorr"},
{EnemyType::ILL_GILL, EP2, 0x52, 0x26, "ILL_GILL", "Ill Gill", nullptr},
{EnemyType::KONDRIEU, EP4 | RARE, 0x5B, 0x2A, "KONDRIEU", "Kondrieu", nullptr},
{EnemyType::LA_DIMENIAN, EP1 | EP2, 0x2A, 0x54, "LA_DIMENIAN", "La Dimenian", "Merlan"},
{EnemyType::LOVE_RAPPY, EP2, 0x33, 0x19, "LOVE_RAPPY", "Love Rappy", nullptr},
{EnemyType::MERICARAND, EP2, 0x38, 0x3A, "MERICARAND", "Mericarand", nullptr},
{EnemyType::MERICAROL, EP2, 0x38, 0x3A, "MERICAROL", "Mericarol", nullptr},
{EnemyType::MERICUS, EP2 | RARE, 0x3A, 0x46, "MERICUS", "Mericus", nullptr},
{EnemyType::MERIKLE, EP2 | RARE, 0x39, 0x45, "MERIKLE", "Merikle", nullptr},
{EnemyType::MERILLIA, EP2, 0x34, 0x4B, "MERILLIA", "Merillia", nullptr},
{EnemyType::MERILTAS, EP2, 0x35, 0x4C, "MERILTAS", "Meriltas", nullptr},
{EnemyType::MERISSA_A, EP4, 0x46, 0x19, "MERISSA_A", "Merissa A", nullptr},
{EnemyType::MERISSA_AA, EP4 | RARE, 0x47, 0x1A, "MERISSA_AA", "Merissa AA", nullptr},
{EnemyType::MIGIUM, EP1 | EP2, 0x16, 0x33, "MIGIUM", "Migium", nullptr},
{EnemyType::MONEST, EP1 | EP2, 0x04, 0x01, "MONEST", "Monest", "Mothvist"},
{EnemyType::MORFOS, EP2, 0x42, 0x40, "MORFOS", "Morfos", nullptr},
{EnemyType::MOTHMANT, EP1 | EP2, 0x03, 0x00, "MOTHMANT", "Mothmant", "Mothvert"},
{EnemyType::NANO_DRAGON, EP1, 0x0F, 0x1A, "NANO_DRAGON", "Nano Dragon", nullptr},
{EnemyType::NAR_LILY, EP1 | EP2 | RARE, 0x0E, 0x05, "NAR_LILY", "Nar Lily", "Mil Lily"},
{EnemyType::OLGA_FLOW_1, EP2, 0xFF, 0x2B, "OLGA_FLOW_1", "Olga Flow (phase 1)", nullptr},
{EnemyType::OLGA_FLOW_2, EP2, 0x4E, 0x2C, "OLGA_FLOW_2", "Olga Flow (phase 2)", nullptr},
{EnemyType::PAL_SHARK, EP1, 0x11, 0x50, "PAL_SHARK", "Pal Shark", "Govulmer"},
{EnemyType::PAN_ARMS, EP1 | EP2, 0x15, 0x31, "PAN_ARMS", "Pan Arms", nullptr},
{EnemyType::PAZUZU_CRATER, EP4 | RARE, 0x4B, 0x08, "PAZUZU_CRATER", "Pazuzu (crater)", nullptr},
{EnemyType::PAZUZU_DESERT, EP4 | RARE, 0x4C, 0x1C, "PAZUZU_DESERT", "Pazuzu (desert)", nullptr},
{EnemyType::PIG_RAY, EP2, 0xFF, 0xFF, "PIG_RAY", "Pig Ray", nullptr},
{EnemyType::POFUILLY_SLIME, EP1, 0x13, 0x30, "POFUILLY_SLIME", "Pofuilly Slime", nullptr},
{EnemyType::POUILLY_SLIME, EP1 | RARE, 0x14, 0x2F, "POUILLY_SLIME", "Pouilly Slime", nullptr},
{EnemyType::POISON_LILY, EP1 | EP2, 0x0D, 0x04, "POISON_LILY", "Poison Lily", "Ob Lily"},
{EnemyType::PYRO_GORAN, EP4, 0x54, 0x12, "PYRO_GORAN", "Pyro Goran", nullptr},
{EnemyType::RAG_RAPPY, EP1 | EP2, 0x05, 0x18, "RAG_RAPPY", "Rag Rappy", "El Rappy"},
{EnemyType::RECOBOX, EP2, 0x43, 0x41, "RECOBOX", "Recobox", nullptr},
{EnemyType::RECON, EP2, 0x44, 0x42, "RECON", "Recon", nullptr},
{EnemyType::SAINT_MILION, EP4, 0x59, 0x22, "SAINT_MILION", "Saint-Milion", nullptr},
{EnemyType::SAINT_RAPPY, EP2, 0x4F, 0x19, "SAINT_RAPPY", "Saint Rappy", nullptr},
{EnemyType::SAND_RAPPY_CRATER, EP4, 0x55, 0x05, "SAND_RAPPY_CRATER", "Sand Rappy (crater)", nullptr},
{EnemyType::SAND_RAPPY_DESERT, EP4, 0x56, 0x17, "SAND_RAPPY_DESERT", "Sand Rappy (desert)", nullptr},
{EnemyType::SATELLITE_LIZARD_CRATER, EP4, 0x44, 0x0D, "SATELLITE_LIZARD_CRATER", "Satellite Lizard (crater)", nullptr},
{EnemyType::SATELLITE_LIZARD_DESERT, EP4, 0x45, 0x1D, "SATELLITE_LIZARD_DESERT", "Satellite Lizard (desert)", nullptr},
{EnemyType::SAVAGE_WOLF, EP1 | EP2, 0x07, 0x02, "SAVAGE_WOLF", "Savage Wolf", "Gulgus"},
{EnemyType::SHAMBERTIN, EP4, 0x5A, 0x26, "SHAMBERTIN", "Shambertin", nullptr},
{EnemyType::SINOW_BEAT, EP1, 0x1A, 0x06, "SINOW_BEAT", "Sinow Beat", "Sinow Blue"},
{EnemyType::SINOW_BERILL, EP2, 0x3E, 0x06, "SINOW_BERILL", "Sinow Berill", nullptr},
{EnemyType::SINOW_GOLD, EP1, 0x1B, 0x13, "SINOW_GOLD", "Sinow Gold", "Sinow Red"},
{EnemyType::SINOW_SPIGELL, EP2, 0x3F, 0x13, "SINOW_SPIGELL", "Sinow Spigell", nullptr},
{EnemyType::SINOW_ZELE, EP2, 0x46, 0x44, "SINOW_ZELE", "Sinow Zele", nullptr},
{EnemyType::SINOW_ZOA, EP2, 0x45, 0x43, "SINOW_ZOA", "Sinow Zoa", nullptr},
{EnemyType::SO_DIMENIAN, EP1 | EP2, 0x2B, 0x55, "SO_DIMENIAN", "So Dimenian", "Del-D"},
{EnemyType::UL_GIBBON, EP2, 0x3B, 0x3B, "UL_GIBBON", "Ul Gibbon", nullptr},
{EnemyType::VOL_OPT_1, EP1, 0xFF, 0xFF, "VOL_OPT_1", "Vol Opt (phase 1)", "Vol Opt ver.2 (phase 1)"},
{EnemyType::VOL_OPT_2, EP1, 0x2E, 0x25, "VOL_OPT_2", "Vol Opt (phase 2)", "Vol Opt ver.2 (phase 2)"},
{EnemyType::VOL_OPT_AMP, EP1, 0xFF, 0xFF, "VOL_OPT_AMP", "Vol Opt (amp)", "Vol Opt ver.2 (amp)"},
{EnemyType::VOL_OPT_CORE, EP1, 0xFF, 0xFF, "VOL_OPT_CORE", "Vol Opt (core)", "Vol Opt ver.2 (core)"},
{EnemyType::VOL_OPT_MONITOR, EP1, 0xFF, 0xFF, "VOL_OPT_MONITOR", "Vol Opt (monitor)", "Vol Opt ver.2 (monitor)"},
{EnemyType::VOL_OPT_PILLAR, EP1, 0xFF, 0xFF, "VOL_OPT_PILLAR", "Vol Opt (pillar)", "Vol Opt ver.2 (pillar)"},
{EnemyType::YOWIE_CRATER, EP4, 0x42, 0x0E, "YOWIE_CRATER", "Yowie (crater)", nullptr},
{EnemyType::YOWIE_DESERT, EP4, 0x43, 0x1E, "YOWIE_DESERT", "Yowie (desert)", nullptr},
{EnemyType::ZE_BOOTA, EP4, 0x4E, 0x01, "ZE_BOOTA", "Ze Boota", nullptr},
{EnemyType::ZOL_GIBBON, EP2, 0x3C, 0x3C, "ZOL_GIBBON", "Zol Gibbon", nullptr},
{EnemyType::ZU_CRATER, EP4, 0x49, 0x07, "ZU_CRATER", "Zu (crater)", nullptr},
{EnemyType::ZU_DESERT, EP4, 0x4A, 0x1B, "ZU_DESERT", "Zu (desert)", nullptr},
// TYPE FLAGS RT OLDRT BP-STATS BP-ATTACK BP-RESIST ENUM NAME IN-GAME NAME ULTIMATE NAME
{EnemyType::UNKNOWN, 0, NONE, NONE, {}, {}, {}, "UNKNOWN", "__UNKNOWN__", nullptr},
{EnemyType::NONE, 0, NONE, NONE, {}, {}, {}, "NONE", "__NONE__", nullptr},
{EnemyType::NON_ENEMY_NPC, EP1 | EP2 | EP4, NONE, NONE, {}, {}, {}, "NON_ENEMY_NPC", "__NPC__", nullptr},
{EnemyType::AL_RAPPY, EP1 | RARE, 0x06, 0x06, {0x19}, {0x19}, {0x19}, "AL_RAPPY", "Al Rappy", "Pal Rappy"},
{EnemyType::ASTARK, EP4, 0x58, 0x41, {0x09}, {0x0B, 0x0A, 0x0C}, {0x09}, "ASTARK", "Astark", nullptr},
{EnemyType::BA_BOOTA, EP4, 0x62, 0x4F, {0x03}, {0x03, 0x02, 0x04}, {0x03}, "BA_BOOTA", "Ba Boota", nullptr},
{EnemyType::BARBA_RAY, EP2 | BOSS, 0x49, 0x49, {0x0F}, {0x0F}, {0x0F}, "BARBA_RAY", "Barba Ray", nullptr},
{EnemyType::BARBA_RAY_JOINT, EP2 | BOSS, 0x49, 0x49, {0x10}, {0x0F}, {0x10}, "BARBA_RAY_JOINT", "Barba Ray (joint)", nullptr},
{EnemyType::BARBAROUS_WOLF, EP1 | EP2, 0x08, 0x08, {0x03}, {0x03}, {0x03}, "BARBAROUS_WOLF", "Barbarous Wolf", "Gulgus-gue"},
{EnemyType::BEE_L, EP1 | EP2, NONE, NONE, {0x0C}, {0x0C}, {0x0C}, "BEE_L", "Bee L", "Gee L"},
{EnemyType::BEE_R, EP1 | EP2, NONE, NONE, {0x0B}, {0x0B}, {0x0B}, "BEE_R", "Bee R", "Gee R"},
{EnemyType::BOOMA, EP1, 0x09, 0x09, {0x4B}, {0x4E}, {0x4A}, "BOOMA", "Booma", "Bartle"},
{EnemyType::BOOTA, EP4, 0x60, 0x4D, {0x00}, {0x00, 0x02, 0x04}, {0x00}, "BOOTA", "Boota", nullptr},
{EnemyType::BULCLAW, EP1, 0x28, 0x28, {0x1F}, {0x1F}, {0x1F}, "BULCLAW", "Bulclaw", nullptr},
{EnemyType::BULK, EP1, 0x27, 0x27, {0x1F}, {0x1F}, {0x1F}, "BULK", "Bulk", nullptr},
{EnemyType::CANADINE, EP1, 0x1C, 0x1C, {0x07}, {0x07}, {0x07}, "CANADINE", "Canadine", "Canabin"},
{EnemyType::CANADINE_GROUP, EP1, 0x1C, 0x1C, {0x08}, {0x08}, {0x08}, "CANADINE_GROUP", "Canadine (group)", "Canabin (group)"},
{EnemyType::CANANE, EP1, 0x1D, 0x1D, {0x09}, {0x09}, {0x09}, "CANANE", "Canane", "Canune"},
{EnemyType::CHAOS_BRINGER, EP1, 0x24, 0x24, {0x0D}, {0x0D}, {0x0D}, "CHAOS_BRINGER", "Chaos Bringer", "Dark Bringer"},
{EnemyType::CHAOS_SORCERER, EP1 | EP2, 0x1F, 0x1F, {0x0A}, {0x0A}, {0x0A}, "CHAOS_SORCERER", "Chaos Sorceror", "Gran Sorceror"},
{EnemyType::CLAW, EP1, 0x26, 0x26, {0x20}, {0x20}, {0x20}, "CLAW", "Claw", nullptr},
{EnemyType::DARK_BELRA, EP1 | EP2, 0x25, 0x25, {0x0E}, {0x0E, 0x13}, {0x0E}, "DARK_BELRA", "Dark Belra", "Indi Belra"},
{EnemyType::DARK_FALZ_1, EP1 | BOSS, NONE, NONE, {0x36}, {0x36}, {0x36}, "DARK_FALZ_1", "Dark Falz (phase 1)", nullptr},
{EnemyType::DARK_FALZ_2, EP1 | BOSS, 0x2F, 0x2F, {0x37}, {0x37}, {0x37}, "DARK_FALZ_2", "Dark Falz (phase 2)", nullptr},
{EnemyType::DARK_FALZ_3, EP1 | BOSS, 0x2F, 0x2F, {0x38}, {0x38}, {0x38}, "DARK_FALZ_3", "Dark Falz (phase 3)", nullptr},
{EnemyType::DARK_GUNNER, EP1, 0x22, 0x22, {0x1E}, {0x1E}, {0x1E}, "DARK_GUNNER", "Dark Gunner", nullptr},
{EnemyType::DARK_GUNNER_CONTROL, EP1, NONE, NONE, {}, {}, {}, "DARK_GUNNER_CONTROL", "Dark Gunner (control)", nullptr},
{EnemyType::DARVANT, EP1, NONE, NONE, {0x35}, {0x35}, {0x35}, "DARVANT", "Darvant", nullptr},
{EnemyType::DE_ROL_LE, EP1 | BOSS, 0x2D, 0x2D, {0x0F}, {0x0F}, {0x0F}, "DE_ROL_LE", "De Rol Le", "Dal Ral Lie"},
{EnemyType::DE_ROL_LE_BODY, EP1 | BOSS, NONE, NONE, {0x10}, {0x0F}, {0x10}, "DE_ROL_LE_BODY", "De Rol Le (body)", "Dal Ral Lie (body)"},
{EnemyType::DE_ROL_LE_MINE, EP1 | BOSS, NONE, NONE, {0x11}, {0x0F}, {0x11}, "DE_ROL_LE_MINE", "De Rol Le (mine)", "Dal Ral Lie (mine)"},
{EnemyType::DEATH_GUNNER, EP1, 0x23, 0x23, {0x1E}, {0x1E}, {0x1E}, "DEATH_GUNNER", "Death Gunner", nullptr},
{EnemyType::DEL_LILY, EP2, 0x53, 0x53, {0x25}, {0x25}, {0x25}, "DEL_LILY", "Del Lily", nullptr},
{EnemyType::DEL_RAPPY_CRATER, EP4, 0x69, 0x57, {0x06}, {0x06}, {0x06}, "DEL_RAPPY_CRATER", "Del Rappy (crater)", nullptr},
{EnemyType::DEL_RAPPY_DESERT, EP4, 0x69, 0x58, {0x18}, {0x18}, {0x18}, "DEL_RAPPY_DESERT", "Del Rappy (desert)", nullptr},
{EnemyType::DELBITER, EP2, 0x48, 0x48, {0x0D}, {0x0D}, {0x0D}, "DELBITER", "Delbiter", nullptr},
{EnemyType::DELDEPTH, EP2, 0x47, 0x47, {0x30}, {0x30}, {0x30}, "DELDEPTH", "Deldepth", nullptr},
{EnemyType::DELSABER, EP1 | EP2, 0x1E, 0x1E, {0x52}, {0x57, 0x58, 0x59}, {0x51}, "DELSABER", "Delsaber", nullptr},
{EnemyType::DIMENIAN, EP1 | EP2, 0x29, 0x29, {0x53}, {0x5A}, {0x52}, "DIMENIAN", "Dimenian", "Arlan"},
{EnemyType::DOLMDARL, EP2, 0x41, 0x41, {0x50}, {0x55}, {0x4F}, "DOLMDARL", "Dolmdarl", nullptr},
{EnemyType::DOLMOLM, EP2, 0x40, 0x40, {0x4F}, {0x54}, {0x4E}, "DOLMOLM", "Dolmolm", nullptr},
{EnemyType::DORPHON, EP4, 0x63, 0x50, {0x0F}, {0x0F}, {0x0F}, "DORPHON", "Dorphon", nullptr},
{EnemyType::DORPHON_ECLAIR, EP4 | RARE, 0x64, 0x51, {0x10}, {0x10}, {0x10}, "DORPHON_ECLAIR", "Dorphon Eclair", nullptr},
{EnemyType::DRAGON, EP1 | BOSS, 0x2C, 0x2C, {0x12}, {0x12, 0x14, 0x15, 0x16, 0x17}, {0x12}, "DRAGON", "Dragon", "Sil Dragon"},
{EnemyType::DUBCHIC, EP1 | EP2, 0x18, 0x18, {0x1B}, {0x1B}, {0x1B}, "DUBCHIC", "Dubchic", "Dubchich"},
{EnemyType::DUBWITCH, EP1 | EP2, NONE, NONE, {}, {}, {}, "DUBWITCH", "Dubwitch", "Duvuik"},
{EnemyType::EGG_RAPPY, EP2, 0x51, 0x51, {0x19}, {0x19}, {0x19}, "EGG_RAPPY", "Egg Rappy", nullptr},
{EnemyType::EPSIGARD, EP2, NONE, NONE, {0x24}, {0x24}, {0x24}, "EPSIGARD", "Episgard", nullptr},
{EnemyType::EPSILON, EP2, 0x54, 0x54, {0x23}, {0x23}, {0x23}, "EPSILON", "Epsilon", nullptr},
{EnemyType::EVIL_SHARK, EP1, 0x10, 0x10, {0x4F}, {0x54}, {0x4E}, "EVIL_SHARK", "Evil Shark", "Vulmer"},
{EnemyType::GAEL_OR_GIEL, EP2, NONE, NONE, {0x2E}, {0x2E}, {0x2E}, "GAEL_OR_GIEL", "Gael/Giel", nullptr},
{EnemyType::GAL_GRYPHON, EP2 | BOSS, 0x4D, 0x4D, {0x1E}, {0x1E, 0x1F, 0x20, 0x21, 0x22}, {0x1E}, "GAL_GRYPHON", "Gal Gryphon", nullptr},
{EnemyType::GARANZ, EP1 | EP2, 0x19, 0x19, {0x1D}, {0x1D}, {0x1D}, "GARANZ", "Garanz", "Baranz"},
{EnemyType::GEE, EP2, 0x36, 0x36, {0x07}, {0x07}, {0x07}, "GEE", "Gee", nullptr},
{EnemyType::GI_GUE, EP2, 0x37, 0x37, {0x1A}, {0x1A}, {0x1A}, "GI_GUE", "Gi Gue", nullptr},
{EnemyType::GIBBLES, EP2, 0x3D, 0x3D, {0x3D}, {0x3D, 0x3E, 0x3F}, {0x3D}, "GIBBLES", "Gibbles", nullptr},
{EnemyType::GIGOBOOMA, EP1, 0x0B, 0x0B, {0x4D}, {0x50}, {0x4C}, "GIGOBOOMA", "Gigobooma", "Tollaw"},
{EnemyType::GILLCHIC, EP1 | EP2, 0x32, 0x32, {0x1C}, {0x1C}, {0x1C}, "GILLCHIC", "Gillchic", "Gillchich"},
{EnemyType::GIRTABLULU, EP4, 0x5D, 0x48, {0x1F}, {0x1F}, {0x1F}, "GIRTABLULU", "Girtablulu", nullptr},
{EnemyType::GOBOOMA, EP1, 0x0A, 0x0A, {0x4C}, {0x4F}, {0x4B}, "GOBOOMA", "Gobooma", "Barble"},
{EnemyType::GOL_DRAGON, EP2 | BOSS, 0x4C, 0x4C, {0x12}, {0x12, 0x14, 0x15, 0x16, 0x17}, {0x12}, "GOL_DRAGON", "Gol Dragon", nullptr},
{EnemyType::GORAN, EP4, 0x65, 0x52, {0x11}, {0x11, 0x14}, {0x11}, "GORAN", "Goran", nullptr},
{EnemyType::GORAN_DETONATOR, EP4, 0x66, 0x53, {0x13}, {0x13, 0x16}, {0x13}, "GORAN_DETONATOR", "Goran Detonator", nullptr},
{EnemyType::GRASS_ASSASSIN, EP1 | EP2, 0x0C, 0x0C, {0x4E}, {0x51, 0x52, 0x53}, {0x4D}, "GRASS_ASSASSIN", "Grass Assassin", "Crimson Assassin"},
{EnemyType::GUIL_SHARK, EP1, 0x12, 0x12, {0x51}, {0x56}, {0x50}, "GUIL_SHARK", "Guil Shark", "Melqueek"},
{EnemyType::HALLO_RAPPY, EP2, 0x50, 0x50, {0x19}, {0x19}, {0x19}, "HALLO_RAPPY", "Hallo Rappy", nullptr},
{EnemyType::HIDOOM, EP1 | EP2, 0x17, 0x17, {0x32}, {0x32}, {0x32}, "HIDOOM", "Hidoom", nullptr},
{EnemyType::HILDEBEAR, EP1 | EP2, 0x01, 0x01, {0x49}, {0x48, 0x49, 0x4A}, {0x48}, "HILDEBEAR", "Hildebear", "Hildelt"},
{EnemyType::HILDEBLUE, EP1 | EP2 | RARE, 0x02, 0x02, {0x4A}, {0x4B, 0x4C, 0x4D}, {0x49}, "HILDEBLUE", "Hildeblue", "Hildetorr"},
{EnemyType::ILL_GILL, EP2, 0x52, 0x52, {0x26}, {0x26, 0x27, 0x28, 0x29}, {0x26}, "ILL_GILL", "Ill Gill", nullptr},
{EnemyType::KONDRIEU, EP4 | RARE | BOSS, 0x6C, 0x5B, {0x28, 0x2A}, {0x28, 0x2A}, {0x28, 0x2A}, "KONDRIEU", "Kondrieu", nullptr},
{EnemyType::KONDRIEU_SPINNER, EP4 | RARE | BOSS, 0x6C, 0x5B, {0x29, 0x2B}, {0x29, 0x2B}, {0x29, 0x2B}, "KONDRIEU_SPINNER", "Kondrieu (spinner)", nullptr},
{EnemyType::LA_DIMENIAN, EP1 | EP2, 0x2A, 0x2A, {0x54}, {0x5B}, {0x53}, "LA_DIMENIAN", "La Dimenian", "Merlan"},
{EnemyType::LOVE_RAPPY, EP2, 0x33, 0x33, {0x19}, {0x19}, {0x19}, "LOVE_RAPPY", "Love Rappy", nullptr},
{EnemyType::MERICARAND, EP2, 0x38, 0x38, {0x3A}, {0x3A}, {0x3A}, "MERICARAND", "Mericarand", nullptr},
{EnemyType::MERICAROL, EP2, 0x38, 0x38, {0x3A}, {0x3A}, {0x3A}, "MERICAROL", "Mericarol", nullptr},
{EnemyType::MERICUS, EP2 | RARE, 0x3A, 0x3A, {0x46}, {0x46}, {0x46}, "MERICUS", "Mericus", nullptr},
{EnemyType::MERIKLE, EP2 | RARE, 0x39, 0x39, {0x45}, {0x45}, {0x45}, "MERIKLE", "Merikle", nullptr},
{EnemyType::MERILLIA, EP2, 0x34, 0x34, {0x4B}, {0x4E}, {0x4A}, "MERILLIA", "Merillia", nullptr},
{EnemyType::MERILTAS, EP2, 0x35, 0x35, {0x4C}, {0x4F}, {0x4B}, "MERILTAS", "Meriltas", nullptr},
{EnemyType::MERISSA_A, EP4, 0x5B, 0x46, {0x19}, {0x19}, {0x19}, "MERISSA_A", "Merissa A", nullptr},
{EnemyType::MERISSA_AA, EP4 | RARE, 0x5C, 0x47, {0x1A}, {0x1A}, {0x1A}, "MERISSA_AA", "Merissa AA", nullptr},
{EnemyType::MIGIUM, EP1 | EP2, 0x16, 0x16, {0x33}, {0x33}, {0x33}, "MIGIUM", "Migium", nullptr},
{EnemyType::MONEST, EP1 | EP2, 0x04, 0x04, {0x01}, {0x01}, {0x01}, "MONEST", "Monest", "Mothvist"},
{EnemyType::MORFOS, EP2, 0x42, 0x42, {0x40}, {0x40, 0x50}, {0x40}, "MORFOS", "Morfos", nullptr},
{EnemyType::MOTHMANT, EP1 | EP2, 0x03, 0x03, {0x00}, {0x00}, {0x00}, "MOTHMANT", "Mothmant", "Mothvert"},
{EnemyType::NANO_DRAGON, EP1, 0x0F, 0x0F, {0x1A}, {0x1A}, {0x1A}, "NANO_DRAGON", "Nano Dragon", nullptr},
{EnemyType::NAR_LILY, EP1 | EP2 | RARE, 0x0E, 0x0E, {0x05}, {0x05}, {0x05}, "NAR_LILY", "Nar Lily", "Mil Lily"},
{EnemyType::OLGA_FLOW_1, EP2 | BOSS, NONE, NONE, {0x2B}, {0x2B}, {0x2B}, "OLGA_FLOW_1", "Olga Flow (phase 1)", nullptr},
{EnemyType::OLGA_FLOW_2, EP2 | BOSS, 0x4E, 0x4E, {0x2C}, {0x2C}, {0x2C}, "OLGA_FLOW_2", "Olga Flow (phase 2)", nullptr},
{EnemyType::PAL_SHARK, EP1, 0x11, 0x11, {0x50}, {0x55}, {0x4F}, "PAL_SHARK", "Pal Shark", "Govulmer"},
{EnemyType::PAN_ARMS, EP1 | EP2, 0x15, 0x15, {0x31}, {0x31}, {0x31}, "PAN_ARMS", "Pan Arms", nullptr},
{EnemyType::PAZUZU_CRATER, EP4 | RARE, 0x5F, 0x4B, {0x08}, {0x08}, {0x08}, "PAZUZU_CRATER", "Pazuzu (crater)", nullptr},
{EnemyType::PAZUZU_DESERT, EP4 | RARE, 0x5F, 0x4C, {0x1C}, {0x1C}, {0x1C}, "PAZUZU_DESERT", "Pazuzu (desert)", nullptr},
{EnemyType::PIG_RAY, EP2, 0x4A, NONE, {0x08}, {0x08}, {0x08}, "PIG_RAY", "Pig Ray", nullptr},
{EnemyType::POFUILLY_SLIME, EP1, 0x13, 0x13, {0x30}, {0x30}, {0x30}, "POFUILLY_SLIME", "Pofuilly Slime", nullptr},
{EnemyType::POUILLY_SLIME, EP1 | RARE, 0x14, 0x14, {0x34}, {0x34}, {0x34}, "POUILLY_SLIME", "Pouilly Slime", nullptr},
{EnemyType::POISON_LILY, EP1 | EP2, 0x0D, 0x0D, {0x04}, {0x04}, {0x04}, "POISON_LILY", "Poison Lily", "Ob Lily"},
{EnemyType::PYRO_GORAN, EP4, 0x67, 0x54, {0x12}, {0x12, 0x15}, {0x12}, "PYRO_GORAN", "Pyro Goran", nullptr},
{EnemyType::RAG_RAPPY, EP1 | EP2, 0x05, 0x05, {0x18}, {0x18}, {0x18}, "RAG_RAPPY", "Rag Rappy", "El Rappy"},
{EnemyType::RECOBOX, EP2, 0x43, 0x43, {0x41}, {0x41}, {0x41}, "RECOBOX", "Recobox", nullptr},
{EnemyType::RECON, EP2, 0x44, 0x44, {0x42}, {0x42}, {0x42}, "RECON", "Recon", nullptr},
{EnemyType::SAINT_MILION, EP4 | BOSS, 0x6A, 0x59, {0x20, 0x22}, {0x20, 0x22}, {0x20, 0x22}, "SAINT_MILION", "Saint-Milion", nullptr},
{EnemyType::SAINT_MILION_SPINNER, EP4 | BOSS, 0x6A, 0x59, {0x21, 0x23}, {0x21, 0x23}, {0x21, 0x23}, "SAINT_MILION_SPINNER", "Saint-Milion (spinner)", nullptr},
{EnemyType::SAINT_RAPPY, EP2, 0x4F, 0x4F, {0x19}, {0x19}, {0x19}, "SAINT_RAPPY", "Saint Rappy", nullptr},
{EnemyType::SAND_RAPPY_CRATER, EP4, 0x68, 0x55, {0x05}, {0x05}, {0x05}, "SAND_RAPPY_CRATER", "Sand Rappy (crater)", nullptr},
{EnemyType::SAND_RAPPY_DESERT, EP4, 0x68, 0x56, {0x17}, {0x17}, {0x17}, "SAND_RAPPY_DESERT", "Sand Rappy (desert)", nullptr},
{EnemyType::SATELLITE_LIZARD_CRATER, EP4, 0x5A, 0x44, {0x0D}, {0x0D}, {0x0D}, "SATELLITE_LIZARD_CRATER", "Satellite Lizard (crater)", nullptr},
{EnemyType::SATELLITE_LIZARD_DESERT, EP4, 0x5A, 0x45, {0x1D}, {0x1D}, {0x1D}, "SATELLITE_LIZARD_DESERT", "Satellite Lizard (desert)", nullptr},
{EnemyType::SAVAGE_WOLF, EP1 | EP2, 0x07, 0x07, {0x02}, {0x02}, {0x02}, "SAVAGE_WOLF", "Savage Wolf", "Gulgus"},
{EnemyType::SHAMBERTIN, EP4 | BOSS, 0x6B, 0x5A, {0x24, 0x26}, {0x24, 0x26}, {0x24, 0x26}, "SHAMBERTIN", "Shambertin", nullptr},
{EnemyType::SHAMBERTIN_SPINNER, EP4 | BOSS, 0x6B, 0x5A, {0x25, 0x27}, {0x25, 0x27}, {0x25, 0x27}, "SHAMBERTIN_SPINNER", "Shambertin (spinner)", nullptr},
{EnemyType::SINOW_BEAT, EP1, 0x1A, 0x1A, {0x06}, {0x06}, {0x06}, "SINOW_BEAT", "Sinow Beat", "Sinow Blue"},
{EnemyType::SINOW_BERILL, EP2, 0x3E, 0x3E, {0x06}, {0x06}, {0x06}, "SINOW_BERILL", "Sinow Berill", nullptr},
{EnemyType::SINOW_GOLD, EP1, 0x1B, 0x1B, {0x13}, {0x47}, {0x13}, "SINOW_GOLD", "Sinow Gold", "Sinow Red"},
{EnemyType::SINOW_SPIGELL, EP2, 0x3F, 0x3F, {0x13}, {0x47}, {0x13}, "SINOW_SPIGELL", "Sinow Spigell", nullptr},
{EnemyType::SINOW_ZELE, EP2, 0x46, 0x46, {0x44}, {0x44}, {0x44}, "SINOW_ZELE", "Sinow Zele", nullptr},
{EnemyType::SINOW_ZOA, EP2, 0x45, 0x45, {0x43}, {0x43}, {0x43}, "SINOW_ZOA", "Sinow Zoa", nullptr},
{EnemyType::SO_DIMENIAN, EP1 | EP2, 0x2B, 0x2B, {0x55}, {0x5C}, {0x54}, "SO_DIMENIAN", "So Dimenian", "Del-D"},
{EnemyType::UL_GIBBON, EP2, 0x3B, 0x3B, {0x3B}, {0x3B}, {0x3B}, "UL_GIBBON", "Ul Gibbon", nullptr},
{EnemyType::UL_RAY, EP2, 0x4B, NONE, {0x09}, {0x09}, {0x09}, "UL_RAY", "Ul Ray", nullptr},
{EnemyType::VOL_OPT_1, EP1 | BOSS, NONE, NONE, {0x21}, {0x21}, {0x21}, "VOL_OPT_1", "Vol Opt (phase 1)", "Vol Opt ver.2 (phase 1)"},
{EnemyType::VOL_OPT_2, EP1 | BOSS, 0x2E, 0x2E, {0x25}, {0x25}, {0x25}, "VOL_OPT_2", "Vol Opt (phase 2)", "Vol Opt ver.2 (phase 2)"},
{EnemyType::VOL_OPT_AMP, EP1 | BOSS, NONE, NONE, {0x24}, {0x24}, {0x24}, "VOL_OPT_AMP", "Vol Opt (amp)", "Vol Opt ver.2 (amp)"},
{EnemyType::VOL_OPT_CORE, EP1 | BOSS, NONE, NONE, {0x26}, {0x26}, {0x26}, "VOL_OPT_CORE", "Vol Opt (core)", "Vol Opt ver.2 (core)"},
{EnemyType::VOL_OPT_MONITOR, EP1 | BOSS, NONE, NONE, {0x23}, {0x23}, {0x23}, "VOL_OPT_MONITOR", "Vol Opt (monitor)", "Vol Opt ver.2 (monitor)"},
{EnemyType::VOL_OPT_PILLAR, EP1 | BOSS, NONE, NONE, {0x22}, {0x22}, {0x22}, "VOL_OPT_PILLAR", "Vol Opt (pillar)", "Vol Opt ver.2 (pillar)"},
{EnemyType::YOWIE_CRATER, EP4, 0x59, 0x42, {0x0E}, {0x0E}, {0x0E}, "YOWIE_CRATER", "Yowie (crater)", nullptr},
{EnemyType::YOWIE_DESERT, EP4, 0x59, 0x43, {0x1E}, {0x1E}, {0x1E}, "YOWIE_DESERT", "Yowie (desert)", nullptr},
{EnemyType::ZE_BOOTA, EP4, 0x61, 0x4E, {0x01}, {0x01, 0x02, 0x04}, {0x01}, "ZE_BOOTA", "Ze Boota", nullptr},
{EnemyType::ZOL_GIBBON, EP2, 0x3C, 0x3C, {0x3C}, {0x3C}, {0x3C}, "ZOL_GIBBON", "Zol Gibbon", nullptr},
{EnemyType::ZU_CRATER, EP4, 0x5E, 0x49, {0x07}, {0x07}, {0x07}, "ZU_CRATER", "Zu (crater)", nullptr},
{EnemyType::ZU_DESERT, EP4, 0x5E, 0x4A, {0x1B}, {0x1B}, {0x1B}, "ZU_DESERT", "Zu (desert)", nullptr},
// clang-format on
};
@@ -172,23 +178,20 @@ EnemyType phosg::enum_for_name<EnemyType>(const char* name) {
}
const vector<EnemyType>& enemy_types_for_rare_table_index(Episode episode, uint8_t rt_index) {
const auto& generate_table = +[](Episode episode) -> vector<vector<EnemyType>> {
vector<vector<EnemyType>> ret;
static array<vector<vector<EnemyType>>, 5> data;
auto& ret = data.at(static_cast<size_t>(episode));
if (ret.empty()) {
for (const auto& def : type_defs) {
if (def.valid_in_episode(episode) && (def.rt_index != 0xFF)) {
if (!def.valid_in_episode(episode)) {
continue;
}
if (def.rt_index != 0xFF) {
if (def.rt_index >= ret.size()) {
ret.resize(def.rt_index + 1);
}
ret[def.rt_index].emplace_back(def.type);
}
}
return ret;
};
static array<vector<vector<EnemyType>>, 5> data;
auto& ret = data.at(static_cast<size_t>(episode));
if (ret.empty()) {
ret = generate_table(episode);
}
try {
return ret.at(rt_index);
@@ -198,24 +201,21 @@ const vector<EnemyType>& enemy_types_for_rare_table_index(Episode episode, uint8
}
}
const vector<EnemyType>& enemy_types_for_battle_param_index(Episode episode, uint8_t bp_index) {
const auto& generate_table = +[](Episode episode) -> vector<vector<EnemyType>> {
vector<vector<EnemyType>> ret;
for (const auto& def : type_defs) {
if (def.valid_in_episode(episode) && (def.bp_index != 0xFF)) {
if (def.bp_index >= ret.size()) {
ret.resize(def.bp_index + 1);
}
ret[def.bp_index].emplace_back(def.type);
}
}
return ret;
};
const vector<EnemyType>& enemy_types_for_battle_param_stats_index(Episode episode, uint8_t bp_index) {
static array<vector<vector<EnemyType>>, 5> data;
auto& ret = data.at(static_cast<size_t>(episode));
if (ret.empty()) {
ret = generate_table(episode);
for (const auto& def : type_defs) {
if (def.valid_in_episode(episode) && !def.bp_stats_indexes.empty()) {
// Some enemies (e.g. Ep4 bosses) have multiple stats structures; we use the last one, since that's the only
// one used when giving EXP
size_t bp_index = def.bp_stats_indexes.back();
if (bp_index >= ret.size()) {
ret.resize(bp_index + 1);
}
ret[bp_index].emplace_back(def.type);
}
}
}
try {
return ret.at(bp_index);
@@ -225,29 +225,28 @@ const vector<EnemyType>& enemy_types_for_battle_param_index(Episode episode, uin
}
}
EnemyType EnemyTypeDefinition::rare_type(Episode episode, uint8_t event, uint8_t floor) const {
EnemyType EnemyTypeDefinition::rare_type(uint8_t area, uint8_t event) const {
switch (this->type) {
case EnemyType::HILDEBEAR:
return EnemyType::HILDEBLUE;
case EnemyType::RAG_RAPPY:
switch (episode) {
case Episode::EP1:
return EnemyType::AL_RAPPY;
case Episode::EP2:
switch (event) {
case 0x01: // rappy_type 1
return EnemyType::SAINT_RAPPY;
case 0x04: // rappy_type 2
return EnemyType::EGG_RAPPY;
case 0x05: // rappy_type 3
return EnemyType::HALLO_RAPPY;
default:
return EnemyType::LOVE_RAPPY;
}
case Episode::EP4:
return (floor > 0x05) ? EnemyType::DEL_RAPPY_DESERT : EnemyType::DEL_RAPPY_CRATER;
default:
throw logic_error("invalid episode");
if (area < 0x12) {
return EnemyType::AL_RAPPY;
} else if (area < 0x24) {
switch (event) {
case 0x01: // rappy_type 1
return EnemyType::SAINT_RAPPY;
case 0x04: // rappy_type 2
return EnemyType::EGG_RAPPY;
case 0x05: // rappy_type 3
return EnemyType::HALLO_RAPPY;
default:
return EnemyType::LOVE_RAPPY;
}
} else if (area <= 0x28) {
return EnemyType::DEL_RAPPY_CRATER;
} else {
return EnemyType::DEL_RAPPY_DESERT;
}
case EnemyType::POISON_LILY:
return EnemyType::NAR_LILY;
+25 -6
View File
@@ -7,7 +7,13 @@
#include "StaticGameData.hh"
#include "Types.hh"
// We don't know what the actual maximum was, since it was presumably only stored server-side on Sega's servers. The
// client uses values up to 0x6C (Kondrieu), so we just choose a value larger than that.
static constexpr size_t NUM_RT_INDEXES_V3 = 0x64;
static constexpr size_t NUM_RT_INDEXES_V4 = 0x70;
enum class EnemyType : uint8_t {
MIN_VALUE = 0,
UNKNOWN = 0,
NONE,
NON_ENEMY_NPC,
@@ -15,6 +21,7 @@ enum class EnemyType : uint8_t {
ASTARK,
BA_BOOTA,
BARBA_RAY,
BARBA_RAY_JOINT,
BARBAROUS_WOLF,
BEE_L,
BEE_R,
@@ -35,7 +42,6 @@ enum class EnemyType : uint8_t {
DARK_GUNNER,
DARK_GUNNER_CONTROL,
DARVANT,
DARVANT_ULTIMATE,
DE_ROL_LE,
DE_ROL_LE_BODY,
DE_ROL_LE_MINE,
@@ -79,6 +85,7 @@ enum class EnemyType : uint8_t {
HILDEBLUE,
ILL_GILL,
KONDRIEU,
KONDRIEU_SPINNER,
LA_DIMENIAN,
LOVE_RAPPY,
MERICARAND,
@@ -110,6 +117,7 @@ enum class EnemyType : uint8_t {
RECOBOX,
RECON,
SAINT_MILION,
SAINT_MILION_SPINNER,
SAINT_RAPPY,
SAND_RAPPY_CRATER,
SAND_RAPPY_DESERT,
@@ -117,6 +125,7 @@ enum class EnemyType : uint8_t {
SATELLITE_LIZARD_DESERT,
SAVAGE_WOLF,
SHAMBERTIN,
SHAMBERTIN_SPINNER,
SINOW_BEAT,
SINOW_BERILL,
SINOW_GOLD,
@@ -125,6 +134,7 @@ enum class EnemyType : uint8_t {
SINOW_ZOA,
SO_DIMENIAN,
UL_GIBBON,
UL_RAY,
VOL_OPT_1,
VOL_OPT_2,
VOL_OPT_AMP,
@@ -137,7 +147,7 @@ enum class EnemyType : uint8_t {
ZOL_GIBBON,
ZU_CRATER,
ZU_DESERT,
MAX_ENEMY_TYPE,
MAX_VALUE,
};
struct EnemyTypeDefinition {
@@ -146,11 +156,17 @@ struct EnemyTypeDefinition {
VALID_EP2 = 0x02,
VALID_EP4 = 0x04,
IS_RARE = 0x08,
IS_BOSS = 0x10,
};
EnemyType type;
uint8_t flags;
uint8_t rt_index; // 0xFF if not valid (e.g. not an enemy)
uint8_t bp_index; // 0xFF if not valid (e.g. not an enemy)
uint8_t rt_index; // 0xFF if not valid (e.g. not an enemy, or has no drops)
uint8_t legacy_rt_index; // Index used by Schtserv in their Ep4 .rel format
std::vector<uint8_t> bp_stats_indexes;
std::vector<uint8_t> bp_attack_data_indexes;
std::vector<uint8_t> bp_resist_data_indexes;
// Note: movement data isn't bound as strongly to the enemy types; some enemies use many entries and some use none at
// all, so we don't list them here. See notes/movement-data.txt for a listing of which enemies use which entries.
const char* enum_name;
const char* in_game_name;
const char* ultimate_name; // May be null if same as in_game_name
@@ -170,7 +186,10 @@ struct EnemyTypeDefinition {
inline bool is_rare() const {
return (this->flags & Flag::IS_RARE);
}
EnemyType rare_type(Episode episode, uint8_t event, uint8_t floor) const;
inline bool is_boss() const {
return (this->flags & Flag::IS_BOSS);
}
EnemyType rare_type(uint8_t area, uint8_t event) const;
};
const EnemyTypeDefinition& type_definition_for_enemy(EnemyType type);
@@ -181,4 +200,4 @@ template <>
EnemyType phosg::enum_for_name<EnemyType>(const char* name);
const std::vector<EnemyType>& enemy_types_for_rare_table_index(Episode episode, uint8_t rt_index);
const std::vector<EnemyType>& enemy_types_for_battle_param_index(Episode episode, uint8_t bp_index);
const std::vector<EnemyType>& enemy_types_for_battle_param_stats_index(Episode episode, uint8_t bp_index);
+18 -29
View File
@@ -11,24 +11,19 @@ const vector<uint16_t>& all_assist_card_ids(bool is_nte) {
// code. This is relevant for consistency of results when choosing a random card
// (for God Whim).
static const vector<uint16_t> ALL_ASSIST_CARD_IDS_TRIAL = {
0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD,
0x00FE, 0x00FF, 0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106,
0x0107, 0x0108, 0x0109, 0x010A, 0x010B, 0x010C, 0x010D, 0x010E, 0x010F,
0x0121, 0x0125, 0x0126, 0x0127, 0x0128, 0x0129, 0x012A, 0x012B, 0x012C,
0x012D, 0x012E, 0x012F, 0x0130, 0x0131, 0x0132, 0x0133, 0x0134, 0x0135,
0x0136, 0x0137, 0x0138, 0x0139, 0x013A, 0x013B, 0x013C, 0x013D, 0x013E,
0x013F, 0x0140, 0x0141, 0x0142, 0x0143, 0x0144, 0x0145, 0x0146, 0x0148,
0x014A, 0x014B, 0x014C, 0x014D, 0x014E, 0x023F, 0x0240, 0x0241, 0x0242};
0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF, 0x0100, 0x0101, 0x0102,
0x0103, 0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010B, 0x010C, 0x010D, 0x010E, 0x010F, 0x0121,
0x0125, 0x0126, 0x0127, 0x0128, 0x0129, 0x012A, 0x012B, 0x012C, 0x012D, 0x012E, 0x012F, 0x0130, 0x0131, 0x0132,
0x0133, 0x0134, 0x0135, 0x0136, 0x0137, 0x0138, 0x0139, 0x013A, 0x013B, 0x013C, 0x013D, 0x013E, 0x013F, 0x0140,
0x0141, 0x0142, 0x0143, 0x0144, 0x0145, 0x0146, 0x0148, 0x014A, 0x014B, 0x014C, 0x014D, 0x014E, 0x023F, 0x0240,
0x0241, 0x0242};
static const vector<uint16_t> ALL_ASSIST_CARD_IDS_FINAL = {
0x0018, 0x0019, 0x001A, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA,
0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF, 0x0100, 0x0101, 0x0102, 0x0103,
0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010B, 0x010C,
0x010D, 0x010E, 0x010F, 0x0121, 0x0125, 0x0126, 0x0127, 0x0128, 0x0129,
0x012A, 0x012B, 0x012C, 0x012D, 0x012E, 0x012F, 0x0130, 0x0131, 0x0132,
0x0133, 0x0134, 0x0135, 0x0136, 0x0137, 0x0138, 0x0139, 0x013A, 0x013B,
0x013C, 0x013D, 0x013E, 0x013F, 0x0140, 0x0141, 0x0142, 0x0143, 0x0144,
0x0145, 0x0146, 0x0148, 0x014A, 0x014B, 0x014C, 0x014D, 0x014E, 0x023F,
0x0240, 0x0241, 0x0242};
0x0018, 0x0019, 0x001A, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF,
0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010B, 0x010C, 0x010D,
0x010E, 0x010F, 0x0121, 0x0125, 0x0126, 0x0127, 0x0128, 0x0129, 0x012A, 0x012B, 0x012C, 0x012D, 0x012E, 0x012F,
0x0130, 0x0131, 0x0132, 0x0133, 0x0134, 0x0135, 0x0136, 0x0137, 0x0138, 0x0139, 0x013A, 0x013B, 0x013C, 0x013D,
0x013E, 0x013F, 0x0140, 0x0141, 0x0142, 0x0143, 0x0144, 0x0145, 0x0146, 0x0148, 0x014A, 0x014B, 0x014C, 0x014D,
0x014E, 0x023F, 0x0240, 0x0241, 0x0242};
return is_nte ? ALL_ASSIST_CARD_IDS_TRIAL : ALL_ASSIST_CARD_IDS_FINAL;
}
@@ -174,13 +169,11 @@ uint32_t AssistServer::compute_num_assist_effects_for_client(uint16_t client_id)
if (ce->def.target_mode == TargetMode::TEAM) {
auto this_deck_entry = this->deck_entries[client_id];
auto other_deck_entry = this->deck_entries[z];
if (this_deck_entry && other_deck_entry &&
(this_deck_entry->team_id == other_deck_entry->team_id)) {
if (this_deck_entry && other_deck_entry && (this_deck_entry->team_id == other_deck_entry->team_id)) {
affected = true;
}
} else if ((ce->def.target_mode == TargetMode::SELF) && (z == client_id)) {
affected = true;
} else if (ce->def.target_mode == TargetMode::EVERYONE) {
} else if (((ce->def.target_mode == TargetMode::SELF) && (z == client_id)) ||
(ce->def.target_mode == TargetMode::EVERYONE)) {
affected = true;
}
if (affected) {
@@ -226,9 +219,8 @@ bool AssistServer::should_block_assist_effects_for_client(uint16_t client_id) co
(this->deck_entries[client_id]->team_id == this->deck_entries[z]->team_id)) {
return true;
}
} else if ((ce->def.target_mode == TargetMode::SELF) && (client_id == z)) {
return true;
} else if (ce->def.target_mode == TargetMode::EVERYONE) {
} else if (((ce->def.target_mode == TargetMode::SELF) && (client_id == z)) ||
(ce->def.target_mode == TargetMode::EVERYONE)) {
return true;
}
}
@@ -237,10 +229,7 @@ bool AssistServer::should_block_assist_effects_for_client(uint16_t client_id) co
}
AssistEffect AssistServer::get_active_assist_by_index(size_t index) const {
if (index < this->num_active_assists) {
return this->active_assist_effects[index];
}
return AssistEffect::NONE;
return (index < this->num_active_assists) ? this->active_assist_effects[index] : AssistEffect::NONE;
}
void AssistServer::populate_effects() {
+31 -50
View File
@@ -7,11 +7,7 @@ using namespace std;
namespace Episode3 {
Card::Card(
uint16_t card_id,
uint16_t card_ref,
uint16_t client_id,
shared_ptr<Server> server)
Card::Card(uint16_t card_id, uint16_t card_ref, uint16_t client_id, shared_ptr<Server> server)
: w_server(server),
w_player_state(server->get_player_state(client_id)),
client_id(client_id),
@@ -132,8 +128,7 @@ ssize_t Card::apply_abnormal_condition(
if (cond.type == eff.type) {
existing_cond_index = z;
if ((!is_nte && eff.type == ConditionType::MV_BONUS) ||
((cond.card_definition_effect_index == def_effect_index) &&
(cond.card_ref == target_card_ref))) {
((cond.card_definition_effect_index == def_effect_index) && (cond.card_ref == target_card_ref))) {
break;
}
} else {
@@ -173,11 +168,7 @@ ssize_t Card::apply_abnormal_condition(
cond.condition_giver_card_ref = sc_card_ref;
cond.card_definition_effect_index = def_effect_index;
cond.order = 10;
if (dice_roll_value < 0) {
cond.dice_roll_value = this->player_state()->roll_dice_with_effects(1);
} else {
cond.dice_roll_value = dice_roll_value;
}
cond.dice_roll_value = (dice_roll_value < 0) ? this->player_state()->roll_dice_with_effects(1) : dice_roll_value;
cond.flags = 0;
cond.value = value + existing_cond_value;
cond.value8 = value + existing_cond_value;
@@ -309,8 +300,7 @@ void Card::commit_attack(
size_t num_assists = s->assist_server->compute_num_assist_effects_for_client(this->client_id);
for (size_t z = 0; z < num_assists; z++) {
auto eff = s->assist_server->get_active_assist_by_index(z);
if ((eff == AssistEffect::RANSOM) &&
(attacker_card->action_chain.chain.attack_medium == AttackMedium::PHYSICAL)) {
if ((eff == AssistEffect::RANSOM) && (attacker_card->action_chain.chain.attack_medium == AttackMedium::PHYSICAL)) {
uint8_t team_id = this->player_state()->get_team_id();
int16_t exp_amount = clamp<int16_t>(s->team_exp[team_id], 0, effective_damage);
s->team_exp[team_id] -= exp_amount;
@@ -339,8 +329,7 @@ void Card::commit_attack(
this->current_hp = clamp<int16_t>(this->current_hp - effective_damage, 0, this->max_hp);
log.debug_f("hp set to {}", this->current_hp);
if ((effective_damage > 0) &&
(attacker_ps->stats.max_attack_damage < effective_damage)) {
if ((effective_damage > 0) && (attacker_ps->stats.max_attack_damage < effective_damage)) {
attacker_ps->stats.max_attack_damage = effective_damage;
log.debug_f("attacker new max damage {}", effective_damage);
}
@@ -396,8 +385,10 @@ int16_t Card::compute_defense_power_for_attacker_card(shared_ptr<const Card> att
}
}
s->card_special->apply_action_conditions(EffectWhen::BEFORE_ANY_CARD_ATTACK, attacker_card, this->shared_from_this(), 0x08, nullptr);
s->card_special->apply_action_conditions(EffectWhen::BEFORE_ANY_CARD_ATTACK, attacker_card, this->shared_from_this(), 0x10, nullptr);
s->card_special->apply_action_conditions(
EffectWhen::BEFORE_ANY_CARD_ATTACK, attacker_card, this->shared_from_this(), 0x08, nullptr);
s->card_special->apply_action_conditions(
EffectWhen::BEFORE_ANY_CARD_ATTACK, attacker_card, this->shared_from_this(), 0x10, nullptr);
return this->action_metadata.defense_power + this->action_metadata.defense_bonus;
}
@@ -439,8 +430,7 @@ void Card::destroy_set_card(shared_ptr<Card> attacker_card) {
}
}
if ((s->map_and_rules->rules.hp_type == HPType::DEFEAT_TEAM) &&
(ps->get_sc_card().get() == this)) {
if ((s->map_and_rules->rules.hp_type == HPType::DEFEAT_TEAM) && (ps->get_sc_card().get() == this)) {
for (size_t set_index = 0; set_index < 8; set_index++) {
auto card = ps->get_set_card(set_index);
if (card) {
@@ -464,7 +454,7 @@ void Card::destroy_set_card(shared_ptr<Card> attacker_card) {
uint8_t other_team_id = s->player_states[client_id]->get_team_id();
uint8_t this_team_id = ps->get_team_id();
if (this_team_id == other_team_id) {
s->add_team_exp(team_id, this->max_hp);
s->add_team_exp(this_team_id, this->max_hp);
}
}
}
@@ -488,8 +478,7 @@ int32_t Card::error_code_for_move_to_location(const Location& loc) const {
if (this->card_flags & 2) {
return -0x60;
}
if (!this->server()->ruler_server->card_ref_can_move(
this->client_id, this->card_ref, 1)) {
if (!this->server()->ruler_server->card_ref_can_move(this->client_id, this->card_ref, 1)) {
return -0x7B;
}
// Note: The original code passes non-null pointers here but ignores the
@@ -529,9 +518,7 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
if (attacker_card->action_chain.chain.attack_medium == AttackMedium::UNKNOWN_03) {
// Probably Resta
for (size_t strike_num = 0; strike_num < attacker_card->action_chain.chain.strike_count; strike_num++) {
this->current_hp = min<int16_t>(
this->current_hp + attacker_card->action_chain.chain.effective_tp,
this->max_hp);
this->current_hp = min<int16_t>(this->current_hp + attacker_card->action_chain.chain.effective_tp, this->max_hp);
}
this->propagate_shared_hp_if_needed();
cmd.effect.tp = attacker_card->action_chain.chain.effective_tp;
@@ -613,11 +600,7 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
}
bool Card::get_condition_value(
ConditionType cond_type,
uint16_t card_ref,
uint8_t def_effect_index,
uint16_t value,
uint16_t* out_value) const {
ConditionType cond_type, uint16_t card_ref, uint8_t def_effect_index, uint16_t value, uint16_t* out_value) const {
return this->action_chain.get_condition_value(cond_type, card_ref, def_effect_index, value, out_value);
}
@@ -697,9 +680,7 @@ int32_t Card::move_to_location(const Location& loc) {
this->card_flags = this->card_flags | 0x80;
// On NTE, traps happen now, not after the Move phase
if (s->options.is_nte() &&
this->def_entry->def.is_sc() &&
((s->overlay_state.tiles[loc.y][loc.x] & 0xF0) == 0x40)) {
if (s->options.is_nte() && this->def_entry->def.is_sc() && ((s->overlay_state.tiles[loc.y][loc.x] & 0xF0) == 0x40)) {
for (size_t z = 0; z < 4; z++) {
auto other_ps = s->player_states[z];
if (!other_ps) {
@@ -752,8 +733,7 @@ void Card::propagate_shared_hp_if_needed() {
((this->def_entry->def.type == CardType::HUNTERS_SC) || (this->def_entry->def.type == CardType::ARKZ_SC))) {
for (size_t other_client_id = 0; other_client_id < 4; other_client_id++) {
auto other_ps = this->server()->player_states[other_client_id];
if ((other_client_id != this->client_id) && other_ps &&
(other_ps->get_team_id() == this->team_id)) {
if ((other_client_id != this->client_id) && other_ps && (other_ps->get_team_id() == this->team_id)) {
other_ps->get_sc_card()->set_current_hp(this->current_hp, false);
}
}
@@ -906,7 +886,8 @@ void Card::clear_action_chain_and_metadata_and_most_flags() {
void Card::compute_action_chain_results(bool apply_action_conditions, bool ignore_this_card_ap_tp) {
auto s = this->server();
auto log = s->log_stack(std::format("compute_action_chain_results(@{:04X} #{:04X}): ", this->get_card_ref(), this->get_card_id()));
auto log = s->log_stack(std::format(
"compute_action_chain_results(@{:04X} #{:04X}): ", this->get_card_ref(), this->get_card_id()));
bool is_nte = s->options.is_nte();
this->action_chain.compute_attack_medium(s);
@@ -930,7 +911,8 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
} else {
stat_swap_type = s->card_special->compute_stat_swap_type(this->shared_from_this());
log.debug_f("stat_swap_type = {} (0=none, 1=a/t, 2=a/h)", static_cast<size_t>(stat_swap_type));
s->card_special->get_effective_ap_tp(stat_swap_type, &effective_ap, &effective_tp, this->get_current_hp(), this->ap, this->tp);
s->card_special->get_effective_ap_tp(
stat_swap_type, &effective_ap, &effective_tp, this->get_current_hp(), this->ap, this->tp);
log.debug_f("effective_ap = {}, effective_tp = {}", effective_ap, effective_tp);
}
@@ -1008,7 +990,7 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
break;
case AssistEffect::INFLUENCE:
if (!is_nte && this->card_type_is_sc_or_creature()) {
int16_t count = ps->count_set_refs();
int16_t count = ps->count_hand_refs();
this->action_chain.chain.ap_effect_bonus += (count >> 1);
}
break;
@@ -1082,8 +1064,7 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
}
auto other_sc_card = other_ps->get_sc_card();
if (other_sc_card &&
(abs(this->loc.x - other_sc_card->loc.x) < 2) &&
(abs(this->loc.y - other_sc_card->loc.y) < 2)) {
(abs(this->loc.x - other_sc_card->loc.x) < 2) && (abs(this->loc.y - other_sc_card->loc.y) < 2)) {
num_scs_in_range++;
}
}
@@ -1106,10 +1087,12 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
int16_t damage = 0;
if (this->action_chain.chain.attack_medium == AttackMedium::TECH) {
damage = this->action_chain.chain.effective_tp + this->action_chain.chain.tp_effect_bonus;
log.debug_f("(tech) damage = {} (eff) + {} (bonus) = {}", this->action_chain.chain.effective_tp, this->action_chain.chain.tp_effect_bonus, damage);
log.debug_f("(tech) damage = {} (eff) + {} (bonus) = {}",
this->action_chain.chain.effective_tp, this->action_chain.chain.tp_effect_bonus, damage);
} else if (this->action_chain.chain.attack_medium == AttackMedium::PHYSICAL) {
damage = this->action_chain.chain.effective_ap + this->action_chain.chain.ap_effect_bonus;
log.debug_f("(physical) damage = {} (eff) + {} (bonus) = {}", this->action_chain.chain.effective_ap, this->action_chain.chain.ap_effect_bonus, damage);
log.debug_f("(physical) damage = {} (eff) + {} (bonus) = {}",
this->action_chain.chain.effective_ap, this->action_chain.chain.ap_effect_bonus, damage);
} else {
log.debug_f("(unknown attack medium) damage = 0");
}
@@ -1117,7 +1100,8 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
this->action_chain.chain.damage = is_nte
? (damage * this->action_chain.chain.damage_multiplier)
: min<int16_t>(damage * this->action_chain.chain.damage_multiplier, 99);
log.debug_f("overall chain damage = {} (base) * {} (mult) = {}", damage, this->action_chain.chain.damage_multiplier, this->action_chain.chain.damage);
log.debug_f("overall chain damage = {} (base) * {} (mult) = {}",
damage, this->action_chain.chain.damage_multiplier, this->action_chain.chain.damage);
if (apply_action_conditions) {
auto this_sh = this->shared_from_this();
@@ -1271,8 +1255,7 @@ void Card::unknown_80236374(shared_ptr<Card> other_card, const ActionState* as)
}
void Card::unknown_802379BC(uint16_t card_ref) {
this->action_chain.chain.unknown_card_ref_a3 =
(card_ref == 0xFFFF) ? this->card_ref : card_ref;
this->action_chain.chain.unknown_card_ref_a3 = (card_ref == 0xFFFF) ? this->card_ref : card_ref;
}
void Card::unknown_802379DC(const ActionState& pa) {
@@ -1359,8 +1342,7 @@ void Card::dice_phase_before() {
cond.remaining_turns--;
}
if (cond.remaining_turns < 1) {
s->card_special->apply_stat_deltas_to_card_from_condition_and_clear_cond(
cond, this->shared_from_this());
s->card_special->apply_stat_deltas_to_card_from_condition_and_clear_cond(cond, this->shared_from_this());
}
}
}
@@ -1382,8 +1364,7 @@ bool Card::unknown_80236554(shared_ptr<Card> other_card, const ActionState* as)
: std::format("unknown_80236554(@{:04X} #{:04X}, null): ", this->get_card_ref(), this->get_card_id()));
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
if (as) {
string as_str = as->str(s);
log.debug_f("as = {}", as_str);
log.debug_f("as = {}", as->str(s));
} else {
log.debug_f("as = null");
}
+195 -289
View File
@@ -84,7 +84,8 @@ void CardSpecial::AttackEnvStats::clear() {
this->target_current_hp = 0;
}
uint32_t CardSpecial::AttackEnvStats::at(size_t index) const {
static_assert(sizeof(parray<uint32_t, 39>) == sizeof(AttackEnvStats), "CardSpecial::AttackEnvStats does not have exactly 39 entries");
static_assert(sizeof(parray<uint32_t, 39>) == sizeof(AttackEnvStats),
"CardSpecial::AttackEnvStats does not have exactly 39 entries");
return reinterpret_cast<const parray<uint32_t, 39>*>(this)->at(index);
}
@@ -454,10 +455,7 @@ bool CardSpecial::apply_defense_condition(
}
bool CardSpecial::apply_defense_conditions(
const ActionState& as,
EffectWhen when,
shared_ptr<Card> defender_card,
uint32_t flags) {
const ActionState& as, EffectWhen when, shared_ptr<Card> defender_card, uint32_t flags) {
for (size_t z = 0; z < 9; z++) {
this->apply_defense_condition(when, &defender_card->action_chain.conditions[z], z, as, defender_card, flags, 0);
}
@@ -474,14 +472,12 @@ bool CardSpecial::apply_stat_deltas_to_all_cards_from_all_conditions_with_card_r
}
auto sc_card = ps->get_sc_card();
if (sc_card) {
ret |= this->apply_stats_deltas_to_card_from_all_conditions_with_card_ref(
card_ref, sc_card);
ret |= this->apply_stats_deltas_to_card_from_all_conditions_with_card_ref(card_ref, sc_card);
}
for (size_t set_index = 0; set_index < 8; set_index++) {
auto set_card = ps->get_set_card(set_index);
if (set_card) {
ret |= this->apply_stats_deltas_to_card_from_all_conditions_with_card_ref(
card_ref, set_card);
ret |= this->apply_stats_deltas_to_card_from_all_conditions_with_card_ref(card_ref, set_card);
}
}
}
@@ -494,8 +490,7 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
auto log = s->log_stack(std::format("apply_stat_deltas_to_card_from_condition_and_clear_cond(@{:04X} #{:04X}): ", card->get_card_ref(), card->get_card_id()));
bool is_nte = s->options.is_nte();
string cond_str = cond.str(s);
log.debug_f("cond: {}", cond_str);
log.debug_f("cond: {}", cond.str(s));
ConditionType cond_type = cond.type;
int16_t cond_value = is_nte ? cond.value.load() : clamp<int16_t>(cond.value, -99, 99);
@@ -643,10 +638,7 @@ bool CardSpecial::apply_stats_deltas_to_card_from_all_conditions_with_card_ref(
}
bool CardSpecial::card_has_condition_with_ref(
shared_ptr<const Card> card,
ConditionType cond_type,
uint16_t card_ref,
uint16_t match_card_ref) const {
shared_ptr<const Card> card, ConditionType cond_type, uint16_t card_ref, uint16_t match_card_ref) const {
size_t z = 0;
while ((z < 9) &&
((card->action_chain.conditions[z].type != cond_type) ||
@@ -666,14 +658,11 @@ bool CardSpecial::card_is_destroyed(shared_ptr<const Card> card) const {
if (card->get_current_hp() > 0) {
return false;
}
return !this->server()->ruler_server->card_ref_or_any_set_card_has_condition_46(
card->get_card_ref());
return !this->server()->ruler_server->card_ref_or_any_set_card_has_condition_46(card->get_card_ref());
}
void CardSpecial::compute_attack_ap(
shared_ptr<const Card> target_card,
int16_t* out_value,
uint16_t attacker_card_ref) {
shared_ptr<const Card> target_card, int16_t* out_value, uint16_t attacker_card_ref) {
auto s = this->server();
auto is_nte = s->options.is_nte();
@@ -773,9 +762,7 @@ CardSpecial::AttackEnvStats CardSpecial::compute_attack_env_stats(
}
ast.total_num_set_cards = ps_num_set_cards;
uint8_t target_card_team_id = target_card
? target_card->player_state()->get_team_id()
: 0xFF;
uint8_t target_card_team_id = target_card ? target_card->player_state()->get_team_id() : 0xFF;
size_t target_team_num_set_cards = 0;
size_t non_target_team_num_set_cards = 0;
@@ -831,13 +818,16 @@ CardSpecial::AttackEnvStats CardSpecial::compute_attack_env_stats(
ast.max_hp = card->get_max_hp();
ast.team_dice_bonus = card ? s->team_dice_bonus[card->get_team_id()] : 0;
ast.effective_ap_if_not_tech = (!attacker_card || (attacker_card->action_chain.chain.attack_medium == AttackMedium::TECH))
ast.effective_ap_if_not_tech =
(!attacker_card || (attacker_card->action_chain.chain.attack_medium == AttackMedium::TECH))
? 0
: attacker_card->action_chain.chain.damage;
ast.effective_ap_if_not_tech2 = (!attacker_card || (attacker_card->action_chain.chain.attack_medium == AttackMedium::TECH))
ast.effective_ap_if_not_tech2 =
(!attacker_card || (attacker_card->action_chain.chain.attack_medium == AttackMedium::TECH))
? 0
: attacker_card->action_chain.chain.damage;
ast.effective_ap_if_not_physical = (!attacker_card || (attacker_card->action_chain.chain.attack_medium == AttackMedium::PHYSICAL))
ast.effective_ap_if_not_physical =
(!attacker_card || (attacker_card->action_chain.chain.attack_medium == AttackMedium::PHYSICAL))
? 0
: attacker_card->action_chain.chain.damage;
ast.sc_effective_ap = attacker_card ? attacker_card->action_chain.chain.damage : 0;
@@ -870,9 +860,7 @@ CardSpecial::AttackEnvStats CardSpecial::compute_attack_env_stats(
uint16_t z_ref = pa.attacker_card_ref;
// Note: The (z < 8) conditions in these two loops are not present in the
// original code.
for (z = 0;
((target_card_ref != z_ref) && (z < 8) && ((z_ref = pa.action_card_refs[z]) != 0xFFFF));
z++) {
for (z = 0; ((target_card_ref != z_ref) && (z < 8) && ((z_ref = pa.action_card_refs[z]) != 0xFFFF)); z++) {
}
ast.action_cards_ap = 0;
@@ -1012,8 +1000,7 @@ shared_ptr<Card> CardSpecial::compute_replaced_target_based_on_conditions(
if (num_candidates > 0) {
uint8_t a = target_ps->roll_dice_with_effects(2);
uint8_t b = target_ps->roll_dice_with_effects(1);
return s->card_for_set_card_ref(
candidate_card_refs[(a + b) - ((a + b) / num_candidates) * num_candidates]);
return s->card_for_set_card_ref(candidate_card_refs[(a + b) - ((a + b) / num_candidates) * num_candidates]);
}
}
}
@@ -1290,8 +1277,7 @@ size_t CardSpecial::count_action_cards_with_condition_for_all_current_attacks(
for (size_t client_id = 0; client_id < 4; client_id++) {
auto ps = this->server()->get_player_state(client_id);
if (ps) {
ret += this->count_action_cards_with_condition_for_current_attack(
ps->get_sc_card(), cond_type, card_ref);
ret += this->count_action_cards_with_condition_for_current_attack(ps->get_sc_card(), cond_type, card_ref);
for (size_t set_index = 0; set_index < 8; set_index++) {
ret += this->count_action_cards_with_condition_for_current_attack(
ps->get_set_card(set_index), cond_type, card_ref);
@@ -1338,8 +1324,7 @@ size_t CardSpecial::count_action_cards_with_condition_for_current_attack(
return ret;
}
size_t CardSpecial::count_cards_with_card_id_except_card_ref(
uint16_t card_id, uint16_t card_ref) const {
size_t CardSpecial::count_cards_with_card_id_except_card_ref(uint16_t card_id, uint16_t card_ref) const {
size_t ret = 0;
for (size_t client_id = 0; client_id < 4; client_id++) {
auto ps = this->server()->get_player_state(client_id);
@@ -1348,9 +1333,7 @@ size_t CardSpecial::count_cards_with_card_id_except_card_ref(
}
for (size_t set_index = 0; set_index < 8; set_index++) {
auto card = ps->get_set_card(set_index);
if (card &&
(card->get_card_ref() != card_ref) &&
(card->get_definition()->def.card_id == card_id)) {
if (card && (card->get_card_ref() != card_ref) && (card->get_definition()->def.card_id == card_id)) {
ret++;
}
}
@@ -1393,8 +1376,7 @@ ActionState CardSpecial::create_attack_state_from_card_action_chain(
shared_ptr<const Card> attacker_card) const {
ActionState ret;
if (attacker_card) {
ret.attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(
attacker_card->get_card_ref(), 4);
ret.attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(attacker_card->get_card_ref(), 4);
for (size_t z = 0; z < attacker_card->action_chain.chain.attack_action_card_ref_count; z++) {
ret.action_card_refs[z] = this->send_6xB4x06_if_card_ref_invalid(
attacker_card->action_chain.chain.attack_action_card_refs[z], 5);
@@ -1408,8 +1390,7 @@ ActionState CardSpecial::create_attack_state_from_card_action_chain(
}
ActionState CardSpecial::create_defense_state_for_card_pair_action_chains(
shared_ptr<const Card> attacker_card,
shared_ptr<const Card> defender_card) const {
shared_ptr<const Card> attacker_card, shared_ptr<const Card> defender_card) const {
ActionState ret;
if (defender_card && attacker_card) {
size_t count = 0;
@@ -1422,18 +1403,15 @@ ActionState CardSpecial::create_defense_state_for_card_pair_action_chains(
}
}
if (defender_card) {
ret.target_card_refs[0] = this->send_6xB4x06_if_card_ref_invalid(
defender_card->get_card_ref(), 8);
ret.target_card_refs[0] = this->send_6xB4x06_if_card_ref_invalid(defender_card->get_card_ref(), 8);
}
if (attacker_card) {
ret.original_attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(
attacker_card->get_card_ref(), 9);
ret.original_attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(attacker_card->get_card_ref(), 9);
}
return ret;
}
void CardSpecial::destroy_card_if_hp_zero(
shared_ptr<Card> card, uint16_t attacker_card_ref) {
void CardSpecial::destroy_card_if_hp_zero(shared_ptr<Card> card, uint16_t attacker_card_ref) {
if (card && (card->get_current_hp() <= 0)) {
card->destroy_set_card(this->server()->card_for_set_card_ref(attacker_card_ref));
}
@@ -1462,9 +1440,15 @@ bool CardSpecial::evaluate_effect_arg2_condition(
bool is_nte = s->options.is_nte();
auto set_card = s->card_for_set_card_ref(set_card_ref);
bool set_card_has_ability_trap =
(!is_nte && set_card && this->card_has_condition_with_ref(set_card, ConditionType::ABILITY_TRAP, 0xFFFF, 0xFFFF));
(!is_nte && set_card &&
this->card_has_condition_with_ref(set_card, ConditionType::ABILITY_TRAP, 0xFFFF, 0xFFFF));
switch (arg2_text[0]) {
case 'b': {
auto attacker_card = s->card_for_set_card_ref(attacker_card_ref);
return (attacker_card && (attacker_card->action_chain.chain.damage <= atoi(arg2_text + 1)));
}
case 'C':
if (is_nte) {
return false;
@@ -1515,11 +1499,6 @@ bool CardSpecial::evaluate_effect_arg2_condition(
return false;
}
case 'b': {
auto attacker_card = s->card_for_set_card_ref(attacker_card_ref);
return (attacker_card && (attacker_card->action_chain.chain.damage <= atoi(arg2_text + 1)));
}
case 'd': {
if (set_card_has_ability_trap) {
return false;
@@ -1596,7 +1575,8 @@ bool CardSpecial::evaluate_effect_arg2_condition(
auto ce = card->get_definition();
return ((ce->def.card_class() == CardClass::GUARD_ITEM) ||
(!is_nte && (ce->def.card_class() == CardClass::MAG_ITEM)) ||
s->ruler_server->find_condition_on_card_ref(card->get_card_ref(), ConditionType::GUARD_CREATURE, 0, 0, 0));
s->ruler_server->find_condition_on_card_ref(
card->get_card_ref(), ConditionType::GUARD_CREATURE, 0, 0, 0));
}
case 0x0E: // n14
return card->get_definition()->def.is_sc();
@@ -1674,8 +1654,7 @@ bool CardSpecial::evaluate_effect_arg2_condition(
return (!set_card_has_ability_trap || is_nte) && (random_percent < atoi(arg2_text + 1));
case 's': {
auto ce = card->get_definition();
return ((ce->def.self_cost >= arg2_text[1] - '0') &&
(ce->def.self_cost <= arg2_text[2] - '0'));
return ((ce->def.self_cost >= arg2_text[1] - '0') && (ce->def.self_cost <= arg2_text[2] - '0'));
}
case 't': {
auto set_card = s->card_for_set_card_ref(set_card_ref);
@@ -1689,14 +1668,12 @@ bool CardSpecial::evaluate_effect_arg2_condition(
return (v < set_card->unknown_a9);
} else if (when == EffectWhen::BEFORE_DICE_PHASE_THIS_TEAM_TURN) {
uint32_t y = set_card->unknown_a9 & 0xFFFFFFFE;
if ((set_card->unknown_a9 > 0) &&
(y == (y / (v & 0xFFFFFFFE)) * (v & 0xFFFFFFFE))) {
if ((set_card->unknown_a9 > 0) && (y == (y / (v & 0xFFFFFFFE)) * (v & 0xFFFFFFFE))) {
return true;
}
} else {
uint32_t y = set_card->unknown_a9;
if ((set_card->unknown_a9 > 0) &&
(y == (y / (v + 1)) * (v + 1))) {
if ((set_card->unknown_a9 > 0) && (y == (y / (v + 1)) * (v + 1))) {
return true;
}
}
@@ -1708,85 +1685,81 @@ bool CardSpecial::evaluate_effect_arg2_condition(
throw logic_error("this should be impossible");
}
int32_t CardSpecial::evaluate_effect_expr(
const AttackEnvStats& ast,
const char* expr,
DiceRoll& dice_roll) const {
int32_t CardSpecial::evaluate_effect_expr(const AttackEnvStats& ast, const char* expr, DiceRoll& dice_roll) const {
using ExprToken = CardDefinition::Effect::ExprToken;
auto log = this->server()->log_stack("evaluate_effect_expr: ");
if (log.min_level == phosg::LogLevel::L_DEBUG) {
log.debug_f("ast, expr=\"{}\", dice_roll=(client_id={:02X}, a2={:02X}, value={:02X}, value_used_in_expr={}, a5={:04X})", expr, dice_roll.client_id, dice_roll.unknown_a2, dice_roll.value, dice_roll.value_used_in_expr ? "true" : "false", dice_roll.unknown_a5);
log.debug_f(
"ast, expr=\"{}\", dice_roll=(client_id={:02X}, a2={:02X}, value={:02X}, value_used_in_expr={}, a5={:04X})",
expr,
dice_roll.client_id,
dice_roll.unknown_a2,
dice_roll.value,
dice_roll.value_used_in_expr ? "true" : "false",
dice_roll.unknown_a5);
ast.print(stderr);
}
// Note: This implementation is not based on the original code because the
// original code was hard to follow - it used a look-behind approach with lots
// of local variables instead of the look-ahead approach that this
// implementation uses. Hopefully this implementation is easier to follow.
vector<pair<ExpressionTokenType, int32_t>> tokens;
while (expr) {
ExpressionTokenType type;
int32_t value = 0;
expr = this->get_next_expr_token(expr, &type, &value);
if (expr) {
if (type == ExpressionTokenType::SPACE) {
throw runtime_error("expression contains space token");
}
// Turn references into numbers, so only numbers and operators can appear
// in the tokens vector
if (type == ExpressionTokenType::REFERENCE) {
if ((value == 1) || (value == 11)) {
dice_roll.value_used_in_expr = true;
}
tokens.emplace_back(make_pair(ExpressionTokenType::NUMBER, ast.at(value)));
} else {
tokens.emplace_back(make_pair(type, value));
// Note: This implementation is not based on the original code because the original code was hard to follow - it used
// look-behind approach with lots of local variables instead of the look-ahead approach that this implementation
// uses. Hopefully this implementation is easier to follow.
auto tokens = ExprToken::parse(expr);
for (auto& token : tokens) {
if (token.type == ExprToken::Type::SPACE) {
throw runtime_error("expression contains space token");
}
// Turn references into numbers, so only numbers and operators can appear in the tokens vector
if (token.type == ExprToken::Type::REFERENCE) {
if ((token.value == 1) || (token.value == 11)) {
dice_roll.value_used_in_expr = true;
}
token.type = ExprToken::Type::NUMBER;
token.value = ast.at(token.value);
}
}
// Operators are evaluated left-to-right - there are no operator precedence
// rules
// Operators are evaluated left-to-right - there are no operator precedence rules
int32_t value = 0;
log.debug_f("value={} (start)", value);
for (size_t token_index = 0; token_index < tokens.size(); token_index++) {
auto token_type = tokens[token_index].first;
int32_t token_value = tokens[token_index].second;
if ((token_type == ExpressionTokenType::SPACE) || (token_type == ExpressionTokenType::REFERENCE)) {
const auto& token = tokens[token_index];
if ((token.type == ExprToken::Type::SPACE) || (token.type == ExprToken::Type::REFERENCE)) {
throw logic_error("space or reference token present in expr evaluation phase 2");
}
if (token_type == ExpressionTokenType::NUMBER) {
value = token_value;
log.debug_f("value={} (token_type=NUMBER, token_value={})", value, token_value);
if (token.type == ExprToken::Type::NUMBER) {
value = token.value;
log.debug_f("value={} (token_type=NUMBER, token_value={})", value, token.value);
} else {
if (token_index >= tokens.size() - 1) {
throw runtime_error("no token on right side of binary operator");
}
token_index++;
auto right_token_type = tokens[token_index].first;
auto right_value = tokens[token_index].second;
if (right_token_type != ExpressionTokenType::NUMBER) {
const auto& right_token = tokens[token_index];
if (right_token.type != ExprToken::Type::NUMBER) {
// REFERENCE was converted to NUMBER after parsing, based on the attack env stats
throw runtime_error("non-number, non-reference token on right side of operator");
}
switch (token_type) {
case ExpressionTokenType::ROUND_DIVIDE:
value = lround(static_cast<double>(value) / right_value);
log.debug_f("value={} (token_type=ROUND_DIVIDE, right_token_value={})", value, right_value);
switch (token.type) {
case ExprToken::Type::ROUND_DIVIDE:
value = lround(static_cast<double>(value) / right_token.value);
log.debug_f("value={} (token_type=ROUND_DIVIDE, right_token_value={})", value, right_token.value);
break;
case ExpressionTokenType::SUBTRACT:
value -= right_value;
log.debug_f("value={} (token_type=SUBTRACT, right_token_value={})", value, right_value);
case ExprToken::Type::SUBTRACT:
value -= right_token.value;
log.debug_f("value={} (token_type=SUBTRACT, right_token_value={})", value, right_token.value);
break;
case ExpressionTokenType::ADD:
value += right_value;
log.debug_f("value={} (token_type=ADD, right_token_value={})", value, right_value);
case ExprToken::Type::ADD:
value += right_token.value;
log.debug_f("value={} (token_type=ADD, right_token_value={})", value, right_token.value);
break;
case ExpressionTokenType::MULTIPLY:
value *= right_value;
log.debug_f("value={} (token_type=MULTIPLY, right_token_value={})", value, right_value);
case ExprToken::Type::MULTIPLY:
value *= right_token.value;
log.debug_f("value={} (token_type=MULTIPLY, right_token_value={})", value, right_token.value);
break;
case ExpressionTokenType::FLOOR_DIVIDE:
value = floor(value / right_value);
log.debug_f("value={} (token_type=FLOOR_DIVIDE, right_token_value={})", value, right_value);
case ExprToken::Type::FLOOR_DIVIDE:
value = floor(value / right_token.value);
log.debug_f("value={} (token_type=FLOOR_DIVIDE, right_token_value={})", value, right_token.value);
break;
default:
throw logic_error("invalid binary operator");
@@ -1835,8 +1808,7 @@ bool CardSpecial::execute_effect(
}
} else if (card->action_metadata.check_flag(0x10) &&
(cond.card_ref != card->get_card_ref()) &&
(cond.condition_giver_card_ref != card->get_card_ref())) {
(cond.card_ref != card->get_card_ref()) && (cond.condition_giver_card_ref != card->get_card_ref())) {
return false;
}
@@ -1916,7 +1888,9 @@ bool CardSpecial::execute_effect(
case ConditionType::GIVE_DAMAGE:
if ((unknown_p7 & 4) != 0) {
int16_t current_hp = is_nte ? card->get_current_hp() : clamp<int16_t>(card->get_current_hp(), -99, 99);
int16_t new_hp = is_nte ? (current_hp - positive_expr_value) : clamp<int16_t>(current_hp - positive_expr_value, -99, 99);
int16_t new_hp = is_nte
? (current_hp - positive_expr_value)
: clamp<int16_t>(current_hp - positive_expr_value, -99, 99);
this->send_6xB4x06_for_stat_delta(card, attacker_card_ref, 0x20, -positive_expr_value, 0, 1);
new_hp = max<int16_t>(new_hp, 0);
if (new_hp != current_hp) {
@@ -2226,8 +2200,7 @@ bool CardSpecial::execute_effect(
if (hand_size > 0) {
uint8_t a = ps->roll_dice_with_effects(2);
uint8_t b = ps->roll_dice_with_effects(1);
uint16_t card_ref = ps->card_ref_for_hand_index(
(a + b) - ((a + b) / hand_size) * hand_size);
uint16_t card_ref = ps->card_ref_for_hand_index((a + b) - ((a + b) / hand_size) * hand_size);
if (card_ref != 0xFFFF) {
ps->discard_ref_from_hand(card_ref);
}
@@ -2264,7 +2237,8 @@ bool CardSpecial::execute_effect(
card->action_metadata.defense_card_ref_count = 0;
} else {
for (size_t z = 0; z < card->action_chain.chain.attack_action_card_ref_count; z++) {
this->apply_stat_deltas_to_all_cards_from_all_conditions_with_card_ref(card->action_chain.chain.attack_action_card_refs[z]);
this->apply_stat_deltas_to_all_cards_from_all_conditions_with_card_ref(
card->action_chain.chain.attack_action_card_refs[z]);
}
}
card->action_chain.chain.attack_action_card_ref_count = 0;
@@ -2418,7 +2392,13 @@ bool CardSpecial::execute_effect(
auto& cond = attacker_card->action_chain.conditions[z];
if (cond.type != ConditionType::UNKNOWN_49) {
this->execute_effect(
cond, attacker_card, positive_expr_value, clamped_unknown_p5, cond.type, unknown_p7, attacker_card_ref);
cond,
attacker_card,
positive_expr_value,
clamped_unknown_p5,
cond.type,
unknown_p7,
attacker_card_ref);
}
}
}
@@ -2428,18 +2408,14 @@ bool CardSpecial::execute_effect(
case ConditionType::AP_GROWTH:
if (unknown_p7 & 4) {
this->send_6xB4x06_for_stat_delta(card, attacker_card_ref, 0xA0, positive_expr_value, 0, 1);
card->ap = is_nte
? (card->ap + positive_expr_value)
: clamp<int16_t>(card->ap + positive_expr_value, -99, 99);
card->ap = is_nte ? (card->ap + positive_expr_value) : clamp<int16_t>(card->ap + positive_expr_value, -99, 99);
}
return true;
case ConditionType::TP_GROWTH:
if (unknown_p7 & 4) {
this->send_6xB4x06_for_stat_delta(card, attacker_card_ref, 0x80, positive_expr_value, 0, 1);
card->tp = is_nte
? (card->tp + positive_expr_value)
: clamp<int16_t>(card->tp + positive_expr_value, -99, 99);
card->tp = is_nte ? (card->tp + positive_expr_value) : clamp<int16_t>(card->tp + positive_expr_value, -99, 99);
}
return true;
@@ -2593,8 +2569,7 @@ bool CardSpecial::execute_effect(
if (is_nte) {
return false;
}
if ((unknown_p7 & 0x40) &&
(static_cast<uint16_t>(attack_medium) == ((s->get_round_num() >> 1) & 1) + 1)) {
if ((unknown_p7 & 0x40) && (static_cast<uint16_t>(attack_medium) == ((s->get_round_num() >> 1) & 1) + 1)) {
card->action_metadata.attack_bonus = 0;
}
return true;
@@ -2668,10 +2643,7 @@ bool CardSpecial::execute_effect(
}
const Condition* CardSpecial::find_condition_with_parameters(
shared_ptr<const Card> card,
ConditionType cond_type,
uint16_t set_card_ref,
uint8_t def_effect_index) const {
shared_ptr<const Card> card, ConditionType cond_type, uint16_t set_card_ref, uint8_t def_effect_index) const {
if (this->server()->options.is_nte()) {
// The NTE version of this function returns a boolean instead of a pointer;
@@ -2711,18 +2683,13 @@ const Condition* CardSpecial::find_condition_with_parameters(
}
Condition* CardSpecial::find_condition_with_parameters(
shared_ptr<Card> card,
ConditionType cond_type,
uint16_t set_card_ref,
uint8_t def_effect_index) const {
shared_ptr<Card> card, ConditionType cond_type, uint16_t set_card_ref, uint8_t def_effect_index) const {
return const_cast<Condition*>(this->find_condition_with_parameters(
static_cast<shared_ptr<const Card>>(card), cond_type, set_card_ref, def_effect_index));
}
void CardSpecial::get_card1_loc_with_card2_opposite_direction(
Location* out_loc,
shared_ptr<const Card> card1,
shared_ptr<const Card> card2) {
Location* out_loc, shared_ptr<const Card> card1, shared_ptr<const Card> card2) {
if (card1) {
if (!card2 || (static_cast<uint8_t>(card2->facing_direction) & 0x80)) {
*out_loc = card1->loc;
@@ -2749,12 +2716,7 @@ uint16_t CardSpecial::get_card_id_with_effective_range(
}
void CardSpecial::get_effective_ap_tp(
StatSwapType type,
int16_t* effective_ap,
int16_t* effective_tp,
int16_t hp,
int16_t ap,
int16_t tp) {
StatSwapType type, int16_t* effective_ap, int16_t* effective_tp, int16_t hp, int16_t ap, int16_t tp) {
switch (type) {
case StatSwapType::NONE:
*effective_ap = ap;
@@ -2773,67 +2735,6 @@ void CardSpecial::get_effective_ap_tp(
}
}
const char* CardSpecial::get_next_expr_token(
const char* expr, ExpressionTokenType* out_type, int32_t* out_value) const {
switch (*expr) {
case '\0':
*out_type = ExpressionTokenType::SPACE;
return nullptr;
case ' ':
*out_type = ExpressionTokenType::SPACE;
return expr + 1;
case '+':
*out_type = ExpressionTokenType::ADD;
return expr + 1;
case '-':
*out_type = ExpressionTokenType::SUBTRACT;
return expr + 1;
case '*':
*out_type = ExpressionTokenType::MULTIPLY;
return expr + 1;
case '/':
if (expr[1] == '/') {
*out_type = ExpressionTokenType::FLOOR_DIVIDE;
return expr + 2;
} else {
*out_type = ExpressionTokenType::ROUND_DIVIDE;
return expr + 1;
}
}
if ((*expr >= 'a') && (*expr <= 'z')) {
string token_buf;
for (; (*expr >= 'a') && (*expr <= 'z'); expr++) {
token_buf.push_back(*expr);
}
*out_type = ExpressionTokenType::SPACE;
*out_value = 0x27;
static const vector<const char*> tokens = {
"f", "d", "ap", "tp", "hp", "mhp", "dm", "tdm", "tf", "ac", "php",
"dc", "cs", "a", "kap", "ktp", "dn", "hf", "df", "ff", "ef", "bi",
"ab", "mc", "dk", "sa", "gn", "wd", "tt", "lv", "adm", "ddm", "sat",
"edm", "ldm", "rdm", "fdm", "ndm", "ehp"};
for (size_t z = 0; z < tokens.size(); z++) {
if (token_buf == tokens[z]) {
*out_type = ExpressionTokenType::REFERENCE;
*out_value = z;
return expr;
}
}
return expr;
}
if ((*expr >= '0') && (*expr <= '9')) {
*out_type = ExpressionTokenType::NUMBER;
*out_value = strtol(expr, const_cast<char**>(&expr), 10);
return expr;
}
throw runtime_error("invalid card effect expression");
}
vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
uint16_t card_ref,
uint8_t def_effect_index,
@@ -2842,8 +2743,11 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
int16_t p_target_type,
bool apply_usability_filters) const {
auto s = this->server();
auto log = s->log_stack(std::format("get_targeted_cards_for_condition(@{:04X}, {}, @{:04X}): ", card_ref, def_effect_index, setter_card_ref));
log.debug_f("card_ref=@{:04X}, def_effect_index={:02X}, setter_card_ref=@{:04X}, as, p_target_type={}, apply_usability_filters={}", card_ref, def_effect_index, setter_card_ref, p_target_type, apply_usability_filters ? "true" : "false");
auto log = s->log_stack(std::format(
"get_targeted_cards_for_condition(@{:04X}, {}, @{:04X}): ", card_ref, def_effect_index, setter_card_ref));
log.debug_f(
"card_ref=@{:04X}, def_effect_index={:02X}, setter_card_ref=@{:04X}, as, p_target_type={}, apply_usability_filters={}",
card_ref, def_effect_index, setter_card_ref, p_target_type, apply_usability_filters ? "true" : "false");
vector<shared_ptr<const Card>> ret;
@@ -2871,9 +2775,7 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
log.debug_f("card1_loc={}", card1_loc_str);
}
AttackMedium attack_medium = card2
? card2->action_chain.chain.attack_medium
: AttackMedium::UNKNOWN;
AttackMedium attack_medium = card2 ? card2->action_chain.chain.attack_medium : AttackMedium::UNKNOWN;
log.debug_f("attack_medium={}", phosg::name_for_enum(attack_medium));
auto add_card_refs = [&](const vector<uint16_t>& result_card_refs) -> void {
@@ -3053,9 +2955,7 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
auto result_card_refs = ps->get_all_cards_within_range(range, card1_loc, card1->get_team_id());
for (uint16_t result_card_ref : result_card_refs) {
auto result_card = s->card_for_set_card_ref(result_card_ref);
if (result_card &&
(result_card->get_definition()->def.type != CardType::ITEM) &&
(card1 != result_card)) {
if (result_card && (result_card->get_definition()->def.type != CardType::ITEM) && (card1 != result_card)) {
ret.emplace_back(result_card);
}
}
@@ -3140,15 +3040,11 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
if (as.original_attacker_card_ref == 0xFFFF) {
for (size_t z = 0; (z < 4 * 9) && (as.target_card_refs[z] != 0xFFFF); z++) {
auto result_card = s->card_for_set_card_ref(as.target_card_refs[z]);
if (result_card &&
result_card->get_definition() &&
!result_card->get_definition()->def.is_sc()) {
if (result_card && result_card->get_definition() && !result_card->get_definition()->def.is_sc()) {
ret.emplace_back(result_card);
}
}
} else if (card2 &&
card2->get_definition() &&
!card2->get_definition()->def.is_sc()) {
} else if (card2 && card2->get_definition() && !card2->get_definition()->def.is_sc()) {
ret.emplace_back(card2);
}
break;
@@ -3250,8 +3146,7 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
case 0x28: { // p40
auto log3940 = log.sub("(p39/p40) ");
ret = this->find_all_set_cards_with_cost_in_range(
(p_target_type == 0x27) ? 4 : 0,
(p_target_type == 0x27) ? 99 : 3);
(p_target_type == 0x27) ? 4 : 0, (p_target_type == 0x27) ? 99 : 3);
if (log3940.should_log(phosg::LogLevel::L_DEBUG)) {
for (const auto& card : ret) {
log3940.debug_f("found target @{:04X} #{:04X}", card->get_card_ref(), card->get_card_id());
@@ -3290,8 +3185,7 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
if (!s->options.is_nte()) {
for (size_t z = 0; z < 8; z++) {
auto result_card = ps->get_set_card(z);
if (result_card && (card1 != result_card) &&
(result_card->get_definition()->def.type == CardType::ITEM)) {
if (result_card && (card1 != result_card) && (result_card->get_definition()->def.type == CardType::ITEM)) {
bool already_in_ret = false;
for (auto c : ret) {
if (c == result_card) {
@@ -3473,8 +3367,7 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
for (size_t set_index = 0; set_index < 8; set_index++) {
auto result_card = ps->get_set_card(set_index);
if (result_card && (card1 != result_card) &&
(result_card->get_definition()->def.type == CardType::ITEM)) {
if (result_card && (card1 != result_card) && (result_card->get_definition()->def.type == CardType::ITEM)) {
bool should_add = true;
for (auto c : ret) {
if (c == result_card) {
@@ -3520,9 +3413,7 @@ vector<shared_ptr<Card>> CardSpecial::get_targeted_cards_for_condition(
}
bool CardSpecial::is_card_targeted_by_condition(
const Condition& cond,
const ActionState& as,
shared_ptr<const Card> card) const {
const Condition& cond, const ActionState& as, shared_ptr<const Card> card) const {
auto s = this->server();
auto log = s->log_stack("is_card_targeted_by_condition: ");
@@ -3609,10 +3500,7 @@ bool CardSpecial::card_ref_has_ability_trap(const Condition& cond) const {
}
void CardSpecial::send_6xB4x06_for_exp_change(
shared_ptr<const Card> card,
uint16_t attacker_card_ref,
uint8_t dice_roll_value,
bool unknown_p5) const {
shared_ptr<const Card> card, uint16_t attacker_card_ref, uint8_t dice_roll_value, bool unknown_p5) const {
G_ApplyConditionEffect_Ep3_6xB4x06 cmd;
cmd.effect.flags = 0x02;
cmd.effect.attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(attacker_card_ref, 10);
@@ -3636,8 +3524,7 @@ void CardSpecial::send_6xB4x06_for_card_destroyed(
auto s = this->server();
G_ApplyConditionEffect_Ep3_6xB4x06 cmd;
cmd.effect.flags = 0x04;
cmd.effect.attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(
attacker_card_ref, 0x13);
cmd.effect.attacker_card_ref = this->send_6xB4x06_if_card_ref_invalid(attacker_card_ref, 0x13);
cmd.effect.target_card_ref = destroyed_card->get_card_ref();
cmd.effect.value = 0;
cmd.effect.operation = s->options.is_nte() ? 0x78 : 0x7E;
@@ -3776,9 +3663,7 @@ bool CardSpecial::should_return_card_ref_to_hand_on_destruction(
continue;
}
auto cond_type = card->action_chain.conditions[cond_index].type;
if ((cond_type == ConditionType::RETURN) &&
!(card->card_flags & 1) &&
(card->get_card_ref() == card_ref)) {
if ((cond_type == ConditionType::RETURN) && !(card->card_flags & 1) && (card->get_card_ref() == card_ref)) {
return true;
} else if ((cond_type == ConditionType::REBORN) &&
!(card->card_flags & 3) &&
@@ -3798,9 +3683,7 @@ bool CardSpecial::should_return_card_ref_to_hand_on_destruction(
}
size_t CardSpecial::sum_last_attack_damage(
vector<shared_ptr<const Card>>* out_cards,
int32_t* out_damage_sum,
size_t* out_damage_count) const {
vector<shared_ptr<const Card>>* out_cards, int32_t* out_damage_sum, size_t* out_damage_count) const {
auto log = this->server()->log_stack("sum_last_attack_damage: ");
size_t damage_count = 0;
@@ -3924,9 +3807,7 @@ void CardSpecial::apply_effects_after_card_move(shared_ptr<Card> card) {
}
void CardSpecial::check_for_defense_interference(
shared_ptr<const Card> attacker_card,
shared_ptr<Card> target_card,
int16_t* inout_unknown_p4) {
shared_ptr<const Card> attacker_card, shared_ptr<Card> target_card, int16_t* inout_unknown_p4) {
auto s = this->server();
// Note: This check is not part of the original implementation.
@@ -3941,8 +3822,7 @@ void CardSpecial::check_for_defense_interference(
return;
}
uint16_t ally_sc_card_ref = s->ruler_server->get_ally_sc_card_ref(
target_card->get_card_ref());
uint16_t ally_sc_card_ref = s->ruler_server->get_ally_sc_card_ref(target_card->get_card_ref());
if (ally_sc_card_ref == 0xFFFF) {
return;
}
@@ -3963,7 +3843,8 @@ void CardSpecial::check_for_defense_interference(
}
auto ally_hes = s->ruler_server->get_hand_and_equip_state_for_client_id(target_ally_client_id);
if (!ally_hes || (!(s->options.behavior_flags & BehaviorFlag::ALLOW_NON_COM_INTERFERENCE) && !ally_hes->is_cpu_player)) {
if (!ally_hes ||
(!(s->options.behavior_flags & BehaviorFlag::ALLOW_NON_COM_INTERFERENCE) && !ally_hes->is_cpu_player)) {
return;
}
@@ -3984,8 +3865,7 @@ void CardSpecial::check_for_defense_interference(
if (target_ps->unknown_a17 >= 1) {
return;
}
auto entry = get_interference_probability_entry(
target_card_id, ally_sc_card_id, false);
auto entry = get_interference_probability_entry(target_card_id, ally_sc_card_id, false);
if (!entry || (s->get_random(99) >= entry->defense_probability)) {
return;
}
@@ -4019,7 +3899,12 @@ void CardSpecial::evaluate_and_apply_effects(
{
string as_str = as.str(s);
log.debug_f("when={}, set_card_ref=@{:04X}, as={}, sc_card_ref=@{:04X}, apply_defense_condition_to_all_cards={}, apply_defense_condition_to_card_ref=@{:04X}",
phosg::name_for_enum(when), set_card_ref, as_str, sc_card_ref, apply_defense_condition_to_all_cards ? "true" : "false", apply_defense_condition_to_card_ref);
phosg::name_for_enum(when),
set_card_ref,
as_str,
sc_card_ref,
apply_defense_condition_to_all_cards ? "true" : "false",
apply_defense_condition_to_card_ref);
}
if (!is_nte) {
@@ -4076,13 +3961,15 @@ void CardSpecial::evaluate_and_apply_effects(
dice_roll.unknown_a2 = 3;
dice_roll.value_used_in_expr = false;
log.debug_f("inputs: dice_roll={:02X}, random_percent={}, unknown_v1={}", dice_roll.value, random_percent, unknown_v1 ? "true" : "false");
log.debug_f("inputs: dice_roll={:02X}, random_percent={}, unknown_v1={}",
dice_roll.value, random_percent, unknown_v1 ? "true" : "false");
for (size_t def_effect_index = 0; (def_effect_index < 3) && !unknown_v1 && (ce->def.effects[def_effect_index].type != ConditionType::NONE); def_effect_index++) {
for (size_t def_effect_index = 0;
(def_effect_index < 3) && !unknown_v1 && (ce->def.effects[def_effect_index].type != ConditionType::NONE);
def_effect_index++) {
auto effect_log = log.sub(std::format("(effect:{}) ", def_effect_index));
const auto& card_effect = ce->def.effects[def_effect_index];
string card_effect_str = card_effect.str();
effect_log.debug_f("effect: {}", card_effect_str);
effect_log.debug_f("effect: {}", card_effect.str());
if (card_effect.when != when) {
effect_log.debug_f("does not apply (effect.when={}, when={})", phosg::name_for_enum(card_effect.when), phosg::name_for_enum(when));
continue;
@@ -4199,9 +4086,16 @@ void CardSpecial::evaluate_and_apply_effects(
target_card->action_chain.conditions[applied_cond_index].flags |= 1;
}
if (apply_defense_condition_to_all_cards || (apply_defense_condition_to_card_ref == targeted_cards[z]->get_card_ref())) {
if (apply_defense_condition_to_all_cards ||
(apply_defense_condition_to_card_ref == targeted_cards[z]->get_card_ref())) {
this->apply_defense_condition(
when, &target_card->action_chain.conditions[applied_cond_index], applied_cond_index, as, target_card, 4, 1);
when,
&target_card->action_chain.conditions[applied_cond_index],
applied_cond_index,
as,
target_card,
4,
1);
target_log.debug_f("applied defense condition");
}
}
@@ -4472,8 +4366,7 @@ const InterferenceProbabilityEntry* get_interference_probability_entry(
const auto& entry = entries[z];
uint16_t current_column_card_id = entry.card_id;
if ((entry.attack_probability != 0xFF) || (entry.defense_probability != 0xFF)) {
if ((row_card_id == current_row_card_id) &&
(column_card_id == current_column_card_id)) {
if ((row_card_id == current_row_card_id) && (column_card_id == current_column_card_id)) {
uint8_t v = is_attack ? entry.attack_probability : entry.defense_probability;
if (current_max <= v) {
ret_entry = &entry;
@@ -4488,11 +4381,9 @@ const InterferenceProbabilityEntry* get_interference_probability_entry(
return ret_entry;
}
void CardSpecial::on_card_destroyed(
shared_ptr<Card> attacker_card, shared_ptr<Card> destroyed_card) {
void CardSpecial::on_card_destroyed(shared_ptr<Card> attacker_card, shared_ptr<Card> destroyed_card) {
ActionState attack_as = this->create_attack_state_from_card_action_chain(attacker_card);
ActionState defense_as = this->create_defense_state_for_card_pair_action_chains(
attacker_card, destroyed_card);
ActionState defense_as = this->create_defense_state_for_card_pair_action_chains(attacker_card, destroyed_card);
uint16_t destroyed_card_ref = destroyed_card->get_card_ref();
this->evaluate_and_apply_effects(EffectWhen::CARD_DESTROYED, destroyed_card_ref, defense_as, 0xFFFF);
@@ -4513,8 +4404,7 @@ void CardSpecial::on_card_destroyed(
this->send_6xB4x06_for_card_destroyed(destroyed_card, attack_as.attacker_card_ref);
}
vector<shared_ptr<const Card>> CardSpecial::find_cards_in_hp_range(
int16_t min, int16_t max) const {
vector<shared_ptr<const Card>> CardSpecial::find_cards_in_hp_range(int16_t min, int16_t max) const {
vector<shared_ptr<const Card>> ret;
for (size_t client_id = 0; client_id < 4; client_id++) {
auto ps = this->server()->get_player_state(client_id);
@@ -4786,8 +4676,7 @@ vector<shared_ptr<const Card>> CardSpecial::filter_cards_by_range(
void CardSpecial::apply_effects_after_attack_target_resolution(const ActionState& as) {
auto s = this->server();
auto log = s->log_stack("apply_effects_after_attack_target_resolution: ");
string as_str = as.str(s);
log.debug_f("as={}", as_str);
log.debug_f("as={}", as.str(s));
for (size_t z = 0; (z < 8) && (as.action_card_refs[z] != 0xFFFF); z++) {
uint16_t card_ref = this->send_6xB4x06_if_card_ref_invalid(as.action_card_refs[z], 0x1E);
@@ -4878,7 +4767,12 @@ void CardSpecial::dice_phase_before_for_card(shared_ptr<Card> card) {
template <EffectWhen When1, EffectWhen When2>
void CardSpecial::apply_effects_on_phase_change_t(shared_ptr<Card> unknown_p2, const ActionState* existing_as) {
auto s = this->server();
auto log = s->log_stack(std::format("apply_effects_on_phase_change_t<{}, {}>(@{:04X} #{:04X}): ", phosg::name_for_enum(When1), phosg::name_for_enum(When2), unknown_p2->get_card_ref(), unknown_p2->get_card_id()));
auto log = s->log_stack(std::format(
"apply_effects_on_phase_change_t<{}, {}>(@{:04X} #{:04X}): ",
phosg::name_for_enum(When1),
phosg::name_for_enum(When2),
unknown_p2->get_card_ref(),
unknown_p2->get_card_id()));
bool is_nte = s->options.is_nte();
ActionState as;
@@ -4904,8 +4798,7 @@ void CardSpecial::apply_effects_on_phase_change_t(shared_ptr<Card> unknown_p2, c
for (size_t z = 0; (z < 4 * 9) && (as.target_card_refs[z] != 0xFFFF); z++) {
auto card = s->card_for_set_card_ref(as.target_card_refs[z]);
if (card) {
ActionState target_as = this->create_defense_state_for_card_pair_action_chains(
unknown_p2, card);
ActionState target_as = this->create_defense_state_for_card_pair_action_chains(unknown_p2, card);
this->evaluate_and_apply_effects(When2, as.target_card_refs[z], target_as, unknown_p2->get_card_ref());
for (size_t w = 0; (w < 8) && (target_as.action_card_refs[w] != 0xFFFF); w++) {
this->evaluate_and_apply_effects(When1, target_as.action_card_refs[w], target_as, card->get_card_ref());
@@ -4925,11 +4818,13 @@ void CardSpecial::action_phase_before_for_card(shared_ptr<Card> unknown_p2) {
}
void CardSpecial::unknown_8024945C(shared_ptr<Card> unknown_p2, const ActionState* existing_as) {
this->apply_effects_on_phase_change_t<EffectWhen::UNKNOWN_0A, EffectWhen::UNKNOWN_0A>(unknown_p2, this->server()->options.is_nte() ? nullptr : existing_as);
this->apply_effects_on_phase_change_t<EffectWhen::UNKNOWN_0A, EffectWhen::UNKNOWN_0A>(
unknown_p2, this->server()->options.is_nte() ? nullptr : existing_as);
}
void CardSpecial::unknown_8024966C(shared_ptr<Card> unknown_p2, const ActionState* existing_as) {
auto log = this->server()->log_stack(std::format("unknown_8024966C(@{:04X} #{:04X}): ", unknown_p2->get_card_ref(), unknown_p2->get_card_id()));
auto log = this->server()->log_stack(std::format("unknown_8024966C(@{:04X} #{:04X}): ",
unknown_p2->get_card_ref(), unknown_p2->get_card_id()));
ActionState as;
if (!existing_as) {
@@ -4966,16 +4861,20 @@ void CardSpecial::unknown_8024966C(shared_ptr<Card> unknown_p2, const ActionStat
}
for (size_t z = 0; (z < 8) && (as.action_card_refs[z] != 0xFFFF); z++) {
this->evaluate_and_apply_effects(EffectWhen::ATTACK_STAT_OVERRIDES, as.action_card_refs[z], as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(EffectWhen::ATTACK_DAMAGE_ADJUSTMENT, as.action_card_refs[z], as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(
EffectWhen::ATTACK_STAT_OVERRIDES, as.action_card_refs[z], as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(
EffectWhen::ATTACK_DAMAGE_ADJUSTMENT, as.action_card_refs[z], as, unknown_p2->get_card_ref());
}
for (size_t z = 0; (z < 4 * 9) && (as.target_card_refs[z] != 0xFFFF); z++) {
card = this->server()->card_for_set_card_ref(as.target_card_refs[z]);
if (card) {
ActionState defense_as = this->create_defense_state_for_card_pair_action_chains(unknown_p2, card);
this->evaluate_and_apply_effects(EffectWhen::ATTACK_STAT_OVERRIDES, card->get_card_ref(), defense_as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(EffectWhen::DEFENSE_DAMAGE_ADJUSTMENT, card->get_card_ref(), defense_as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(
EffectWhen::ATTACK_STAT_OVERRIDES, card->get_card_ref(), defense_as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(
EffectWhen::DEFENSE_DAMAGE_ADJUSTMENT, card->get_card_ref(), defense_as, unknown_p2->get_card_ref());
}
}
}
@@ -4987,7 +4886,8 @@ shared_ptr<Card> CardSpecial::sc_card_for_card(shared_ptr<Card> unknown_p2) {
void CardSpecial::unknown_8024A9D8(const ActionState& pa, uint16_t action_card_ref) {
for (size_t z = 0; (z < 8) && (pa.action_card_refs[z] != 0xFFFF); z++) {
if (this->server()->options.is_nte() || (action_card_ref == 0xFFFF) || (action_card_ref == pa.action_card_refs[z])) {
if (this->server()->options.is_nte() ||
(action_card_ref == 0xFFFF) || (action_card_ref == pa.action_card_refs[z])) {
if (pa.original_attacker_card_ref == 0xFFFF) {
this->evaluate_and_apply_effects(EffectWhen::UNKNOWN_29, pa.action_card_refs[z], pa, pa.attacker_card_ref);
this->evaluate_and_apply_effects(EffectWhen::UNKNOWN_2A, pa.action_card_refs[z], pa, pa.attacker_card_ref);
@@ -5009,8 +4909,7 @@ void CardSpecial::check_for_attack_interference(shared_ptr<Card> unknown_p2) {
return;
}
uint16_t ally_sc_card_ref = this->server()->ruler_server->get_ally_sc_card_ref(
unknown_p2->get_card_ref());
uint16_t ally_sc_card_ref = this->server()->ruler_server->get_ally_sc_card_ref(unknown_p2->get_card_ref());
if (ally_sc_card_ref == 0xFFFF) {
return;
}
@@ -5081,7 +4980,12 @@ template <
void CardSpecial::apply_effects_before_or_after_attack(shared_ptr<Card> unknown_p2) {
auto s = this->server();
auto log = s->log_stack(std::format("apply_effects_before_or_after_attack<{}, {}, {}, {}>(@{:04X} #{:04X}): ",
phosg::name_for_enum(WhenAllCards), phosg::name_for_enum(WhenAttackerAndActionCards), phosg::name_for_enum(WhenAttackerOrHunterSCCard), phosg::name_for_enum(WhenTargetsAndActionCards), unknown_p2->get_card_ref(), unknown_p2->get_card_id()));
phosg::name_for_enum(WhenAllCards),
phosg::name_for_enum(WhenAttackerAndActionCards),
phosg::name_for_enum(WhenAttackerOrHunterSCCard),
phosg::name_for_enum(WhenTargetsAndActionCards),
unknown_p2->get_card_ref(),
unknown_p2->get_card_id()));
ActionState as = this->create_attack_state_from_card_action_chain(unknown_p2);
@@ -5119,17 +5023,21 @@ void CardSpecial::apply_effects_before_or_after_attack(shared_ptr<Card> unknown_
}
for (size_t z = 0; (z < 8) && (as.action_card_refs[z] != 0xFFFF); z++) {
this->evaluate_and_apply_effects(WhenAllCards, as.action_card_refs[z], as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(WhenAttackerAndActionCards, as.action_card_refs[z], as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(
WhenAttackerAndActionCards, as.action_card_refs[z], as, unknown_p2->get_card_ref());
}
for (size_t z = 0; (z < 4 * 9) && (as.target_card_refs[z] != 0xFFFF); z++) {
auto set_card = s->card_for_set_card_ref(as.target_card_refs[z]);
if (set_card) {
ActionState target_as = this->create_defense_state_for_card_pair_action_chains(unknown_p2, set_card);
this->evaluate_and_apply_effects(WhenAllCards, set_card->get_card_ref(), target_as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(WhenTargetsAndActionCards, set_card->get_card_ref(), target_as, unknown_p2->get_card_ref());
this->evaluate_and_apply_effects(
WhenTargetsAndActionCards, set_card->get_card_ref(), target_as, unknown_p2->get_card_ref());
for (size_t z = 0; (z < 8) && (target_as.action_card_refs[z] != 0xFFFF); z++) {
this->evaluate_and_apply_effects(WhenAllCards, target_as.action_card_refs[z], target_as, set_card->get_card_ref());
this->evaluate_and_apply_effects(WhenTargetsAndActionCards, target_as.action_card_refs[z], target_as, set_card->get_card_ref());
this->evaluate_and_apply_effects(
WhenAllCards, target_as.action_card_refs[z], target_as, set_card->get_card_ref());
this->evaluate_and_apply_effects(
WhenTargetsAndActionCards, target_as.action_card_refs[z], target_as, set_card->get_card_ref());
}
}
}
@@ -5182,16 +5090,14 @@ bool CardSpecial::client_has_atk_dice_boost_condition(uint8_t client_id) {
}
void CardSpecial::unknown_8024A6DC(shared_ptr<Card> unknown_p2, shared_ptr<Card> unknown_p3) {
ActionState as = this->create_defense_state_for_card_pair_action_chains(
unknown_p2, unknown_p3);
ActionState as = this->create_defense_state_for_card_pair_action_chains(unknown_p2, unknown_p3);
for (size_t z = 0; (z < 8) && (as.action_card_refs[z] != 0xFFFF); z++) {
this->evaluate_and_apply_effects(EffectWhen::CARD_SET, as.action_card_refs[z], as, unknown_p3->get_card_ref());
this->evaluate_and_apply_effects(EffectWhen::UNKNOWN_15, as.action_card_refs[z], as, unknown_p3->get_card_ref());
}
}
vector<shared_ptr<const Card>> CardSpecial::find_all_sc_cards_of_class(
CardClass card_class) const {
vector<shared_ptr<const Card>> CardSpecial::find_all_sc_cards_of_class(CardClass card_class) const {
vector<shared_ptr<const Card>> ret;
for (size_t z = 0; z < 4; z++) {
auto ps = this->server()->get_player_state(z);
+34 -94
View File
@@ -17,23 +17,10 @@ struct InterferenceProbabilityEntry {
};
const InterferenceProbabilityEntry* get_interference_probability_entry(
uint16_t row_card_id,
uint16_t column_card_id,
bool is_attack);
uint16_t row_card_id, uint16_t column_card_id, bool is_attack);
class CardSpecial {
public:
enum class ExpressionTokenType {
SPACE = 0, // Also used for end of string (get_next_expr_token returns null)
REFERENCE = 1, // Reference to a value from the env stats (e.g. hp)
NUMBER = 2, // Constant value (e.g. 2)
SUBTRACT = 3, // "-" in input string
ADD = 4, // "+" in input string
ROUND_DIVIDE = 5, // "/" in input string
FLOOR_DIVIDE = 6, // "//" in input string
MULTIPLY = 7, // "*" in input string
};
struct DiceRoll {
uint8_t client_id;
uint8_t unknown_a2;
@@ -77,9 +64,8 @@ public:
/* 70 */ uint32_t effective_ap_if_not_tech2; // "tt" in expr
/* 74 */ uint32_t team_dice_bonus; // "lv" in expr
/* 78 */ uint32_t sc_effective_ap; // "adm" in expr
// The following fields do not exist in Trial Edition. Because this struct
// is never sent to the client, we use the full struct even when playing
// Trial Edition, just for simplicity.
// The following fields do not exist in Trial Edition. Because this struct is never sent to the client, we use the
// full struct even when playing Trial Edition, just for simplicity.
/* 7C */ uint32_t attack_bonus; // "ddm" in expr
/* 80 */ uint32_t num_sword_type_items_on_team; // "sat" in expr
/* 84 */ uint32_t target_attack_bonus; // "edm" in expr
@@ -126,26 +112,14 @@ public:
uint32_t flags,
bool unknown_p8);
bool apply_defense_conditions(
const ActionState& as,
EffectWhen when,
std::shared_ptr<Card> defender_card,
uint32_t flags);
bool apply_stat_deltas_to_all_cards_from_all_conditions_with_card_ref(
uint16_t card_ref);
bool apply_stat_deltas_to_card_from_condition_and_clear_cond(
Condition& cond, std::shared_ptr<Card> card);
bool apply_stats_deltas_to_card_from_all_conditions_with_card_ref(
uint16_t card_ref, std::shared_ptr<Card> card);
const ActionState& as, EffectWhen when, std::shared_ptr<Card> defender_card, uint32_t flags);
bool apply_stat_deltas_to_all_cards_from_all_conditions_with_card_ref(uint16_t card_ref);
bool apply_stat_deltas_to_card_from_condition_and_clear_cond(Condition& cond, std::shared_ptr<Card> card);
bool apply_stats_deltas_to_card_from_all_conditions_with_card_ref(uint16_t card_ref, std::shared_ptr<Card> card);
bool card_has_condition_with_ref(
std::shared_ptr<const Card> card,
ConditionType cond_type,
uint16_t card_ref,
uint16_t match_card_ref) const;
std::shared_ptr<const Card> card, ConditionType cond_type, uint16_t card_ref, uint16_t match_card_ref) const;
bool card_is_destroyed(std::shared_ptr<const Card> card) const;
void compute_attack_ap(
std::shared_ptr<const Card> target_card,
int16_t* out_value,
uint16_t attacker_card_ref);
void compute_attack_ap(std::shared_ptr<const Card> target_card, int16_t* out_value, uint16_t attacker_card_ref);
AttackEnvStats compute_attack_env_stats(
const ActionState& pa,
std::shared_ptr<const Card> card,
@@ -166,21 +140,16 @@ public:
StatSwapType compute_stat_swap_type(std::shared_ptr<const Card> card) const;
void compute_team_dice_bonus(uint8_t team_id);
bool condition_applies_on_sc_or_item_attack(const Condition& cond) const;
size_t count_action_cards_with_condition_for_all_current_attacks(
ConditionType cond_type, uint16_t card_ref) const;
size_t count_action_cards_with_condition_for_all_current_attacks(ConditionType cond_type, uint16_t card_ref) const;
size_t count_action_cards_with_condition_for_current_attack(
std::shared_ptr<const Card> card, ConditionType cond_type, uint16_t card_ref) const;
size_t count_cards_with_card_id_except_card_ref(
uint16_t card_id, uint16_t card_ref) const;
size_t count_cards_with_card_id_except_card_ref(uint16_t card_id, uint16_t card_ref) const;
std::vector<std::shared_ptr<const Card>> get_all_set_cards_by_team_and_class(
CardClass card_class, uint8_t team_id, bool exclude_destroyed_cards) const;
ActionState create_attack_state_from_card_action_chain(
std::shared_ptr<const Card> attacker_card) const;
ActionState create_attack_state_from_card_action_chain(std::shared_ptr<const Card> attacker_card) const;
ActionState create_defense_state_for_card_pair_action_chains(
std::shared_ptr<const Card> attacker_card,
std::shared_ptr<const Card> defender_card) const;
void destroy_card_if_hp_zero(
std::shared_ptr<Card> card, uint16_t attacker_card_ref);
std::shared_ptr<const Card> attacker_card, std::shared_ptr<const Card> defender_card) const;
void destroy_card_if_hp_zero(std::shared_ptr<Card> card, uint16_t attacker_card_ref);
bool evaluate_effect_arg2_condition(
const ActionState& as,
std::shared_ptr<const Card> card,
@@ -190,10 +159,7 @@ public:
uint16_t sc_card_ref,
uint8_t random_percent,
EffectWhen when) const;
int32_t evaluate_effect_expr(
const AttackEnvStats& ast,
const char* expr,
DiceRoll& dice_roll) const;
int32_t evaluate_effect_expr(const AttackEnvStats& ast, const char* expr, DiceRoll& dice_roll) const;
bool execute_effect(
Condition& cond,
std::shared_ptr<Card> card,
@@ -208,25 +174,13 @@ public:
uint16_t set_card_ref,
uint8_t def_effect_index) const;
Condition* find_condition_with_parameters(
std::shared_ptr<Card> card,
ConditionType cond_type,
uint16_t set_card_ref,
uint8_t def_effect_index) const;
std::shared_ptr<Card> card, ConditionType cond_type, uint16_t set_card_ref, uint8_t def_effect_index) const;
static void get_card1_loc_with_card2_opposite_direction(
Location* out_loc,
std::shared_ptr<const Card> card1,
std::shared_ptr<const Card> card2);
Location* out_loc, std::shared_ptr<const Card> card1, std::shared_ptr<const Card> card2);
uint16_t get_card_id_with_effective_range(
std::shared_ptr<const Card> card1, uint16_t default_card_id, std::shared_ptr<const Card> card2) const;
static void get_effective_ap_tp(
StatSwapType type,
int16_t* effective_ap,
int16_t* effective_tp,
int16_t hp,
int16_t ap,
int16_t tp);
const char* get_next_expr_token(
const char* expr, ExpressionTokenType* out_type, int32_t* out_value) const;
StatSwapType type, int16_t* effective_ap, int16_t* effective_tp, int16_t hp, int16_t ap, int16_t tp);
std::vector<std::shared_ptr<const Card>> get_targeted_cards_for_condition(
uint16_t card_ref,
uint8_t def_effect_index,
@@ -244,18 +198,12 @@ public:
bool is_card_targeted_by_condition(
const Condition& cond, const ActionState& as, std::shared_ptr<const Card> card) const;
void on_card_set(std::shared_ptr<PlayerState> ps, uint16_t card_ref);
const CardDefinition::Effect* original_definition_for_condition(
const Condition& cond) const;
const CardDefinition::Effect* original_definition_for_condition(const Condition& cond) const;
bool card_ref_has_ability_trap(const Condition& eff) const;
void send_6xB4x06_for_exp_change(
std::shared_ptr<const Card> card,
uint16_t attacker_card_ref,
uint8_t dice_roll_value,
bool unknown_p5) const;
void send_6xB4x06_for_card_destroyed(
std::shared_ptr<const Card> destroyed_card, uint16_t attacker_card_ref) const;
uint16_t send_6xB4x06_if_card_ref_invalid(
uint16_t card_ref, int16_t value) const;
std::shared_ptr<const Card> card, uint16_t attacker_card_ref, uint8_t dice_roll_value, bool unknown_p5) const;
void send_6xB4x06_for_card_destroyed(std::shared_ptr<const Card> destroyed_card, uint16_t attacker_card_ref) const;
uint16_t send_6xB4x06_if_card_ref_invalid(uint16_t card_ref, int16_t value) const;
void send_6xB4x06_for_stat_delta(
std::shared_ptr<const Card> card,
uint16_t attacker_card_ref,
@@ -268,19 +216,14 @@ public:
std::shared_ptr<const Card> card,
uint16_t target_card_ref,
uint16_t sc_card_ref) const;
bool should_return_card_ref_to_hand_on_destruction(
uint16_t card_ref) const;
bool should_return_card_ref_to_hand_on_destruction(uint16_t card_ref) const;
size_t sum_last_attack_damage(
std::vector<std::shared_ptr<const Card>>* out_cards,
int32_t* out_damage_sum,
size_t* out_damage_count) const;
std::vector<std::shared_ptr<const Card>>* out_cards, int32_t* out_damage_sum, size_t* out_damage_count) const;
void update_condition_orders(std::shared_ptr<Card> card);
int16_t max_all_attack_bonuses(size_t* out_count) const;
void apply_effects_after_card_move(std::shared_ptr<Card> card);
void check_for_defense_interference(
std::shared_ptr<const Card> attacker_card,
std::shared_ptr<Card> target_card,
int16_t* inout_unknown_p4);
std::shared_ptr<const Card> attacker_card, std::shared_ptr<Card> target_card, int16_t* inout_unknown_p4);
void evaluate_and_apply_effects(
EffectWhen when,
uint16_t set_card_ref,
@@ -294,20 +237,19 @@ public:
ConditionType exclude_cond = ConditionType::NONE,
AssistEffect include_eff = AssistEffect::NONE,
AssistEffect exclude_eff = AssistEffect::NONE) const;
void clear_invalid_conditions_on_card(
std::shared_ptr<Card> card, const ActionState& as);
void on_card_destroyed(
std::shared_ptr<Card> attacker_card, std::shared_ptr<Card> destroyed_card);
std::vector<std::shared_ptr<const Card>> find_cards_in_hp_range(
int16_t min, int16_t max) const;
void clear_invalid_conditions_on_card(std::shared_ptr<Card> card, const ActionState& as);
void on_card_destroyed(std::shared_ptr<Card> attacker_card, std::shared_ptr<Card> destroyed_card);
std::vector<std::shared_ptr<const Card>> find_cards_in_hp_range(int16_t min, int16_t max) const;
std::vector<std::shared_ptr<const Card>> find_all_cards_by_aerial_attribute(bool is_aerial) const;
std::vector<std::shared_ptr<const Card>> find_cards_damaged_by_at_least(int16_t damage) const;
std::vector<std::shared_ptr<const Card>> find_all_set_cards_on_client_team(uint8_t client_id) const;
std::vector<std::shared_ptr<const Card>> find_all_cards_on_same_or_other_team(uint8_t client_id, bool same_team) const;
std::vector<std::shared_ptr<const Card>> find_all_cards_on_same_or_other_team(
uint8_t client_id, bool same_team) const;
std::shared_ptr<const Card> sc_card_for_client_id(uint8_t client_id) const;
std::shared_ptr<const Card> get_attacker_card(const ActionState& as) const;
std::vector<std::shared_ptr<const Card>> get_attacker_card_and_sc_if_item(const ActionState& as) const;
std::vector<std::shared_ptr<const Card>> find_all_set_cards_with_cost_in_range(uint8_t min_cost, uint8_t max_cost) const;
std::vector<std::shared_ptr<const Card>> find_all_set_cards_with_cost_in_range(
uint8_t min_cost, uint8_t max_cost) const;
std::vector<std::shared_ptr<const Card>> filter_cards_by_range(
const std::vector<std::shared_ptr<const Card>>& cards,
std::shared_ptr<const Card> card1,
@@ -334,10 +276,8 @@ public:
void apply_effects_before_attack(std::shared_ptr<Card> card);
void apply_effects_after_attack(std::shared_ptr<Card> card);
bool client_has_atk_dice_boost_condition(uint8_t client_id);
void unknown_8024A6DC(
std::shared_ptr<Card> unknown_p2, std::shared_ptr<Card> unknown_p3);
std::vector<std::shared_ptr<const Card>> find_all_sc_cards_of_class(
CardClass card_class) const;
void unknown_8024A6DC(std::shared_ptr<Card> unknown_p2, std::shared_ptr<Card> unknown_p3);
std::vector<std::shared_ptr<const Card>> find_all_sc_cards_of_class(CardClass card_class) const;
private:
std::weak_ptr<Server> w_server;
+398 -204
View File
@@ -102,10 +102,8 @@ Location::Location(uint8_t x, uint8_t y, Direction direction)
unused(0) {}
bool Location::operator==(const Location& other) const {
return (this->x == other.x) &&
(this->y == other.y) &&
(this->direction == other.direction) &&
(this->unused == other.unused);
return (this->x == other.x) && (this->y == other.y) &&
(this->direction == other.direction) && (this->unused == other.unused);
}
bool Location::operator!=(const Location& other) const {
return !this->operator==(other);
@@ -176,81 +174,66 @@ Direction turn_around(Direction d) {
}
bool card_class_is_tech_like(CardClass cc, bool is_nte) {
// NTE does not consider BOSS_TECH to be a tech-like card class, but that's
// probably because that card class just doesn't exist on NTE.
if (is_nte) {
return (cc == CardClass::TECH) || (cc == CardClass::PHOTON_BLAST);
} else {
return (cc == CardClass::TECH) || (cc == CardClass::PHOTON_BLAST) || (cc == CardClass::BOSS_TECH);
}
// NTE does not consider BOSS_TECH to be a tech-like card class, but that's probably because that card class just
// doesn't exist on NTE.
return (cc == CardClass::TECH) || (cc == CardClass::PHOTON_BLAST) || (!is_nte && (cc == CardClass::BOSS_TECH));
}
static const unordered_map<string, const char*> description_for_expr_token({
{"f", "Number of FCs controlled by current SC"},
{"d", "Die roll"},
{"ap", "Attacker effective AP"},
{"tp", "Attacker effective TP"},
{"hp", "Current HP"},
{"mhp", "Maximum HP"},
{"dm", "Physical damage"},
{"tdm", "Technique damage"},
{"tf", "Number of SC\'s destroyed FCs"},
{"ac", "Remaining ATK points"},
{"php", "Maximum HP"},
{"dc", "Die roll"},
{"cs", "Card set cost"},
{"a", "Number of FCs on all teams"},
{"kap", "Action cards AP"},
{"ktp", "Action cards TP"},
{"dn", "Unknown: dn"},
{"hf", "Number of item or creature cards in hand"},
{"df", "Number of destroyed ally FCs (including SC\'s own)"},
{"ff", "Number of ally FCs (including SC\'s own)"},
{"ef", "Number of enemy FCs"},
{"bi", "Number of Native FCs on either team"},
{"ab", "Number of A.Beast FCs on either team"},
{"mc", "Number of Machine FCs on either team"},
{"dk", "Number of Dark FCs on either team"},
{"sa", "Number of Sword-type items on either team"},
{"gn", "Number of Gun-type items on either team"},
{"wd", "Number of Cane-type items on either team"},
{"tt", "Physical damage"},
{"lv", "Dice boost"},
{"adm", "SC attack damage"},
{"ddm", "Attack bonus"},
{"sat", "Number of Sword-type items on SC\'s team"},
{"edm", "Target attack bonus"},
{"ldm", "Last attack damage before defense"}, // Unused
{"rdm", "Last attack damage"},
{"fdm", "Final damage (after defense)"},
{"ndm", "Unknown: ndm"}, // Unused
{"ehp", "Attacker HP"},
});
// Arguments are encoded as 3-character null-terminated strings (why?!), and are
// used for adding conditions to effects (e.g. making them only trigger in
// certain situations) or otherwise customizing their results. The arguments are
// heterogeneous based on their position; that is, the first argument always has
// the same meaning, and meaning letters that are valid in arg1 are not
// necessarily valid in arg2, etc.
// Argument meanings:
// a01 = ???
// e00 = effect lasts while equipped? (in contrast to tXX)
// pXX = who to target (see description_for_p_target)
// In arg2:
// bXX = require attack doing not more than XX damage
// cXY/CXY = linked items (require item with cYX/CYX to be equipped as well)
// dXY = roll one die; require result between X and Y inclusive
// hXX = require HP >= XX
// iXX = require HP <= XX
// mXX = require attack doing at least XX damage
// nXX = require condition (see description_for_n_condition below)
// oXX = seems to be "require previous random-condition effect to have happened"
// TODO: this is used as both o01 (recovery) and o11 (reflection)
// conditions - why the difference?
// rXX = randomly pass with XX% chance (if XX == 00, 100% chance?)
// sXY = require card cost between X and Y ATK points (inclusive)
// tXX = lasts XX turns, or activate after XX turns
struct ExprTokenDefinition {
int32_t value;
std::string token;
std::string description;
};
static const vector<ExprTokenDefinition> expr_token_defs{
{0x00, "f", "Number of FCs controlled by current SC"},
{0x01, "d", "Die roll"},
{0x02, "ap", "Attacker effective AP"},
{0x03, "tp", "Attacker effective TP"},
{0x04, "hp", "Current HP"},
{0x05, "mhp", "Maximum HP"},
{0x06, "dm", "Physical damage"},
{0x07, "tdm", "Technique damage"},
{0x08, "tf", "Number of SC\'s destroyed FCs"},
{0x09, "ac", "Remaining ATK points"},
{0x0A, "php", "Maximum HP"},
{0x0B, "dc", "Die roll"},
{0x0C, "cs", "Card set cost"},
{0x0D, "a", "Number of FCs on all teams"},
{0x0E, "kap", "Action cards AP"},
{0x0F, "ktp", "Action cards TP"},
{0x10, "dn", "Unknown: dn"},
{0x11, "hf", "Number of item or creature cards in hand"},
{0x12, "df", "Number of destroyed ally FCs (including SC\'s own)"},
{0x13, "ff", "Number of ally FCs (including SC\'s own)"},
{0x14, "ef", "Number of enemy FCs"},
{0x15, "bi", "Number of Native FCs on either team"},
{0x16, "ab", "Number of A.Beast FCs on either team"},
{0x17, "mc", "Number of Machine FCs on either team"},
{0x18, "dk", "Number of Dark FCs on either team"},
{0x19, "sa", "Number of Sword-type items on either team"},
{0x1A, "gn", "Number of Gun-type items on either team"},
{0x1B, "wd", "Number of Cane-type items on either team"},
{0x1C, "tt", "Physical damage"},
{0x1D, "lv", "Dice boost"},
{0x1E, "adm", "SC attack damage"},
{0x1F, "ddm", "Attack bonus"},
{0x20, "sat", "Number of Sword-type items on SC\'s team"},
{0x21, "edm", "Target attack bonus"},
{0x22, "ldm", "Last attack damage before defense"}, // Unused
{0x23, "rdm", "Last attack damage"},
{0x24, "fdm", "Final damage (after defense)"},
{0x25, "ndm", "Unknown: ndm"}, // Unused
{0x26, "ehp", "Attacker HP"},
};
const ExprTokenDefinition& def_for_expr_token(const std::string& token) {
static unordered_map<std::string, const ExprTokenDefinition*> index;
if (index.empty()) {
for (const auto& def : expr_token_defs) {
index.emplace(def.token, &def);
}
}
return *index.at(token);
}
static const vector<const char*> description_for_n_condition({
/* n00 */ "Always true",
@@ -516,6 +499,71 @@ string CardDefinition::Stat::str() const {
}
}
std::vector<CardDefinition::Effect::ExprToken> CardDefinition::Effect::ExprToken::parse(const char* expr) {
using T = ExprToken::Type;
std::vector<ExprToken> ret;
while (*expr) {
size_t ret_count = ret.size();
switch (*expr) {
case ' ':
ret.emplace_back(ExprToken{.type = T::SPACE, .value = 0, .text = expr, .text_size = 1});
break;
case '+':
ret.emplace_back(ExprToken{.type = T::ADD, .value = 0, .text = expr, .text_size = 1});
break;
case '-':
ret.emplace_back(ExprToken{.type = T::SUBTRACT, .value = 0, .text = expr, .text_size = 1});
break;
case '*':
ret.emplace_back(ExprToken{.type = T::MULTIPLY, .value = 0, .text = expr, .text_size = 1});
break;
case '/':
ret.emplace_back(ExprToken{
.type = ((expr[1] == '/') ? T::FLOOR_DIVIDE : T::ROUND_DIVIDE),
.value = 0,
.text = expr,
.text_size = static_cast<size_t>((expr[1] == '/') ? 2 : 1)});
break;
default:
if ((*expr >= 'a') && (*expr <= 'z')) {
string token_buf;
for (const char* z = expr; (*z >= 'a') && (*z <= 'z'); z++) {
token_buf.push_back(*z);
}
try {
const auto& def = def_for_expr_token(token_buf);
ret.emplace_back(ExprToken{
.type = T::REFERENCE,
.value = def.value,
.text = expr - token_buf.size(),
.text_size = token_buf.size()});
} catch (const std::out_of_range&) {
throw std::runtime_error("unknown token in card effect expression: " + token_buf);
}
} else if ((*expr >= '0') && (*expr <= '9')) {
const char* end_ptr;
int32_t value = strtol(expr, const_cast<char**>(&end_ptr), 10);
ret.emplace_back(ExprToken{
.type = T::NUMBER, .value = value, .text = expr, .text_size = static_cast<size_t>(end_ptr - expr)});
} else {
throw runtime_error("invalid card effect expression");
}
}
if (ret.size() != ret_count + 1) {
throw std::logic_error("expr parsing step did not add exactly one token");
}
expr += ret.back().text_size;
}
return ret;
}
bool CardDefinition::Effect::is_empty() const {
return (this->effect_num == 0 &&
this->type == ConditionType::NONE &&
@@ -604,7 +652,49 @@ string CardDefinition::Effect::str(const char* separator, const TextSet* text_ar
tokens.emplace_back(std::move(cmd_str));
}
if (!this->expr.empty()) {
tokens.emplace_back("expr=" + this->expr.decode());
std::string expr_decoded = this->expr.decode();
std::vector<std::string> explanation_tokens;
try {
auto tokens = ExprToken::parse(expr_decoded.c_str());
for (const auto& token : tokens) {
switch (token.type) {
case ExprToken::Type::REFERENCE:
try {
explanation_tokens.emplace_back(expr_token_defs.at(token.value).description);
} catch (const out_of_range&) {
explanation_tokens.emplace_back(std::format("<<invalid reference: {:X}>>", token.value));
}
break;
case ExprToken::Type::NUMBER:
explanation_tokens.emplace_back(std::format("{}", token.value));
break;
case ExprToken::Type::SUBTRACT:
explanation_tokens.emplace_back("-");
break;
case ExprToken::Type::ADD:
explanation_tokens.emplace_back("+");
break;
case ExprToken::Type::ROUND_DIVIDE:
explanation_tokens.emplace_back("/ (round-divide)");
break;
case ExprToken::Type::FLOOR_DIVIDE:
explanation_tokens.emplace_back("/ (floor-divide)");
break;
case ExprToken::Type::MULTIPLY:
explanation_tokens.emplace_back("*");
break;
default:
explanation_tokens.emplace_back("<<invalid token>>");
}
}
} catch (const exception& e) {
explanation_tokens.emplace_back(std::format("failed to parse expr: {}", e.what()));
}
if ((explanation_tokens.size() == 1) && (explanation_tokens.front() == expr_decoded)) {
tokens.emplace_back(std::format("expr={}", expr_decoded));
} else {
tokens.emplace_back(std::format("expr={} ({})", expr_decoded, phosg::join(explanation_tokens, " ")));
}
}
tokens.emplace_back(std::format("when={:02X}:{}", static_cast<uint8_t>(this->when), phosg::name_for_enum(this->when)));
tokens.emplace_back("arg1=" + this->str_for_arg(this->arg1.decode()));
@@ -730,8 +820,7 @@ void CardDefinition::decode_range() {
}
string name_for_rank(CardRank rank) {
static const vector<const char*> names(
{"N1", "R1", "S", "E", "N2", "N3", "N4", "R2", "R3", "R4", "SS", "D1", "D2"});
static const vector<const char*> names({"N1", "R1", "S", "E", "N2", "N3", "N4", "R2", "R3", "R4", "SS", "D1", "D2"});
try {
return names.at(static_cast<uint8_t>(rank) - 1);
} catch (const out_of_range&) {
@@ -1155,9 +1244,7 @@ void PlayerConfig::decrypt() {
return;
}
decrypt_trivial_gci_data(
&this->card_counts,
offsetof(PlayerConfig, decks) - offsetof(PlayerConfig, card_counts),
this->basis);
&this->card_counts, offsetof(PlayerConfig, decks) - offsetof(PlayerConfig, card_counts), this->basis);
this->is_encrypted = 0;
this->basis = 0;
}
@@ -1170,9 +1257,7 @@ void PlayerConfig::encrypt(uint8_t basis) {
this->decrypt();
}
decrypt_trivial_gci_data(
&this->card_counts,
offsetof(PlayerConfig, decks) - offsetof(PlayerConfig, card_counts),
basis);
&this->card_counts, offsetof(PlayerConfig, decks) - offsetof(PlayerConfig, card_counts), basis);
this->is_encrypted = 1;
this->basis = basis;
}
@@ -1215,8 +1300,7 @@ PlayerConfigNTE::PlayerConfigNTE(const PlayerConfig& config)
last_online_battle_start_timestamp(config.last_online_battle_start_timestamp),
unknown_t3(config.unknown_t3),
unknown_a14(config.unknown_a14) {
// TODO: Do we need to recompute card_count_checksums? (Here or in operator
// PlayerConfig?)
// TODO: Do we need to recompute card_count_checksums? (Here or in operator PlayerConfig?)
}
PlayerConfigNTE::operator PlayerConfig() const {
@@ -1390,8 +1474,7 @@ string Rules::str() const {
if (static_cast<uint8_t>(this->hp_type) == 0xFF) {
tokens.emplace_back("hp_type=(open)");
} else {
tokens.emplace_back(std::format("hp_type=({:02X})",
static_cast<uint8_t>(this->hp_type)));
tokens.emplace_back(std::format("hp_type=({:02X})", static_cast<uint8_t>(this->hp_type)));
}
break;
}
@@ -1439,8 +1522,7 @@ string Rules::str() const {
if (static_cast<uint8_t>(this->dice_exchange_mode) == 0xFF) {
tokens.emplace_back("dice_exchange=(open)");
} else {
tokens.emplace_back(std::format("dice_exchange=({:02X})",
static_cast<uint8_t>(this->dice_exchange_mode)));
tokens.emplace_back(std::format("dice_exchange=({:02X})", static_cast<uint8_t>(this->dice_exchange_mode)));
}
break;
}
@@ -1479,8 +1561,7 @@ string Rules::str() const {
if (static_cast<uint8_t>(this->allowed_cards) == 0xFF) {
tokens.emplace_back("allowed_cards=(open)");
} else {
tokens.emplace_back(std::format("allowed_cards=({:02X})",
static_cast<uint8_t>(this->allowed_cards)));
tokens.emplace_back(std::format("allowed_cards=({:02X})", static_cast<uint8_t>(this->allowed_cards)));
}
break;
}
@@ -1518,20 +1599,12 @@ RulesTrial::RulesTrial(const Rules& r)
no_assist_cards(r.no_assist_cards),
disable_dialogue(r.disable_dialogue),
dice_exchange_mode(r.dice_exchange_mode) {
if (r.max_dice_value == r.min_dice_value) {
this->atk_die_behavior = r.max_dice_value;
} else {
this->atk_die_behavior = 0; // Random
}
this->atk_die_behavior = (r.max_dice_value == r.min_dice_value) ? r.max_dice_value : 0;
if (r.def_dice_value_range == 0xFF) {
this->def_die_behavior = 0xFF;
} else {
auto def_range = r.def_dice_range(false);
if (def_range.first == def_range.second) {
this->def_die_behavior = def_range.first;
} else {
this->def_die_behavior = 0;
}
this->def_die_behavior = (def_range.first == def_range.second) ? def_range.first : 0;
}
}
@@ -1741,7 +1814,7 @@ phosg::JSON MapDefinition::AIParams::json(Language language) const {
return phosg::JSON::dict({
{"IsArkz", this->is_arkz ? true : false},
{"Name", this->ai_name.decode(language)},
{"CardIDs", std::move(params_json)},
{"Params", std::move(params_json)},
});
}
@@ -1753,7 +1826,7 @@ phosg::JSON MapDefinition::DialogueSet::json(Language language) const {
return phosg::JSON::dict({
{"When", this->when.load()},
{"PercentChance", this->percent_chance.load()},
{"CardIDs", std::move(strings_json)},
{"Strings", std::move(strings_json)},
});
}
@@ -1795,29 +1868,69 @@ phosg::JSON MapDefinition::EntryState::json() const {
default:
deck_type_json = this->deck_type;
}
return phosg::JSON::dict({
{"PlayerType", std::move(player_type_json)},
{"DeckType", std::move(deck_type_json)},
});
return phosg::JSON::dict({{"PlayerType", std::move(player_type_json)}, {"DeckType", std::move(deck_type_json)}});
}
// TODO:
// phosg::JSON MapDefinition::json() const { ... }
string MapDefinition::CameraSpec::str() const {
return std::format(
"CameraSpec[a1=({:g} {:g} {:g} {:g} {:g} {:g} {:g} {:g} {:g}) camera=({:g} {:g} {:g}) focus=({:g} {:g} {:g}) a2=({:g} {:g} {:g})]",
this->unknown_a1[0], this->unknown_a1[1],
this->unknown_a1[2], this->unknown_a1[3],
this->unknown_a1[4], this->unknown_a1[5],
this->unknown_a1[6], this->unknown_a1[7],
this->unknown_a1[8], this->camera_x,
this->camera_y, this->camera_z,
this->focus_x, this->focus_y,
this->focus_z, this->unknown_a2[0],
this->unknown_a2[1], this->unknown_a2[2]);
this->unknown_a1[0], this->unknown_a1[1], this->unknown_a1[2], this->unknown_a1[3], this->unknown_a1[4],
this->unknown_a1[5], this->unknown_a1[6], this->unknown_a1[7], this->unknown_a1[8],
this->camera_x, this->camera_y, this->camera_z, this->focus_x, this->focus_y, this->focus_z,
this->unknown_a2[0], this->unknown_a2[1], this->unknown_a2[2]);
}
struct UnavailableSCCardDefinition {
size_t index;
uint16_t card_id;
const char* internal_name;
};
static const array<UnavailableSCCardDefinition, 0x2A> unavailable_sc_card_defs = {
UnavailableSCCardDefinition{0x00, 0x0005, "Guykild"},
UnavailableSCCardDefinition{0x01, 0x0006, "Kylria"},
UnavailableSCCardDefinition{0x02, 0x0110, "Saligun"},
UnavailableSCCardDefinition{0x03, 0x0111, "Relmitos"},
UnavailableSCCardDefinition{0x04, 0x0002, "Kranz"},
UnavailableSCCardDefinition{0x05, 0x0004, "Sil'fer"},
UnavailableSCCardDefinition{0x06, 0x0003, "Ino'lis"},
UnavailableSCCardDefinition{0x07, 0x0112, "Viviana"},
UnavailableSCCardDefinition{0x08, 0x0113, "Teifu"},
UnavailableSCCardDefinition{0x09, 0x0001, "Orland"},
UnavailableSCCardDefinition{0x0A, 0x0114, "Stella"},
UnavailableSCCardDefinition{0x0B, 0x0115, "Glustar"},
UnavailableSCCardDefinition{0x0C, 0x0117, "Hyze"},
UnavailableSCCardDefinition{0x0D, 0x0118, "Rufina"},
UnavailableSCCardDefinition{0x0E, 0x0119, "Peko"},
UnavailableSCCardDefinition{0x0F, 0x011A, "Creinu"},
UnavailableSCCardDefinition{0x10, 0x011B, "Reiz"},
UnavailableSCCardDefinition{0x11, 0x0007, "Lura"},
UnavailableSCCardDefinition{0x12, 0x0008, "Break"},
UnavailableSCCardDefinition{0x13, 0x011C, "Rio"},
UnavailableSCCardDefinition{0x14, 0x0116, "Endu"},
UnavailableSCCardDefinition{0x15, 0x011D, "Memoru"},
UnavailableSCCardDefinition{0x16, 0x011E, "K.C."},
UnavailableSCCardDefinition{0x17, 0x011F, "Ohgun"},
UnavailableSCCardDefinition{0x18, 0x02AA, "HERO_1"},
UnavailableSCCardDefinition{0x19, 0x02AB, "HERO_2"},
UnavailableSCCardDefinition{0x1A, 0x02AC, "HERO_3"},
UnavailableSCCardDefinition{0x1B, 0x02AD, "HERO_4"},
UnavailableSCCardDefinition{0x1C, 0x02AE, "HERO_5"},
UnavailableSCCardDefinition{0x1D, 0x02AF, "HERO_6"},
UnavailableSCCardDefinition{0x1E, 0x02B0, "DARK_1"},
UnavailableSCCardDefinition{0x1F, 0x02B1, "DARK_2"},
UnavailableSCCardDefinition{0x20, 0x02B2, "DARK_3"},
UnavailableSCCardDefinition{0x21, 0x02B3, "DARK_4"},
UnavailableSCCardDefinition{0x22, 0x02B4, "DARK_5"},
UnavailableSCCardDefinition{0x23, 0x02B5, "DARK_6"},
UnavailableSCCardDefinition{0x24, 0x029B, "LEUKON"},
UnavailableSCCardDefinition{0x25, 0x029C, "CASTOR"},
UnavailableSCCardDefinition{0x26, 0x029D, "POLLUX"},
UnavailableSCCardDefinition{0x27, 0x029E, "AMPLUM"},
UnavailableSCCardDefinition{0x28, 0x02BE, "CASTOR_USR"},
UnavailableSCCardDefinition{0x29, 0x02BF, "POLLUX_USR"},
};
string MapDefinition::str(const CardIndex* card_index, Language language) const {
deque<string> lines;
auto add_map = [&](const parray<parray<uint8_t, 0x10>, 0x10>& tiles) {
@@ -1830,21 +1943,19 @@ string MapDefinition::str(const CardIndex* card_index, Language language) const
}
};
lines.emplace_back(std::format("Map {:08X}: {}x{}",
this->map_number, this->width, this->height));
lines.emplace_back(std::format("Map {:08X}: {}x{}", this->map_number, this->width, this->height));
lines.emplace_back(std::format(" tag: {:08X}", this->tag));
lines.emplace_back(std::format(" environment_number: {:02X} ({})", this->environment_number, name_for_environment_number(this->environment_number)));
lines.emplace_back(std::format(" environment_number: {:02X} ({})",
this->environment_number, name_for_environment_number(this->environment_number)));
lines.emplace_back(std::format(" num_camera_zones: {:02X}", this->num_camera_zones));
lines.emplace_back(" tiles:");
add_map(this->map_tiles);
lines.emplace_back(std::format(
" start_tile_definitions: A:[1p: {:02X}; 2p: {:02X},{:02X}; 3p: {:02X},{:02X},{:02X}], B:[1p: {:02X}; 2p: {:02X},{:02X}; 3p: {:02X},{:02X},{:02X}]",
this->start_tile_definitions[0][0], this->start_tile_definitions[0][1],
this->start_tile_definitions[0][2], this->start_tile_definitions[0][3],
this->start_tile_definitions[0][4], this->start_tile_definitions[0][5],
this->start_tile_definitions[1][0], this->start_tile_definitions[1][1],
this->start_tile_definitions[1][2], this->start_tile_definitions[1][3],
this->start_tile_definitions[1][4], this->start_tile_definitions[1][5]));
this->start_tile_definitions[0][0], this->start_tile_definitions[0][1], this->start_tile_definitions[0][2],
this->start_tile_definitions[0][3], this->start_tile_definitions[0][4], this->start_tile_definitions[0][5],
this->start_tile_definitions[1][0], this->start_tile_definitions[1][1], this->start_tile_definitions[1][2],
this->start_tile_definitions[1][3], this->start_tile_definitions[1][4], this->start_tile_definitions[1][5]));
for (size_t z = 0; z < this->num_camera_zones; z++) {
for (size_t w = 0; w < 2; w++) {
lines.emplace_back(std::format(" camera zone {} (team {}):", z, w ? 'A' : 'B'));
@@ -1862,47 +1973,28 @@ string MapDefinition::str(const CardIndex* card_index, Language language) const
add_map(this->overlay_state.tiles);
lines.emplace_back(std::format(
" unused1: {:08X} {:08X} {:08X} {:08X} {:08X}",
this->overlay_state.unused1[0],
this->overlay_state.unused1[1],
this->overlay_state.unused1[2],
this->overlay_state.unused1[3],
this->overlay_state.unused1[4]));
this->overlay_state.unused1[0], this->overlay_state.unused1[1], this->overlay_state.unused1[2],
this->overlay_state.unused1[3], this->overlay_state.unused1[4]));
lines.emplace_back(std::format(
" trap_tile_colors_nte: {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X}",
this->overlay_state.trap_tile_colors_nte[0],
this->overlay_state.trap_tile_colors_nte[1],
this->overlay_state.trap_tile_colors_nte[2],
this->overlay_state.trap_tile_colors_nte[3],
this->overlay_state.trap_tile_colors_nte[4],
this->overlay_state.trap_tile_colors_nte[5],
this->overlay_state.trap_tile_colors_nte[6],
this->overlay_state.trap_tile_colors_nte[7],
this->overlay_state.trap_tile_colors_nte[8],
this->overlay_state.trap_tile_colors_nte[9],
this->overlay_state.trap_tile_colors_nte[10],
this->overlay_state.trap_tile_colors_nte[11],
this->overlay_state.trap_tile_colors_nte[12],
this->overlay_state.trap_tile_colors_nte[13],
this->overlay_state.trap_tile_colors_nte[14],
this->overlay_state.trap_tile_colors_nte[15]));
this->overlay_state.trap_tile_colors_nte[0], this->overlay_state.trap_tile_colors_nte[1],
this->overlay_state.trap_tile_colors_nte[2], this->overlay_state.trap_tile_colors_nte[3],
this->overlay_state.trap_tile_colors_nte[4], this->overlay_state.trap_tile_colors_nte[5],
this->overlay_state.trap_tile_colors_nte[6], this->overlay_state.trap_tile_colors_nte[7],
this->overlay_state.trap_tile_colors_nte[8], this->overlay_state.trap_tile_colors_nte[9],
this->overlay_state.trap_tile_colors_nte[10], this->overlay_state.trap_tile_colors_nte[11],
this->overlay_state.trap_tile_colors_nte[12], this->overlay_state.trap_tile_colors_nte[13],
this->overlay_state.trap_tile_colors_nte[14], this->overlay_state.trap_tile_colors_nte[15]));
lines.emplace_back(std::format(
" trap_card_ids_nte: #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X} #{:04X}",
this->overlay_state.trap_card_ids_nte[0],
this->overlay_state.trap_card_ids_nte[1],
this->overlay_state.trap_card_ids_nte[2],
this->overlay_state.trap_card_ids_nte[3],
this->overlay_state.trap_card_ids_nte[4],
this->overlay_state.trap_card_ids_nte[5],
this->overlay_state.trap_card_ids_nte[6],
this->overlay_state.trap_card_ids_nte[7],
this->overlay_state.trap_card_ids_nte[8],
this->overlay_state.trap_card_ids_nte[9],
this->overlay_state.trap_card_ids_nte[10],
this->overlay_state.trap_card_ids_nte[11],
this->overlay_state.trap_card_ids_nte[12],
this->overlay_state.trap_card_ids_nte[13],
this->overlay_state.trap_card_ids_nte[14],
this->overlay_state.trap_card_ids_nte[15]));
this->overlay_state.trap_card_ids_nte[0], this->overlay_state.trap_card_ids_nte[1],
this->overlay_state.trap_card_ids_nte[2], this->overlay_state.trap_card_ids_nte[3],
this->overlay_state.trap_card_ids_nte[4], this->overlay_state.trap_card_ids_nte[5],
this->overlay_state.trap_card_ids_nte[6], this->overlay_state.trap_card_ids_nte[7],
this->overlay_state.trap_card_ids_nte[8], this->overlay_state.trap_card_ids_nte[9],
this->overlay_state.trap_card_ids_nte[10], this->overlay_state.trap_card_ids_nte[11],
this->overlay_state.trap_card_ids_nte[12], this->overlay_state.trap_card_ids_nte[13],
this->overlay_state.trap_card_ids_nte[14], this->overlay_state.trap_card_ids_nte[15]));
lines.emplace_back(" default_rules: " + this->default_rules.str());
lines.emplace_back(" name: " + this->name.decode(language));
@@ -1999,32 +2091,6 @@ string MapDefinition::str(const CardIndex* card_index, Language language) const
lines.emplace_back(std::format(" map_category: {:02X}", this->map_category));
lines.emplace_back(std::format(" cyber_block_type: {:02X}", this->cyber_block_type));
lines.emplace_back(std::format(" a11: {:04X}", this->unknown_a11));
static const array<const char*, 0x18> sc_card_entry_names = {
"00 (Guykild; 0005)",
"01 (Kylria; 0006)",
"02 (Saligun; 0110)",
"03 (Relmitos; 0111)",
"04 (Kranz; 0002)",
"05 (Sil'fer; 0004)",
"06 (Ino'lis; 0003)",
"07 (Viviana; 0112)",
"08 (Teifu; 0113)",
"09 (Orland; 0001)",
"0A (Stella; 0114)",
"0B (Glustar; 0115)",
"0C (Hyze; 0117)",
"0D (Rufina; 0118)",
"0E (Peko; 0119)",
"0F (Creinu; 011A)",
"10 (Reiz; 011B)",
"11 (Lura; 0007)",
"12 (Break; 0008)",
"13 (Rio; 011C)",
"14 (Endu; 0116)",
"15 (Memoru; 011D)",
"16 (K.C.; 011E)",
"17 (Ohgun; 011F)",
};
string unavailable_sc_cards = " unavailable_sc_cards: [";
for (size_t z = 0; z < 0x18; z++) {
if (this->unavailable_sc_cards[z] == 0xFFFF) {
@@ -2033,10 +2099,11 @@ string MapDefinition::str(const CardIndex* card_index, Language language) const
if (unavailable_sc_cards.size() > 25) {
unavailable_sc_cards += ", ";
}
if (this->unavailable_sc_cards[z] >= sc_card_entry_names.size()) {
if (this->unavailable_sc_cards[z] >= unavailable_sc_card_defs.size()) {
unavailable_sc_cards += std::format("{:04X} (invalid)", this->unavailable_sc_cards[z]);
} else {
unavailable_sc_cards += sc_card_entry_names[this->unavailable_sc_cards[z]];
const auto& def = unavailable_sc_card_defs[this->unavailable_sc_cards[z]];
unavailable_sc_cards += std::format("{:04X} ({}; {:04X})", def.index, def.internal_name, def.card_id);
}
}
unavailable_sc_cards += ']';
@@ -2081,12 +2148,139 @@ string MapDefinition::str(const CardIndex* card_index, Language language) const
deck_type = std::format("({:02X})", this->entry_states[z].deck_type);
break;
}
lines.emplace_back(std::format(
" entry_states[{}]: {} / {}", z, player_type, deck_type));
lines.emplace_back(std::format(" entry_states[{}]: {} / {}", z, player_type, deck_type));
}
return phosg::join(lines, "\n");
}
phosg::JSON MapDefinition::json(Language language) const {
phosg::JSON camera_zones_json = phosg::JSON::list();
for (size_t team_id = 0; team_id < 2; team_id++) {
phosg::JSON team_camera_zones_json = phosg::JSON::list();
for (size_t camera_zone_id = 0; camera_zone_id < std::min<size_t>(this->num_camera_zones, 10); camera_zone_id++) {
team_camera_zones_json.emplace_back(phosg::JSON::dict({
{"Map", this->camera_zone_maps[team_id][camera_zone_id].json()},
{"Spec", this->camera_zone_specs[team_id][camera_zone_id].json()},
}));
}
camera_zones_json.emplace_back(std::move(team_camera_zones_json));
}
phosg::JSON overview_specs_json = phosg::JSON::list();
for (size_t team_id = 0; team_id < 2; team_id++) {
phosg::JSON team_overview_specs_json = phosg::JSON::list();
for (size_t spec_id = 0; spec_id < 3; spec_id++) {
team_overview_specs_json.emplace_back(this->overview_specs[spec_id][team_id].json());
}
overview_specs_json.emplace_back(std::move(team_overview_specs_json));
}
auto overlay_state_json = phosg::JSON::dict({
{"Tiles", this->overlay_state.tiles.json()},
{"NTETrapTileColors", this->overlay_state.trap_tile_colors_nte.json()},
{"NTETrapCardIDs", this->overlay_state.trap_card_ids_nte.json()},
});
// Note: All typos/errors here are from AIPrm.dat
static const array<string, 30> default_ai_names = {
"Sample_Hunter", "Glustar", "Guykild", "Inolis", "Kilia", "Kranz", "Orland", "Relmitos", "Saligun", "Silfer",
"Sample_Hunter", "Teifu", "Viviana", "Sample_Dark", "Break", "Creinu", "Endu", "Heiz", "KC", "Lura",
"memoru", "Ohgun", "Peko", "Reiz", "Rio", "Rufina", "LKnight", "Boss_Castor", "Boss_Pollux", "Sample_Dark"};
auto npcs_json = phosg::JSON::list();
for (size_t npc_index = 0; npc_index < 3; npc_index++) {
auto npc = phosg::JSON::dict();
const auto& deck = this->npc_decks[npc_index];
if (deck.deck_name.at(0)) {
npc.emplace("Deck", deck.json(language));
} else {
npc.emplace("Deck", nullptr);
}
int32_t entry_index = this->npc_ai_params_entry_index[npc_index];
if (entry_index < 0) {
const auto& ai_params = this->npc_ai_params[npc_index];
if (ai_params.ai_name.at(0)) {
npc.emplace("AIParams", ai_params.json(language));
} else {
npc.emplace("AIParams", nullptr);
}
} else if (static_cast<uint32_t>(entry_index) < default_ai_names.size()) {
npc.emplace("AIParams", default_ai_names[entry_index]);
} else {
npc.emplace("AIParams", entry_index);
}
auto dialogue_set_json = phosg::JSON::list();
for (size_t ds_index = 0; ds_index < this->dialogue_sets[npc_index].size(); ds_index++) {
const auto& ds = this->dialogue_sets[npc_index][ds_index];
if (ds.when >= 0) {
dialogue_set_json.emplace_back(ds.json(language));
}
}
npc.emplace("DialogueSet", std::move(dialogue_set_json));
}
auto unavailable_sc_cards_json = phosg::JSON::list();
for (size_t z = 0; z < this->unavailable_sc_cards.size(); z++) {
uint16_t index = this->unavailable_sc_cards[z];
if (index < unavailable_sc_card_defs.size()) {
const auto& def = unavailable_sc_card_defs[index];
unavailable_sc_cards_json.emplace_back(phosg::JSON::dict({
{"Index", def.index},
{"Name", def.internal_name},
{"CardID", def.card_id},
}));
} else if (index != 0xFFFF) {
unavailable_sc_cards_json.emplace_back(index);
}
}
auto reward_card_ids_json = phosg::JSON::list();
for (size_t z = 0; z < this->reward_card_ids.size(); z++) {
if (this->reward_card_ids[z] != 0xFFFF) {
reward_card_ids_json.emplace_back(this->reward_card_ids[z].load());
}
}
auto entry_states_json = phosg::JSON::list();
for (size_t z = 0; z < this->entry_states.size(); z++) {
entry_states_json.emplace_back(this->entry_states[z].json());
}
return phosg::JSON::dict({
{"Tag", this->tag.load()},
{"MapNumber", this->map_number.load()},
{"Width", this->width},
{"Height", this->height},
{"EnvironmentNumber", this->environment_number},
{"EnvironmentName", name_for_environment_number(this->environment_number)},
{"MapTiles", this->map_tiles.json()},
{"StartTileDefinitions", this->start_tile_definitions.json()},
{"CameraZones", std::move(camera_zones_json)},
{"OverviewSpecs", std::move(overview_specs_json)},
{"OverlayState", std::move(overlay_state_json)},
{"Rules", this->default_rules.json()},
{"Name", this->name.decode(language)},
{"LocationName", this->location_name.decode(language)},
{"QuestName", this->quest_name.decode(language)},
{"Description", this->description.decode(language)},
{"WorldMapCoords", phosg::JSON::list({this->map_x.load(), this->map_y.load()})},
{"NPCs", std::move(npcs_json)},
{"BeforeMessage", this->before_message.decode(language)},
{"AfterMessage", this->after_message.decode(language)},
{"DispatchMessage", this->dispatch_message.decode(language)},
{"UnavailableSCCards", std::move(unavailable_sc_cards_json)},
{"RewardCardIDs", std::move(reward_card_ids_json)},
{"WinLevelOverride", this->win_level_override.load()},
{"LossLevelOverride", this->loss_level_override.load()},
{"FieldOffset", phosg::JSON::list({this->field_offset_x.load(), this->field_offset_y.load()})},
{"MapCategory", this->map_category},
{"CyberBlockType", this->cyber_block_type},
{"EntryStates", std::move(entry_states_json)},
});
}
MapDefinitionTrial::MapDefinitionTrial(const MapDefinition& map)
: tag(map.tag),
map_number(map.map_number),
@@ -2480,8 +2674,7 @@ CardIndex::CardIndex(
const auto& footer = r.pget<RELFileFooterBE>(r.size() - sizeof(RELFileFooterBE));
uint32_t offset = r.pget_u32b(footer.root_offset);
uint32_t count = r.pget_u32b(footer.root_offset + 4);
if (offset > decompressed_data.size() ||
((offset + count * sizeof(CardDefinition)) > decompressed_data.size())) {
if (offset > decompressed_data.size() || ((offset + count * sizeof(CardDefinition)) > decompressed_data.size())) {
throw runtime_error("definitions array reference out of bounds");
}
CardDefinition* defs = reinterpret_cast<CardDefinition*>(decompressed_data.data() + offset);
@@ -2497,8 +2690,7 @@ CardIndex::CardIndex(
auto entry = make_shared<CardEntry>(CardEntry{def, "", "", "", {}});
if (!this->card_definitions.emplace(entry->def.card_id, entry).second) {
throw runtime_error(std::format(
"duplicate card id: {:08X}", entry->def.card_id));
throw runtime_error(std::format("duplicate card id: {:08X}", entry->def.card_id));
}
// Some cards intentionally have the same name, so we just leave them
@@ -2801,7 +2993,8 @@ MapIndex::MapIndex(const string& directory, bool raise_on_any_failure) {
name);
} else {
if (map_it->second->visibility_flags != visibility_flags) {
throw std::runtime_error(std::format("visibility flags {:02X} for added map {} do not match existing flags {}",
throw std::runtime_error(std::format(
"visibility flags {:02X} for added map {} do not match existing flags {}",
map_it->second->visibility_flags, file_path, visibility_flags));
}
map_it->second->add_version(vm);
@@ -2951,7 +3144,8 @@ const string& MapIndex::get_compressed_list(size_t num_players, Language languag
is_trial ? "trial" : "final", num_players, compressed_map_list.size()));
}
size_t decompressed_size = sizeof(header) + entries_w.size() + strings_w.size();
static_game_data_log.info_f("Generated Episode 3 compressed {} map list for {} player(s) ({} maps; 0x{:X} -> 0x{:X} bytes)",
static_game_data_log.info_f(
"Generated Episode 3 compressed {} map list for {} player(s) ({} maps; 0x{:X} -> 0x{:X} bytes)",
is_trial ? "trial" : "final", num_players, num_maps, decompressed_size, compressed_map_list.size());
}
return compressed_map_list;
File diff suppressed because it is too large Load Diff
+14 -21
View File
@@ -92,8 +92,7 @@ bool DeckState::draw_card_by_ref(uint16_t card_ref) {
auto& entry = this->entries[index];
if (entry.state == CardState::DISCARDED) {
// If the card is discarded, then it should be before the draw index, and we
// can just change its state.
// If the card is discarded, then it should be before the draw index, and we can just change its state.
entry.state = CardState::IN_HAND;
return true;
}
@@ -102,9 +101,8 @@ bool DeckState::draw_card_by_ref(uint16_t card_ref) {
return false;
}
// If the card is still drawable, we need to move it so it's just in front of
// the draw index, then immediately draw it. Ep3 NTE does not handle this
// case, but we do even when playing NTE.
// If the card is still drawable, we need to move it so it's just in front of the draw index, then immediately draw
// it. Ep3 NTE does not handle this case, but we do even when playing NTE.
size_t ref_index;
for (ref_index = 0; ref_index < this->card_refs.size(); ref_index++) {
if (this->card_refs[ref_index] == card_ref) {
@@ -131,13 +129,8 @@ uint16_t DeckState::card_id_for_card_ref(uint16_t card_ref) const {
if (card_ref == 0xFFFF) {
return 0xFFFF;
}
uint8_t index = index_for_card_ref(card_ref);
if (index < this->entries.size()) {
return this->entries[index].card_id;
} else {
return 0xFFFF;
}
return (index < this->entries.size()) ? this->entries[index].card_id : 0xFFFF;
}
uint16_t DeckState::sc_card_id() const {
@@ -167,8 +160,7 @@ void DeckState::restart() {
}
}
// For any cards that are still in hand or still in play, move their refs to
// the already-drawn part of the deck
// For any cards that are still in hand or still in play, move their refs to the already-drawn part of the deck
this->draw_index = 0;
for (size_t z = 0; z < this->entries.size(); z++) {
if (this->entries[z].state != CardState::DRAWABLE) {
@@ -196,8 +188,7 @@ void DeckState::redraw_initial_hand(bool is_nte) {
this->draw_index = 1;
if (is_nte || this->shuffle_enabled) {
// Get the next 5 cards from the deck, and put the previous 5 cards after
// them (so they will be shuffled back in).
// Get the next 5 cards from the deck, and put the previous 5 cards after them (so they will be shuffled back in).
for (uint8_t z = 0; z < 5; z++) {
uint8_t index = z + this->draw_index;
uint16_t temp_ref = this->card_refs[index];
@@ -274,11 +265,9 @@ void DeckState::shuffle() {
size_t max = this->num_drawable_cards();
for (size_t z = 0; z < this->card_refs.size(); z++) {
// Note: This is the way Sega originally implemented shuffling - they just
// do N swaps on the entire array. A more uniform way to do it would be to
// instead swap each item with another random item (possibly itself) that
// doesn't appear earlier than it in the array, but this is not what Sega
// did.
// Note: This is the way Sega originally implemented shuffling - they just do N swaps on the entire array. A more
// uniform way to do it would be to instead swap each item with another random item (possibly itself) that
// doesn't appear earlier than it in the array, but this is not what Sega did.
uint8_t index1 = this->draw_index + s->get_random(max);
uint8_t index2 = this->draw_index + s->get_random(max);
uint16_t temp_ref = this->card_refs[index1];
@@ -309,7 +298,11 @@ static const char* name_for_card_state(DeckState::CardState st) {
void DeckState::print(FILE* stream, std::shared_ptr<const CardIndex> card_index) const {
phosg::fwrite_fmt(stream, "DeckState: client_id={} draw_index={} card_ref_base=@{:04X} shuffle={} loop={}\n",
this->client_id, this->draw_index, this->card_ref_base, this->shuffle_enabled ? "true" : "false", this->loop_enabled ? "true" : "false");
this->client_id,
this->draw_index,
this->card_ref_base,
this->shuffle_enabled ? "true" : "false",
this->loop_enabled ? "true" : "false");
for (size_t z = 0; z < 31; z++) {
const auto& e = this->entries[z];
shared_ptr<const CardIndex::CardEntry> ce;
+3 -7
View File
@@ -28,9 +28,8 @@ struct DeckEntry {
/* 00 */ pstring<TextEncoding::MARKED, 0x10> name;
/* 10 */ le_uint32_t team_id;
/* 14 */ parray<le_uint16_t, 31> card_ids;
// If the following flag is not set to 3, then the God Whim assist effect can
// use cards that are hidden from the player during deck building. The client
// always sets this to 3, and it's not clear why this even exists.
// If the following flag is not set to 3, then the God Whim assist effect can use cards that are hidden from the
// player during deck building. The client always sets this to 3, and it's not clear why this even exists.
/* 52 */ uint8_t god_whim_flag;
/* 53 */ uint8_t unused1;
/* 54 */ le_uint16_t player_level;
@@ -56,10 +55,7 @@ public:
};
template <typename CardIDT>
DeckState(
uint8_t client_id,
const parray<CardIDT, 0x1F>& card_ids,
std::shared_ptr<Server> server)
DeckState(uint8_t client_id, const parray<CardIDT, 0x1F>& card_ids, std::shared_ptr<Server> server)
: server(server),
client_id(client_id),
draw_index(1),
+43 -90
View File
@@ -110,9 +110,7 @@ void PlayerState::init() {
this->set_card_action_chains,
this->set_card_action_metadatas);
s->ruler_server->set_client_team_id(this->client_id, this->team_id);
s->card_special->on_card_set(this->shared_from_this(), this->sc_card_ref);
this->god_whim_can_use_hidden_cards = (s->deck_entries[this->client_id]->god_whim_flag != 3);
}
@@ -153,8 +151,7 @@ bool PlayerState::draw_cards_allowed() const {
return true;
}
void PlayerState::apply_assist_card_effect_on_set(
shared_ptr<PlayerState> setter_ps) {
void PlayerState::apply_assist_card_effect_on_set(shared_ptr<PlayerState> setter_ps) {
auto s = this->server();
uint16_t assist_card_id = this->set_assist_card_id;
@@ -163,8 +160,7 @@ void PlayerState::apply_assist_card_effect_on_set(
}
auto assist_effect = assist_effect_number_for_card_id(assist_card_id, s->options.is_nte());
if ((assist_effect == AssistEffect::RESISTANCE) ||
(assist_effect == AssistEffect::INDEPENDENT)) {
if ((assist_effect == AssistEffect::RESISTANCE) || (assist_effect == AssistEffect::INDEPENDENT)) {
this->assist_card_set_number = 0;
}
@@ -314,8 +310,7 @@ void PlayerState::apply_assist_card_effect_on_set(
auto other_ps = s->get_player_state(client_id);
if (other_ps.get() != this) {
other_ps->deck_state->draw_card_by_ref(this->card_refs[7]);
other_ps->set_card_from_hand(
this->card_refs[7], 0xF, nullptr, client_id, 1);
other_ps->set_card_from_hand(this->card_refs[7], 0xF, nullptr, client_id, 1);
}
}
break;
@@ -362,9 +357,7 @@ void PlayerState::apply_assist_card_effect_on_set(
}
for (ssize_t set_index = is_nte ? 0 : -1; set_index < 8; set_index++) {
auto card = (set_index == -1)
? other_ps->get_sc_card()
: other_ps->get_set_card(set_index);
auto card = (set_index == -1) ? other_ps->get_sc_card() : other_ps->get_set_card(set_index);
if (card) {
for (size_t cond_index = 0; cond_index < 9; cond_index++) {
auto& cond = card->action_chain.conditions[cond_index];
@@ -404,9 +397,7 @@ void PlayerState::apply_assist_card_effect_on_set(
}
for (ssize_t set_index = is_nte ? 0 : -1; set_index < 8; set_index++) {
auto card = (set_index == -1)
? other_ps->get_sc_card()
: other_ps->get_set_card(set_index);
auto card = (set_index == -1) ? other_ps->get_sc_card() : other_ps->get_set_card(set_index);
if (card) {
for (size_t cond_index = 0; cond_index < 9; cond_index++) {
auto& cond = card->action_chain.conditions[cond_index];
@@ -537,9 +528,9 @@ size_t PlayerState::count_set_cards() const {
return ret;
}
size_t PlayerState::count_set_refs() const {
size_t PlayerState::count_hand_refs() const {
size_t ret = 0;
for (size_t set_index = 0; set_index < 8; set_index++) {
for (size_t set_index = 8; set_index < 16; set_index++) {
if (this->card_refs[set_index] != 0xFFFF) {
ret++;
}
@@ -577,8 +568,7 @@ void PlayerState::discard_all_attack_action_cards_from_hand() {
for (size_t hand_index = 0; hand_index < 6; hand_index++) {
uint16_t card_ref = temp_card_refs[hand_index];
auto ce = s->definition_for_card_ref(card_ref);
if (ce && (ce->def.type == CardType::ACTION) &&
(ce->def.card_class() != CardClass::DEFENSE_ACTION)) {
if (ce && (ce->def.type == CardType::ACTION) && (ce->def.card_class() != CardClass::DEFENSE_ACTION)) {
this->discard_ref_from_hand(card_ref);
}
}
@@ -771,9 +761,8 @@ void PlayerState::draw_hand(ssize_t override_count) {
}
void PlayerState::draw_initial_hand() {
// Note: The original code called this->deck_state->init_card_states here, but
// we don't because that logic is now in the DeckState constructor, and this
// function should only be called during PlayerState construction (so, shortly
// Note: The original code called this->deck_state->init_card_states here, but we don't because that logic is now in
// the DeckState constructor, and this function should only be called during PlayerState construction (so, shortly
// after DeckState construction as well).
this->deck_state->restart();
this->card_refs.clear(0xFFFF);
@@ -782,10 +771,7 @@ void PlayerState::draw_initial_hand() {
}
int32_t PlayerState::error_code_for_client_setting_card(
uint16_t card_ref,
uint8_t card_index,
const Location* loc,
uint8_t assist_target_client_id) const {
uint16_t card_ref, uint8_t card_index, const Location* loc, uint8_t assist_target_client_id) const {
auto s = this->server();
int32_t code = s->ruler_server->error_code_for_client_setting_card(
@@ -816,8 +802,7 @@ int32_t PlayerState::error_code_for_client_setting_card(
if (this->card_refs[card_index + 1] != 0xFFFF) {
return -0x7E;
}
if ((ce->def.type == CardType::CREATURE) &&
!s->map_and_rules->tile_is_vacant(loc->x, loc->y)) {
if ((ce->def.type == CardType::CREATURE) && !s->map_and_rules->tile_is_vacant(loc->x, loc->y)) {
return -0x7A;
}
return 0;
@@ -834,9 +819,7 @@ int32_t PlayerState::error_code_for_client_setting_card(
}
vector<uint16_t> PlayerState::get_all_cards_within_range(
const parray<uint8_t, 9 * 9>& range,
const Location& loc,
uint8_t target_team_id) const {
const parray<uint8_t, 9 * 9>& range, const Location& loc, uint8_t target_team_id) const {
auto s = this->server();
auto log = s->log_stack("get_all_cards_within_range: ");
@@ -846,8 +829,7 @@ vector<uint16_t> PlayerState::get_all_cards_within_range(
vector<uint16_t> ret;
for (size_t client_id = 0; client_id < 4; client_id++) {
auto other_ps = s->player_states[client_id];
if (other_ps &&
((target_team_id == 0xFF) || (target_team_id == other_ps->get_team_id()))) {
if (other_ps && ((target_team_id == 0xFF) || (target_team_id == other_ps->get_team_id()))) {
auto card_refs = get_card_refs_within_range(range, loc, *other_ps->card_short_statuses, &log);
ret.insert(ret.end(), card_refs.begin(), card_refs.end());
}
@@ -945,9 +927,8 @@ bool PlayerState::is_hand_redraw_allowed() const {
bool PlayerState::is_team_turn() const {
auto s = this->server();
// Note: The original code checks if this->w_server is null before doing this.
// We don't check because that should never happen, and server() will throw if
// it does.
// Note: The original code checks if this->w_server is null before doing this. We don't check because that should
// never happen, and server() will throw if it does.
return s->get_current_team_turn() == this->team_id;
}
@@ -961,9 +942,8 @@ void PlayerState::log_discard(uint16_t card_ref, uint16_t reason) {
}
uint16_t PlayerState::pop_from_discard_log(uint16_t) {
// NTE appears to have a bug here (or some obviated code): it searches for an
// entry with the given reason, then ignores the result of that search and
// always returns the first entry instead.
// NTE appears to have a bug here (or some obviated code): it searches for an entry with the given reason, then
// ignores the result of that search and always returns the first entry instead. That code is:
// size_t z;
// for (size_t z = 0; z < this->discard_log_card_refs.size(); z++) {
// if ((this->discard_log_card_refs[z] != 0xFFFF) && (this->discard_log_reasons[z] == reason)) {
@@ -1030,9 +1010,7 @@ void PlayerState::move_null_hand_refs_to_end() {
void PlayerState::on_cards_destroyed() {
auto s = this->server();
// {card_ref: should_return_to_hand}
unordered_multimap<uint16_t, bool> card_refs_map;
unordered_multimap<uint16_t, bool> card_refs_map; // {card_ref: should_return_to_hand}
for (size_t z = 0; z < 8; z++) {
auto card = this->set_cards[z];
if (!card || !(card->card_flags & 2)) {
@@ -1106,8 +1084,7 @@ void PlayerState::replace_all_set_assists_with_random_assists() {
const auto& assist_card_ids = all_assist_card_ids(is_nte);
for (size_t client_id = 0; client_id < 4; client_id++) {
auto other_ps = s->get_player_state(client_id);
if (other_ps &&
((other_ps->card_refs[6] != 0xFFFF) || (!is_nte && (other_ps->set_assist_card_id != 0xFFFF)))) {
if (other_ps && ((other_ps->card_refs[6] != 0xFFFF) || (!is_nte && (other_ps->set_assist_card_id != 0xFFFF)))) {
uint16_t card_id = 0x0130;
while (card_id == 0x0130) { // God Whim
size_t index = s->get_random(assist_card_ids.size());
@@ -1355,8 +1332,7 @@ bool PlayerState::set_card_from_hand(
return 0;
}
this->card_refs[card_index + 1] = card_ref;
// Note: NTE doesn't call the destructor on the existing card, if there is
// one. Is that a bug?
// Note: NTE doesn't call the destructor on the existing card, if there is one. Is that a bug?
this->set_cards[card_index - 7] = make_shared<Card>(s->card_id_for_card_ref(card_ref), card_ref, this->client_id, s);
auto new_card = this->set_cards[card_index - 7];
new_card->init();
@@ -1365,8 +1341,7 @@ bool PlayerState::set_card_from_hand(
new_card->loc.x = loc->x;
new_card->loc.y = loc->y;
}
// Note: NTE doesn't track this, but NTE can't use it anyway, so we don't
// check for NTE here.
// Note: NTE doesn't track this, but NTE can't use it anyway, so we don't check for NTE here.
this->stats.num_item_or_creature_cards_set++;
} else if (ce->def.type == CardType::ASSIST) {
@@ -1436,7 +1411,6 @@ bool PlayerState::set_card_from_hand(
void PlayerState::set_initial_location() {
auto s = this->server();
auto mr = s->map_and_rules;
uint8_t num_team_players;
@@ -1485,8 +1459,7 @@ void PlayerState::set_initial_location() {
}
}
void PlayerState::set_map_occupied_bit_for_card_on_warp_tile(
shared_ptr<const Card> card) {
void PlayerState::set_map_occupied_bit_for_card_on_warp_tile(shared_ptr<const Card> card) {
if (!card) {
return;
}
@@ -1498,8 +1471,7 @@ void PlayerState::set_map_occupied_bit_for_card_on_warp_tile(
if ((s->warp_positions[warp_type][warp_end][0] == card->loc.x) &&
(s->warp_positions[warp_type][warp_end][1] == card->loc.y)) {
s->map_and_rules->set_occupied_bit_for_tile(
s->warp_positions[warp_type][warp_end ^ 1][0],
s->warp_positions[warp_type][warp_end ^ 1][1]);
s->warp_positions[warp_type][warp_end ^ 1][0], s->warp_positions[warp_type][warp_end ^ 1][1]);
}
}
}
@@ -1509,8 +1481,7 @@ void PlayerState::set_map_occupied_bits_for_sc_and_creatures() {
auto s = this->server();
if (this->sc_card && !(this->sc_card->card_flags & 2)) {
s->map_and_rules->set_occupied_bit_for_tile(
this->sc_card->loc.x, this->sc_card->loc.y);
s->map_and_rules->set_occupied_bit_for_tile(this->sc_card->loc.x, this->sc_card->loc.y);
this->set_map_occupied_bit_for_card_on_warp_tile(this->sc_card);
}
@@ -1518,8 +1489,7 @@ void PlayerState::set_map_occupied_bits_for_sc_and_creatures() {
for (size_t set_index = 0; set_index < 8; set_index++) {
auto card = this->set_cards[set_index];
if (card) {
s->map_and_rules->set_occupied_bit_for_tile(
card->loc.x, card->loc.y);
s->map_and_rules->set_occupied_bit_for_tile(card->loc.x, card->loc.y);
this->set_map_occupied_bit_for_card_on_warp_tile(card);
}
}
@@ -1530,8 +1500,7 @@ void PlayerState::subtract_def_points(uint8_t cost) {
this->def_points -= cost;
}
bool PlayerState::subtract_or_check_atk_or_def_points_for_action(
const ActionState& pa, bool deduct_points) {
bool PlayerState::subtract_or_check_atk_or_def_points_for_action(const ActionState& pa, bool deduct_points) {
auto s = this->server();
int16_t cost = this->compute_attack_or_defense_atk_costs(pa);
@@ -1580,9 +1549,7 @@ G_UpdateHand_Ep3_6xB4x02 PlayerState::prepare_6xB4x02() const {
cmd.state.assist_card_ref = this->card_refs[6];
cmd.state.sc_card_ref = this->sc_card_ref;
cmd.state.assist_card_ref2 = this->card_refs[6];
cmd.state.assist_card_set_number = (this->card_refs[6] == 0xFFFF)
? 0
: this->assist_card_set_number;
cmd.state.assist_card_set_number = (this->card_refs[6] == 0xFFFF) ? 0 : this->assist_card_set_number;
cmd.state.assist_card_id = this->set_assist_card_id;
cmd.state.assist_remaining_turns = this->assist_remaining_turns;
cmd.state.assist_delay_turns = this->assist_delay_turns;
@@ -1591,8 +1558,7 @@ G_UpdateHand_Ep3_6xB4x02 PlayerState::prepare_6xB4x02() const {
return cmd;
}
void PlayerState::update_hand_and_equip_state_and_send_6xB4x02_if_needed(
bool always_send) {
void PlayerState::update_hand_and_equip_state_and_send_6xB4x02_if_needed(bool always_send) {
auto cmd = this->prepare_6xB4x02();
if (always_send || memcmp(&this->hand_and_equip, &cmd.state, sizeof(this->hand_and_equip))) {
*this->hand_and_equip = cmd.state;
@@ -1618,8 +1584,7 @@ void PlayerState::set_random_assist_card_from_hand_for_free() {
if (!candidate_card_refs.empty()) {
this->discard_set_assist_card();
size_t index = s->get_random(candidate_card_refs.size());
this->set_card_from_hand(
candidate_card_refs[index], 15, nullptr, this->client_id, 1);
this->set_card_from_hand(candidate_card_refs[index], 15, nullptr, this->client_id, 1);
}
}
@@ -1641,11 +1606,9 @@ G_UpdateShortStatuses_Ep3_6xB4x04 PlayerState::prepare_6xB4x04() const {
}
for (size_t hand_index = 0; hand_index < 6; hand_index++) {
this->get_short_status_for_card_index_in_hand(
hand_index + 1, &cmd.card_statuses[hand_index + 1]);
// This write is required to mimic memset()'s effect from the original code.
// This field is probably ignored for hand refs anyway, but we might as well
// be as consistent as possible.
this->get_short_status_for_card_index_in_hand(hand_index + 1, &cmd.card_statuses[hand_index + 1]);
// This write is required to mimic memset()'s effect from the original code. This field is probably ignored for
// hand refs anyway, but we might as well be as consistent as possible.
cmd.card_statuses[hand_index + 1].unused1 = 0;
}
@@ -1674,9 +1637,7 @@ void PlayerState::send_6xB4x04_if_needed(bool always_send) {
}
vector<uint16_t> PlayerState::get_card_refs_within_range_from_all_players(
const parray<uint8_t, 9 * 9>& range,
const Location& loc,
CardType type) const {
const parray<uint8_t, 9 * 9>& range, const Location& loc, CardType type) const {
auto s = this->server();
vector<uint16_t> ret;
@@ -1726,8 +1687,7 @@ void PlayerState::move_phase_before() {
void PlayerState::handle_before_turn_assist_effects() {
auto s = this->server();
if ((this->assist_delay_turns > 0) &&
(--this->assist_delay_turns == 0)) {
if ((this->assist_delay_turns > 0) && (--this->assist_delay_turns == 0)) {
this->update_hand_and_equip_state_and_send_6xB4x02_if_needed();
size_t num_assists = s->assist_server->compute_num_assist_effects_for_client(this->client_id);
for (size_t z = 0; z < num_assists; z++) {
@@ -1736,8 +1696,7 @@ void PlayerState::handle_before_turn_assist_effects() {
s->execute_bomb_assist_effect();
break;
case AssistEffect::ATK_DICE_2:
// Note: This behavior doesn't match the card description. Is it
// supposed to add 2 or multiply by 2?
// Note: This behavior doesn't match the card description. Is it supposed to add 2 or multiply by 2?
this->atk_points = min<int16_t>(this->atk_points + 2, 9);
this->update_hand_and_equip_state_and_send_6xB4x02_if_needed();
break;
@@ -1885,9 +1844,7 @@ void PlayerState::dice_phase_before() {
this->compute_total_set_cards_cost();
this->unknown_a14 = 0;
if ((this->assist_remaining_turns > 0) &&
(this->assist_remaining_turns < 90) &&
(this->assist_delay_turns == 0)) {
if ((this->assist_remaining_turns > 0) && (this->assist_remaining_turns < 90) && (this->assist_delay_turns == 0)) {
this->assist_remaining_turns--;
if (this->assist_remaining_turns < 1) {
this->discard_set_assist_card();
@@ -1984,12 +1941,10 @@ void PlayerState::roll_main_dice_or_apply_after_effects() {
auto s = this->server();
const auto& rules = s->map_and_rules->rules;
// In NTE, the dice behave differently - there is no minimum, and instead the
// player can specify a fixed value for each die or a random value (1-6). The
// implementation of this function is therefore quite different on NTE, but
// since we already support custom ranges for ATK and DEF dice, we just use
// the non-NTE logic and assign the dice ranges at battle start time to yield
// the NTE behavior. (See RulesTrial in DataIndexes.cc for how this is done.)
// In NTE, the dice behave differently - there is no minimum, and instead the player can specify a fixed value for
// each die or a random value (1-6). The implementation of this function is therefore quite different on NTE, but
// since we already support custom ranges for ATK and DEF dice, we just use the non-NTE logic and assign the dice
// ranges at battle start time to yield the NTE behavior. (See RulesTrial in DataIndexes.cc for how this is done.)
bool is_1p_2v1 = (s->team_client_count.at(this->get_team_id()) < s->team_client_count[this->get_team_id() ^ 1]);
@@ -2079,10 +2034,8 @@ void PlayerState::compute_team_dice_bonus_after_draw_phase() {
}
uint8_t current_team_turn = s->get_current_team_turn();
uint8_t dice_boost = s->get_team_exp(current_team_turn) /
(s->team_client_count[current_team_turn] * 12);
s->card_special->adjust_dice_boost_if_team_has_condition_52(
current_team_turn, &dice_boost, 0);
uint8_t dice_boost = s->get_team_exp(current_team_turn) / (s->team_client_count[current_team_turn] * 12);
s->card_special->adjust_dice_boost_if_team_has_condition_52(current_team_turn, &dice_boost, 0);
s->team_dice_bonus[current_team_turn] = clamp<int16_t>(dice_boost, 0, 8);
this->update_hand_and_equip_state_and_send_6xB4x02_if_needed();
}
+16 -24
View File
@@ -15,9 +15,8 @@ namespace Episode3 {
class Server;
enum AssistFlag : uint32_t {
// Note: This enum is a uint32_t even though only 16 bits are used because
// the corresponding field in the protocol is a 32-bit field. There may also
// be bits used only by the client which are not documented here.
// Note: This enum is a uint32_t even though only 16 bits are used because the corresponding field in the protocol is
// a 32-bit field. There may also be bits used only by the client which are not documented here.
// clang-format off
NONE = 0x0000,
@@ -57,7 +56,7 @@ public:
void compute_total_set_cards_cost();
size_t count_set_cards_for_env_stats_nte() const;
size_t count_set_cards() const;
size_t count_set_refs() const;
size_t count_hand_refs() const;
void discard_all_assist_cards_from_hand();
void discard_all_attack_action_cards_from_hand();
void discard_all_item_and_creature_cards_from_hand();
@@ -70,14 +69,9 @@ public:
void draw_hand(ssize_t override_count = 0);
void draw_initial_hand();
int32_t error_code_for_client_setting_card(
uint16_t card_ref,
uint8_t card_index,
const Location* loc,
uint8_t assist_target_client_id) const;
uint16_t card_ref, uint8_t card_index, const Location* loc, uint8_t assist_target_client_id) const;
std::vector<uint16_t> get_all_cards_within_range(
const parray<uint8_t, 9 * 9>& range,
const Location& loc,
uint8_t target_team_id) const;
const parray<uint8_t, 9 * 9>& range, const Location& loc, uint8_t target_team_id) const;
uint8_t get_atk_points() const;
void get_short_status_for_card_index_in_hand(size_t hand_index, CardShortStatus* stat) const;
std::shared_ptr<DeckState> get_deck();
@@ -128,9 +122,7 @@ public:
G_UpdateShortStatuses_Ep3_6xB4x04 prepare_6xB4x04() const;
void send_6xB4x04_if_needed(bool always_send = false);
std::vector<uint16_t> get_card_refs_within_range_from_all_players(
const parray<uint8_t, 9 * 9>& range,
const Location& loc,
CardType type) const;
const parray<uint8_t, 9 * 9>& range, const Location& loc, CardType type) const;
void draw_phase_before();
void action_phase_before();
void move_phase_before();
@@ -169,10 +161,10 @@ public:
uint16_t sc_card_ref;
// This array is unfortunately heterogeneous; specifically:
// [0] through [5] are hand refs
// [6] is the current assist card ref (which may belong to another player)
// [7] is the previous assist card ref
// [8] through [15] are set refs
// [0] through [5] are hand refs
// [6] is the current assist card ref (which may belong to another player)
// [7] is the previous assist card ref
// [8] through [15] are set refs
parray<uint16_t, 0x10> card_refs;
std::shared_ptr<DeckState> deck_state;
@@ -190,12 +182,12 @@ public:
Direction start_facing_direction;
std::shared_ptr<HandAndEquipState> hand_and_equip;
// Like card_refs above, these arrays are also heterogeneous, but the indices
// are not the same as for card_refs! THe indices here are:
// [0] is the SC card status
// [1] through [6] are hand cards
// [7] through [14] are set cards
// [15] is the assist card
// Like card_refs above, these arrays are also heterogeneous, but the indices are not the same as for card_refs! The
// indices here are:
// [0] is the SC card status
// [1] through [6] are hand cards
// [7] through [14] are set cards
// [15] is the assist card
std::shared_ptr<parray<CardShortStatus, 0x10>> card_short_statuses;
parray<CardShortStatus, 0x10> prev_card_short_statuses;
+59 -112
View File
@@ -62,8 +62,6 @@ void Condition::clear_FF() {
}
std::string Condition::str(shared_ptr<const Server> s) const {
auto card_ref_str = s->debug_str_for_card_ref(this->card_ref);
auto giver_ref_str = s->debug_str_for_card_ref(this->condition_giver_card_ref);
return std::format(
"Condition[type={}, turns={}, a_arg={}, dice={}, flags={:02X}, "
"def_eff_index={}, ref={}, value={}, giver_ref={} "
@@ -74,9 +72,9 @@ std::string Condition::str(shared_ptr<const Server> s) const {
this->dice_roll_value,
this->flags,
this->card_definition_effect_index,
card_ref_str,
s->debug_str_for_card_ref(this->card_ref),
this->value,
giver_ref_str,
s->debug_str_for_card_ref(this->condition_giver_card_ref),
this->random_percent,
this->value8,
this->order,
@@ -101,14 +99,10 @@ void EffectResult::clear() {
}
std::string EffectResult::str(shared_ptr<const Server> s) const {
string attacker_ref_str = s->debug_str_for_card_ref(this->attacker_card_ref);
string target_ref_str = s->debug_str_for_card_ref(this->target_card_ref);
return std::format(
"EffectResult[att_ref={}, target_ref={}, value={}, "
"cur_hp={}, ap={}, tp={}, flags={:02X}, op={}, "
"cond_index={}, dice={}]",
attacker_ref_str,
target_ref_str,
"EffectResult[att_ref={}, target_ref={}, value={}, cur_hp={}, ap={}, tp={}, flags={:02X}, op={}, cond_index={}, dice={}]",
s->debug_str_for_card_ref(this->attacker_card_ref),
s->debug_str_for_card_ref(this->target_card_ref),
this->value,
this->current_hp,
this->ap,
@@ -137,15 +131,12 @@ bool CardShortStatus::operator!=(const CardShortStatus& other) const {
}
std::string CardShortStatus::str(shared_ptr<const Server> s) const {
string loc_s = this->loc.str();
string ref_str = s->debug_str_for_card_ref(this->card_ref);
return std::format(
"CardShortStatus[ref={}, cur_hp={}, flags={:08X}, loc={}, "
"u1={:04X}, max_hp={}, u2={}]",
ref_str,
"CardShortStatus[ref={}, cur_hp={}, flags={:08X}, loc={}, u1={:04X}, max_hp={}, u2={}]",
s->debug_str_for_card_ref(this->card_ref),
this->current_hp,
this->card_flags,
loc_s,
this->loc.str(),
this->unused1,
this->max_hp,
this->unused2);
@@ -188,23 +179,16 @@ void ActionState::clear() {
}
std::string ActionState::str(shared_ptr<const Server> s) const {
string attacker_ref_s = s->debug_str_for_card_ref(this->attacker_card_ref);
string defense_ref_s = s->debug_str_for_card_ref(this->defense_card_ref);
string original_attacker_ref_s = s->debug_str_for_card_ref(this->original_attacker_card_ref);
string target_refs_s = s->debug_str_for_card_refs(this->target_card_refs);
string action_refs_s = s->debug_str_for_card_refs(this->action_card_refs);
return std::format(
"ActionState[client={:X}, u={}, facing={}, attacker_ref={}, "
"def_ref={}, target_refs={}, action_refs={}, "
"orig_attacker_ref={}]",
"ActionState[client={:X}, u={}, facing={}, attacker_ref={}, def_ref={}, target_refs={}, action_refs={}, orig_attacker_ref={}]",
this->client_id,
this->unused,
phosg::name_for_enum(this->facing_direction),
attacker_ref_s,
defense_ref_s,
target_refs_s,
action_refs_s,
original_attacker_ref_s);
s->debug_str_for_card_ref(this->attacker_card_ref),
s->debug_str_for_card_ref(this->defense_card_ref),
s->debug_str_for_card_refs(this->target_card_refs),
s->debug_str_for_card_refs(this->action_card_refs),
s->debug_str_for_card_ref(this->original_attacker_card_ref));
}
ActionChain::ActionChain() {
@@ -239,24 +223,17 @@ bool ActionChain::operator!=(const ActionChain& other) const {
}
std::string ActionChain::str(shared_ptr<const Server> s) const {
string acting_card_ref_s = s->debug_str_for_card_ref(this->acting_card_ref);
string unknown_card_ref_a3_s = s->debug_str_for_card_ref(this->unknown_card_ref_a3);
string attack_action_card_refs_s = s->debug_str_for_card_refs(this->attack_action_card_refs);
string target_card_refs_s = s->debug_str_for_card_refs(this->target_card_refs);
return std::format(
"ActionChain[eff_ap={}, eff_tp={}, ap_bonus={}, damage={}, "
"acting_ref={}, unknown_ref_a3={}, attack_action_refs={}, "
"attack_action_ref_count={}, medium={}, target_ref_count={}, "
"subphase={}, strikes={}, damage_mult={}, attack_num={}, "
"tp_bonus={}, phys_bonus_nte={}, tech_bonus_nte={}, card_ap={}, "
"card_tp={}, flags={:08X}, target_refs={}]",
"ActionChain[eff_ap={}, eff_tp={}, ap_bonus={}, damage={}, acting_ref={}, unknown_ref_a3={}, attack_action_refs={}, "
"attack_action_ref_count={}, medium={}, target_ref_count={}, subphase={}, strikes={}, damage_mult={}, attack_num={}, "
"tp_bonus={}, phys_bonus_nte={}, tech_bonus_nte={}, card_ap={}, card_tp={}, flags={:08X}, target_refs={}]",
this->effective_ap,
this->effective_tp,
this->ap_effect_bonus,
this->damage,
acting_card_ref_s,
unknown_card_ref_a3_s,
attack_action_card_refs_s,
s->debug_str_for_card_ref(this->acting_card_ref),
s->debug_str_for_card_ref(this->unknown_card_ref_a3),
s->debug_str_for_card_refs(this->attack_action_card_refs),
this->attack_action_card_ref_count,
phosg::name_for_enum(this->attack_medium),
this->target_card_ref_count,
@@ -270,7 +247,7 @@ std::string ActionChain::str(shared_ptr<const Server> s) const {
this->card_ap,
this->card_tp,
this->flags,
target_card_refs_s);
s->debug_str_for_card_refs(this->target_card_refs));
}
void ActionChain::clear() {
@@ -406,8 +383,7 @@ void ActionChainWithConds::set_flags(uint32_t flags) {
this->chain.flags |= flags;
}
void ActionChainWithConds::add_attack_action_card_ref(
uint16_t card_ref, shared_ptr<Server> server) {
void ActionChainWithConds::add_attack_action_card_ref(uint16_t card_ref, shared_ptr<Server> server) {
if (card_ref != 0xFFFF) {
this->chain.attack_action_card_refs[this->chain.attack_action_card_ref_count++] = card_ref;
}
@@ -416,8 +392,7 @@ void ActionChainWithConds::add_attack_action_card_ref(
}
void ActionChainWithConds::add_target_card_ref(uint16_t card_ref) {
if (card_ref != 0xFFFF &&
this->chain.target_card_ref_count < this->chain.target_card_refs.size()) {
if (card_ref != 0xFFFF && this->chain.target_card_ref_count < this->chain.target_card_refs.size()) {
this->chain.target_card_refs[this->chain.target_card_ref_count++] = card_ref;
}
}
@@ -440,11 +415,7 @@ void ActionChainWithConds::compute_attack_medium(shared_ptr<Server> server) {
}
bool ActionChainWithConds::get_condition_value(
ConditionType cond_type,
uint16_t card_ref,
uint8_t def_effect_index,
uint16_t value,
uint16_t* out_value) const {
ConditionType cond_type, uint16_t card_ref, uint8_t def_effect_index, uint16_t value, uint16_t* out_value) const {
bool any_found = false;
uint8_t max_order = 10;
for (size_t z = 0; z < 9; z++) {
@@ -466,8 +437,7 @@ bool ActionChainWithConds::get_condition_value(
return any_found;
}
void ActionChainWithConds::set_action_subphase_from_card(
shared_ptr<const Card> card) {
void ActionChainWithConds::set_action_subphase_from_card(shared_ptr<const Card> card) {
this->chain.action_subphase = card->server()->get_current_action_subphase();
}
@@ -576,16 +546,10 @@ bool ActionMetadata::operator!=(const ActionMetadata& other) const {
}
std::string ActionMetadata::str(shared_ptr<const Server> s) const {
string card_ref_s = s->debug_str_for_card_ref(this->card_ref);
string target_card_refs_s = s->debug_str_for_card_refs(this->target_card_refs);
string defense_card_refs_s = s->debug_str_for_card_refs(this->defense_card_refs);
string original_attacker_card_refs_s = s->debug_str_for_card_refs(this->original_attacker_card_refs);
return std::format(
"ActionMetadata[ref={}, target_ref_count={}, def_ref_count={}, "
"subphase={}, def_power={}, def_bonus={}, "
"att_bonus={}, flags={:08X}, target_refs={}, "
"defense_refs={}, original_attacker_refs={}]",
card_ref_s,
"ActionMetadata[ref={}, target_ref_count={}, def_ref_count={}, subphase={}, def_power={}, def_bonus={}, "
"att_bonus={}, flags={:08X}, target_refs={}, defense_refs={}, original_attacker_refs={}]",
s->debug_str_for_card_ref(this->card_ref),
this->target_card_ref_count,
this->defense_card_ref_count,
phosg::name_for_enum(this->action_subphase),
@@ -593,9 +557,9 @@ std::string ActionMetadata::str(shared_ptr<const Server> s) const {
this->defense_bonus,
this->attack_bonus,
this->flags,
target_card_refs_s,
defense_card_refs_s,
original_attacker_card_refs_s);
s->debug_str_for_card_refs(this->target_card_refs),
s->debug_str_for_card_refs(this->defense_card_refs),
s->debug_str_for_card_refs(this->original_attacker_card_refs));
}
void ActionMetadata::clear() {
@@ -605,8 +569,7 @@ void ActionMetadata::clear() {
this->action_subphase = ActionSubphase::INVALID_FF;
this->defense_power = 0;
this->defense_bonus = 0;
// TODO: Ep3 NTE doesn't set attack_bonus to zero here. Is the field just
// unused in NTE?
// TODO: Ep3 NTE doesn't set attack_bonus to zero here. Is the field just unused in NTE?
this->attack_bonus = 0;
this->flags = 0;
this->target_card_refs.clear(0xFFFF);
@@ -652,16 +615,13 @@ void ActionMetadata::clear_target_card_refs() {
}
void ActionMetadata::add_target_card_ref(uint16_t card_ref) {
if (card_ref != 0xFFFF &&
this->target_card_ref_count < this->target_card_refs.size()) {
if ((card_ref != 0xFFFF) && (this->target_card_ref_count < this->target_card_refs.size())) {
this->target_card_refs[this->target_card_ref_count++] = card_ref;
}
}
void ActionMetadata::add_defense_card_ref(
uint16_t defense_card_ref,
shared_ptr<Card> card,
uint16_t original_attacker_card_ref) {
uint16_t defense_card_ref, shared_ptr<Card> card, uint16_t original_attacker_card_ref) {
if ((defense_card_ref != 0xFFFF) && (this->defense_card_ref_count < 8)) {
this->defense_card_refs[this->defense_card_ref_count] = defense_card_ref;
this->original_attacker_card_refs[this->defense_card_ref_count] = original_attacker_card_ref;
@@ -675,21 +635,10 @@ HandAndEquipState::HandAndEquipState() {
}
std::string HandAndEquipState::str(shared_ptr<const Server> s) const {
string assist_card_ref_s = s->debug_str_for_card_ref(this->assist_card_ref);
string assist_card_ref2_s = s->debug_str_for_card_ref(this->assist_card_ref2);
string assist_card_id_s = s->debug_str_for_card_id(this->assist_card_id);
string sc_card_ref_s = s->debug_str_for_card_ref(this->sc_card_ref);
string hand_card_refs_s = s->debug_str_for_card_refs(this->hand_card_refs);
string set_card_refs_s = s->debug_str_for_card_refs(this->set_card_refs);
string hand_card_refs2_s = s->debug_str_for_card_refs(this->hand_card_refs2);
string set_card_refs2_s = s->debug_str_for_card_refs(this->set_card_refs2);
return std::format(
"HandAndEquipState[dice=[{}, {}], atk={}, def={}, atk2={}, "
"a1={}, total_set_cost={}, is_cpu={}, assist_flags={:08X}, "
"hand_refs={}, assist_ref={}, set_refs={}, sc_ref={}, hand_refs2={}, "
"set_refs2={}, assist_ref2={}, assist_set_num={}, assist_card_id={}, "
"assist_turns={}, assist_delay={}, atk_bonus={}, def_bonus={}, "
"u2=[{}, {}]]",
"HandAndEquipState[dice=[{}, {}], atk={}, def={}, atk2={}, a1={}, total_set_cost={}, is_cpu={}, assist_flags={:08X}, "
"hand_refs={}, assist_ref={}, set_refs={}, sc_ref={}, hand_refs2={}, set_refs2={}, assist_ref2={}, assist_set_num={}, assist_card_id={}, "
"assist_turns={}, assist_delay={}, atk_bonus={}, def_bonus={}, u2=[{}, {}]]",
this->dice_results[0],
this->dice_results[1],
this->atk_points,
@@ -699,15 +648,15 @@ std::string HandAndEquipState::str(shared_ptr<const Server> s) const {
this->total_set_cards_cost,
this->is_cpu_player,
this->assist_flags,
hand_card_refs_s,
assist_card_ref_s,
set_card_refs_s,
sc_card_ref_s,
hand_card_refs2_s,
set_card_refs2_s,
assist_card_ref2_s,
s->debug_str_for_card_refs(this->hand_card_refs),
s->debug_str_for_card_ref(this->assist_card_ref),
s->debug_str_for_card_refs(this->set_card_refs),
s->debug_str_for_card_ref(this->sc_card_ref),
s->debug_str_for_card_refs(this->hand_card_refs2),
s->debug_str_for_card_refs(this->set_card_refs2),
s->debug_str_for_card_ref(this->assist_card_ref2),
this->assist_card_set_number,
assist_card_id_s,
s->debug_str_for_card_id(this->assist_card_id),
this->assist_remaining_turns,
this->assist_delay_turns,
this->atk_bonuses,
@@ -795,17 +744,15 @@ void PlayerBattleStats::clear() {
float PlayerBattleStats::score(size_t num_rounds) const {
// Note: This formula doesn't match the formula on PSO-World, which is:
// 35
// + (Attack Damage - Damage Taken)
// + (Max Card Combo x 3)
// - (Story Character Damage x 1.8)
// - (Turns x 2.7)
// + (Action Card Negated Damage x 0.8)
// I don't know where that formula came from, but this one came from the USA
// Ep3 PsoV3.dol, so it's presumably correct. Is the PSO-World formula simply
// incorrect, or is it from e.g. the Japanese version, which may have a
// 35 + (Attack Damage - Damage Taken)
// + (Max Card Combo x 3)
// - (Story Character Damage x 1.8)
// - (Turns x 2.7)
// + (Action Card Negated Damage x 0.8)
// I don't know where that formula came from, but this one came from the USA Ep3 PsoV3.dol, so it's presumably
// correct. Is the PSO-World formula simply incorrect, or is it from e.g. the Japanese version, which may have a
// different rank calculation function?
return 38.0f + 0.8f * this->action_card_negated_damage - 2.3f * num_rounds - 1.8f * this->sc_damage_taken + 3.0f * this->max_attack_combo_size + (this->damage_given - this->damage_taken);
return 38.0f + (0.8f * this->action_card_negated_damage) - (2.3f * num_rounds) - (1.8f * this->sc_damage_taken) + (3.0f * this->max_attack_combo_size) + (this->damage_given - this->damage_taken);
}
uint8_t PlayerBattleStats::rank(size_t num_rounds) const {
@@ -817,10 +764,8 @@ const char* PlayerBattleStats::rank_name(size_t num_rounds) const {
}
constexpr size_t RANK_THRESHOLD_COUNT = 9;
static const float RANK_THRESHOLDS[RANK_THRESHOLD_COUNT] = {
15.0f, 25.0f, 30.0f, 40.0f, 50.0f, 60.0f, 65.0f, 75.0f, 85.0f};
static const char* RANK_NAMES[RANK_THRESHOLD_COUNT + 1] = {
"E", "D", "D+", "C", "C+", "B", "B+", "A", "A+", "S"};
static const float RANK_THRESHOLDS[RANK_THRESHOLD_COUNT] = {15, 25, 30, 40, 50, 60, 65, 75, 85};
static const char* RANK_NAMES[RANK_THRESHOLD_COUNT + 1] = {"E", "D", "D+", "C", "C+", "B", "B+", "A", "A+", "S"};
uint8_t PlayerBattleStats::rank_for_score(float score) {
size_t rank = 0;
@@ -874,13 +819,15 @@ static bool is_card_within_range(
if ((ss.loc.x < anchor_loc.x - 4) || (ss.loc.x > anchor_loc.x + 4)) {
if (log) {
log->debug_f("is_card_within_range: (false) outside x range (ss.loc.x={}, anchor_loc.x={})", ss.loc.x, anchor_loc.x);
log->debug_f(
"is_card_within_range: (false) outside x range (ss.loc.x={}, anchor_loc.x={})", ss.loc.x, anchor_loc.x);
}
return false;
}
if ((ss.loc.y < anchor_loc.y - 4) || (ss.loc.y > anchor_loc.y + 4)) {
if (log) {
log->debug_f("is_card_within_range: (false) outside y range (ss.loc.y={}, anchor_loc.y={})", ss.loc.y, anchor_loc.y);
log->debug_f(
"is_card_within_range: (false) outside y range (ss.loc.y={}, anchor_loc.y={})", ss.loc.y, anchor_loc.y);
}
return false;
}
+3 -7
View File
@@ -102,8 +102,7 @@ struct ActionState {
} __packed_ws__(ActionState, 0x64);
struct ActionChain {
// Note: Episode 3 Trial Edition has a different format for this structure.
// See ActionChainWithCondsTrial for details.
// Note: Trial Edition has a different format for this structure. See ActionChainWithCondsTrial for details.
/* 00 */ int8_t effective_ap;
/* 01 */ int8_t effective_tp;
/* 02 */ int8_t ap_effect_bonus;
@@ -196,8 +195,7 @@ struct ActionChainWithCondsTrial {
/* 0022 */ int8_t card_ap;
/* 0023 */ int8_t card_tp;
/* 0024 */ le_uint32_t flags;
// The only difference between this structure and ActionChainWithConds is that
// these two fields are in the opposite order.
// The only difference between this structure and ActionChainWithConds is that these two fields are swapped.
/* 0028 */ parray<Condition, 9> conditions;
/* 00B8 */ parray<le_uint16_t, 4 * 9> target_card_refs;
/* 0100 */
@@ -236,9 +234,7 @@ struct ActionMetadata {
void clear_target_card_refs();
void add_target_card_ref(uint16_t card_ref);
void add_defense_card_ref(
uint16_t defense_card_ref,
std::shared_ptr<Card> card,
uint16_t original_attacker_card_ref);
uint16_t defense_card_ref, std::shared_ptr<Card> card, uint16_t original_attacker_card_ref);
std::string str(std::shared_ptr<const Server> s) const;
} __packed_ws__(ActionMetadata, 0x74);
+82 -135
View File
@@ -25,8 +25,7 @@ void compute_effective_range(
ret.clear(0);
parray<uint32_t, 6> range_def;
if (card_id == 0xFFFE) {
// Heavy Fog: one tile directly in front
if (card_id == 0xFFFE) { // Heavy Fog: one tile directly in front
range_def[3] = 0x00000100;
} else {
shared_ptr<const CardIndex::CardEntry> ce;
@@ -40,11 +39,11 @@ void compute_effective_range(
}
}
if (log) {
log->debug_f("compute_effective_range: range_def: {:05X} {:05X} {:05X} {:05X} {:05X} {:05X}", range_def[0], range_def[1], range_def[2], range_def[3], range_def[4], range_def[5]);
log->debug_f("compute_effective_range: range_def: {:05X} {:05X} {:05X} {:05X} {:05X} {:05X}",
range_def[0], range_def[1], range_def[2], range_def[3], range_def[4], range_def[5]);
}
if (range_def[0] == 0x000FFFFF) {
// Entire field
if (range_def[0] == 0x000FFFFF) { // Entire field
ret.clear(2);
if (log) {
log->debug_f("compute_effective_range: entire field (2)");
@@ -65,7 +64,9 @@ void compute_effective_range(
if (log) {
for (size_t y = 0; y < 9; y++) {
log->debug_f("compute_effective_range: decoded_range: {:X} {:X} {:X} {:X} {:X} {:X} {:X} {:X} {:X}",
decoded_range[y * 9 + 0], decoded_range[y * 9 + 1], decoded_range[y * 9 + 2], decoded_range[y * 9 + 3], decoded_range[y * 9 + 4], decoded_range[y * 9 + 5], decoded_range[y * 9 + 6], decoded_range[y * 9 + 7], decoded_range[y * 9 + 8]);
decoded_range[y * 9 + 0], decoded_range[y * 9 + 1], decoded_range[y * 9 + 2],
decoded_range[y * 9 + 3], decoded_range[y * 9 + 4], decoded_range[y * 9 + 5],
decoded_range[y * 9 + 6], decoded_range[y * 9 + 7], decoded_range[y * 9 + 8]);
}
}
@@ -98,7 +99,8 @@ void compute_effective_range(
}
ret[y * 9 + x] = decoded_range[up_y * 9 + up_x];
if (log) {
log->debug_f("compute_effective_range: x={} y={} up_x={} up_y={} v={:X}", x, y, up_x, up_y, ret[y * 9 + x]);
log->debug_f(
"compute_effective_range: x={} y={} up_x={} up_y={} v={:X}", x, y, up_x, up_y, ret[y * 9 + x]);
}
}
}
@@ -108,7 +110,8 @@ void compute_effective_range(
if (log) {
for (size_t y = 0; y < 9; y++) {
log->debug_f("compute_effective_range: ret: {:X} {:X} {:X} {:X} {:X} {:X} {:X} {:X} {:X}",
ret[y * 9 + 0], ret[y * 9 + 1], ret[y * 9 + 2], ret[y * 9 + 3], ret[y * 9 + 4], ret[y * 9 + 5], ret[y * 9 + 6], ret[y * 9 + 7], ret[y * 9 + 8]);
ret[y * 9 + 0], ret[y * 9 + 1], ret[y * 9 + 2], ret[y * 9 + 3], ret[y * 9 + 4],
ret[y * 9 + 5], ret[y * 9 + 6], ret[y * 9 + 7], ret[y * 9 + 8]);
}
}
}
@@ -124,9 +127,7 @@ bool card_linkage_is_valid(
bool sc_is_named_android_without_permission_effect = false;
bool sc_is_named_android = sc_ce->def.is_named_android_sc();
if (sc_is_named_android &&
!has_permission_effect &&
(left_ce->def.type == CardType::ITEM)) {
if (sc_is_named_android && !has_permission_effect && (left_ce->def.type == CardType::ITEM)) {
sc_is_named_android_without_permission_effect = true;
}
@@ -136,8 +137,7 @@ bool card_linkage_is_valid(
for (size_t x = 0; x < 8; x++) {
uint8_t right_color = left_ce->def.right_colors[x];
if ((right_color != 0) &&
(!sc_is_named_android_without_permission_effect || (right_color != 3))) {
if ((right_color != 0) && (!sc_is_named_android_without_permission_effect || (right_color != 3))) {
for (size_t y = 0; y < 8; y++) {
if (right_color == right_ce->def.left_colors[y]) {
return true;
@@ -146,15 +146,13 @@ bool card_linkage_is_valid(
}
}
// If we get here, then the linkage does not make sense based only on the
// cards' left/right colors. It may still be allowed if Permission is in
// effect, though.
// If we get here, then the linkage does not make sense based only on the cards' left/right colors. It may still be
// allowed if Permission is in effect, though.
// Ignore Permission effect if the left card is another action card (the Tech
// color linkage must make sense in that case). (The way they do this is kind
// of dumb - they should have checked that type == ACTION, but instead they
// checked that type *isn't* most of the other types... but curiously, ASSIST
// is not checked. This is probably just an oversight.)
// Ignore Permission effect if the left card is another action card (the Tech color linkage must make sense in that
// case). (The way they do this is kind of dumb - they should have checked that type == ACTION, but instead they
// checked that type *isn't* most of the other types... but curiously, ASSIST is not checked. This is probably just
// an oversight.)
if (has_permission_effect &&
(left_ce->def.type != CardType::HUNTERS_SC) &&
(left_ce->def.type != CardType::ARKZ_SC) &&
@@ -198,17 +196,14 @@ shared_ptr<const Server> RulerServer::server() const {
return s;
}
ActionChainWithConds* RulerServer::action_chain_with_conds_for_card_ref(
uint16_t card_ref) {
ActionChainWithConds* RulerServer::action_chain_with_conds_for_card_ref(uint16_t card_ref) {
return const_cast<ActionChainWithConds*>(as_const(*this).action_chain_with_conds_for_card_ref(card_ref));
}
const ActionChainWithConds* RulerServer::action_chain_with_conds_for_card_ref(
uint16_t card_ref) const {
const ActionChainWithConds* RulerServer::action_chain_with_conds_for_card_ref(uint16_t card_ref) const {
uint8_t client_id = client_id_for_card_ref(card_ref);
if (client_id != 0xFF) {
// There appears to be a bug in Trial Edition: the bound on this loop is
// 0x10, not 9.
// There appears to be a bug in Trial Edition: the bound on this loop is 0x10, not 9.
for (size_t z = 0; z < 9; z++) {
const auto* chain = &this->set_card_action_chains[client_id]->at(z);
if (card_ref == chain->chain.acting_card_ref) {
@@ -219,8 +214,7 @@ const ActionChainWithConds* RulerServer::action_chain_with_conds_for_card_ref(
return nullptr;
}
bool RulerServer::any_attack_action_card_is_support_tech_or_support_pb(
const ActionState& pa) const {
bool RulerServer::any_attack_action_card_is_support_tech_or_support_pb(const ActionState& pa) const {
if (pa.attacker_card_ref != 0xFFFF) {
for (size_t z = 0; (z < 8) && (pa.action_card_refs[z] != 0xFFFF); z++) {
uint16_t card_id = this->card_id_for_card_ref(pa.action_card_refs[z]);
@@ -292,8 +286,7 @@ bool RulerServer::card_has_pierce_or_rampage(
const auto& sc_status = short_statuses->at(0);
auto ce = this->definition_for_card_ref(sc_status.card_ref);
// This appears to be an NTE bug: Major Pierce doesn't work on Arkz SCs.
if (ce &&
(!is_nte || (ce->def.type == CardType::HUNTERS_SC)) &&
if (ce && (!is_nte || (ce->def.type == CardType::HUNTERS_SC)) &&
(this->get_card_ref_max_hp(sc_status.card_ref) <= sc_status.current_hp * 2)) {
return ret;
}
@@ -354,8 +347,7 @@ bool RulerServer::attack_action_has_rampage_and_not_pierce(const ActionState& pa
}
}
const auto* chain = this->action_chain_with_conds_for_card_ref(
pa.attacker_card_ref);
const auto* chain = this->action_chain_with_conds_for_card_ref(pa.attacker_card_ref);
if (chain) {
for (ssize_t z = 8; z >= 0; z--) {
bool has_rampage = this->check_pierce_and_rampage(
@@ -396,7 +388,8 @@ bool RulerServer::attack_action_has_pierce_and_not_rampage(const ActionState& pa
}
if ((card_ref1 != 0xFFFF) &&
(card_ref1 != pa.attacker_card_ref) &&
!this->check_usability_or_apply_condition_for_card_refs(card_ref1, pa.attacker_card_ref, stat->at(0).card_ref, 0xFF, AttackMedium::INVALID_FF)) {
!this->check_usability_or_apply_condition_for_card_refs(
card_ref1, pa.attacker_card_ref, stat->at(0).card_ref, 0xFF, AttackMedium::INVALID_FF)) {
return false;
}
@@ -433,8 +426,7 @@ bool RulerServer::attack_action_has_pierce_and_not_rampage(const ActionState& pa
}
for (; last_action_card_index >= 0; last_action_card_index--) {
auto ce = this->definition_for_card_ref(
pa.action_card_refs[last_action_card_index]);
auto ce = this->definition_for_card_ref(pa.action_card_refs[last_action_card_index]);
if (!ce) {
continue;
}
@@ -560,8 +552,7 @@ bool RulerServer::card_ref_can_attack(uint16_t card_ref) {
return true;
}
size_t num_assists = this->assist_server->compute_num_assist_effects_for_client(
client_id);
size_t num_assists = this->assist_server->compute_num_assist_effects_for_client(client_id);
for (size_t z = 0; z < num_assists; z++) {
if (this->assist_server->get_active_assist_by_index(z) == AssistEffect::PERMISSION) {
return true;
@@ -571,8 +562,7 @@ bool RulerServer::card_ref_can_attack(uint16_t card_ref) {
return !ce->def.cannot_attack;
}
bool RulerServer::card_ref_can_move(
uint8_t client_id, uint16_t card_ref, bool ignore_atk_points) const {
bool RulerServer::card_ref_can_move(uint8_t client_id, uint16_t card_ref, bool ignore_atk_points) const {
if (client_id == 0xFF) {
return false;
}
@@ -644,8 +634,7 @@ bool RulerServer::card_ref_can_move(
}
}
bool RulerServer::card_ref_has_class_usability_condition(
uint16_t card_ref) const {
bool RulerServer::card_ref_has_class_usability_condition(uint16_t card_ref) const {
auto ce = this->definition_for_card_ref(card_ref);
if (ce) {
uint8_t criterion = static_cast<uint8_t>(ce->def.usable_criterion);
@@ -685,8 +674,7 @@ bool RulerServer::card_ref_is_aerial(uint16_t card_ref) const {
return this->find_condition_on_card_ref(card_ref, ConditionType::AERIAL);
}
bool RulerServer::card_ref_is_aerial_or_has_free_maneuver(
uint16_t card_ref) const {
bool RulerServer::card_ref_is_aerial_or_has_free_maneuver(uint16_t card_ref) const {
return (this->card_ref_has_free_maneuver(card_ref) || this->card_ref_is_aerial(card_ref));
}
@@ -694,8 +682,7 @@ bool RulerServer::card_ref_is_boss_sc(uint32_t card_ref) const {
return this->card_id_is_boss_sc(this->card_id_for_card_ref(card_ref));
}
bool RulerServer::card_ref_or_any_set_card_has_condition_46(
uint16_t card_ref) const {
bool RulerServer::card_ref_or_any_set_card_has_condition_46(uint16_t card_ref) const {
uint16_t card_id = this->card_id_for_card_ref(card_ref);
if (card_id == 0xFFFF) {
return false;
@@ -752,8 +739,7 @@ bool RulerServer::card_ref_or_sc_has_fixed_range(uint16_t card_ref) const {
return false;
}
return this->find_condition_on_card_ref(
this->short_statuses[client_id]->at(0).card_ref, ConditionType::FIXED_RANGE);
return this->find_condition_on_card_ref(this->short_statuses[client_id]->at(0).card_ref, ConditionType::FIXED_RANGE);
}
bool RulerServer::check_move_path_and_get_cost(
@@ -772,9 +758,8 @@ bool RulerServer::check_move_path_and_get_cost(
}
uint8_t atk = this->hand_and_equip_states[client_id]->atk_points;
// Note: In the original code, it seems atk was signed, which doesn't make
// much sense. We've fixed that here.
// if (atk < 0) { // Uhhh what? This is supposed to be impossible
// Note: In the original code, it seems atk was signed, which doesn't make much sense.
// if (atk < 0) { // This is supposed to be impossible
// return false;
// }
@@ -833,8 +818,7 @@ bool RulerServer::check_pierce_and_rampage(
return false;
}
if ((card_ref != 0xFFFF) &&
(!card_short_status || !this->card_exists_by_status(*card_short_status))) {
if ((card_ref != 0xFFFF) && (!card_short_status || !this->card_exists_by_status(*card_short_status))) {
return false;
}
@@ -971,8 +955,7 @@ bool RulerServer::check_usability_or_condition_apply(
}
log.debug_f("criterion_code={}", phosg::name_for_enum(criterion_code));
// For item usability checks, prevent criteria that depend on player
// positioning/team setup
// For item usability checks, prevent criteria that depend on player positioning/team setup
if (is_item_usability_check &&
((criterion_code == CriterionCode::SAME_TEAM) ||
(criterion_code == CriterionCode::SAME_PLAYER) ||
@@ -984,13 +967,11 @@ bool RulerServer::check_usability_or_condition_apply(
criterion_code = CriterionCode::NONE;
}
// Presumably this odd-looking expression here is used to handle two different
// cases. When checking for a condition, def_effect_index should be non-0xFF,
// so we'd return true if the criterion passes. When checking if an item or
// creature card is usable, the two client IDs should be the same or the
// second should not be given, so we'd return true if the criterion passes. If
// neither of these cases apply, we should return false as a failsafe even if
// the criterion passes. NTE did not have such a check.
// Presumably this odd-looking expression here is used to handle two different cases. When checking for a condition,
// def_effect_index should be non-0xFF, so we'd return true if the criterion passes. When checking if an item or
// creature card is usable, the two client IDs should be the same or the second should not be given, so we'd return
// true if the criterion passes. If neither of these cases apply, we should return false as a failsafe even if the
// criterion passes. NTE did not have such a check.
bool ret = is_nte || (!(def_effect_index & 0x80) || (client_id1 == client_id2)) || (client_id2 == 0xFF);
switch (criterion_code) {
case CriterionCode::NONE:
@@ -1359,9 +1340,7 @@ bool RulerServer::check_usability_or_condition_apply(
}
uint16_t RulerServer::compute_attack_or_defense_costs(
const ActionState& pa,
bool allow_mighty_knuckle,
uint8_t* out_ally_cost) const {
const ActionState& pa, bool allow_mighty_knuckle, uint8_t* out_ally_cost) const {
int16_t final_cost = 1;
bool has_mighty_knuckle = false;
int16_t cost_bias = 0;
@@ -1383,8 +1362,7 @@ uint16_t RulerServer::compute_attack_or_defense_costs(
uint8_t client_id = client_id_for_card_ref(pa.attacker_card_ref);
uint16_t sc_card_ref_if_item = 0xFFFF;
if ((client_id != 0xFF) && ce && (ce->def.type == CardType::ITEM) &&
this->short_statuses[client_id]) {
if ((client_id != 0xFF) && ce && (ce->def.type == CardType::ITEM) && this->short_statuses[client_id]) {
sc_card_ref_if_item = this->short_statuses[client_id]->at(0).card_ref;
}
@@ -1514,8 +1492,7 @@ bool RulerServer::compute_effective_range_and_target_mode_for_attack(
if (sc_ce && (static_cast<uint8_t>(target_mode) < 6)) {
target_mode = sc_ce->def.target_mode;
const char* target_mode_name = name_for_target_mode(target_mode);
log.debug_f("sc_ce overrides target mode with {} ({})",
target_mode_name, static_cast<uint8_t>(target_mode));
log.debug_f("sc_ce overrides target mode with {} ({})", target_mode_name, static_cast<uint8_t>(target_mode));
}
}
}
@@ -1568,9 +1545,7 @@ size_t RulerServer::count_rampage_targets_for_attack(const ActionState& pa, uint
}
bool RulerServer::defense_card_can_apply_to_attack(
uint16_t defense_card_ref,
uint16_t attacker_card_ref,
uint16_t attacker_sc_card_ref) const {
uint16_t defense_card_ref, uint16_t attacker_card_ref, uint16_t attacker_sc_card_ref) const {
uint16_t defense_card_id = this->card_id_for_card_ref(defense_card_ref);
uint16_t attacker_sc_card_id = this->card_id_for_card_ref(attacker_sc_card_ref);
uint16_t attacker_card_id = this->card_id_for_card_ref(attacker_card_ref);
@@ -1654,8 +1629,7 @@ bool RulerServer::defense_card_matches_any_attack_card_top_color(const ActionSta
if (!ce) {
throw runtime_error("defense card definition is missing");
}
const auto* chain = this->action_chain_with_conds_for_card_ref(
pa.original_attacker_card_ref);
const auto* chain = this->action_chain_with_conds_for_card_ref(pa.original_attacker_card_ref);
if (chain->chain.attack_action_card_ref_count < 1) {
auto other_ce = this->definition_for_card_ref(pa.original_attacker_card_ref);
if (other_ce && other_ce->def.any_top_color_matches(ce->def)) {
@@ -1681,10 +1655,7 @@ shared_ptr<const CardIndex::CardEntry> RulerServer::definition_for_card_ref(uint
}
int32_t RulerServer::error_code_for_client_setting_card(
uint8_t client_id,
uint16_t card_ref,
const Location* loc,
uint8_t assist_target_client_id) const {
uint8_t client_id, uint16_t card_ref, const Location* loc, uint8_t assist_target_client_id) const {
if (client_id > 3) {
return -0x7D;
}
@@ -1843,8 +1814,7 @@ int32_t RulerServer::error_code_for_client_setting_card(
if (!this->get_creature_summon_area(client_id, &summon_area_loc, &summon_area_size)) {
if (team_id != 1) {
if ((loc->x > 0) && (loc->x < this->map_and_rules->map.width - 1)) {
if ((loc->y < this->map_and_rules->map.height - summon_cost - 1) &&
(loc->y > 0)) {
if ((loc->y < this->map_and_rules->map.height - summon_cost - 1) && (loc->y > 0)) {
return 0;
}
if (loc->y == 1) {
@@ -1852,8 +1822,7 @@ int32_t RulerServer::error_code_for_client_setting_card(
}
}
} else {
if ((loc->x > 0) &&
(loc->x < this->map_and_rules->map.width - 1)) {
if ((loc->x > 0) && (loc->x < this->map_and_rules->map.width - 1)) {
if ((summon_cost + 1 <= loc->y) && (loc->y < this->map_and_rules->map.height - 1)) {
return 0;
}
@@ -1965,8 +1934,7 @@ bool RulerServer::flood_fill_move_path(
size_t num_occupied_tiles,
size_t num_vacant_tiles) const {
auto state = this->map_and_rules;
if ((x < 1) || (x >= state->map.width - 1) ||
(y < 1) || (y >= state->map.height - 1)) {
if ((x < 1) || (x >= state->map.width - 1) || (y < 1) || (y >= state->map.height - 1)) {
return 0;
}
@@ -1979,15 +1947,12 @@ bool RulerServer::flood_fill_move_path(
} else {
uint32_t cost = this->get_path_cost(
chain,
num_vacant_tiles + num_occupied_tiles + 1,
is_aerial ? num_occupied_tiles : 0);
chain, num_vacant_tiles + num_occupied_tiles + 1, is_aerial ? num_occupied_tiles : 0);
if (max_atk_points < cost) {
return 0;
}
visited_map->at(x * 0x10 + y) = 1;
if (path && (path->end_loc.x == x) && (path->end_loc.y == y) &&
((path->length == -1) || (cost < path->cost))) {
if (path && (path->end_loc.x == x) && (path->end_loc.y == y) && ((path->length == -1) || (cost < path->cost))) {
ret = true;
path->reset_totals();
path->remaining_distance = max_distance;
@@ -2005,8 +1970,7 @@ bool RulerServer::flood_fill_move_path(
int16_t new_max_distance = max_distance - 1;
if (new_max_distance > 0) {
static const int8_t offsets[4][2] = {
{1, 0}, {0, -1}, {-1, 0}, {0, 1}};
static const int8_t offsets[4][2] = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};
Direction dirs[3] = {direction, turn_left(direction), turn_right(direction)};
for (size_t dir_index = 0; dir_index < 3; dir_index++) {
if (static_cast<uint8_t>(dirs[dir_index]) > 3) {
@@ -2061,9 +2025,7 @@ uint32_t RulerServer::get_card_id_with_effective_range(
uint16_t card_ref, uint16_t card_id_override, TargetMode* out_target_mode) const {
auto log = this->server()->log_stack(std::format("get_card_id_with_effective_range(@{:04X}, #{:04X}): ", card_ref, card_id_override));
uint16_t card_id = (card_id_override == 0xFFFF)
? this->card_id_for_card_ref(card_ref)
: card_id_override;
uint16_t card_id = (card_id_override == 0xFFFF) ? this->card_id_for_card_ref(card_ref) : card_id_override;
log.debug_f("card_id=#{:04X}", card_id);
if (card_id != 0xFFFF) {
@@ -2079,7 +2041,8 @@ uint32_t RulerServer::get_card_id_with_effective_range(
card_id = this->card_id_for_card_ref(card_ref);
auto orig_ce = this->definition_for_card_id(card_id);
if (orig_ce && (static_cast<uint8_t>(effective_target_mode) < 6)) {
log.debug_f("ce valid for #{:04X} with effective target mode {}; overriding to {}", card_id, name_for_target_mode(effective_target_mode), name_for_target_mode(orig_ce->def.target_mode));
log.debug_f("ce valid for #{:04X} with effective target mode {}; overriding to {}",
card_id, name_for_target_mode(effective_target_mode), name_for_target_mode(orig_ce->def.target_mode));
effective_target_mode = orig_ce->def.target_mode;
}
}
@@ -2123,8 +2086,7 @@ uint8_t RulerServer::get_card_ref_max_hp(uint16_t card_ref) const {
}
}
bool RulerServer::get_creature_summon_area(
uint8_t client_id, Location* out_loc, uint8_t* out_region_size) const {
bool RulerServer::get_creature_summon_area(uint8_t client_id, Location* out_loc, uint8_t* out_region_size) const {
if (!this->map_and_rules || (client_id > 3)) {
return false;
}
@@ -2155,8 +2117,7 @@ bool RulerServer::get_creature_summon_area(
region_size = this->map_and_rules->map.height - 3;
break;
default:
// This case isn't in the original code; probably it fell through to one
// of the above
// This case isn't in the original code; probably it fell through to one of the above
return false;
}
@@ -2169,27 +2130,20 @@ bool RulerServer::get_creature_summon_area(
return true;
}
shared_ptr<HandAndEquipState> RulerServer::get_hand_and_equip_state_for_client_id(
uint8_t client_id) {
shared_ptr<HandAndEquipState> RulerServer::get_hand_and_equip_state_for_client_id(uint8_t client_id) {
return (client_id < 4) ? this->hand_and_equip_states[client_id] : nullptr;
}
shared_ptr<const HandAndEquipState> RulerServer::get_hand_and_equip_state_for_client_id(
uint8_t client_id) const {
shared_ptr<const HandAndEquipState> RulerServer::get_hand_and_equip_state_for_client_id(uint8_t client_id) const {
return (client_id < 4) ? this->hand_and_equip_states[client_id] : nullptr;
}
bool RulerServer::get_move_path_length_and_cost(
uint32_t client_id,
uint32_t card_ref,
const Location& loc,
uint32_t* out_length,
uint32_t* out_cost) const {
uint32_t client_id, uint32_t card_ref, const Location& loc, uint32_t* out_length, uint32_t* out_cost) const {
MovePath path;
parray<uint8_t, 0x100> visited_map;
path.end_loc = loc;
if (!this->check_move_path_and_get_cost(
client_id, card_ref, &visited_map, &path, out_cost)) {
if (!this->check_move_path_and_get_cost(client_id, card_ref, &visited_map, &path, out_cost)) {
return false;
}
@@ -2206,9 +2160,7 @@ bool RulerServer::get_move_path_length_and_cost(
}
ssize_t RulerServer::get_path_cost(
const ActionChainWithConds& chain,
ssize_t path_length,
ssize_t cost_penalty) const {
const ActionChainWithConds& chain, ssize_t path_length, ssize_t cost_penalty) const {
for (size_t x = 0; x < 9; x++) {
const auto& cond = chain.conditions[x];
if (cond.type == ConditionType::SET_MV_COST_TO_0) {
@@ -2253,13 +2205,11 @@ bool RulerServer::is_attack_valid(const ActionState& pa) {
return false;
}
// Note: The original code has a case here that results in error code -0x5E,
// triggered by a function returning false. However, that function always
// returns true and has no side effects, so we've omitted the case here.
// Note: The original code has a case here that results in error code -0x5E, triggered by a function returning false.
// However, that function always returns true and has no side effects, so we've omitted the case here.
const auto* attacker_card_status = this->short_status_for_card_ref(attacker_card_ref);
if (!attacker_card_status ||
!this->card_ref_can_attack(attacker_card_ref) ||
if (!attacker_card_status || !this->card_ref_can_attack(attacker_card_ref) ||
(attacker_card_status->card_flags & 0x500)) {
this->error_code3 = -0x6F;
return false;
@@ -2272,9 +2222,7 @@ bool RulerServer::is_attack_valid(const ActionState& pa) {
auto attacker_ce = this->definition_for_card_ref(attacker_card_ref);
auto attacker_chain = this->action_chain_with_conds_for_card_ref(attacker_card_ref);
if (!attacker_chain ||
(attacker_chain->chain.acting_card_ref != attacker_card_ref) ||
!attacker_ce ||
if (!attacker_chain || (attacker_chain->chain.acting_card_ref != attacker_card_ref) || !attacker_ce ||
((attacker_ce->def.type != CardType::HUNTERS_SC &&
(attacker_ce->def.type != CardType::ARKZ_SC) &&
(attacker_ce->def.type != CardType::CREATURE) &&
@@ -2313,7 +2261,9 @@ bool RulerServer::is_attack_valid(const ActionState& pa) {
return false;
}
auto left_card_ce = (z == 0) ? this->definition_for_card_ref(card_ref) : this->definition_for_card_ref(pa.action_card_refs[z - 1]);
auto left_card_ce = (z == 0)
? this->definition_for_card_ref(card_ref)
: this->definition_for_card_ref(pa.action_card_refs[z - 1]);
auto right_card_ce = this->definition_for_card_ref(right_card_ref);
if (right_card_ce->def.type != CardType::ACTION) {
@@ -2326,7 +2276,9 @@ bool RulerServer::is_attack_valid(const ActionState& pa) {
}
uint8_t attacker_client_id = client_id_for_card_ref(pa.attacker_card_ref);
auto sc_ce = (attacker_client_id != 0xFF) ? this->definition_for_card_ref(this->set_card_action_chains[attacker_client_id]->at(0).chain.acting_card_ref) : nullptr;
auto sc_ce = (attacker_client_id != 0xFF)
? this->definition_for_card_ref(this->set_card_action_chains[attacker_client_id]->at(0).chain.acting_card_ref)
: nullptr;
if (!card_linkage_is_valid(right_card_ce, left_card_ce, sc_ce, has_permission_effect)) {
this->error_code3 = -0x6B;
@@ -2363,8 +2315,7 @@ bool RulerServer::is_attack_valid(const ActionState& pa) {
}
bool RulerServer::is_attack_or_defense_valid(const ActionState& pa) {
// This error code is present in the original code, but is no longer possible
// since we require pa instead of using a pointer.
// This error code is present in the original code, but is no longer possible since we require pa instead.
// if (!pa) {
// this->error_code3 = -0x78;
// return false;
@@ -2450,9 +2401,8 @@ bool RulerServer::is_defense_valid(const ActionState& pa) {
return false;
}
// Note: The original code has a case here that results in error code -0x5E,
// triggered by a function returning false. However, that function always
// returns true and has no side effects, so we've omitted the case here.
// Note: The original code has a case here that results in error code -0x5E, triggered by a function returning false.
// However, that function always returns true and has no side effects, so we've omitted the case here.
const auto* stat = this->short_status_for_card_ref(pa.target_card_refs[0]);
if ((!stat || !this->card_exists_by_status(*stat)) || (stat->card_flags & 0x800)) {
@@ -2590,9 +2540,8 @@ bool RulerServer::MovePath::is_valid() const {
void RulerServer::offsets_for_direction(
const Location& loc, int32_t* out_x_offset, int32_t* out_y_offset) {
// Note: This function has opposite behavior for the UP and DOWN directions
// as compared to the global array of the same name.
// TODO: Figure out why this difference exists and document it.
// Note: This function has opposite behavior for the UP and DOWN directions as compared to the global array of the
// same name. TODO: Figure out why this difference exists and document it.
switch (loc.direction) {
case Direction::LEFT:
*out_x_offset = -1;
@@ -2629,8 +2578,7 @@ void RulerServer::register_player(
this->set_card_action_metadatas[client_id] = set_card_action_metadatas;
}
void RulerServer::replace_D1_D2_rank_cards_with_Attack(
parray<le_uint16_t, 0x1F>& card_ids) const {
void RulerServer::replace_D1_D2_rank_cards_with_Attack(parray<le_uint16_t, 0x1F>& card_ids) const {
for (size_t z = 0; z < card_ids.size(); z++) {
auto ce = this->definition_for_card_id(card_ids[z]);
if (ce && ((ce->def.rank == CardRank::D1) || (ce->def.rank == CardRank::D2))) {
@@ -2737,8 +2685,7 @@ bool RulerServer::should_allow_attacks_on_current_turn() const {
}
int32_t RulerServer::verify_deck(
const parray<le_uint16_t, 0x1F>& card_ids,
const parray<uint8_t, 0x2F0>* owned_card_counts) const {
const parray<le_uint16_t, 0x1F>& card_ids, const parray<uint8_t, 0x2F0>* owned_card_counts) const {
for (size_t z = 0; z < card_ids.size(); z++) {
if (!this->definition_for_card_id(card_ids.at(z))) {
return -0x7C;
+2 -4
View File
@@ -152,8 +152,7 @@ public:
uint32_t get_card_id_with_effective_range(
uint16_t card_ref, uint16_t card_id_override, TargetMode* out_target_mode) const;
uint8_t get_card_ref_max_hp(uint16_t card_ref) const;
bool get_creature_summon_area(
uint8_t client_id, Location* out_loc, uint8_t* out_region_size) const;
bool get_creature_summon_area(uint8_t client_id, Location* out_loc, uint8_t* out_region_size) const;
std::shared_ptr<HandAndEquipState> get_hand_and_equip_state_for_client_id(uint8_t client_id);
std::shared_ptr<const HandAndEquipState> get_hand_and_equip_state_for_client_id(uint8_t client_id) const;
bool get_move_path_length_and_cost(
@@ -191,8 +190,7 @@ public:
const CardShortStatus* short_status_for_card_ref(uint16_t card_ref) const;
bool should_allow_attacks_on_current_turn() const;
int32_t verify_deck(
const parray<le_uint16_t, 0x1F>& card_ids,
const parray<uint8_t, 0x2F0>* owned_card_counts = nullptr) const;
const parray<le_uint16_t, 0x1F>& card_ids, const parray<uint8_t, 0x2F0>* owned_card_counts = nullptr) const;
private:
std::weak_ptr<Server> w_server;
+80 -124
View File
@@ -12,12 +12,10 @@ using namespace std;
namespace Episode3 {
// This is (obviously) not the original string. The original string is:
// "03/05/29 18:00 by K.Toya" (NTE)
// "[V1][FINAL2.0] 03/09/13 15:30 by K.Toya" (Final)
static const char* VERSION_SIGNATURE =
"newserv Ep3 based on [V1][FINAL2.0] 03/09/13 15:30 by K.Toya";
static const char* VERSION_SIGNATURE_NTE =
"newserv Ep3 NTE based on 03/05/29 18:00 by K.Toya";
// NTE: "03/05/29 18:00 by K.Toya"
// Final: "[V1][FINAL2.0] 03/09/13 15:30 by K.Toya"
static const char* VERSION_SIGNATURE = "newserv Ep3 based on [V1][FINAL2.0] 03/09/13 15:30 by K.Toya";
static const char* VERSION_SIGNATURE_NTE = "newserv Ep3 NTE based on 03/05/29 18:00 by K.Toya";
Server::PresenceEntry::PresenceEntry() {
this->clear();
@@ -103,10 +101,9 @@ void Server::init() {
this->card_special = make_shared<CardSpecial>(this->shared_from_this());
// Note: The original implementation calls the default PSOV2Encryption
// constructor for random_crypt, which just uses 0 as the seed. It then
// re-seeds the generator later. We instead expect the caller to provide a
// seeded generator, and we don't re-seed it at all.
// Note: The original implementation calls the default PSOV2Encryption constructor for random_crypt, which just uses
// 0 as the seed. It then re-seeds the generator later. We instead expect the caller to provide a seeded generator,
// and we don't re-seed it at all.
// this->random_crypt = make_shared<PSOV2Encryption>(0);
this->state_flags = make_shared<StateFlags>();
@@ -254,10 +251,6 @@ void Server::send(const void* data, size_t size, uint8_t command, bool enable_ma
size = masked_data.size();
}
// Note: Sega's servers sent battle commands with the 60 command. The handlers
// for 60, 62, and C9 on the client are identical, so we choose to use C9
// instead because it's unique to Episode 3, and therefore seems more
// appropriate to convey battle commands.
send_command(l, command, 0x00, data, size);
for (auto watcher_l : l->watcher_lobbies) {
send_command_if_not_loading(watcher_l, command, 0x00, data, size);
@@ -273,14 +266,15 @@ void Server::send(const void* data, size_t size, uint8_t command, bool enable_ma
}
void Server::send_6xB4x46() const {
// Note: This function is not part of the original implementation; it was
// factored out from its callsites in this file and the strings were changed.
// Note: This function is not part of the original implementation; it was factored out from its callsites in this
// file and the strings were changed.
// NTE doesn't have the date_str2 field, but we send it anyway to make
// debugging easier.
// NTE doesn't have the date_str2 field, but we send it anyway to make debugging easier.
G_ServerVersionStrings_Ep3_6xB4x46 cmd;
cmd.version_signature.encode(this->options.is_nte() ? VERSION_SIGNATURE_NTE : VERSION_SIGNATURE, Language::ENGLISH);
cmd.date_str1.encode(std::format("Card definitions: {:016X}", this->options.card_index->definitions_hash()), Language::ENGLISH);
cmd.date_str1.encode(
std::format("Card definitions: {:016X}", this->options.card_index->definitions_hash()),
Language::ENGLISH);
string build_date = phosg::format_time(BUILD_TIMESTAMP);
cmd.date_str2.encode(std::format("newserv {} compiled at {}", GIT_REVISION_HASH, build_date), Language::ENGLISH);
this->send(cmd);
@@ -293,29 +287,24 @@ string Server::prepare_6xB6x41_map_definition(shared_ptr<const MapIndex::Map> ma
phosg::StringWriter w;
uint32_t subcommand_size = (compressed->size() + sizeof(G_MapData_Ep3_6xB6x41) + 3) & (~3);
w.put<G_MapData_Ep3_6xB6x41>({{{{0xB6, 0, 0}, subcommand_size}, 0x41, {}}, vm->map->map_number.load(), compressed->size(), 0});
w.put<G_MapData_Ep3_6xB6x41>(
{{{{0xB6, 0, 0}, subcommand_size}, 0x41, {}}, vm->map->map_number.load(), compressed->size(), 0});
w.write(*compressed);
return std::move(w.str());
}
void Server::send_commands_for_joining_spectator(std::shared_ptr<Channel> ch) const {
bool should_send_state = true;
if (this->setup_phase == SetupPhase::REGISTRATION) {
// If registration is still in progress, we only need to send the map data
// (if a map is even chosen yet)
if ((this->registration_phase != RegistrationPhase::REGISTERED) &&
(this->registration_phase != RegistrationPhase::BATTLE_STARTED)) {
should_send_state = false;
}
}
if (this->last_chosen_map) {
string data = this->prepare_6xB6x41_map_definition(this->last_chosen_map, ch->language, this->options.is_nte());
this->log().info_f("Sending {} version of map {:08X}", name_for_language(ch->language), this->last_chosen_map->map_number);
this->log().info_f(
"Sending {} version of map {:08X}", name_for_language(ch->language), this->last_chosen_map->map_number);
ch->send(0x6C, 0x00, data);
}
if (should_send_state) {
// If registration is still in progress, we don't need to send the battle state
if ((this->setup_phase != SetupPhase::REGISTRATION) ||
(this->registration_phase == RegistrationPhase::REGISTERED) ||
(this->registration_phase == RegistrationPhase::BATTLE_STARTED)) {
ch->send(0xC9, 0x00, this->prepare_6xB4x03());
for (uint8_t client_id = 0; client_id < 4; client_id++) {
auto ps = this->player_states[client_id];
@@ -339,8 +328,8 @@ void Server::send_commands_for_joining_spectator(std::shared_ptr<Channel> ch) co
// (send 6xB4x4F for client_id)
// }
ch->send(0xC9, 0x00, this->prepare_6xB4x07_decks_update());
// TODO: Sega sends 6xB4x05 here again; why? Is that necessary? They also
// send 6xB4x02 again for each player after that (but not 6xB4x04)
// TODO: Sega sends 6xB4x05 here again; why? Is that necessary? They also send 6xB4x02 again for each player after
// that (but not 6xB4x04)
ch->send(0xC9, 0x00, this->prepare_6xB4x1C_names_update());
ch->send(0xC9, 0x00, this->prepare_6xB4x50_trap_tile_locations());
{
@@ -613,8 +602,8 @@ void Server::force_destroy_field_character(uint8_t client_id, size_t visible_ind
throw runtime_error("player does not exist");
}
// TODO: Is it possible for there to be gaps in the set cards array? If not,
// we could just do a direct array lookup here instead of this loop
// TODO: Is it possible for there to be gaps in the set cards array? If not, we could just do a direct array lookup
// here instead of this loop
shared_ptr<Card> set_card = nullptr;
for (size_t set_index = 0; set_index < 8; set_index++) {
if (!ps->set_cards[set_index]) {
@@ -663,9 +652,7 @@ void Server::check_for_destroyed_cards_and_send_6xB4x05_6xB4x02() {
}
bool Server::check_presence_entry(uint8_t client_id) const {
return (client_id < 4)
? this->presence_entries[client_id].player_present
: false;
return (client_id < 4) ? this->presence_entries[client_id].player_present : false;
}
void Server::clear_player_flags_after_dice_phase() {
@@ -826,9 +813,8 @@ void Server::draw_phase_after() {
if (this->current_team_turn1 == this->first_team_turn) {
if (this->map_and_rules->rules.overall_time_limit > 0) {
// Battle time limits are specified in increments of 5 minutes.
// Note: This part is not based on the original code because the timing
// facilities used are different.
// Battle time limits are specified in increments of 5 minutes. This part is not based on the original code
// because the timing facilities used are different.
uint64_t limit_5mins = this->map_and_rules->rules.overall_time_limit;
uint64_t end_usecs = this->battle_start_usecs + (limit_5mins * 300 * 1000 * 1000);
if (phosg::now() >= end_usecs) {
@@ -924,9 +910,8 @@ void Server::end_attack_list_for_client(uint8_t client_id) {
void Server::end_action_phase() {
this->num_pending_attacks = 0;
this->unknown_a15 = 1;
// Annoyingly, this is the original logic. We use an enum because it appears
// that this can only ever be 0 or 2, but we may have to delete the enum if
// that turns out to be false.
// Annoyingly, this is the original logic. We use an enum because it appears that this can only ever be 0 or 2, but
// we may have to delete the enum if that turns out to be false.
this->action_subphase = static_cast<ActionSubphase>(static_cast<uint8_t>(this->action_subphase) + 2);
if (this->options.is_nte()) {
this->unknown_8023EEF4();
@@ -1005,8 +990,7 @@ bool Server::enqueue_attack_or_defense(uint8_t client_id, ActionState* pa) {
card_ps->send_6xB4x04_if_needed();
}
}
card = this->card_for_set_card_ref(this->send_6xB4x06_if_card_ref_invalid(
pa->original_attacker_card_ref, 2));
card = this->card_for_set_card_ref(this->send_6xB4x06_if_card_ref_invalid(pa->original_attacker_card_ref, 2));
if (card) {
card = this->card_for_set_card_ref(pa->target_card_refs[0]);
if (card) {
@@ -1100,8 +1084,7 @@ void Server::move_phase_after() {
auto ps = this->player_states[client_id];
if (ps) {
auto sc_card = ps->get_sc_card();
if (sc_card && (sc_card->card_flags & 0x80) &&
(sc_card->loc.x == trap_x) && (sc_card->loc.y == trap_y)) {
if (sc_card && (sc_card->card_flags & 0x80) && (sc_card->loc.x == trap_x) && (sc_card->loc.y == trap_y)) {
should_trigger = true;
break;
}
@@ -1111,7 +1094,7 @@ void Server::move_phase_after() {
continue;
}
static const array<vector<uint16_t>, 5> default_trap_card_ids = {
static const array<vector<uint16_t>, 5> DEFAULT_TRAP_CARD_IDS = {
// Red: Dice Fever, Heavy Fog, Muscular, Immortality, Snail Pace
vector<uint16_t>{0x00F7, 0x010F, 0x012E, 0x013B, 0x013C},
// Blue: Gold Rush, Charity, Requiem
@@ -1125,7 +1108,7 @@ void Server::move_phase_after() {
const vector<uint16_t>* trap_card_ids = &this->options.trap_card_ids.at(trap_type);
if (trap_card_ids->empty()) {
trap_card_ids = &default_trap_card_ids.at(trap_type);
trap_card_ids = &DEFAULT_TRAP_CARD_IDS.at(trap_type);
}
// This is the original implementation. We do something smarter instead.
@@ -1145,9 +1128,7 @@ void Server::move_phase_after() {
auto ps = this->player_states[client_id];
if (ps) {
auto sc_card = ps->get_sc_card();
if (sc_card &&
(abs(sc_card->loc.x - trap_x) < 2) &&
(abs(sc_card->loc.y - trap_y) < 2) &&
if (sc_card && (abs(sc_card->loc.x - trap_x) < 2) && (abs(sc_card->loc.y - trap_y) < 2) &&
ps->replace_assist_card_by_id(trap_card_id)) {
G_EnqueueAnimation_Ep3_6xB4x2C cmd;
cmd.change_type = 0x01;
@@ -1173,14 +1154,12 @@ void Server::move_phase_after() {
// this->chosen_trap_tile_index_of_type[trap_type] = new_index;
// this->send_6xB4x50();
// }
// We instead use an implementation that consumes a constant amount of
// randomness per pass.
// We instead use an implementation that consumes a constant amount of randomness per pass.
if (this->num_trap_tiles_of_type[trap_type] == 2) {
this->chosen_trap_tile_index_of_type[trap_type] ^= 1;
this->send_6xB4x50_trap_tile_locations();
} else if (this->num_trap_tiles_of_type[trap_type] > 2) {
// Generate a new random index, but forbid it from matching the existing
// index
// Generate a new random index, but forbid it from matching the existing index
uint8_t new_index = this->get_random(this->num_trap_tiles_of_type[trap_type] - 1);
if (new_index >= this->chosen_trap_tile_index_of_type[trap_type]) {
new_index++;
@@ -1249,8 +1228,7 @@ int8_t Server::send_6xB4x33_remove_ally_atk_if_needed(const ActionState& pa) {
for (size_t z = 0; z < 4; z++) {
auto ally_ps = this->get_player_state(z);
if ((z != setter_client_id) && ally_ps) {
if ((ally_ps->get_team_id() == setter_ps->get_team_id()) &&
(ally_ps->get_atk_points() >= ally_cost)) {
if ((ally_ps->get_team_id() == setter_ps->get_team_id()) && (ally_ps->get_atk_points() >= ally_cost)) {
ally_has_sufficient_atk = true;
}
}
@@ -1376,11 +1354,10 @@ void Server::set_client_id_ready_to_advance_phase(uint8_t client_id, BattlePhase
ps->assist_flags |= AssistFlag::ELIGIBLE_FOR_DICE_BOOST;
}
} else {
// TODO: It'd be nice to do this in a constant-randomness way, but I'm
// lazy, and this matches Sega's original implementation. The less-lazy
// way to do it would be to roll three dice: one in the range [1, N],
// one in the range [3, N], and one in the range [1, 2] to decide
// whether to swap the first two results.
// TODO: It'd be nice to do this in a constant-randomness way, but I'm lazy, and this matches Sega's original
// implementation. The less-lazy way to do it would be to roll three dice: one in the range [1, 2] to decide
// which of ATK or DEF will be boosted, then roll the ATK die in range [1, N] (or [3, N] if it's boosted), and
// do the same for the DEF die.
for (size_t z = 0; z < 200; z++) {
ps->roll_main_dice_or_apply_after_effects();
if ((ps->get_atk_points() >= 3) || (ps->get_def_points() >= 3)) {
@@ -1431,12 +1408,14 @@ void Server::set_phase_after() {
if (ps) {
auto card = ps->get_sc_card();
if (card) {
this->card_special->apply_action_conditions(EffectWhen::AFTER_SET_PHASE, nullptr, card, is_nte ? 0x1F : 0x04, nullptr);
this->card_special->apply_action_conditions(
EffectWhen::AFTER_SET_PHASE, nullptr, card, is_nte ? 0x1F : 0x04, nullptr);
}
for (size_t set_index = 0; set_index < 8; set_index++) {
auto card = ps->get_set_card(set_index);
if (card) {
this->card_special->apply_action_conditions(EffectWhen::AFTER_SET_PHASE, nullptr, card, is_nte ? 0x1F : 0x04, nullptr);
this->card_special->apply_action_conditions(
EffectWhen::AFTER_SET_PHASE, nullptr, card, is_nte ? 0x1F : 0x04, nullptr);
}
}
}
@@ -1494,9 +1473,7 @@ void Server::set_phase_after() {
for (size_t client_id = 0; client_id < 4; client_id++) {
auto ps = this->player_states[client_id];
if (ps &&
(ps->get_assist_turns_remaining() == 90) &&
(ps->assist_delay_turns < 1)) {
if (ps && (ps->get_assist_turns_remaining() == 90) && (ps->assist_delay_turns < 1)) {
ps->discard_set_assist_card();
ps->update_hand_and_equip_state_and_send_6xB4x02_if_needed();
}
@@ -1630,8 +1607,7 @@ void Server::setup_and_start_battle() {
size_t num_trap_tiles = 0;
for (size_t y = 0; y < 0x10; y++) {
for (size_t x = 0; x < 0x10; x++) {
if ((this->overlay_state.tiles[y][x] == (trap_type | 0x40)) &&
(num_trap_tiles < 8)) {
if ((this->overlay_state.tiles[y][x] == (trap_type | 0x40)) && (num_trap_tiles < 8)) {
this->trap_tile_locs[trap_type][num_trap_tiles][0] = x;
this->trap_tile_locs[trap_type][num_trap_tiles][1] = y;
num_trap_tiles++;
@@ -1639,7 +1615,6 @@ void Server::setup_and_start_battle() {
}
}
this->num_trap_tiles_of_type[trap_type] = num_trap_tiles;
if (num_trap_tiles > 0) {
this->chosen_trap_tile_index_of_type[trap_type] = this->get_random(num_trap_tiles);
}
@@ -1684,8 +1659,7 @@ void Server::setup_and_start_battle() {
this->send_6xB4x46();
// Re-send game metadata to spectator teams, since loading the battle scene
// seems to delete it
// Re-send game metadata to spectator teams, since loading the battle scene seems to delete it
auto l = this->lobby.lock();
if (l) {
send_ep3_update_game_metadata(l);
@@ -1709,11 +1683,7 @@ G_SetStateFlags_Ep3_6xB4x03 Server::prepare_6xB4x03() const {
cmd.state.tournament_flag = this->options.tournament ? 1 : 0;
for (size_t z = 0; z < 4; z++) {
auto ps = this->player_states[z];
if (!ps) {
cmd.state.client_sc_card_types[z] = CardType::INVALID_FF;
} else {
cmd.state.client_sc_card_types[z] = ps->get_sc_card_type();
}
cmd.state.client_sc_card_types[z] = ps ? ps->get_sc_card_type() : CardType::INVALID_FF;
}
return cmd;
}
@@ -1726,9 +1696,8 @@ void Server::update_battle_state_flags_and_send_6xB4x03_if_needed(bool always_se
}
}
// Returns true if the battle can begin
bool Server::update_registration_phase() {
// Returns true if the battle can begin
auto log = this->log_stack("update_registration_phase: ");
if (this->setup_phase != SetupPhase::REGISTRATION) {
@@ -1801,7 +1770,8 @@ void Server::on_server_data_input(shared_ptr<Client> sender_c, const string& dat
size_t expected_size = header.size * 4;
if (expected_size < data.size()) {
phosg::print_data(stderr, data);
throw runtime_error(std::format("command is incomplete: expected {:X} bytes, received {:X} bytes", expected_size, data.size()));
throw runtime_error(std::format(
"command is incomplete: expected {:X} bytes, received {:X} bytes", expected_size, data.size()));
}
if (header.subcommand != 0xB3) {
throw runtime_error("server data command is not 6xB3");
@@ -1867,8 +1837,7 @@ void Server::handle_CAx0C_end_redraw_initial_hand_phase(shared_ptr<Client>, cons
}
int32_t error_code = 0;
if ((this->setup_phase != SetupPhase::HAND_REDRAW_OPTION) &&
(this->setup_phase != SetupPhase::STARTER_ROLLS)) {
if ((this->setup_phase != SetupPhase::HAND_REDRAW_OPTION) && (this->setup_phase != SetupPhase::STARTER_ROLLS)) {
error_code = -0x5D;
}
@@ -2138,15 +2107,14 @@ void Server::handle_CAx13_update_map_during_setup_t(shared_ptr<Client> c, const
(this->registration_phase != RegistrationPhase::REGISTERED) &&
(this->registration_phase != RegistrationPhase::BATTLE_STARTED)) {
*this->map_and_rules = in_cmd.map_and_rules_state;
// The client will likely send incorrect values for the extended rules (or
// in the case of NTE, no values at all, since the Rules structure is
// smaller). So, use the values from the last chosen map if applicable, or
// the values from the $dicerange command if available.
// The client will likely send incorrect values for the extended rules (or in the case of NTE, no values at all,
// since the Rules structure is smaller). So, use the values from the last chosen map if applicable, or the values
// from the $dicerange command if available.
Language language = c ? c->language() : Language::ENGLISH;
const Rules* map_rules = this->last_chosen_map ? &this->last_chosen_map->version(language)->map->default_rules : nullptr;
auto& server_rules = this->map_and_rules->rules;
// NTE can specify the DEF dice value range in its Rules struct, so we use
// that unless the map or $dicerange overrides it.
// NTE can specify the DEF dice value range in its Rules struct, so we use that unless the map or $dicerange
// overrides it.
server_rules.def_dice_value_range = (map_rules && (map_rules->def_dice_value_range != 0xFF))
? map_rules->def_dice_value_range
: (this->def_dice_value_range_override != 0xFF)
@@ -2165,8 +2133,7 @@ void Server::handle_CAx13_update_map_during_setup_t(shared_ptr<Client> c, const
? this->def_dice_value_range_2v1_override
: 0;
// If this match is part of a tournament, ignore the rules sent by the
// client and use the tournament rules instead.
// If this match is part of a tournament, ignore the rules sent by the client and use the tournament rules instead.
if (this->options.tournament) {
this->map_and_rules->rules = this->options.tournament->get_rules();
}
@@ -2248,10 +2215,9 @@ void Server::handle_CAx15_unused_hard_reset_server_state(shared_ptr<Client>, con
const auto& in_cmd = check_size_t<G_HardResetServerState_Ep3_CAx15>(data);
this->send_debug_command_received_message(in_cmd.header.subsubcommand, "HARD RESET");
// In the original implementation, this command recreates the server object.
// This is possible because the dispatch function is not part of the server
// object in the original implementation; however, in our implementation, it
// is, so we don't support this. The original implementation did this:
// In the original implementation, this command recreates the server object. This is possible because the dispatch
// function is not part of the server object in the original implementation; however, in our implementation, it is,
// so we don't support this. The original implementation did this:
// this->base()->recreate_server(); // Destroys *this, which we can't do
// root_card_server = this->server;
// *this->map_and_rules = *this->initial_map_and_rules;
@@ -2271,8 +2237,8 @@ void Server::handle_CAx1B_update_player_name(shared_ptr<Client>, const string& d
this->name_entries_valid[in_cmd.entry.client_id] = false;
}
// Note: This check is not part of the original code. This replaces a
// disconnecting player with a CPU if the battle is in progress.
// Note: This check is not part of the original code. This replaces a disconnecting player with a CPU if the battle
// is in progress.
auto l = this->lobby.lock();
if (l && !l->clients[in_cmd.entry.client_id]) {
this->name_entries[in_cmd.entry.client_id].is_cpu_player = 1;
@@ -2325,8 +2291,8 @@ void Server::handle_CAx1D_start_battle(shared_ptr<Client>, const string& data) {
auto l = this->lobby.lock();
if (l) {
// Note: Sega's implementation doesn't set EX results values here; they
// did it at game join time instead. We do it here for code simplicity.
// Note: Sega's implementation doesn't set EX results values here; they did it at game join time instead. We do
// it here for code simplicity.
if (!this->options.is_nte() && l->ep3_ex_result_values) {
this->send(*l->ep3_ex_result_values);
}
@@ -2370,8 +2336,7 @@ void Server::handle_CAx28_end_defense_list(shared_ptr<Client>, const string& dat
for (size_t z = 0; z < 4; z++) {
auto ps = this->player_states[z];
if (ps && (this->current_team_turn1 != ps->get_team_id())) {
if (!ps->get_sc_card()->check_card_flag(2) &&
(this->defense_list_ended_for_client[z] == 0)) {
if (!ps->get_sc_card()->check_card_flag(2) && (this->defense_list_ended_for_client[z] == 0)) {
all_defense_lists_ended = false;
break;
}
@@ -2517,8 +2482,7 @@ void Server::handle_CAx37_client_ready_to_advance_from_starter_roll_phase(shared
void Server::handle_CAx3A_time_limit_expired(shared_ptr<Client>, const string& data) {
const auto& in_cmd = check_size_t<G_OverallTimeLimitExpired_Ep3_CAx3A>(data);
this->send_debug_command_received_message(in_cmd.header.subsubcommand, "TIME EXPIRED");
// We don't need to do anything here because the overall time limit is tracked
// server-side instead.
// We don't need to do anything here because the overall time limit is tracked server-side instead.
}
void Server::handle_CAx40_map_list_request(shared_ptr<Client> sender_c, const string& data) {
@@ -2579,9 +2543,8 @@ void Server::send_6xB6x41_to_all_clients() const {
}
if (this->battle_record && this->battle_record->writable()) {
// TODO: It's not great that we just pick the first one; ideally we'd put
// all of them in the recording and send the appropriate one to the client
// in the playback lobby
// TODO: It's not great that we just pick the first one; ideally we'd put all of them in the recording and send
// the appropriate one to the client in the playback lobby
for (string& data : map_commands_by_language) {
if (!data.empty()) {
this->battle_record->add_command(BattleRecord::Event::Type::BATTLE_COMMAND, std::move(data));
@@ -2626,8 +2589,7 @@ void Server::handle_CAx49_card_counts(shared_ptr<Client>, const string& data) {
const auto& in_cmd = check_size_t<G_CardCounts_Ep3_CAx49>(data);
this->send_debug_command_received_message(in_cmd.header.sender_client_id, in_cmd.header.subsubcommand, "CARD COUNTS");
// Note: Sega's implmentation completely ignores this command. This
// implementation is not based on the original code.
// Note: Sega's implmentation completely ignores this command. This implementation is not based on the original code.
auto& dest_counts = this->client_card_counts[in_cmd.header.sender_client_id];
dest_counts = in_cmd.card_id_to_count;
decrypt_trivial_gci_data(dest_counts.data(), dest_counts.bytes(), in_cmd.basis);
@@ -2884,10 +2846,9 @@ void Server::execute_bomb_assist_effect() {
for (size_t client_id = 0; client_id < 4; client_id++) {
auto ps = this->player_states[client_id];
// Possible bug: shouldn't we check should_block_assist_effects_for_client
// here too? If the player has a card with the same HP as another one that
// would be destroyed, it looks like the card can be destroyed even if the
// client should be immune to assist effects here.
// Possible bug: shouldn't we check should_block_assist_effects_for_client here too? If the player has a card with
// the same HP as another one that would be destroyed, it looks like the card can be destroyed even if the client
// should be immune to assist effects here.
if (ps) {
for (size_t set_index = 0; set_index < 8; set_index++) {
auto card = ps->get_set_card(set_index);
@@ -2917,10 +2878,7 @@ void Server::replace_targets_due_to_destruction_nte(ActionState* as) {
shared_ptr<Card> found_guard_item;
for (size_t z = 0; z < 8; z++) {
auto set_card = ps->get_set_card(z);
if (set_card &&
(set_card != target_card) &&
!(set_card->card_flags & 2) &&
set_card->is_guard_item()) {
if (set_card && (set_card != target_card) && !(set_card->card_flags & 2) && set_card->is_guard_item()) {
found_guard_item = set_card;
break;
}
@@ -3039,8 +2997,8 @@ void Server::replace_targets_due_to_destruction_or_conditions(ActionState* as) {
}
}
// Note: The original code only writes a single FFFF after the last card ref
// in this array; we instead clear the entire array.
// Note: The original code only writes a single FFFF after the last card ref in this array; we instead clear the
// entire array.
as->target_card_refs.clear(0xFFFF);
for (size_t z = 0; z < phase1_replaced_card_refs.size(); z++) {
as->target_card_refs[z] = this->send_6xB4x06_if_card_ref_invalid(phase1_replaced_card_refs[z], 4);
@@ -3062,8 +3020,7 @@ void Server::replace_targets_due_to_destruction_or_conditions(ActionState* as) {
}
}
// Note: This is different from the original code in the same way as above: we
// clear the entire array first.
// Note: This is different from the original code in the same way as above: we clear the entire array first.
as->target_card_refs.clear(0xFFFF);
for (size_t z = 0; z < phase2_replaced_card_refs.size(); z++) {
as->target_card_refs[z] = this->send_6xB4x06_if_card_ref_invalid(phase2_replaced_card_refs[z], 4);
@@ -3148,8 +3105,7 @@ void Server::unknown_802402F4() {
}
}
vector<shared_ptr<Card>> Server::const_cast_set_cards_v(
const vector<shared_ptr<const Card>>& cards) {
vector<shared_ptr<Card>> Server::const_cast_set_cards_v(const vector<shared_ptr<const Card>>& cards) {
// TODO: This is dumb. Figure out a not-dumb way to do this.
vector<shared_ptr<Card>> ret;
for (auto const_card : cards) {
+45 -52
View File
@@ -20,53 +20,43 @@ struct Lobby;
namespace Episode3 {
/**
* This implementation of Episode 3 battles is derived from Sega's original
* server implementation, reverse-engineered from the Episode 3 client
* executable. The control flow, function breakdown, and structure definitions
* in these files map very closely to how their server implementation was
* written; notable differences (due to necessary environment differences or bug
* fixes) are described in the comments therein.
*
* The following files are direct reverse-engineerings of Sega's original code,
* except where noted in the comments:
* AssistServer.hh/cc
* Card.hh/cc
* CardSpecial.hh/cc
* DeckState.hh/cc
* MapState.hh/cc
* PlayerState.hh/cc
* PlayerStateSubordinates.hh/cc
* RulerServer.hh/cc
* Server.hh/cc
*
* There are likely undiscovered bugs in this code, some originally written by
* Sega, but more written by me as I manually transcribed and updated this code.
*
* Class ownership levels (classes may only contain weak_ptrs, not shared_ptrs,
* to classes at the same or higher level):
* - Server
* - - RulerServer
* - - - AssistServer
* - - - CardSpecial
* - - - - StateFlags
* - - - - DeckEntry
* - - - - PlayerState
* - - - - - Card
* - - - - - - CardShortStatus
* - - - - - - DeckState
* - - - - - - HandAndEquipState
* - - - - - - MapAndRulesState / OverlayState
* - - - - - - - Everything within DataIndexes
*/
// This implementation of Episode 3 battles is derived from Sega's original server implementation, reverse-engineered
// from the Episode 3 client executable. The control flow, function breakdown, and structure definitions in these files
// map very closely to how their server implementation was written; notable differences (due to necessary environment
// differences or bug fixes) are described in the comments therein. There are likely undiscovered bugs in this code,
// some originally written by Sega, but more written by me as I manually transcribed and updated this code.
// The following files are direct reverse-engineerings of Sega's original code, except where noted in the comments:
// AssistServer.hh/cc
// Card.hh/cc
// CardSpecial.hh/cc
// DeckState.hh/cc
// MapState.hh/cc
// PlayerState.hh/cc
// PlayerStateSubordinates.hh/cc
// RulerServer.hh/cc
// Server.hh/cc
// Class ownership levels (classes may contain weak_ptrs but not shared_ptrs to classes at the same or higher level):
// - Server
// - - RulerServer
// - - - AssistServer
// - - - CardSpecial
// - - - - StateFlags
// - - - - DeckEntry
// - - - - PlayerState
// - - - - - Card
// - - - - - - CardShortStatus
// - - - - - - DeckState
// - - - - - - HandAndEquipState
// - - - - - - MapAndRulesState / OverlayState
// - - - - - - - Everything within DataIndexes
class Server : public std::enable_shared_from_this<Server> {
// In the original code, there is a TCardServerBase class and a TCardServer
// class, with the former containing some basic parts of the game state and
// a pointer to the latter. It seems these two classes exist (instead of one
// big class) so that the force reset command could be implemented; however,
// it appears that that command is never sent by the client, so we combine
// the two classes into one in our implementation.
// In the original code, there is a TCardServerBase class and a TCardServer class, with the former containing some
// basic parts of the game state and a pointer to the latter. It seems these two classes exist (instead of one big
// class) so that the force reset command could be implemented; however, it appears that that command is never sent
// by the client, so we combine the two classes into one in our implementation.
public:
struct Options {
std::shared_ptr<const CardIndex> card_index;
@@ -131,6 +121,9 @@ public:
int8_t get_winner_team_id() const;
// Note: Sega's servers sent battle commands with the 60 command. The handlers for 60, 62, and C9 on the client are
// identical, so we choose to use C9 instead because it's unique to Episode 3, and therefore seems more appropriate
// to convey Episode 3 battle commands.
template <typename T>
void send(const T& cmd, uint8_t command = 0xC9, bool enable_masking = true) const {
if (cmd.header.size != sizeof(cmd) / 4) {
@@ -241,7 +234,8 @@ public:
void handle_CAx28_end_defense_list(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx2B_legacy_set_card(std::shared_ptr<Client> sender_c, const std::string&);
void handle_CAx34_subtract_ally_atk_points(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx37_client_ready_to_advance_from_starter_roll_phase(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx37_client_ready_to_advance_from_starter_roll_phase(
std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx3A_time_limit_expired(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx40_map_list_request(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx41_map_request(std::shared_ptr<Client> sender_c, const std::string& data);
@@ -266,12 +260,12 @@ public:
G_UpdateDecks_Ep3_6xB4x07 prepare_6xB4x07_decks_update() const;
G_SetPlayerNames_Ep3_6xB4x1C prepare_6xB4x1C_names_update() const;
static std::string prepare_6xB6x41_map_definition(std::shared_ptr<const MapIndex::Map> map, Language language, bool is_nte);
static std::string prepare_6xB6x41_map_definition(
std::shared_ptr<const MapIndex::Map> map, Language language, bool is_nte);
void send_6xB6x41_to_all_clients() const;
G_SetTrapTileLocations_Ep3_6xB4x50 prepare_6xB4x50_trap_tile_locations() const;
std::vector<std::shared_ptr<Card>> const_cast_set_cards_v(
const std::vector<std::shared_ptr<const Card>>& cards);
std::vector<std::shared_ptr<Card>> const_cast_set_cards_v(const std::vector<std::shared_ptr<const Card>>& cards);
private:
typedef void (Server::*handler_t)(std::shared_ptr<Client>, const std::string&);
@@ -326,9 +320,8 @@ public:
parray<uint8_t, 4> player_ready_to_end_phase;
uint32_t unknown_a10;
uint32_t overall_time_expired;
// Note: In the original implementation, this is a uint32_t and is measured in
// seconds. In our environment, the simplest implementation uses now(), which
// returns microseconds, so we use a uint64_t instead.
// Note: In the original implementation, this is a uint32_t and is measured in seconds. In our environment, the
// simplest implementation uses now(), which returns microseconds, so we use a uint64_t instead.
uint64_t battle_start_usecs;
uint32_t should_copy_prev_states_to_current_states;
std::shared_ptr<CardSpecial> card_special;
+38 -73
View File
@@ -67,10 +67,7 @@ string Tournament::Team::str() const {
return ret + "]";
}
void Tournament::Team::register_player(
shared_ptr<Client> c,
const string& team_name,
const string& password) {
void Tournament::Team::register_player(shared_ptr<Client> c, const string& team_name, const string& password) {
if (this->players.size() >= this->max_players) {
throw runtime_error("team is full");
}
@@ -104,8 +101,7 @@ void Tournament::Team::register_player(
bool Tournament::Team::unregister_player(uint32_t account_id) {
size_t index;
for (index = 0; index < this->players.size(); index++) {
if (this->players[index].is_human() &&
(this->players[index].account_id == account_id)) {
if (this->players[index].is_human() && (this->players[index].account_id == account_id)) {
break;
}
}
@@ -123,12 +119,10 @@ bool Tournament::Team::unregister_player(uint32_t account_id) {
return false;
}
// If the tournament has already started, make the team forfeit their game.
// If any player withdraws from a team after the registration phase, the
// entire team essentially forfeits their entry.
// If the tournament has already started, make the team forfeit their game. If any player withdraws from a team
// after the registration phase, the entire team essentially forfeits their entry.
if (tournament->get_state() != Tournament::State::REGISTRATION) {
// Look through the pending matches to see if this team is involved in any
// of them
// Look through the pending matches to see if this team is involved in any of them
for (auto match : tournament->pending_matches) {
if (!match->preceding_a || !match->preceding_b) {
throw logic_error("zero-round match is pending after tournament registration phase");
@@ -142,9 +136,8 @@ bool Tournament::Team::unregister_player(uint32_t account_id) {
}
}
// If the tournament has not started yet, just remove the player from the
// team
} else {
// If the tournament has not started yet, just remove the player from the team
if (!tournament->all_player_account_ids.erase(account_id)) {
throw logic_error("player removed from team but not from tournament");
}
@@ -183,9 +176,7 @@ size_t Tournament::Team::num_com_players() const {
}
Tournament::Match::Match(
shared_ptr<Tournament> tournament,
shared_ptr<Match> preceding_a,
shared_ptr<Match> preceding_b)
shared_ptr<Tournament> tournament, shared_ptr<Match> preceding_a, shared_ptr<Match> preceding_b)
: tournament(tournament),
preceding_a(preceding_a),
preceding_b(preceding_b),
@@ -197,9 +188,7 @@ Tournament::Match::Match(
this->round_num = this->preceding_a->round_num + 1;
}
Tournament::Match::Match(
shared_ptr<Tournament> tournament,
shared_ptr<Team> winner_team)
Tournament::Match::Match(shared_ptr<Tournament> tournament, shared_ptr<Team> winner_team)
: tournament(tournament),
preceding_a(nullptr),
preceding_b(nullptr),
@@ -228,9 +217,8 @@ bool Tournament::Match::resolve_if_skippable() {
this->set_winner_team(winner_a->players.empty() ? winner_b : winner_a);
return true;
}
// If neither preceding winner team has any humans on it, skip this match
// entirely and just make one team advance arbitrarily (note that this also
// handles the case where both preceding winner teams are empty)
// If neither preceding winner team has any humans on it, skip this match entirely and just make one team advance
// arbitrarily (note that this also handles the case where both preceding winner teams are empty)
if (!winner_a->has_any_human_players() && !winner_b->has_any_human_players()) {
this->set_winner_team((phosg::random_object<uint8_t>() & 1) ? winner_b : winner_a);
return true;
@@ -247,8 +235,8 @@ void Tournament::Match::on_winner_team_set() {
tournament->pending_matches.erase(this->shared_from_this());
// Resolve the following match if possible (this skips CPU-only matches). If
// the following match can't be resolved, mark it pending.
// Resolve the following match if possible (this skips CPU-only matches). If the following match can't be resolved,
// mark it pending.
auto following = this->following.lock();
if (following && !following->resolve_if_skippable()) {
tournament->pending_matches.emplace(following);
@@ -259,8 +247,8 @@ void Tournament::Match::on_winner_team_set() {
tournament->current_state = Tournament::State::COMPLETE;
}
// Unlink the losing team's players (if any) - this allows them to enter
// another tournament before this tournament has ended
// Unlink the losing team's players (if any) - this allows them to enter another tournament before this tournament
// has ended
if (this->preceding_a && this->preceding_b) {
auto losing_team = (this->winner_team == this->preceding_a->winner_team)
? this->preceding_b->winner_team
@@ -278,8 +266,7 @@ void Tournament::Match::set_winner_team_without_triggers(shared_ptr<Team> team)
if (!this->preceding_a || !this->preceding_b) {
throw logic_error("set_winner_team called on zero-round match");
}
if ((team != this->preceding_a->winner_team) &&
(team != this->preceding_b->winner_team)) {
if ((team != this->preceding_a->winner_team) && (team != this->preceding_b->winner_team)) {
throw logic_error("winner team did not participate in match");
}
@@ -298,8 +285,7 @@ void Tournament::Match::set_winner_team(shared_ptr<Team> team) {
this->on_winner_team_set();
}
shared_ptr<Tournament::Team> Tournament::Match::opponent_team_for_team(
shared_ptr<Team> team) const {
shared_ptr<Tournament::Team> Tournament::Match::opponent_team_for_team(shared_ptr<Team> team) const {
if (!this->preceding_a || !this->preceding_b) {
throw logic_error("zero-round matches do not have opponents");
}
@@ -342,9 +328,7 @@ Tournament::Tournament(
}
Tournament::Tournament(
shared_ptr<const MapIndex> map_index,
shared_ptr<const COMDeckIndex> com_deck_index,
const phosg::JSON& json)
shared_ptr<const MapIndex> map_index, shared_ptr<const COMDeckIndex> com_deck_index, const phosg::JSON& json)
: log(std::format("[Tournament:{}] ", json.get_string("name"))),
map_index(map_index),
com_deck_index(com_deck_index),
@@ -394,8 +378,7 @@ void Tournament::init() {
} else {
// Create empty teams
while (this->teams.size() < this->num_teams) {
auto t = make_shared<Team>(
this->shared_from_this(), this->teams.size(), (this->flags & Flag::IS_2V2) ? 2 : 1);
auto t = make_shared<Team>(this->shared_from_this(), this->teams.size(), (this->flags & Flag::IS_2V2) ? 2 : 1);
this->teams.emplace_back(t);
}
is_registration_complete = false;
@@ -444,9 +427,7 @@ void Tournament::init() {
// If both preceding matches of the following match are resolved, put
// the following match on the queue since it may be resolvable as well
auto following = match->following.lock();
if (following &&
following->preceding_a->winner_team &&
following->preceding_b->winner_team) {
if (following && following->preceding_a->winner_team && following->preceding_b->winner_team) {
match_queue.emplace(following);
}
}
@@ -477,8 +458,7 @@ void Tournament::create_bracket_matches() {
throw logic_error("tournaments team count is not a power of 2");
}
// Create the zero-round matches, and make them all pending if registration
// is still open
// Create the zero-round matches, and make them all pending if registration is still open
this->zero_round_matches.clear();
for (const auto& team : this->teams) {
auto m = make_shared<Match>(this->shared_from_this(), team);
@@ -493,10 +473,7 @@ void Tournament::create_bracket_matches() {
while (current_round_matches.size() > 1) {
vector<shared_ptr<Match>> next_round_matches;
for (size_t z = 0; z < current_round_matches.size(); z += 2) {
auto m = make_shared<Match>(
this->shared_from_this(),
current_round_matches[z],
current_round_matches[z + 1]);
auto m = make_shared<Match>(this->shared_from_this(), current_round_matches[z], current_round_matches[z + 1]);
current_round_matches[z]->following = m;
current_round_matches[z + 1]->following = m;
next_round_matches.emplace_back(std::move(m));
@@ -552,8 +529,7 @@ shared_ptr<Tournament::Team> Tournament::get_winner_team() const {
return this->final_match->winner_team;
}
shared_ptr<Tournament::Match> Tournament::next_match_for_team(
shared_ptr<Team> team) const {
shared_ptr<Tournament::Match> Tournament::next_match_for_team(shared_ptr<Team> team) const {
if (this->current_state == Tournament::State::REGISTRATION) {
return nullptr;
}
@@ -561,8 +537,7 @@ shared_ptr<Tournament::Match> Tournament::next_match_for_team(
if (!match->preceding_a || !match->preceding_b) {
throw logic_error("zero-round match is pending after tournament registration phase");
}
if ((team == match->preceding_a->winner_team) ||
(team == match->preceding_b->winner_team)) {
if ((team == match->preceding_a->winner_team) || (team == match->preceding_b->winner_team)) {
return match;
}
}
@@ -573,8 +548,7 @@ shared_ptr<Tournament::Match> Tournament::get_final_match() const {
return this->final_match;
}
shared_ptr<Tournament::Team> Tournament::team_for_account_id(
uint32_t account_id) const {
shared_ptr<Tournament::Team> Tournament::team_for_account_id(uint32_t account_id) const {
if (!this->all_player_account_ids.count(account_id)) {
return nullptr;
}
@@ -601,9 +575,8 @@ void Tournament::start() {
bool has_com_teams = (this->flags & Flag::HAS_COM_TEAMS);
// If there aren't enough entrants (1 if has_com_teams is false, else 2),
// don't allow the tournament to start (because it would enter the COMPLETE
// state immediately)
// If there aren't enough entrants (1 if has_com_teams is false, else 2), don't allow the tournament to start
// (because it would enter the COMPLETE state immediately)
size_t num_human_teams = 0;
for (size_t z = 0; z < this->teams.size(); z++) {
if (this->teams[z]->has_any_human_players()) {
@@ -615,9 +588,8 @@ void Tournament::start() {
}
if ((this->flags & Flag::SHUFFLE_ENTRIES) && (this->flags & Flag::RESIZE_ON_START)) {
// If both of these flags are set, pack the human teams into the lowest part
// of the teams list so we can resize the tournament to the smallest
// possible size. This is OK since we're going to shuffle them later anyway
// If both of these flags are set, pack the human teams into the lowest part of the teams list so we can resize the
// tournament to the smallest possible size. This is OK since we're going to shuffle them later anyway
size_t r_offset = 0, w_offset = 0;
for (; r_offset < this->teams.size(); r_offset++) {
if (this->teams[r_offset]->has_any_human_players()) {
@@ -630,8 +602,8 @@ void Tournament::start() {
}
if (this->flags & Flag::RESIZE_ON_START) {
// Resize the tournament by repeatedly deleting the second half of it, until
// the second half contains human players or the tournament size is 4
// Resize the tournament by repeatedly deleting the second half of it, until the second half contains human players
// or the tournament size is 4
while (this->teams.size() > 4) {
size_t z;
for (z = this->teams.size() >> 1; z < this->teams.size(); z++) {
@@ -661,8 +633,7 @@ void Tournament::start() {
this->current_state = State::IN_PROGRESS;
this->create_bracket_matches();
// Assign names to COM teams, and assign COM decks to all empty slots unless
// has_com_teams is false
// Assign names to COM teams, and assign COM decks to all empty slots unless has_com_teams is false
for (size_t z = 0; z < this->zero_round_matches.size(); z++) {
auto m = this->zero_round_matches[z];
auto t = m->winner_team;
@@ -677,11 +648,9 @@ void Tournament::start() {
if (this->com_deck_index->num_decks() < t->max_players - t->players.size()) {
throw runtime_error("not enough COM decks to complete team");
}
// If we allow all-COM teams, or this is a 2v2 tournament and the team has
// only one human on it, add a COM
// If we allow all-COM teams, or this is a 2v2 tournament and the team has only one human on it, add a COM
if (has_com_teams || !t->players.empty()) {
// TODO: Don't allow duplicate COM decks, nor duplicate COM SCs on the
// same team
// TODO: Don't allow duplicate COM decks, nor duplicate COM SCs on the same team
while (t->players.size() < t->max_players) {
t->players.emplace_back(this->com_deck_index->random_deck());
}
@@ -698,9 +667,8 @@ void Tournament::send_all_state_updates() const {
for (const auto& team : this->teams) {
for (const auto& player : team->players) {
auto c = player.client.lock();
// Note: The last check here is to make sure the client is still linked
// with this instance of the tournament - an intervening shell command
// `reload ep3` could have changed the client's linkage
// Note: The last check here is to make sure the client is still linked with this instance of the tournament - an
// intervening shell command `reload ep3` could have changed the client's linkage
if (c && (c->version() == Version::GC_EP3) && (c->ep3_tournament_team.lock() == team)) {
send_ep3_confirm_tournament_entry(c, this->shared_from_this());
}
@@ -828,8 +796,7 @@ TournamentIndex::TournamentIndex(
auto tourn = make_shared<Tournament>(this->map_index, this->com_deck_index, *it.second);
tourn->init();
if (!this->name_to_tournament.emplace(tourn->get_name(), tourn).second) {
// This is logic_error instead of runtime_error because phosg::JSON dicts are
// supposed to already have unique keys
// This is logic_error instead of runtime_error because phosg::JSON dicts already have unique keys
throw logic_error("multiple tournaments have the same name: " + tourn->get_name());
}
tourn->set_menu_item_id(this->menu_item_id_to_tournament.size());
@@ -862,8 +829,7 @@ shared_ptr<Tournament> TournamentIndex::create_tournament(
throw runtime_error("there can be at most 32 tournaments at a time");
}
auto t = make_shared<Tournament>(
this->map_index, this->com_deck_index, name, map, rules, num_teams, flags);
auto t = make_shared<Tournament>(this->map_index, this->com_deck_index, name, map, rules, num_teams, flags);
t->init();
if (!this->name_to_tournament.emplace(t->get_name(), t).second) {
throw runtime_error("a tournament with the same name already exists");
@@ -942,8 +908,7 @@ void TournamentIndex::link_client(shared_ptr<Client> c) {
}
void TournamentIndex::link_all_clients(std::shared_ptr<ServerState> s) {
// This can be called before the game server exists, so do nothing in that
// case
// This can be called before the game server exists, so do nothing in that case
if (s->game_server) {
for (const auto& c : s->game_server->all_clients()) {
this->link_client(c);
+8 -18
View File
@@ -62,16 +62,10 @@ public:
size_t num_rounds_cleared;
bool is_active;
Team(
std::shared_ptr<Tournament> tournament,
size_t index,
size_t max_players);
Team(std::shared_ptr<Tournament> tournament, size_t index, size_t max_players);
std::string str() const;
void register_player(
std::shared_ptr<Client> c,
const std::string& team_name,
const std::string& password);
void register_player(std::shared_ptr<Client> c, const std::string& team_name, const std::string& password);
bool unregister_player(uint32_t account_id);
bool has_any_human_players() const;
@@ -91,9 +85,7 @@ public:
std::shared_ptr<Tournament> tournament,
std::shared_ptr<Match> preceding_a,
std::shared_ptr<Match> preceding_b);
Match(
std::shared_ptr<Tournament> tournament,
std::shared_ptr<Team> winner_team);
Match(std::shared_ptr<Tournament> tournament, std::shared_ptr<Team> winner_team);
std::string str() const;
bool resolve_if_skippable();
@@ -180,14 +172,12 @@ private:
std::set<uint32_t> all_player_account_ids;
std::unordered_set<std::shared_ptr<Match>> pending_matches;
// This vector contains all teams in the original starting order of the
// tournament (that is, all teams in the first round). The order within this
// vector determines which team will play against which other team in the
// first round: [0] will play against [1], [2] will play against [3], etc.
// This vector contains all teams in the original starting order of the tournament (that is, all teams in the first
// round). The order within this vector determines which team will play against which other team in the first round:
// [0] will play against [1], [2] will play against [3], etc.
std::vector<std::shared_ptr<Team>> teams;
// The tournament begins with a "zero round", in which each team automatically
// "wins" a match, putting them into the first round. This is just to make the
// data model easier to manage, so we don't have to have a type of match with
// The tournament begins with a "zero round", in which each team automatically "wins" a match, putting them into the
// first round. This is just to make the data model easier to manage, so we don't have to have a type of match with
// no preceding round.
std::vector<std::shared_ptr<Match>> zero_round_matches;
std::shared_ptr<Match> final_match;
+2 -4
View File
@@ -44,16 +44,14 @@ FileContentsCache::GetResult FileContentsCache::get_or_load(const char* name) {
return this->get_or_load(string(name));
}
shared_ptr<const FileContentsCache::File> FileContentsCache::get_or_throw(
const std::string& name) {
shared_ptr<const FileContentsCache::File> FileContentsCache::get_or_throw(const std::string& name) {
auto throw_fn = +[](const std::string&) -> string {
throw out_of_range("file missing from cache");
};
return this->get(name, throw_fn).file;
}
shared_ptr<const FileContentsCache::File> FileContentsCache::get_or_throw(
const char* name) {
shared_ptr<const FileContentsCache::File> FileContentsCache::get_or_throw(const char* name) {
return this->get_or_throw(string(name));
}
+3 -3
View File
@@ -114,9 +114,9 @@ public:
ThreadSafeFileCache& operator=(ThreadSafeFileCache&&) = delete;
~ThreadSafeFileCache() = default;
// Warning: generate() is called while the lock is held for writing, so it
// will block other threads.
std::shared_ptr<const std::string> get(const std::string& name, std::function<std::shared_ptr<const std::string>(const std::string&)> generate);
// generate() is called while the lock is held for writing, so it will block other threads.
std::shared_ptr<const std::string> get(
const std::string& name, std::function<std::shared_ptr<const std::string>(const std::string&)> generate);
private:
std::shared_mutex lock;
+11 -3
View File
@@ -105,7 +105,7 @@ string CompiledFunctionCode::generate_client_command(
}
bool CompiledFunctionCode::is_big_endian() const {
return this->arch == Architecture::POWERPC;
return (this->arch == Architecture::POWERPC);
}
static unordered_map<uint32_t, std::string> preprocess_function_code(const std::string& text) {
@@ -152,6 +152,11 @@ static unordered_map<uint32_t, std::string> preprocess_function_code(const std::
size_t line_num = 1;
vector<uint32_t> current_only_versions;
unordered_set<uint32_t> current_only_versions_set;
auto add_blank_line = [&]() -> void {
for (size_t vers_index = 0; vers_index < specific_versions.size(); vers_index++) {
version_lines[vers_index].emplace_back("");
}
};
for (auto& line : lines) {
phosg::strip_whitespace(line);
if (line.starts_with(".only_versions ")) {
@@ -160,10 +165,12 @@ static unordered_map<uint32_t, std::string> preprocess_function_code(const std::
for (uint32_t specific_version : current_only_versions) {
current_only_versions_set.emplace(specific_version);
}
add_blank_line();
} else if (line == ".all_versions") {
current_only_versions.clear();
current_only_versions_set.clear();
add_blank_line();
} else {
size_t vers_offset = line.find("<VERS ");
@@ -306,6 +313,8 @@ static vector<shared_ptr<CompiledFunctionCode>> compile_function_code(
compiled->description = it.second;
} else if (it.first == "client_flag") {
compiled->client_flag = stoull(it.second, nullptr, 0);
} else if (it.first == "show_return_value") {
compiled->show_return_value = true;
} else {
throw runtime_error("unknown metadata key: " + it.first);
}
@@ -483,8 +492,7 @@ bool FunctionCodeIndex::patch_menu_empty(uint32_t specific_version) const {
std::shared_ptr<const CompiledFunctionCode> FunctionCodeIndex::get_patch(
const std::string& name, uint32_t specific_version) const {
return this->name_and_specific_version_to_patch_function.at(
std::format("{}-{:08X}", name, specific_version));
return this->name_and_specific_version_to_patch_function.at(std::format("{}-{:08X}", name, specific_version));
}
DOLFileIndex::DOLFileIndex(const string& directory) {
+1
View File
@@ -33,6 +33,7 @@ struct CompiledFunctionCode {
uint64_t client_flag = 0; // From .meta client_flag directive
uint32_t menu_item_id = 0;
bool hide_from_patches_menu = false;
bool show_return_value = false;
uint32_t specific_version = 0; // 0 = not a client-selectable patch
bool is_big_endian() const;
+3 -8
View File
@@ -15,12 +15,9 @@ struct GSLHeaderEntryT {
U32T<BE> offset; // In pages, so actual offset is this * 0x800
U32T<BE> size;
uint64_t unused;
} __attribute__((packed));
} __packed_ws_be__(GSLHeaderEntryT, 0x30);
using GSLHeaderEntry = GSLHeaderEntryT<false>;
using GSLHeaderEntryBE = GSLHeaderEntryT<true>;
check_struct_size(GSLHeaderEntry, 0x30);
check_struct_size(GSLHeaderEntryBE, 0x30);
template <bool BE>
void GSLArchive::load_t() {
@@ -39,8 +36,7 @@ void GSLArchive::load_t() {
}
}
GSLArchive::GSLArchive(shared_ptr<const string> data, bool big_endian)
: data(data) {
GSLArchive::GSLArchive(shared_ptr<const string> data, bool big_endian) : data(data) {
if (big_endian) {
this->load_t<true>();
} else {
@@ -87,8 +83,7 @@ template <bool BE>
string GSLArchive::generate_t(const unordered_map<string, string>& files) {
phosg::StringWriter w;
// Make sure there's enough space for a blank header entry before any file's
// data pages begin
// Make sure there's enough space for a blank header entry before any file's data pages begin
uint32_t data_start_offset = ((sizeof(GSLHeaderEntryT<BE>) * (files.size() + 1)) + 0x7FF) & (~0x7FF);
uint32_t data_offset = data_start_offset;
for (const auto& file : files) {
+10 -10
View File
@@ -21,8 +21,7 @@
using namespace std;
using namespace std::placeholders;
GameServer::GameServer(shared_ptr<ServerState> state)
: Server(state->io_context, "[GameServer] "), state(state) {}
GameServer::GameServer(shared_ptr<ServerState> state) : Server(state->io_context, "[GameServer] "), state(state) {}
void GameServer::listen(
const std::string& name,
@@ -45,6 +44,7 @@ void GameServer::listen(
shared_ptr<Client> GameServer::connect_channel(shared_ptr<Channel> ch, uint16_t port, ServerBehavior initial_state) {
auto c = make_shared<Client>(this->shared_from_this(), ch, initial_state);
c->listener_port = port;
this->log.info_f("Client connected: C-{:X} via TSI-{}-{}-{}",
c->id, port, phosg::name_for_enum(ch->version), phosg::name_for_enum(initial_state));
@@ -75,8 +75,8 @@ vector<shared_ptr<Client>> GameServer::get_clients_by_identifier(const string& i
} catch (const invalid_argument&) {
}
// TODO: It's kind of not great that we do a linear search here, but this is
// only used in the shell, so it should be pretty rare.
// TODO: It's kind of not great that we do a linear search here, but this is only used in the shell, so it should be
// pretty rare.
vector<shared_ptr<Client>> results;
for (const auto& c : this->clients) {
if (c->login && c->login->account->account_id == account_id_hex) {
@@ -115,7 +115,8 @@ vector<shared_ptr<Client>> GameServer::get_clients_by_identifier(const string& i
return results;
}
shared_ptr<Client> GameServer::create_client(shared_ptr<GameServerSocket> listen_sock, asio::ip::tcp::socket&& client_sock) {
shared_ptr<Client> GameServer::create_client(
shared_ptr<GameServerSocket> listen_sock, asio::ip::tcp::socket&& client_sock) {
uint32_t addr = ipv4_addr_for_asio_addr(client_sock.remote_endpoint().address());
if (this->state->banned_ipv4_ranges->check(addr)) {
if (client_sock.is_open()) {
@@ -133,6 +134,7 @@ shared_ptr<Client> GameServer::create_client(shared_ptr<GameServerSocket> listen
phosg::TerminalFormat::FG_YELLOW,
phosg::TerminalFormat::FG_GREEN);
auto c = make_shared<Client>(this->shared_from_this(), channel, listen_sock->behavior);
c->listener_port = listen_sock->endpoint.port();
this->log.info_f("Client connected: C-{:X} via {}", c->id, listen_sock->name);
return c;
@@ -166,8 +168,7 @@ asio::awaitable<void> GameServer::handle_client(shared_ptr<Client> c) {
asio::awaitable<void> GameServer::destroy_client(std::shared_ptr<Client> c) {
this->log.info_f("Running cleanup tasks for {}", c->channel->name);
// The client may not actually be disconnected yet if an uncaught exception
// occurred in a handler task
// The client may not actually be disconnected yet if an uncaught exception occurred in a handler task
c->channel->disconnect();
// Close the proxy session, if any
@@ -184,9 +185,8 @@ asio::awaitable<void> GameServer::destroy_client(std::shared_ptr<Client> c) {
this->log.warning_f("Error during client disconnect cleanup: {}", e.what());
}
// Note: It's important to move the disconnect hooks out of the client here
// because the hooks could modify c->disconnect_hooks while it's being
// iterated here, which would invalidate these iterators.
// Note: It's important to move the disconnect hooks out of the client here because the hooks could modify
// c->disconnect_hooks while it's being iterated here, which would invalidate these iterators.
unordered_map<string, function<void()>> hooks = std::move(c->disconnect_hooks);
for (auto h_it : hooks) {
try {
+2 -1
View File
@@ -25,7 +25,8 @@ public:
explicit GameServer(std::shared_ptr<ServerState> state);
virtual ~GameServer() = default;
void listen(const std::string& name, const std::string& addr, uint16_t port, Version version, ServerBehavior initial_state);
void listen(
const std::string& name, const std::string& addr, uint16_t port, Version version, ServerBehavior initial_state);
std::shared_ptr<Client> connect_channel(std::shared_ptr<Channel> ch, uint16_t port, ServerBehavior initial_state);
+205 -7
View File
@@ -5,6 +5,7 @@
#include <phosg/Network.hh>
#include <string>
#include <map>
#include <vector>
#include "GameServer.hh"
@@ -54,6 +55,156 @@ HTTPServer::HTTPServer(shared_ptr<ServerState> state)
co_return nullptr;
});
this->router.add(HTTPRequest::Method::GET, "/metrics", [this](ArgsT&&) -> RetT {
auto version_label = +[](Version v) -> const char* {
if (is_patch(v)) {
return "patch";
} else if (is_v4(v)) {
return "v4";
} else if (is_v3(v)) {
return "v3";
} else if (is_v1_or_v2(v)) {
return "v2";
} else {
return "other";
}
};
auto escape_label = +[](const string& in) -> string {
string out;
for (char ch : in) {
if (ch == '\\') {
out += "\\\\";
} else if (ch == '"') {
out += "\\\"";
} else if (ch == '\n') {
out += "\\n";
} else {
out += ch;
}
}
return out;
};
auto add_metric = [](string& out, const string& name, uint64_t value) -> void {
out += name;
out += " ";
out += std::to_string(value);
out += "\n";
};
auto add_metric_1label = [](string& out, const string& name, const string& label_name, const string& label_value, uint64_t value) -> void {
out += name;
out += "{";
out += label_name;
out += "=\"";
out += label_value;
out += "\"} ";
out += std::to_string(value);
out += "\n";
};
map<string, uint64_t> connected_by_version;
map<string, uint64_t> lobby_players_by_version;
map<string, uint64_t> game_players_by_version;
uint64_t connected_total = 0;
uint64_t lobbies_total = 0;
uint64_t games_total = 0;
uint64_t players_in_lobbies_total = 0;
uint64_t players_in_games_total = 0;
for (const auto& c : this->state->game_server->all_clients()) {
connected_total++;
connected_by_version[version_label(c->version())]++;
}
for (const auto& [_, l] : this->state->id_to_lobby) {
if (l->is_game()) {
games_total++;
} else {
lobbies_total++;
}
for (size_t z = 0; z < l->max_clients; z++) {
auto lc = l->clients[z];
if (!lc) {
continue;
}
const char* v = version_label(lc->version());
if (l->is_game()) {
players_in_games_total++;
game_players_by_version[v]++;
} else {
players_in_lobbies_total++;
lobby_players_by_version[v]++;
}
}
}
string server_name = escape_label(this->state->name);
string revision = escape_label(GIT_REVISION_HASH);
string out;
out += "# HELP pso_newserv_up Whether this newserv HTTP metrics endpoint is reachable\n";
out += "# TYPE pso_newserv_up gauge\n";
add_metric(out, "pso_newserv_up", 1);
out += "# HELP pso_newserv_build_info Build and server identity info\n";
out += "# TYPE pso_newserv_build_info gauge\n";
out += "pso_newserv_build_info{server_name=\"";
out += server_name;
out += "\",revision=\"";
out += revision;
out += "\",build_time=\"";
out += std::to_string(BUILD_TIMESTAMP);
out += "\"} 1\n";
out += "# HELP pso_newserv_clients_connected_total Connected clients, including patch/proxy/menu states\n";
out += "# TYPE pso_newserv_clients_connected_total gauge\n";
add_metric(out, "pso_newserv_clients_connected_total", connected_total);
out += "# HELP pso_newserv_clients_connected Connected clients by coarse version family\n";
out += "# TYPE pso_newserv_clients_connected gauge\n";
for (const auto& [version, count] : connected_by_version) {
add_metric_1label(out, "pso_newserv_clients_connected", "version", version, count);
}
out += "# HELP pso_newserv_lobbies_total Non-game lobby count\n";
out += "# TYPE pso_newserv_lobbies_total gauge\n";
add_metric(out, "pso_newserv_lobbies_total", lobbies_total);
out += "# HELP pso_newserv_games_total Game room count\n";
out += "# TYPE pso_newserv_games_total gauge\n";
add_metric(out, "pso_newserv_games_total", games_total);
out += "# HELP pso_newserv_players_in_lobbies_total Players currently in non-game lobbies\n";
out += "# TYPE pso_newserv_players_in_lobbies_total gauge\n";
add_metric(out, "pso_newserv_players_in_lobbies_total", players_in_lobbies_total);
out += "# HELP pso_newserv_players_in_games_total Players currently in game rooms\n";
out += "# TYPE pso_newserv_players_in_games_total gauge\n";
add_metric(out, "pso_newserv_players_in_games_total", players_in_games_total);
out += "# HELP pso_newserv_players_in_lobbies Players currently in non-game lobbies by coarse version family\n";
out += "# TYPE pso_newserv_players_in_lobbies gauge\n";
for (const auto& [version, count] : lobby_players_by_version) {
add_metric_1label(out, "pso_newserv_players_in_lobbies", "version", version, count);
}
out += "# HELP pso_newserv_players_in_games Players currently in game rooms by coarse version family\n";
out += "# TYPE pso_newserv_players_in_games gauge\n";
for (const auto& [version, count] : game_players_by_version) {
add_metric_1label(out, "pso_newserv_players_in_games", "version", version, count);
}
co_return RouterRetT(RawResponse{
.content_type = "text/plain; version=0.0.4; charset=utf-8",
.data = std::move(out),
});
});
this->router.add(HTTPRequest::Method::GET, "/y/clients", [this](ArgsT&&) -> RetT {
auto res = make_shared<phosg::JSON>(phosg::JSON::list());
for (const auto& c : this->state->game_server->all_clients()) {
@@ -88,6 +239,7 @@ HTTPServer::HTTPServer(shared_ptr<ServerState> state)
{"SwitchAssistEnabled", (c->check_flag(Client::Flag::SWITCH_ASSIST_ENABLED) ? true : false)},
{"InfiniteHPEnabled", (c->check_flag(Client::Flag::INFINITE_HP_ENABLED) ? true : false)},
{"InfiniteTPEnabled", (c->check_flag(Client::Flag::INFINITE_TP_ENABLED) ? true : false)},
{"FastKillsEnabled", (c->check_flag(Client::Flag::FAST_KILLS_ENABLED) ? true : false)},
{"DropNotificationMode", drop_notifications_mode},
{"DebugEnabled", (c->check_flag(Client::Flag::DEBUG_ENABLED) ? true : false)},
{"ProxySaveFilesEnabled", (c->check_flag(Client::Flag::PROXY_SAVE_FILES) ? true : false)},
@@ -160,7 +312,6 @@ HTTPServer::HTTPServer(shared_ptr<ServerState> state)
}
client_json.emplace("TechniqueLevels", std::move(tech_levels_json));
}
client_json.emplace("Height", p->disp.stats.height.load());
client_json.emplace("Level", p->disp.stats.level.load() + 1);
client_json.emplace("NameColor", p->disp.visual.name_color.load());
client_json.emplace("ExtraModel", (p->disp.visual.validation_flags & 2) ? p->disp.visual.extra_model : phosg::JSON(nullptr));
@@ -217,7 +368,9 @@ HTTPServer::HTTPServer(shared_ptr<ServerState> state)
}
string grave_enemy_types;
if (p->challenge_records.grave_defeated_by_enemy_rt_index) {
for (EnemyType type : enemy_types_for_rare_table_index(p->challenge_records.grave_is_ep2 ? Episode::EP2 : Episode::EP1, p->challenge_records.grave_defeated_by_enemy_rt_index)) {
for (EnemyType type : enemy_types_for_rare_table_index(
p->challenge_records.grave_is_ep2 ? Episode::EP2 : Episode::EP1,
p->challenge_records.grave_defeated_by_enemy_rt_index)) {
if (!grave_enemy_types.empty()) {
grave_enemy_types += "/";
}
@@ -470,9 +623,10 @@ HTTPServer::HTTPServer(shared_ptr<ServerState> state)
{"BattleStartTimeUsecs", ep3s->battle_start_usecs},
{"TeamEXP", phosg::JSON::list({ep3s->team_exp[0], ep3s->team_exp[1]})},
{"TeamDiceBonus", phosg::JSON::list({ep3s->team_dice_bonus[0], ep3s->team_dice_bonus[1]})},
// TODO: Include information from these too?
// std::shared_ptr<StateFlags> state_flags;
// std::array<std::shared_ptr<PlayerState>, 4> player_states;
});
// std::shared_ptr<StateFlags> state_flags;
// std::array<std::shared_ptr<PlayerState>, 4> player_states;
lobby_json.emplace("Episode3BattleState", std::move(battle_state_json));
} else {
lobby_json.emplace("Episode3BattleState", nullptr);
@@ -659,7 +813,51 @@ HTTPServer::HTTPServer(shared_ptr<ServerState> state)
}
});
// TODO: Add /y/data/ep3/maps, /y/data/ep3/map/:map_number and /y/data/ep3/map/:map_number/raw
this->router.add(HTTPRequest::Method::GET, "/y/data/ep3/maps", [this](ArgsT&&) -> RetT {
co_return co_await call_on_thread_pool(*this->state->thread_pool, [&]() -> shared_ptr<phosg::JSON> {
auto ret = make_shared<phosg::JSON>(phosg::JSON::dict());
for (const auto& [map_number, map] : this->state->ep3_map_index->all_maps()) {
auto languages_json = phosg::JSON::list();
for (const auto& vm : map->all_versions()) {
if (vm) {
languages_json.emplace_back(name_for_language(vm->language));
}
}
auto map_json = phosg::JSON::dict({
{"Name", map->version(Language::ENGLISH)->map->name.decode(Language::ENGLISH)},
{"VisibilityFlags", map->visibility_flags},
{"Languages", std::move(languages_json)},
});
ret->emplace(std::format("{:08X}", map_number), std::move(map_json));
}
return ret;
});
});
this->router.add(HTTPRequest::Method::GET, "/y/data/ep3/map/:map_number/:language", [this](ArgsT&& args) -> RetT {
co_return co_await call_on_thread_pool(*this->state->thread_pool, [&]() -> shared_ptr<phosg::JSON> {
try {
auto map = this->state->ep3_map_index->map_for_id(args.get_param<uint32_t>("map_number", true));
auto vm = map->version(language_for_name(args.params.at("language")));
return make_shared<phosg::JSON>(vm->map->json(vm->language));
} catch (const std::out_of_range&) {
throw HTTPError(404, "Map version does not exist");
}
});
});
this->router.add(HTTPRequest::Method::GET, "/y/data/ep3/map/:map_number/:language/raw", [this](ArgsT&& args) -> RetT {
co_return co_await call_on_thread_pool(*this->state->thread_pool, [&]() -> RawResponse {
try {
auto map = this->state->ep3_map_index->map_for_id(args.get_param<uint32_t>("map_number"));
auto vm = map->version(language_for_name(args.params.at("language")));
string data(reinterpret_cast<const char*>(vm->map.get()), sizeof(Episode3::MapDefinition));
return RawResponse{.content_type = "application/octet-stream", .data = std::move(data)};
} catch (const std::out_of_range&) {
throw HTTPError(404, "Map version does not exist");
}
});
});
this->router.add(HTTPRequest::Method::GET, "/y/data/common-tables", [this](ArgsT&&) -> RetT {
auto ret = make_shared<phosg::JSON>(phosg::JSON::list());
@@ -730,8 +928,8 @@ asio::awaitable<void> HTTPServer::send_rare_drop_notification(shared_ptr<const p
if (!this->rare_drop_subscribers.empty()) {
string data = message->serialize();
// Make a copy of the rare drop subscribers set, so we can guarantee that
// the client objects are all valid until this coroutine returns
// Make a copy of the rare drop subscribers set, so we can guarantee that the client objects are all valid until
// this coroutine returns
unordered_set<shared_ptr<HTTPClient>> subscribers = this->rare_drop_subscribers;
size_t expected_results = subscribers.size();
+2 -1
View File
@@ -32,6 +32,7 @@ protected:
void require_GET(const HTTPRequest& req);
phosg::JSON require_POST(const HTTPRequest& req);
virtual asio::awaitable<std::unique_ptr<HTTPResponse>> handle_request(std::shared_ptr<HTTPClient> c, HTTPRequest&& req);
virtual asio::awaitable<std::unique_ptr<HTTPResponse>> handle_request(
std::shared_ptr<HTTPClient> c, HTTPRequest&& req);
virtual asio::awaitable<void> destroy_client(std::shared_ptr<HTTPClient> c);
};
+1 -2
View File
@@ -7,8 +7,7 @@
using namespace std;
static inline uint16_t collapse_checksum(uint32_t sum) {
// It's impossible for this to be necessary more than twice: the first
// addition can carry out at most a single bit.
// It's impossible for this to be necessary more than twice: the first addition can carry out at most a single bit.
sum = (sum & 0xFFFF) + (sum >> 16);
return (sum & 0xFFFF) + (sum >> 16);
}
+54 -78
View File
@@ -78,9 +78,8 @@ static string escape_hdlc_frame(const string& data, uint32_t escape_control_char
return escape_hdlc_frame(data.data(), data.size(), escape_control_character_flags);
}
// Note: these functions exist because seq nums are allowed to wrap around the
// 32-bit integer space by design. We have to do the subtraction before the
// comparison to allow integer overflow to occur if needed.
// Note: these functions exist because seq nums are allowed to wrap around the 32-bit integer space by design. We have
// to do the subtraction before the comparison to allow integer overflow to occur if needed.
static inline bool seq_num_less(uint32_t a, uint32_t b) {
return (a - b) & 0x80000000;
@@ -200,9 +199,8 @@ void IPSSChannel::disconnect() {
}
void IPSSChannel::add_inbound_data(const void* data, size_t size) {
// If recv_buf is not null, there is a coroutine waiting to receive data, and
// inbound_data must be empty. Copy the data directly to the waiting
// coroutine's buffer, and put the rest in this->inbound_data if needed.
// If recv_buf is not null, there is a coroutine waiting to receive data, and inbound_data must be empty. Copy the
// data directly to the waiting coroutine's buffer, and put the rest in this->inbound_data if needed.
if (this->recv_buf) {
size_t direct_size = min<size_t>(this->recv_buf_size, size);
memcpy(this->recv_buf, data, direct_size);
@@ -212,8 +210,7 @@ void IPSSChannel::add_inbound_data(const void* data, size_t size) {
this->recv_buf = this->recv_buf_size ? (reinterpret_cast<uint8_t*>(this->recv_buf) + direct_size) : nullptr;
}
// If there is still data left after the above, add it to the pending inbound
// data buffer
// If there is still data left after the above, add it to the pending inbound data buffer
if (size > 0) {
this->inbound_data.emplace_back(reinterpret_cast<const char*>(data), size);
}
@@ -239,10 +236,9 @@ void IPSSChannel::send_raw(string&& data) {
conn->outbound_data_bytes += data.size();
conn->outbound_data.emplace_back(std::move(data));
// If we're already waiting for an ACK from the remote client, don't send
// another PSH right now - we will either send another PSH when we receive
// the ACK or will retry sending the PSH soon (which will then include the
// new data, if it's within the MTU from the last acked sequence number).
// If we're already waiting for an ACK from the remote client, don't send another PSH right now - we will either send
// another PSH when we receive the ACK or will retry sending the PSH soon (which will then include the new data, if
// it's within the MTU from the last acked sequence number).
if (!conn->awaiting_ack) {
sim->schedule_send_pending_push_frame(conn, 0);
}
@@ -270,8 +266,7 @@ asio::awaitable<void> IPSSChannel::recv_raw(void* data, size_t size) {
}
}
// If there's still more data to read, block until it's available
// (add_inbound_data is responsible for waking this coroutine)
// If there's still more data to read, block until it's available (add_inbound_data will wake this coroutine)
if (size > 0) {
this->recv_buf = data;
this->recv_buf_size = size;
@@ -304,9 +299,8 @@ void IPStackSimulator::listen(const std::string& name, const string& addr, int p
}
uint32_t IPStackSimulator::connect_address_for_remote_address(uint32_t remote_addr) {
// Use an address not on the same subnet as the client, so that PSO Plus and
// Episode III will think they're talking to a remote network and won't
// reject the connection.
// Use an address not on the same subnet as the client, so that PSO Plus and Episode III will think they're talking
// to a remote network and won't reject the connection.
return ((remote_addr & 0xFF000000) == 0x23000000) ? 0x24242424 : 0x23232323;
}
@@ -555,10 +549,9 @@ asio::awaitable<void> IPStackSimulator::on_client_lcp_frame(shared_ptr<IPSSClien
throw runtime_error("unknown LCP option");
}
}
// Technically, we should implement the LCP state machine, but I'm too
// lazy to do this right now. In our situation, it should suffice to
// simply always send a Configure-Request to the client with a magic
// number not equal to the one we received.
// Technically, we should implement the LCP state machine, but I'm too lazy to do this right now. In our
// situation, it should suffice to simply always send a Configure-Request to the client with a magic number not
// equal to the one we received.
phosg::StringWriter opts_w;
opts_w.put_u8(0x01); // Maximum receive unit
opts_w.put_u8(0x04);
@@ -700,8 +693,7 @@ asio::awaitable<void> IPStackSimulator::on_client_ipcp_frame(shared_ptr<IPSSClie
} else if ((remote_ip != 0x1E1E1E1E) ||
(remote_primary_dns != 0x23232323) ||
(remote_secondary_dns != 0x24242424)) {
// Send a Configure-Nak if the client's request doesn't exactly match
// what we want them to use.
// Send a Configure-Nak if the client's request doesn't exactly match what we want them to use.
phosg::StringWriter opts_w;
opts_w.put_u8(0x03); // IP address
opts_w.put_u8(0x06);
@@ -725,8 +717,7 @@ asio::awaitable<void> IPStackSimulator::on_client_ipcp_frame(shared_ptr<IPSSClie
} else { // Options OK
c->ipv4_addr = remote_ip;
// As with LCP, we technically should implement the state machine, but I
// continue to be lazy.
// As with LCP, we technically should implement the state machine, but I continue to be lazy.
phosg::StringWriter opts_w;
opts_w.put_u8(0x03); // IP address
opts_w.put_u8(0x06);
@@ -806,15 +797,15 @@ asio::awaitable<void> IPStackSimulator::on_client_arp_frame(shared_ptr<IPSSClien
});
// The incoming payload is:
// uint8_t src_mac[6]; // MAC address of client
// uint8_t src_ip[4]; // IP address of client
// uint8_t dest_mac[6]; // MAC address of host (all zeroes)
// uint8_t dest_ip[4]; // IP address of host
// uint8_t src_mac[6]; // MAC address of client
// uint8_t src_ip[4]; // IP address of client
// uint8_t dest_mac[6]; // MAC address of host (all zeroes)
// uint8_t dest_ip[4]; // IP address of host
// The outgoing payload is:
// uint8_t dest_mac[6]; // MAC address of host (from configuration)
// uint8_t dest_ip[4]; // IP address of host
// uint8_t src_mac[6]; // MAC address of client
// uint8_t src_ip[4]; // IP address of client
// uint8_t dest_mac[6]; // MAC address of host (from configuration)
// uint8_t dest_ip[4]; // IP address of host
// uint8_t src_mac[6]; // MAC address of client
// uint8_t src_ip[4]; // IP address of client
const char* payload_bytes = reinterpret_cast<const char*>(fi.payload);
w.write(this->host_mac_address_bytes.data(), 6);
w.write(payload_bytes + 16, 4);
@@ -826,9 +817,7 @@ asio::awaitable<void> IPStackSimulator::on_client_arp_frame(shared_ptr<IPSSClien
asio::awaitable<void> IPStackSimulator::on_client_udp_frame(shared_ptr<IPSSClient> c, const FrameInfo& fi) {
// We only implement DHCP and newserv's DNS server here.
// Every received UDP packet will elicit exactly one UDP response from
// newserv, so we prepare the response headers in advance
// Every received UDP packet will elicit exactly one UDP response from newserv, so we prepare the headers in advance
IPv4Header r_ipv4;
r_ipv4.version_ihl = 0x45;
r_ipv4.tos = 0;
@@ -888,8 +877,8 @@ asio::awaitable<void> IPStackSimulator::on_client_udp_frame(shared_ptr<IPSSClien
// Populate the client's addresses
c->mac_addr = dhcp.client_hardware_address.data();
c->ipv4_addr = 0x0A000105; // 10.0.1.5
// In this case, the client doesn't know its IPv4 address or ours yet,
// so we overwrite the existing fields with the appropriate addresses.
// In this case, the client doesn't know its IPv4 address or ours yet, so we overwrite the existing fields with
// the appropriate addresses.
r_ipv4.src_addr = 0x0A000101; // 10.0.1.1
r_ipv4.dest_addr = c->ipv4_addr;
@@ -1005,8 +994,8 @@ asio::awaitable<void> IPStackSimulator::on_client_tcp_frame(shared_ptr<IPSSClien
}
if (fi.tcp->flags & TCPHeader::Flag::SYN) {
// We never make connections back to the client, so we should never receive
// a SYN+ACK. Essentially, no other flags should be set in any received SYN.
// We never make connections back to the client, so we should never receive a SYN+ACK. Essentially, no other flags
// should be set in any received SYN.
if ((fi.tcp->flags & 0x0FFF) != TCPHeader::Flag::SYN) {
throw runtime_error("TCP SYN contains extra flags");
}
@@ -1081,8 +1070,7 @@ asio::awaitable<void> IPStackSimulator::on_client_tcp_frame(shared_ptr<IPSSClien
if (!conn->awaiting_first_ack) {
throw logic_error("SYN received on already-open connection after initial phase");
}
// TODO: We should check the syn/ack numbers here instead of just assuming
// they're correct
// TODO: We should check the syn/ack numbers here instead of just assuming they're correct
conn_str = this->str_for_tcp_connection(c, conn);
this->log.debug_f("Client resent SYN for TCP connection {}", conn_str);
}
@@ -1093,8 +1081,7 @@ asio::awaitable<void> IPStackSimulator::on_client_tcp_frame(shared_ptr<IPSSClien
conn_str, conn->acked_server_seq, conn->next_client_seq);
} else {
// This frame isn't a SYN, so a connection object should already exist;
// ignore the frame if there's no connection
// This frame isn't a SYN, so a connection object should already exist; ignore the frame if there's no connection
uint64_t key = this->tcp_conn_key_for_client_frame(fi);
auto conn_it = c->tcp_connections.find(key);
if (conn_it == c->tcp_connections.end()) {
@@ -1158,24 +1145,20 @@ asio::awaitable<void> IPStackSimulator::on_client_tcp_frame(shared_ptr<IPSSClien
conn->server_channel.reset();
}
// TODO: Are we supposed to send a response to an RST? Here we do, and the
// client probably just ignores it anyway
// TODO: Are we supposed to send a response to an RST? Here we do, and the client probably just ignores it anyway
co_await this->send_tcp_frame(c, conn, fi.tcp->flags & (TCPHeader::Flag::RST | TCPHeader::Flag::FIN));
// Delete the connection object. The unique_ptr destructor flushes the
// bufferevent, and thereby sends an EOF to the server's end.
// Delete the connection object. The unique_ptr destructor flushes the bufferevent, and thereby sends an EOF to
// the server's end.
c->tcp_connections.erase(key);
conn_valid = false;
} else if (fi.payload_size != 0) {
// Note: The PSH flag isn't required to be set on all packets that
// contain data. The PSH flag just means "tell the application that data
// is available", so some senders only set the PSH flag on the last frame
// of a large segment of data, since the application wouldn't be able to
// process the segment until all of it is available. newserv can handle
// incomplete commands, so we just ignore the PSH flag and forward any
// data to the server immediately (hence the lack of a flag check in the
// above condition).
// Note: The PSH flag isn't required to be set on all packets that contain data. The PSH flag just means "tell
// the application that data is available", so some senders only set the PSH flag on the last frame of a large
// segment of data, since the application wouldn't be able to process the segment until all of it is available.
// newserv can handle incomplete commands, so we just ignore the PSH flag and forward any data to the server
// immediately (hence the lack of a flag check in the above condition).
string conn_str = this->log.should_log(phosg::LogLevel::L_WARNING)
? this->str_for_tcp_connection(c, conn)
@@ -1186,8 +1169,8 @@ asio::awaitable<void> IPStackSimulator::on_client_tcp_frame(shared_ptr<IPSSClien
payload_skip_bytes = 0;
} else if (seq_num_less(fi.tcp->seq_num, conn->next_client_seq)) {
// If the frame overlaps an existing boundary, we'll accept some of the
// data; otherwise we'll ignore it entirely (but still send an ACK)
// If the frame overlaps an existing boundary, we'll accept some of the data; otherwise we'll ignore it
// entirely (but still send an ACK)
uint32_t end_seq = fi.tcp->seq_num + fi.payload_size;
if (seq_num_less_or_equal(end_seq, conn->next_client_seq)) { // Fully "in the past"
payload_skip_bytes = fi.payload_size;
@@ -1196,9 +1179,8 @@ asio::awaitable<void> IPStackSimulator::on_client_tcp_frame(shared_ptr<IPSSClien
}
} else {
// Payload is in the future - we must have missed a data frame. We'll
// ignore it (but warn) and send an ACK later, and the client should
// retransmit the lost data
// Payload is in the future - we must have missed a data frame. We'll ignore it (but warn) and send an ACK
// later, and the client should retransmit the lost data
this->log.warning_f(
"Client sent out-of-order sequence number (expected {:08X}, received {:08X}, 0x{:X} data bytes)",
conn->next_client_seq, fi.tcp->seq_num, fi.payload_size);
@@ -1288,10 +1270,8 @@ asio::awaitable<void> IPStackSimulator::send_pending_push_frame(
size_t bytes_to_send = min<size_t>(conn->outbound_data_bytes, conn->next_push_max_frame_size);
if (c->protocol == VirtualNetworkProtocol::HDLC_TAPSERVER) {
// There is a bug in Dolphin's modem implementation (which I wrote, so it's
// my fault) that causes commands to be dropped when too much data is sent
// at once. To work around this, we only send up to 200 bytes in each push
// frame.
// There is a bug in Dolphin's modem implementation (which I wrote, so it's my fault) that causes commands to be
// dropped when too much data is sent. To work around this, we only send up to 200 bytes in each push frame.
bytes_to_send = min<size_t>(bytes_to_send, 200);
}
@@ -1300,23 +1280,20 @@ asio::awaitable<void> IPStackSimulator::send_pending_push_frame(
conn->linearize_outbound_data(bytes_to_send);
if (conn->outbound_data.empty() || conn->outbound_data.front().size() < bytes_to_send) {
// This should never happen because bytes_to_send should always be less
// than or equal to conn->outbound_data_bytes, which itself should be equal
// to the number of bytes that can be linearized
// This should never happen because bytes_to_send should always be less than or equal to conn->outbound_data_bytes,
// which itself should be equal to the number of bytes that can be linearized
throw logic_error("failed to linearize enough bytes before sending TCP PSH");
}
co_await this->send_tcp_frame(c, conn, TCPHeader::Flag::PSH, conn->outbound_data.front().data(), bytes_to_send);
conn->awaiting_ack = true;
// Schedule the timer for sending another PSH, in case the client doesn't
// respond quickly enough
// Schedule the timer for sending another PSH, in case the client doesn't respond quickly enough
this->schedule_send_pending_push_frame(conn, conn->resend_push_usecs);
// If the client isn't responding to our PSHes, back off exponentially up to
// a limit of 5 seconds between PSH frames. This window is reset when
// acked_server_seq changes (that is, when the client has acknowledged any new
// data). It seems some situations cause GameCube clients to drop packets more
// often; to alleviate this, we also try to resend less data.
// If the client isn't responding to our PSHes, back off exponentially up to a limit of 5 seconds between PSH frames.
// This window is reset when acked_server_seq changes (that is, when the client has acknowledged any new data). It
// seems some situations cause GameCube clients to drop packets more often; to alleviate this, we also try to resend
// less data.
conn->resend_push_usecs *= 2;
if (conn->resend_push_usecs > 5000000) {
conn->resend_push_usecs = 5000000;
@@ -1401,9 +1378,8 @@ asio::awaitable<void> IPStackSimulator::open_server_connection(
asio::awaitable<void> IPStackSimulator::close_tcp_connection(
shared_ptr<IPSSClient> c, shared_ptr<IPSSClient::TCPConnection> conn) {
// Send an RST to the client. This is kind of rude (we really should use FIN)
// but the PSO network stack always sends an RST to us when disconnecting, so
// whatever
// Send an RST to the client. This is kind of rude (we really should use FIN) but the PSO network stack always sends
// an RST to us when disconnecting, so whatever
co_await this->send_tcp_frame(c, conn, TCPHeader::Flag::RST);
// Delete the connection object
+4 -1
View File
@@ -20,7 +20,10 @@ enum class GVRDataFormat : uint8_t {
};
std::string encode_gvm(
const phosg::ImageRGBA8888N& img, GVRDataFormat data_format, const std::string& internal_name, uint32_t global_index);
const phosg::ImageRGBA8888N& img,
GVRDataFormat data_format,
const std::string& internal_name,
uint32_t global_index);
phosg::ImageRGB888 decode_fon(const std::string& data, size_t width);
std::string encode_fon(const phosg::ImageRGB888& img);
+8 -15
View File
@@ -164,8 +164,7 @@ string IntegralExpression::UnaryOperatorNode::str() const {
}
}
IntegralExpression::FlagLookupNode::FlagLookupNode(uint16_t flag_index)
: flag_index(flag_index) {}
IntegralExpression::FlagLookupNode::FlagLookupNode(uint16_t flag_index) : flag_index(flag_index) {}
bool IntegralExpression::FlagLookupNode::operator==(const Node& other) const {
try {
@@ -187,10 +186,8 @@ string IntegralExpression::FlagLookupNode::str() const {
return std::format("F_{:04X}", this->flag_index);
}
IntegralExpression::ChallengeCompletionLookupNode::ChallengeCompletionLookupNode(
Episode episode, uint8_t stage_index)
: episode(episode),
stage_index(stage_index) {}
IntegralExpression::ChallengeCompletionLookupNode::ChallengeCompletionLookupNode(Episode episode, uint8_t stage_index)
: episode(episode), stage_index(stage_index) {}
bool IntegralExpression::ChallengeCompletionLookupNode::operator==(const Node& other) const {
try {
@@ -217,8 +214,7 @@ string IntegralExpression::ChallengeCompletionLookupNode::str() const {
return std::format("CC_{}_{}", abbreviation_for_episode(this->episode), static_cast<uint8_t>(this->stage_index + 1));
}
IntegralExpression::TeamRewardLookupNode::TeamRewardLookupNode(const string& reward_name)
: reward_name(reward_name) {}
IntegralExpression::TeamRewardLookupNode::TeamRewardLookupNode(const string& reward_name) : reward_name(reward_name) {}
bool IntegralExpression::TeamRewardLookupNode::operator==(const Node& other) const {
try {
@@ -310,9 +306,8 @@ unique_ptr<const IntegralExpression::Node> IntegralExpression::parse_expr(string
text = text.substr(0, text.size() - 1);
}
if (text.at(0) == '(' && text.at(text.size() - 1) == ')') {
// It doesn't suffice to just check the first ant last characters, since
// text could be like "(a) && (b)". Instead, we ignore the first and last
// characters, and don't strip anything if the internal parentheses are
// It doesn't suffice to just check the first and last characters, since text could be like "(a) && (b)".
// Instead, we ignore the first and last characters, and don't strip anything if the internal parentheses are
// unbalanced.
size_t paren_level = 1;
for (size_t z = 1; z < text.size() - 1; z++) {
@@ -363,10 +358,8 @@ unique_ptr<const IntegralExpression::Node> IntegralExpression::parse_expr(string
}
if (!paren_level) {
for (const auto& oper : operators) {
// Awful hack (because I'm too lazy to add a tokenization step): if
// the operator is followed or preceded by another copy of itself,
// don't match it (this prevents us from matching & when the token is
// actually &&)
// Awful hack (because I'm too lazy to add a tokenization step): if the operator is followed or preceded by
// another copy of itself, don't match it (this prevents us from matching & when the token is actually &&)
if ((text.size() > z + oper.first.size()) &&
((z < oper.first.size()) || (text.compare(z - oper.first.size(), oper.first.size(), oper.first) != 0)) &&
(text.compare(z, oper.first.size(), oper.first) == 0) &&
+397 -437
View File
File diff suppressed because it is too large Load Diff
+56 -53
View File
@@ -9,6 +9,11 @@
#include "RareItemSet.hh"
#include "StaticGameData.hh"
// This file and ItemCreator.cc are essentially a direct reverse-engineering of the item creation algorithm in PSO GC.
// Only minor changes have been made to support BB (as described in the comments in the implementation) and to support
// cross-episode quests. The latter consists mostly of delaying table_index lookups and ItemPT table lookups until much
// later than in the original implementation; the actual logic for generating item data is the same.
class ItemCreator {
public:
ItemCreator(
@@ -20,7 +25,6 @@ public:
std::shared_ptr<const TekkerAdjustmentSet> tekker_adjustment_set,
std::shared_ptr<const ItemParameterTable> item_parameter_table,
std::shared_ptr<const ItemData::StackLimits> stack_limits,
Episode episode,
GameMode mode,
Difficulty difficulty,
uint8_t section_id,
@@ -33,13 +37,21 @@ public:
bool is_from_rare_table = false;
};
DropResult on_monster_item_drop(uint32_t enemy_type, uint8_t area);
DropResult on_box_item_drop(uint8_t area);
inline void set_legacy_replay() {
this->is_legacy_replay = true;
}
inline void set_rare_drop_rate_multiplier(double multiplier) {
this->rare_drop_rate_multiplier = multiplier;
}
DropResult on_monster_item_drop(EnemyType enemy_type, uint8_t area, bool force_rare);
DropResult on_box_item_drop(uint8_t area, bool force_rare);
// Note: param3-6 refer to the corresponding fields of the object definition
DropResult on_specialized_box_item_drop(uint8_t area, float param3, uint32_t param4, uint32_t param5, uint32_t param6);
DropResult on_specialized_box_item_drop(
uint8_t area, float param3, uint32_t param4, uint32_t param5, uint32_t param6);
ItemData base_item_for_specialized_box(uint32_t param4, uint32_t param5, uint32_t param6) const;
std::vector<ItemData> generate_armor_shop_contents(size_t player_level);
std::vector<ItemData> generate_armor_shop_contents(Episode episode, size_t player_level);
std::vector<ItemData> generate_tool_shop_contents(size_t player_level);
std::vector<ItemData> generate_weapon_shop_contents(size_t player_level);
@@ -56,10 +68,18 @@ public:
void set_section_id(uint8_t new_section_id);
private:
inline std::shared_ptr<const CommonItemSet::Table> pt(Episode episode) const {
return this->common_item_set->get_table(episode, this->mode, this->difficulty, this->section_id);
}
inline std::shared_ptr<const CommonItemSet::Table> pt(uint8_t area) const {
return this->pt(episode_for_area(area));
}
phosg::PrefixedLogger log;
Version logic_version;
bool is_legacy_replay;
double rare_drop_rate_multiplier = 1.0;
std::shared_ptr<const ItemData::StackLimits> stack_limits;
Episode episode;
GameMode mode;
Difficulty difficulty;
uint8_t section_id;
@@ -70,7 +90,6 @@ private:
std::shared_ptr<const TekkerAdjustmentSet> tekker_adjustment_set;
std::shared_ptr<const ItemParameterTable> item_parameter_table;
std::shared_ptr<const CommonItemSet> common_item_set;
std::shared_ptr<const CommonItemSet::Table> pt;
std::shared_ptr<const BattleRules> restrictions;
struct UnitResult {
@@ -102,42 +121,38 @@ private:
std::shared_ptr<RandomGenerator> rand_crypt;
bool are_rare_drops_allowed() const;
uint8_t normalize_area_number(uint8_t area) const;
DropResult on_monster_item_drop_with_area_norm(uint32_t enemy_type, uint8_t area_norm);
DropResult on_box_item_drop_with_area_norm(uint8_t area_norm);
uint8_t table_index_for_area(uint8_t area) const;
uint32_t rand_int(uint64_t max);
float rand_float_0_1_from_crypt();
template <size_t NumRanges>
uint32_t choose_meseta_amount(
const parray<CommonItemSet::Table::Range<uint16_t>, NumRanges> ranges,
size_t table_index);
uint32_t choose_meseta_amount(const CommonItemSet::Table::Range<uint16_t>& range);
bool should_allow_meseta_drops() const;
ItemData check_rare_spec_and_create_rare_enemy_item(uint32_t enemy_type, uint8_t area_norm);
ItemData check_rare_specs_and_create_rare_box_item(uint8_t area_norm);
ItemData check_rate_and_create_rare_item(const RareItemSet::ExpandedDrop& drop, uint8_t area_norm);
ItemData check_rare_spec_and_create_rare_enemy_item(EnemyType enemy_type, uint8_t area, bool force_rare);
ItemData check_rare_specs_and_create_rare_box_item(uint8_t area, bool force_rare);
ItemData check_rare_specs_and_create_rare_item(
const std::vector<RareItemSet::ExpandedDrop>& specs, uint8_t area, bool force_rare);
ItemData create_rare_item(const ItemData& drop_item, uint8_t area);
void generate_rare_weapon_bonuses(ItemData& item, uint32_t random_sample);
void generate_rare_weapon_bonuses(ItemData& item, Episode episode, uint32_t random_sample);
void deduplicate_weapon_bonuses(ItemData& item) const;
void set_item_kill_count_if_unsealable(ItemData& item) const;
void set_item_unidentified_flag_if_not_challenge(ItemData& item) const;
void set_tool_item_amount_to_1(ItemData& item) const;
void generate_common_item_variances(uint32_t area_norm, ItemData& item);
void generate_common_armor_slots_and_bonuses(ItemData& item);
void generate_common_armor_slot_count(ItemData& item);
void generate_common_armor_or_shield_type_and_variances(char area_norm, ItemData& item);
void generate_common_tool_variances(uint32_t area_norm, ItemData& item);
uint8_t generate_tech_disk_level(uint32_t tech_num, uint32_t area_norm);
void generate_common_item_variances(ItemData& item, uint8_t area);
void generate_common_armor_slots_and_bonuses(ItemData& item, Episode episode);
void generate_common_armor_slot_count(ItemData& item, Episode episode);
void generate_common_armor_or_shield_type_and_variances(ItemData& item, uint8_t area);
void generate_common_tool_variances(ItemData& item, uint8_t area);
uint8_t generate_tech_disk_level(uint32_t tech_num, uint8_t area);
void generate_common_mag_variances(ItemData& item);
void generate_common_weapon_variances(uint8_t area_norm, ItemData& item);
void generate_common_weapon_grind(ItemData& item, uint8_t offset_within_subtype_range);
void generate_common_weapon_bonuses(ItemData& item, uint8_t area_norm);
void generate_common_weapon_special(ItemData& item, uint8_t area_norm);
void generate_common_weapon_variances(ItemData& item, uint8_t area);
void generate_common_weapon_grind(ItemData& item, uint8_t area, uint8_t offset_within_subtype_range);
void generate_common_weapon_bonuses(ItemData& item, uint8_t area);
void generate_common_weapon_special(ItemData& item, uint8_t area);
uint8_t choose_weapon_special(uint8_t det);
void generate_unit_stars_tables();
void generate_common_unit_variances(uint8_t stars, ItemData& item);
@@ -146,28 +161,18 @@ private:
void clear_item_if_restricted(ItemData& item) const;
static size_t get_table_index_for_armor_shop(size_t player_level);
static bool shop_does_not_contain_duplicate_armor(
const std::vector<ItemData>& shop, const ItemData& item);
static bool shop_does_not_contain_duplicate_tech_disk(
const std::vector<ItemData>& shop, const ItemData& item);
static bool shop_does_not_contain_duplicate_or_too_many_similar_weapons(
const std::vector<ItemData>& shop, const ItemData& item);
static bool shop_does_not_contain_duplicate_item_by_data1_0_1_2(
const std::vector<ItemData>& shop, const ItemData& item);
void generate_armor_shop_armors(
std::vector<ItemData>& shop, size_t player_level);
void generate_armor_shop_shields(
std::vector<ItemData>& shop, size_t player_level);
void generate_armor_shop_units(
std::vector<ItemData>& shop, size_t player_level);
static bool shop_does_not_contain_duplicate_armor(const std::vector<ItemData>& shop, const ItemData& item);
static bool shop_does_not_contain_duplicate_tech_disk(const std::vector<ItemData>& shop, const ItemData& item);
static bool shop_does_not_contain_duplicate_or_too_many_similar_weapons(const std::vector<ItemData>& shop, const ItemData& item);
static bool shop_does_not_contain_duplicate_item_by_data1_0_1_2(const std::vector<ItemData>& shop, const ItemData& item);
void generate_armor_shop_armors(std::vector<ItemData>& shop, Episode episode, size_t player_level);
void generate_armor_shop_shields(std::vector<ItemData>& shop, size_t player_level);
void generate_armor_shop_units(std::vector<ItemData>& shop, size_t player_level);
static size_t get_table_index_for_tool_shop(size_t player_level);
void generate_common_tool_shop_recovery_items(
std::vector<ItemData>& shop, size_t player_level);
void generate_rare_tool_shop_recovery_items(
std::vector<ItemData>& shop, size_t player_level);
void generate_tool_shop_tech_disks(
std::vector<ItemData>& shop, size_t player_level);
void generate_common_tool_shop_recovery_items(std::vector<ItemData>& shop, size_t player_level);
void generate_rare_tool_shop_recovery_items(std::vector<ItemData>& shop, size_t player_level);
void generate_tool_shop_tech_disks(std::vector<ItemData>& shop, size_t player_level);
void generate_weapon_shop_item_grind(ItemData& item, size_t player_level);
void generate_weapon_shop_item_special(ItemData& item, size_t player_level);
@@ -175,11 +180,9 @@ private:
void generate_weapon_shop_item_bonus2(ItemData& item, size_t player_level);
template <typename IntT>
IntT get_rand_from_weighted_tables(
const IntT* tables, size_t offset, size_t num_values, size_t stride);
IntT get_rand_from_weighted_tables(const IntT* tables, size_t offset, size_t num_values, size_t stride);
template <typename IntT, size_t X>
IntT get_rand_from_weighted_tables_1d(const parray<IntT, X>& tables);
template <typename IntT, size_t X, size_t Y>
IntT get_rand_from_weighted_tables_2d_vertical(
const parray<parray<IntT, X>, Y>& tables, size_t offset);
IntT get_rand_from_weighted_tables_2d_vertical(const parray<parray<IntT, X>, Y>& tables, size_t offset);
};
+15 -30
View File
@@ -8,10 +8,8 @@
using namespace std;
const vector<uint8_t> ItemData::StackLimits::DEFAULT_TOOL_LIMITS_DC_NTE(
{10});
const vector<uint8_t> ItemData::StackLimits::DEFAULT_TOOL_LIMITS_V1_V2(
{10, 10, 1, 10, 10, 10, 10, 10, 10, 1});
const vector<uint8_t> ItemData::StackLimits::DEFAULT_TOOL_LIMITS_DC_NTE({10});
const vector<uint8_t> ItemData::StackLimits::DEFAULT_TOOL_LIMITS_V1_V2({10, 10, 1, 10, 10, 10, 10, 10, 10, 1});
const vector<uint8_t> ItemData::StackLimits::DEFAULT_TOOL_LIMITS_V3_V4(
{10, 10, 1, 10, 10, 10, 10, 10, 10, 1, 1, 1, 1, 1, 1, 1, 99, 1});
@@ -28,8 +26,7 @@ ItemData::StackLimits::StackLimits(
max_tool_stack_sizes_by_data1_1(max_tool_stack_sizes_by_data1_1),
max_meseta_stack_size(max_meseta_stack_size) {}
ItemData::StackLimits::StackLimits(Version version, const phosg::JSON& json)
: version(version) {
ItemData::StackLimits::StackLimits(Version version, const phosg::JSON& json) : version(version) {
this->max_tool_stack_sizes_by_data1_1.clear();
for (const auto& limit_json : json.at("ToolLimits").as_list()) {
this->max_tool_stack_sizes_by_data1_1.emplace_back(limit_json->as_int());
@@ -116,8 +113,7 @@ uint32_t ItemData::primary_identifier() const {
// - 03TTSS00 = tool
// - 04000000 = meseta
// The game treats any item starting with 04 as Meseta, and ignores the rest
// of data1 (the value is in data2)
// The game treats any item starting with 04 as Meseta, and ignores the rest of data1 (the value is in data2)
if (this->data1[0] == 0x04) {
return 0x04000000;
}
@@ -150,17 +146,14 @@ void ItemData::change_primary_identifier(uint32_t primary_identifier) {
}
break;
}
case 0x01: // Armor/shield/unit
// Apply data1[1] and data1[2]
case 0x01: // Armor/shield/unit; apply data1[1] and data1[2]
this->data1[1] = (primary_identifier >> 16) & 0xFF;
this->data1[2] = (primary_identifier >> 8) & 0xFF;
break;
case 0x02: // Mag
// Apply data1[1] only
case 0x02: // Mag; apply data1[1] only
this->data1[1] = (primary_identifier >> 16) & 0xFF;
break;
case 0x03: // Tool
// Apply data1[1] and data1[2] (or data1[4] if it's a tech disk)
case 0x03: // Tool; apply data1[1] and data1[2] (or data1[4] if it's a tech disk)
this->data1[1] = (primary_identifier >> 16) & 0xFF;
if (this->data1[1] == 0x02) {
this->data1[4] = (primary_identifier >> 8) & 0xFF;
@@ -169,8 +162,7 @@ void ItemData::change_primary_identifier(uint32_t primary_identifier) {
this->data1[2] = (primary_identifier >> 8) & 0xFF;
}
break;
case 0x04: // Meseta
// Nothing to apply
case 0x04: // Meseta; nothing to apply
break;
default:
throw std::runtime_error("invalid item class");
@@ -298,10 +290,7 @@ void ItemData::clear_mag_stats() {
}
uint16_t ItemData::compute_mag_level() const {
return (this->data1w[2] / 100) +
(this->data1w[3] / 100) +
(this->data1w[4] / 100) +
(this->data1w[5] / 100);
return (this->data1w[2] / 100) + (this->data1w[3] / 100) + (this->data1w[4] / 100) + (this->data1w[5] / 100);
}
uint16_t ItemData::compute_mag_strength_flags() const {
@@ -432,8 +421,7 @@ void ItemData::decode_for_version(Version from_version) {
}
if (is_v1(from_version) || is_v2(from_version)) {
// PSO PC and GC NTE encode mags in a tediously annoying manner. The
// first four bytes are the same, but then...
// PSO PC and GC NTE encode mags in a tediously annoying manner. The first four bytes are the same, but then:
// V2: pHHHHHHHHHHHHHHc pIIIIIIIIIIIIIIc JJJJJJJJJJJJJJJc KKKKKKKKKKKKKKKc QQQQQQQQ QQQQQQQQ YYYYYYYY pYYYYYYY
// V3: HHHHHHHHHHHHHHHH IIIIIIIIIIIIIIII JJJJJJJJJJJJJJJJ KKKKKKKKKKKKKKKK YYYYYYYY QQQQQQQQ PPPPPPPP CCCCCCCC
// c = color in V2 (4 bits; low bit first)
@@ -455,10 +443,8 @@ void ItemData::decode_for_version(Version from_version) {
this->data1w[5] &= 0xFFFE;
} else if (is_big_endian(from_version)) {
// PSO GC (but not GC NTE, which uses the above logic) byteswaps the
// data2d field, since internally it's actually a uint32_t. We treat it
// as individual bytes instead, so we correct for the client's
// byteswapping here.
// PSO GC (but not GC NTE, which uses the above logic) byteswaps the data2d field, since internally it's
// actually a uint32_t. We treat it as individual bytes, so we correct for the client's byteswapping here.
this->data2d = phosg::bswap32(this->data2d);
}
break;
@@ -500,7 +486,7 @@ void ItemData::encode_for_version(Version to_version, shared_ptr<const ItemParam
if (should_encode_v2_data && (this->data1[1] > 0x26)) {
if (this->data1[1] < 0x89) {
this->data1[5] = this->data1[1];
this->data1[1] = item_parameter_table->get_weapon_v1_replacement(this->data1[1]);
this->data1[1] = item_parameter_table->get_weapon_kind(this->data1[1]);
if (this->data1[1] == 0x00) {
this->data1[1] = 0x0F;
}
@@ -529,9 +515,8 @@ void ItemData::encode_for_version(Version to_version, shared_ptr<const ItemParam
this->data1[1] = 0x00;
}
// This logic is the inverse of the corresponding logic in
// decode_for_version; see that function for a description of what's
// going on here.
// This logic is the inverse of the corresponding logic in decode_for_version; see that function for a
// description of what's going on here.
if (is_v1(to_version) || is_v2(to_version)) {
this->data1w[2] = (this->data1w[2] & 0x7FFE) | ((this->data2[2] << 14) & 0x8000) | (this->data2[3] & 1);
this->data1w[3] = (this->data1w[3] & 0x7FFE) | ((this->data2[2] << 13) & 0x8000) | ((this->data2[3] >> 1) & 1);
+21 -26
View File
@@ -10,13 +10,11 @@
class ItemParameterTable;
enum class EquipSlot {
// When equipping items through the Item Pack pause menu, the client sends
// UNKNOWN for the slot. The receiving client (and server, in our case) have
// to analyze the item being equipped and put it in the appropriate slot in
// this case. See ItemData::default_equip_slot() for this computation.
// When equipping items through the Item Pack pause menu, the client sends UNKNOWN for the slot. The receiving client
// (and server, in our case) have to analyze the item being equipped and put it in the appropriate slot in this case.
// See ItemData::default_equip_slot() for this computation.
UNKNOWN = 0x00,
// When equipping items through the quick menu or Equip pause menu, the client
// sends one of the slots below.
// When equipping items through the quick menu or Equip pause menu, the client sends one of the slots below.
MAG = 0x01,
ARMOR = 0x02,
SHIELD = 0x03,
@@ -80,21 +78,21 @@ struct ItemData {
};
// QUICK ITEM FORMAT REFERENCE
// data1/0 data1/4 data1/8 data2
// Weapon: 00ZZZZGG SSNNAABB AABBAABB 00000000
// Armor: 0101ZZ00 FFTTDDDD EEEEXXXX 00000000
// Shield: 0102ZZ00 FFTTDDDD EEEEXXXX 00000000
// Unit: 0103ZZ00 FF00RRRR 0000XXXX 00000000
// Mag: 02ZZLLWW HHHHIIII JJJJKKKK YYQQPPVV
// Tool: 03ZZZZUU 00CC0000 0000XXXX 00000000
// Tech disk: 0302&&UU %%CC0000 0000XXXX 00000000
// Meseta: 04000000 00000000 00000000 MMMMMMMM
// data1/0 data1/4 data1/8 data2
// Weapon: 00ZZZZGG SSNNAABB AABBAABB 00000000
// Armor: 0101ZZ00 FFTTDDDD EEEEXXXX 00000000
// Shield: 0102ZZ00 FFTTDDDD EEEEXXXX 00000000
// Unit: 0103ZZ00 FF00RRRR 0000XXXX 00000000
// Mag: 02ZZLLWW HHHHIIII JJJJKKKK YYQQPPVV
// Tool: 03ZZZZUU 00CC0000 0000XXXX 00000000
// Tech disk: 0302&&UU %%CC0000 0000XXXX 00000000
// Meseta: 04000000 00000000 00000000 MMMMMMMM
// A = attribute type (for S-ranks, custom name; last pair is kill count for some weapons)
// B = attribute amount (for S-ranks, custom name; last pair is kill count for some weapons)
// C = stack size (for tools)
// D = DEF bonus
// E = EVP bonus
// F = armor/shield/unit flags (40=present; low 4 bits are present color)
// F = armor/shield/unit flags (40=wrapped; low 4 bits are present color)
// G = weapon grind
// H = mag DEF
// I = mag POW
@@ -103,12 +101,12 @@ struct ItemData {
// L = mag level
// M = meseta amount
// N = present color (weapon only; for other types this is in the flags field)
// P = mag flags (40=present, 04=has left pb, 02=has right pb, 01=has center pb)
// P = mag flags (40=wrapped, 04=has left pb, 02=has right pb, 01=has center pb)
// Q = mag IQ
// R = unit modifier (little-endian)
// S = weapon flags (80=unidentified, 40=present) and special (low 6 bits)
// S = weapon flags (80=unidentified, 40=wrapped) and special (low 6 bits)
// T = slot count
// U = tool flags (40=present; unused if item is stackable)
// U = tool flags (40=wrapped; unused if item is stackable)
// V = mag color
// W = photon blasts
// X = kill count (big-endian; high bit always set)
@@ -116,13 +114,10 @@ struct ItemData {
// Z = item ID
// & = technique level
// % = technique number
// Note: PSO GC erroneously byteswaps data2 even when the item is a mag. This
// makes it incompatible with little-endian versions of PSO (i.e. all other
// versions). We manually byteswap data2 upon receipt and immediately before
// sending where needed.
// Related note: PSO V2 has an annoyingly complicated format for mags that
// doesn't match the above table. We decode this upon receipt and encode it
// immediately before sending when interacting with V2 clients; see the
// Note: PSO GC byteswaps data2 even when the item is a mag. This makes it incompatible with little-endian versions
// of PSO (i.e. all other versions). We manually byteswap data2 upon receipt and before sending where needed.
// Related note: PSO V2 has an annoyingly complicated format for mags that doesn't match the above table. We decode
// this upon receipt and encode it immediately before sending when interacting with V2 clients; see the
// implementation of decode_for_version() for details.
union {
+244 -76
View File
@@ -1,5 +1,7 @@
#include "ItemNameIndex.hh"
#include <algorithm>
#include "StaticGameData.hh"
using namespace std;
@@ -146,9 +148,8 @@ std::string ItemNameIndex::describe_item(const ItemData& item, uint8_t flags) co
}
}
// Armors, shields, and units (0x01) can be wrapped, as can mags (0x02) and
// non-stackable tools (0x03). However, each of these item classes has its
// flags in a different location.
// Armors, shields, and units (0x01) can be wrapped, as can mags (0x02) and non-stackable tools (0x03). However, each
// of these item classes has its flags in a different location.
if (!name_only &&
(((item.data1[0] == 0x01) && (item.data1[4] & 0x40)) ||
((item.data1[0] == 0x02) && (item.data2[2] & 0x40)) ||
@@ -188,12 +189,10 @@ std::string ItemNameIndex::describe_item(const ItemData& item, uint8_t flags) co
}
if (item.is_s_rank_weapon()) {
// S-rank weapons have names instead of percent bonuses. The name is
// encoded as 9 5-bit characters in the bytes where the bonuses usually
// go. The first character does not appear when the name is rendered;
// instead, it's used to determine if the weapon type name should appear
// or not. Unlike the client, we check the first character directly and
// don't bother decoding it.
// S-rank weapons have names instead of percent bonuses. The name is encoded as 9 5-bit characters in the bytes
// where the bonuses usually go. The first character does not appear when the name is rendered; instead, it's
// used to determine if the weapon type name should appear or not. Unlike the client, we check the first
// character directly and don't bother decoding it.
uint16_t be_data1w3 = phosg::bswap16(item.data1w[3]);
uint16_t be_data1w4 = phosg::bswap16(item.data1w[4]);
uint16_t be_data1w5 = phosg::bswap16(item.data1w[5]);
@@ -324,8 +323,7 @@ std::string ItemNameIndex::describe_item(const ItemData& item, uint8_t flags) co
uint8_t flags = item.data2[2];
if (flags & 7) {
static const vector<const char*> pb_shortnames = {
"F", "E", "G", "P", "L", "M&Y", "MG", "GR"};
static const vector<const char*> pb_shortnames = {"F", "E", "G", "P", "L", "M&Y", "MG", "GR"};
const char* pb_names[3] = {nullptr, nullptr, nullptr};
uint8_t left_pb = item.mag_photon_blast_for_slot(2);
@@ -587,9 +585,8 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript
}
auto name_it = this->name_index.lower_bound(desc);
// Look up to 3 places before the lower bound. We have to do this to catch
// cases like Sange vs. Sange & Yasha - if the input is like "Sange 0/...",
// then we'll see Sange & Yasha first, which we should skip.
// Look up to 3 places before the lower bound. We have to do this to catch cases like Sange vs. Sange & Yasha - if
// the input is like "Sange 0/...", then we'll see Sange & Yasha first, which we should skip.
size_t lookback = 0;
while (lookback < 4) {
if (name_it != this->name_index.end() && desc.starts_with(name_it->first)) {
@@ -610,16 +607,14 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript
desc = desc.substr(1);
}
// Tech disks should have already been handled above, so we don't need to
// special-case 0302xxxx identifiers here.
// Tech disks should have already been handled above, so we don't need to special-case 0302xxxx identifiers here.
uint32_t primary_identifier = name_it->second->primary_identifier;
ret.data1[0] = (primary_identifier >> 24) & 0xFF;
ret.data1[1] = (primary_identifier >> 16) & 0xFF;
ret.data1[2] = (primary_identifier >> 8) & 0xFF;
if (ret.data1[0] == 0x00) {
// Weapons: add special, grind and percentages (or name, if S-rank) and
// kill count if unsealable
// Weapons: add special, grind and percentages (or name, if S-rank) and kill count if unsealable
ret.data1[4] = weapon_special | (is_wrapped ? 0x40 : 0x00) | (is_unidentified ? 0x80 : 0x00);
bool kill_count_set = false;
@@ -728,16 +723,8 @@ ItemData ItemNameIndex::parse_item_description_phase(const std::string& descript
if (pb_tokens.size() > 3) {
throw runtime_error("too many photon blasts specified");
}
static const unordered_map<string, uint8_t> name_to_pb_num({
{"f", 0},
{"e", 1},
{"g", 2},
{"p", 3},
{"l", 4},
{"m", 5},
{"my", 5},
{"m&y", 5},
});
static const unordered_map<string, uint8_t> name_to_pb_num(
{{"f", 0}, {"e", 1}, {"g", 2}, {"p", 3}, {"l", 4}, {"m", 5}, {"my", 5}, {"m&y", 5}});
for (const auto& pb_token : pb_tokens) {
ret.add_mag_photon_blast(name_to_pb_num.at(pb_token));
}
@@ -802,9 +789,9 @@ void ItemNameIndex::print_table(FILE* stream) const {
auto pmt = this->item_parameter_table;
phosg::fwrite_fmt(stream, "WEAPONS\n");
phosg::fwrite_fmt(stream, " CODE => ---ID--- TYPE SKIN POINTS FLAG ATPLO ATPHI ATPRQ MSTRQ ATARQ -MST- GND PH SP ATA SB(S1:AMT1,S2:AMT2) PJ 1X 1Y 2X 2Y CL --A1-- A4 A5 TB BF V1 ST* USL ---DIVISOR--- NAME\n");
for (size_t data1_1 = 0; data1_1 < pmt->num_weapon_classes; data1_1++) {
uint8_t v1_replacement = pmt->get_weapon_v1_replacement(data1_1);
phosg::fwrite_fmt(stream, " CODE => ---ID--- TYPE SKIN POINTS FLAG ATPLO ATPHI ATPRQ MSTRQ ATARQ -MST- GND PH SP ATA SB(S1:AMT1,S2:AMT2) PJ 1X 1Y 2X 2Y CR --A1-- A4 A5 TB(TN:FL:AMOUNT, ... ) BF CL ST* USL ---DIVISOR--- NAME\n");
for (size_t data1_1 = 0; data1_1 < pmt->num_weapon_classes(); data1_1++) {
uint8_t weapon_class = pmt->get_weapon_kind(data1_1);
float sale_divisor = pmt->get_sale_divisor(0x00, data1_1);
string divisor_str = std::format("{:g}", sale_divisor);
divisor_str.resize(13, ' ');
@@ -812,7 +799,7 @@ void ItemNameIndex::print_table(FILE* stream) const {
size_t data1_2_limit = pmt->num_weapons_in_class(data1_1);
for (size_t data1_2 = 0; data1_2 < data1_2_limit; data1_2++) {
const auto& w = pmt->get_weapon(data1_1, data1_2);
uint8_t stars = pmt->get_item_stars(w.base.id);
uint8_t stars = pmt->get_item_stars(w.id);
bool is_unsealable = pmt->is_unsealable_item(0x00, data1_1, data1_2);
ItemData item;
@@ -821,14 +808,30 @@ void ItemNameIndex::print_table(FILE* stream) const {
item.data1[2] = data1_2;
string name = this->describe_item(item);
auto& stat_boost = pmt->get_stat_boost(w.stat_boost_entry_index);
phosg::fwrite_fmt(stream, " 00{:02X}{:02X} => {:08X} {:04X} {:04X} {:6} {:04X} {:5} {:5} {:5} {:5} {:5} {:5} {:3} {:02X} {:02X} {:3} {:02X}({:02X}:{:04X},{:02X}:{:04X}) {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}{:02X}{:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:2}* {} {} {}\n",
const auto& stat_boost = pmt->get_stat_boost(w.stat_boost_entry_index);
string tech_boost_str;
if (w.tech_boost_entry_index < pmt->num_tech_boosts()) {
const auto& tech_boost = pmt->get_tech_boost(w.tech_boost_entry_index);
tech_boost_str = std::format("({:02X}:{:02X}:{:g},{:02X}:{:02X}:{:g},{:02X}:{:02X}:{:g})",
tech_boost.tech_num1, tech_boost.flags1, tech_boost.amount1, tech_boost.tech_num2, tech_boost.flags2,
tech_boost.amount2, tech_boost.tech_num3, tech_boost.flags3, tech_boost.amount3);
}
tech_boost_str.resize(40, ' ');
phosg::fwrite_fmt(stream,
// CODE => ID TYPE SKIN PTS FLAG ATP- ATP+ ATPR MSTR ATAR MST GND PH SP ATA
" 00{:02X}{:02X} => {:08X} {:04X} {:04X} {:6} {:04X} {:5} {:5} {:5} {:5} {:5} {:5} {:3} {:02X} {:02X} {:3} "
// SB( S1:AMT1 , S2:AMT2 ) PJ 1X 1Y 2X 2Y CR --------A1-------- A4
"{:02X}({:02X}:{:04X},{:02X}:{:04X}) {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}{:02X}{:02X} {:02X} "
// A5 TB( TN: FL: AMT, TN: FL: AMT, TN: FL: AMT) BF CL ST* US DV NAME\n"
"{:02X} {:02X}{} {:02X} {:02X} {:2}* {} {} {}\n",
data1_1,
data1_2,
w.base.id,
w.base.type,
w.base.skin,
w.base.team_points,
w.id,
w.type,
w.skin,
w.team_points,
w.class_flags,
w.atp_min,
w.atp_max,
@@ -841,10 +844,10 @@ void ItemNameIndex::print_table(FILE* stream) const {
w.special,
w.ata,
w.stat_boost_entry_index,
stat_boost.stats[0],
stat_boost.amounts[0],
stat_boost.stats[1],
stat_boost.amounts[1],
stat_boost.stat1,
stat_boost.amount1,
stat_boost.stat2,
stat_boost.amount2,
w.projectile,
w.trail1_x,
w.trail1_y,
@@ -856,9 +859,10 @@ void ItemNameIndex::print_table(FILE* stream) const {
w.unknown_a1[2],
w.unknown_a4,
w.unknown_a5,
w.tech_boost,
w.tech_boost_entry_index,
tech_boost_str,
w.behavior_flags,
v1_replacement,
weapon_class,
stars,
is_unsealable ? "YES" : " no",
divisor_str,
@@ -867,7 +871,7 @@ void ItemNameIndex::print_table(FILE* stream) const {
}
phosg::fwrite_fmt(stream, "ARMORS\n");
phosg::fwrite_fmt(stream, " CODE => ---ID--- TYPE SKIN POINTS -DFP- -EVP- BP BE FLAG LVL EFR ETH EIC EDK ELT DFR EVR SB(S1:AMT1,S2:AMT2) TB FT A4 ST* ---DIVISOR--- NAME\n");
phosg::fwrite_fmt(stream, " CODE => ---ID--- TYPE SKIN POINTS -DFP- -EVP- BP BE FLAG LVL EFR ETH EIC EDK ELT DFR EVR SB(S1:AMT1,S2:AMT2) TB(TN:FL:AMOUNT, ... ) FT A4 ST* ---DIVISOR--- NAME\n");
for (size_t data1_1 = 1; data1_1 < 3; data1_1++) {
float sale_divisor = pmt->get_sale_divisor(0x01, data1_1);
string divisor_str = std::format("{:g}", sale_divisor);
@@ -876,7 +880,7 @@ void ItemNameIndex::print_table(FILE* stream) const {
size_t data1_2_limit = pmt->num_armors_or_shields_in_class(data1_1);
for (size_t data1_2 = 0; data1_2 < data1_2_limit; data1_2++) {
const auto& a = pmt->get_armor_or_shield(data1_1, data1_2);
uint8_t stars = pmt->get_item_stars(a.base.id);
uint8_t stars = pmt->get_item_stars(a.id);
ItemData item;
item.data1[0] = 0x01;
@@ -885,13 +889,23 @@ void ItemNameIndex::print_table(FILE* stream) const {
string name = this->describe_item(item);
auto& stat_boost = pmt->get_stat_boost(a.stat_boost_entry_index);
phosg::fwrite_fmt(stream, " 01{:02X}{:02X} => {:08X} {:04X} {:04X} {:6} {:5} {:5} {:02X} {:02X} {:04X} {:3} {:3} {:3} {:3} {:3} {:3} {:3} {:3} {:02X}({:02X}:{:04X},{:02X}:{:04X}) {:02X} {:02X} {:02X} {:2}* {} {}\n",
string tech_boost_str;
if (a.tech_boost_entry_index < pmt->num_tech_boosts()) {
const auto& tech_boost = pmt->get_tech_boost(a.tech_boost_entry_index);
tech_boost_str = std::format("({:02X}:{:02X}:{:g},{:02X}:{:02X}:{:g},{:02X}:{:02X}:{:g})",
tech_boost.tech_num1, tech_boost.flags1, tech_boost.amount1, tech_boost.tech_num2, tech_boost.flags2,
tech_boost.amount2, tech_boost.tech_num3, tech_boost.flags3, tech_boost.amount3);
}
tech_boost_str.resize(40, ' ');
phosg::fwrite_fmt(stream, " 01{:02X}{:02X} => {:08X} {:04X} {:04X} {:6} {:5} {:5} {:02X} {:02X} {:04X} {:3} {:3} {:3} {:3} {:3} {:3} {:3} {:3} {:02X}({:02X}:{:04X},{:02X}:{:04X}) {:02X}{} {:02X} {:02X} {:2}* {} {}\n",
data1_1,
data1_2,
a.base.id,
a.base.type,
a.base.skin,
a.base.team_points,
a.id,
a.type,
a.skin,
a.team_points,
a.dfp,
a.evp,
a.block_particle,
@@ -906,11 +920,12 @@ void ItemNameIndex::print_table(FILE* stream) const {
a.dfp_range,
a.evp_range,
a.stat_boost_entry_index,
stat_boost.stats[0],
stat_boost.amounts[0],
stat_boost.stats[1],
stat_boost.amounts[1],
a.tech_boost,
stat_boost.stat1,
stat_boost.amount1,
stat_boost.stat2,
stat_boost.amount2,
a.tech_boost_entry_index,
tech_boost_str,
a.flags_type,
a.unknown_a4,
stars,
@@ -929,7 +944,7 @@ void ItemNameIndex::print_table(FILE* stream) const {
size_t data1_2_limit = pmt->num_units();
for (size_t data1_2 = 0; data1_2 < data1_2_limit; data1_2++) {
const auto& u = pmt->get_unit(data1_2);
uint8_t stars = pmt->get_item_stars(u.base.id);
uint8_t stars = pmt->get_item_stars(u.id);
ItemData item;
item.data1[0] = 0x01;
@@ -939,10 +954,10 @@ void ItemNameIndex::print_table(FILE* stream) const {
phosg::fwrite_fmt(stream, " 0103{:02X} => {:08X} {:04X} {:04X} {:6} {:04X} {:5} {:6} {:2}* {} {}\n",
data1_2,
u.base.id,
u.base.type,
u.base.skin,
u.base.team_points,
u.id,
u.type,
u.skin,
u.team_points,
u.stat,
u.stat_amount,
u.modifier_amount,
@@ -971,10 +986,10 @@ void ItemNameIndex::print_table(FILE* stream) const {
phosg::fwrite_fmt(stream, " 02{:02X}00 => {:08X} {:04X} {:04X} {:6} {:04X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:04X} {} {}\n",
data1_1,
m.base.id,
m.base.type,
m.base.skin,
m.base.team_points,
m.id,
m.type,
m.skin,
m.team_points,
m.feed_table,
m.photon_blast,
m.activation,
@@ -994,7 +1009,7 @@ void ItemNameIndex::print_table(FILE* stream) const {
phosg::fwrite_fmt(stream, "TOOLS\n");
phosg::fwrite_fmt(stream, " CODE => ---ID--- TYPE SKIN POINTS COUNT TECH -COST- ITEMFLAG ---DIVISOR--- NAME\n");
for (size_t data1_1 = 0; data1_1 < pmt->num_tool_classes; data1_1++) {
for (size_t data1_1 = 0; data1_1 < pmt->num_tool_classes(); data1_1++) {
float sale_divisor = pmt->get_sale_divisor(0x03, data1_1);
string divisor_str = std::format("{:g}", sale_divisor);
divisor_str.resize(13, ' ');
@@ -1013,10 +1028,10 @@ void ItemNameIndex::print_table(FILE* stream) const {
phosg::fwrite_fmt(stream, " 03{:02X}{:02X} => {:08X} {:04X} {:04X} {:6} {:5} {:04X} {:6} {:08X} {} {}\n",
data1_1,
data1_2,
t.base.id,
t.base.type,
t.base.skin,
t.base.team_points,
t.id,
t.type,
t.skin,
t.team_points,
t.amount,
t.tech,
t.cost,
@@ -1044,8 +1059,7 @@ void ItemNameIndex::print_table(FILE* stream) const {
phosg::fwrite_fmt(stream, "MAG FEED TABLES\n");
for (size_t table_index = 0; table_index < 8; table_index++) {
static const char* names[11] = {
"Monomate", "Dimate", "Trimate", "Monofluid",
"Difluid", "Trifluid", "Antidote", "Antiparalysis",
"Monomate", "Dimate", "Trimate", "Monofluid", "Difluid", "Trifluid", "Antidote", "Antiparalysis",
"Sol Atomizer", "Moon Atomizer", "Star Atomizer"};
phosg::fwrite_fmt(stream, " TABLE {:02X} => -DEF -POW -DEX MIND -IQ- SYNC\n", table_index);
for (size_t which = 0; which < 11; which++) {
@@ -1056,8 +1070,8 @@ void ItemNameIndex::print_table(FILE* stream) const {
}
phosg::fwrite_fmt(stream, "SPECIAL DEFINITIONS\n");
phosg::fwrite_fmt(stream, " SPECIAL => TYPE COUNT ST* NAME\n");
for (size_t index = 0; index < pmt->num_specials; index++) {
phosg::fwrite_fmt(stream, " SP => TYPE COUNT ST* NAME\n");
for (size_t index = 0; index < pmt->num_specials(); index++) {
const auto& sp = pmt->get_special(index);
uint8_t stars = pmt->get_special_stars(index);
const char* name = "";
@@ -1067,12 +1081,12 @@ void ItemNameIndex::print_table(FILE* stream) const {
} catch (const out_of_range&) {
}
}
phosg::fwrite_fmt(stream, " {:02X} => {:04X} {:5} {:2}* {}\n", index, sp.type, sp.amount, stars, name);
phosg::fwrite_fmt(stream, " {:02X} => {:04X} {:5} {:2}* {}\n", index, sp.type, sp.amount, stars, name);
}
phosg::fwrite_fmt(stream, "ITEM COMBINATIONS\n");
phosg::fwrite_fmt(stream, " ---USE + -EQUIP => RESULT MLV GND LVL CLS\n");
for (const auto& combo_list_it : pmt->get_all_item_combinations()) {
for (const auto& combo_list_it : pmt->item_combinations_index()) {
for (const auto& combo : combo_list_it.second) {
phosg::fwrite_fmt(stream, " {:02X}{:02X}{:02X} + {:02X}{:02X}{:02X} => {:02X}{:02X}{:02X}",
combo.used_item[0], combo.used_item[1], combo.used_item[2],
@@ -1112,4 +1126,158 @@ void ItemNameIndex::print_table(FILE* stream) const {
event_item.item[0], event_item.item[1], event_item.item[2], event_item.probability);
}
}
phosg::fwrite_fmt(stream, "PHOTON COLORS\n");
phosg::fwrite_fmt(stream, " ## => ---A1--- (A2) (A3)\n");
for (size_t z = 0; z < pmt->num_photon_colors(); z++) {
const auto& pc = pmt->get_photon_color(z);
phosg::fwrite_fmt(stream, " {:02X} => {:08X} ({:g}, {:g}, {:g}, {:g}) ({:g}, {:g}, {:g}, {:g})\n",
z, pc.unknown_a1, pc.unknown_a2.x, pc.unknown_a2.y, pc.unknown_a2.z, pc.unknown_a2.t,
pc.unknown_a3.x, pc.unknown_a3.y, pc.unknown_a3.z, pc.unknown_a3.t);
}
phosg::fwrite_fmt(stream, "WEAPON RANGES\n");
phosg::fwrite_fmt(stream, " ## => ---A3--- ---A4--- ---A5--- (A1) (A2)\n");
for (size_t z = 0; z < pmt->num_weapon_ranges(); z++) {
const auto& wr = pmt->get_weapon_range(z);
phosg::fwrite_fmt(stream, " {:02X} => {:08X} {:08X} {:08X} ({:g}) ({:g})\n",
z, wr.unknown_a3, wr.unknown_a4, wr.unknown_a5, wr.unknown_a1, wr.unknown_a2);
}
phosg::fwrite_fmt(stream, "SALE DIVISORS\n");
phosg::fwrite_fmt(stream, " ARMOR = {:g}\n", pmt->get_sale_divisor(1, 1));
phosg::fwrite_fmt(stream, " SHIELD = {:g}\n", pmt->get_sale_divisor(1, 2));
phosg::fwrite_fmt(stream, " UNIT = {:g}\n", pmt->get_sale_divisor(1, 3));
phosg::fwrite_fmt(stream, " MAG = {:g}\n", pmt->get_sale_divisor(2, 0));
auto write_data_string = [&](const std::string& data, size_t addr = 0) -> void {
if (data.empty()) {
phosg::fwrite_fmt(stream, " (no data)\n");
} else {
auto data_str = phosg::format_data(data, addr);
phosg::strip_trailing_whitespace(data_str);
phosg::fwrite_fmt(stream, " {}\n", phosg::str_replace_all(data_str, "\n", "\n "));
}
};
phosg::fwrite_fmt(stream, "STAR VALUES\n");
write_data_string(pmt->get_star_value_table(), pmt->get_star_value_index_range().first);
phosg::fwrite_fmt(stream, "UNKNOWN_A1\n");
write_data_string(pmt->get_unknown_a1());
phosg::fwrite_fmt(stream, "WEAPON EFFECTS\n");
phosg::fwrite_fmt(stream, " ## => -SOUND1- -VALUE1- -SOUND2- -VALUE2- ----------------A5---------------\n");
for (size_t z = 0; z < pmt->num_weapon_effects(); z++) {
const auto& we = pmt->get_weapon_effect(z);
auto a5_str = phosg::format_data_string(we.unknown_a5.data(), we.unknown_a5.size());
phosg::fwrite_fmt(stream, " {:02X} => {:08X} {:08X} {:08X} {:08X} {}\n",
z, we.sound_id1, we.eff_value1, we.sound_id2, we.eff_value2, a5_str);
}
phosg::fwrite_fmt(stream, "WEAPON STAT BOOST INDEX TABLE\n");
write_data_string(pmt->get_weapon_stat_boost_index_table());
phosg::fwrite_fmt(stream, "ARMOR STAT BOOST INDEX TABLE\n");
write_data_string(pmt->get_armor_stat_boost_index_table());
phosg::fwrite_fmt(stream, "SHIELD STAT BOOST INDEX TABLE\n");
write_data_string(pmt->get_shield_stat_boost_index_table());
phosg::fwrite_fmt(stream, "STAT BOOSTS\n");
phosg::fwrite_fmt(stream, " ## => BOOSTS\n");
for (size_t z = 0; z < pmt->num_stat_boosts(); z++) {
const auto& sb = pmt->get_stat_boost(z);
static constexpr std::array<const char*, 0x10> stat_names{
"ATP+", "ATA+", "EVP+", "DFP+", "MST+", "HP+", "LCK+", "ALL+",
"ATP-", "ATA-", "EVP-", "DFP-", "MST-", "HP-", "LCK-", "ALL-"};
string s;
if (sb.stat1 > 0x10) {
s = std::format("[{:02X}:{:04X}]", sb.stat1, sb.amount1);
} else if (sb.stat1 > 0) {
s = std::format("{}{}", stat_names[sb.stat1 - 1], sb.amount1);
}
if (sb.stat2) {
if (!s.empty()) {
s += ", ";
}
if (sb.stat2 > 0x10) {
s += std::format("[{:02X}:{:04X}]", sb.stat2, sb.amount2);
} else if (sb.stat2 > 0) {
s += std::format("{}{}", stat_names[sb.stat2 - 1], sb.amount2);
}
}
if (s.empty()) {
s = "(none)";
}
phosg::fwrite_fmt(stream, " {:02X} => {}\n", z, s);
}
phosg::fwrite_fmt(stream, "SHIELD EFFECTS\n");
phosg::fwrite_fmt(stream, " ## => -SOUND1- ---A1---\n");
for (size_t z = 0; z < pmt->num_shield_effects(); z++) {
const auto& se = pmt->get_shield_effect(z);
phosg::fwrite_fmt(stream, " {:02X} => {:08X} {:08X}\n", z, se.sound_id, se.unknown_a1);
}
phosg::fwrite_fmt(stream, "SOUND REMAPS\n");
phosg::fwrite_fmt(stream, " -SOUND1- => RT:[...] CC:[...]\n");
for (const auto& remap : pmt->get_all_sound_remaps()) {
std::string rt_str;
for (uint32_t rt_sound_id : remap.by_rt_index) {
if (!rt_str.empty()) {
rt_str += ",";
}
rt_str += std::format("{:08X}", rt_sound_id);
}
std::string cc_str;
for (uint32_t cc_sound_id : remap.by_char_class) {
if (!cc_str.empty()) {
cc_str += ",";
}
cc_str += std::format("{:08X}", cc_sound_id);
}
phosg::fwrite_fmt(stream, " {:08X} => RT:[{}] CC:[{}]\n", remap.sound_id, rt_str, cc_str);
}
phosg::fwrite_fmt(stream, "TECH BOOSTS\n");
phosg::fwrite_fmt(stream, " ## => BOOSTS\n");
for (size_t z = 0; z < pmt->num_tech_boosts(); z++) {
const auto& tb = pmt->get_tech_boost(z);
string s;
if (tb.amount1) {
s += std::format("{:02X}:{:02X}:{:g}", tb.tech_num1, tb.flags1, tb.amount1);
}
if (tb.amount2) {
s += std::format("{:02X}:{:02X}:{:g}", tb.tech_num2, tb.flags2, tb.amount2);
}
if (tb.amount3) {
s += std::format("{:02X}:{:02X}:{:g}", tb.tech_num3, tb.flags3, tb.amount3);
}
phosg::fwrite_fmt(stream, " {:02X} => {}\n", z, s);
}
phosg::fwrite_fmt(stream, "UNSEALABLE ITEMS\n");
phosg::fwrite_fmt(stream, " -ITEM- NAME\n");
std::vector<uint32_t> unsealable_items;
for (uint32_t item_code : pmt->all_unsealable_items()) {
unsealable_items.emplace_back(item_code);
}
std::sort(unsealable_items.begin(), unsealable_items.end());
for (uint32_t item_code : unsealable_items) {
ItemData item;
item.data1[0] = item_code >> 16;
item.data1[1] = item_code >> 8;
item.data1[2] = item_code;
string name = this->describe_item(item);
phosg::fwrite_fmt(stream, " {:06X} {}\n", item_code, name);
}
phosg::fwrite_fmt(stream, "RANGED SPECIALS\n");
phosg::fwrite_fmt(stream, " ## => 11 12 WR A1\n");
for (size_t z = 0; z < pmt->num_ranged_specials(); z++) {
const auto& rs = pmt->get_ranged_special(z);
phosg::fwrite_fmt(stream, " {:02X} => {:02X} {:02X} {:02X} {:02X}\n",
z, rs.data1_1, rs.data1_2, rs.weapon_range_index, rs.unknown_a1);
}
}
+3194 -1088
View File
File diff suppressed because it is too large Load Diff
+356 -621
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -46,18 +46,18 @@ ItemTranslationTable::ItemTranslationTable(
uint32_t e_id = this->entries[z].id_for_version[v_s];
if (is_canonical(e_id)) {
if (!entry_index.count(e_id)) {
throw logic_error(std::format("(row {} version {}) canonical ID {:X} is missing from the index", z, phosg::name_for_enum(v), e_id));
throw logic_error(std::format("(row {} version {}) canonical ID {:08X} is missing from the index", z, phosg::name_for_enum(v), e_id));
}
try {
item_parameter_table->definition_for_primary_identifier(e_id);
} catch (const out_of_range&) {
throw runtime_error(std::format("(row {} version {}) ID {:X} not defined in item parameter table", z, phosg::name_for_enum(v), e_id));
throw runtime_error(std::format("(row {} version {}) ID {:08X} not defined in item parameter table", z, phosg::name_for_enum(v), e_id));
}
if (!remaining_identifiers.erase(e_id)) {
throw runtime_error(std::format("(row {} version {}) ID {:X} not in item parameter table's primary identifier list", z, phosg::name_for_enum(v), e_id));
throw runtime_error(std::format("(row {} version {}) ID {:08X} not in item parameter table's primary identifier list", z, phosg::name_for_enum(v), e_id));
}
} else if (!entry_index.count(make_canonical(e_id))) {
throw runtime_error(std::format("(row {} version {}) ID {:X} refers to nonexistent canonical ID", z, phosg::name_for_enum(v), e_id));
throw runtime_error(std::format("(row {} version {}) ID {:08X} refers to nonexistent canonical ID", z, phosg::name_for_enum(v), e_id));
}
}
+23 -46
View File
@@ -9,9 +9,8 @@ using namespace std;
void player_use_item(shared_ptr<Client> c, size_t item_index, shared_ptr<RandomGenerator> rand_crypt) {
auto s = c->require_server_state();
// On PC (and presumably DC), the client sends a 6x29 after this to delete the
// used item. On GC and later versions, this does not happen, so we should
// delete the item here.
// On PC (and presumably DC), the client sends a 6x29 after this to delete the used item. On GC and later versions,
// this does not happen, so we should delete the item here.
bool is_v4 = ::is_v4(c->version());
bool is_v3_or_later = is_v3(c->version()) || is_v4;
bool should_delete_item = is_v3_or_later;
@@ -37,8 +36,7 @@ void player_use_item(shared_ptr<Client> c, size_t item_index, shared_ptr<RandomG
}
auto& weapon = player->inventory.items[player->inventory.find_equipped_item(EquipSlot::WEAPON)];
// Only enforce grind limits on BB, since the server doesn't have direct
// control over players' inventories on other versions
// Only enforce grind limits on BB, since the server doesn't have direct control over inventories on other versions
auto item_parameter_table = s->item_parameter_table(c->version());
auto weapon_def = item_parameter_table->get_weapon(weapon.data.data1[1], weapon.data.data1[2]);
if (is_v4 && (weapon.data.data1[3] >= weapon_def.max_grind)) {
@@ -77,8 +75,6 @@ void player_use_item(shared_ptr<Client> c, size_t item_index, shared_ptr<RandomG
case 6: // Hit Material (v1/v2) or Luck Material (v3/v4)
type = Type::LUCK;
if (!is_v3_or_later && (c->version() != Version::GC_NTE)) {
// Hit material doesn't exist on v3/v4, but we'll ignore type anyway
// in this case because track_non_hp_tp_materials is false
p->disp.stats.char_stats.ata += 2;
} else {
p->disp.stats.char_stats.lck += 2;
@@ -137,7 +133,8 @@ void player_use_item(shared_ptr<Client> c, size_t item_index, shared_ptr<RandomG
} else if ((primary_identifier & 0xFFFF0000) == 0x030C0000) { // Non-combo mag cells
auto& mag = player->inventory.items[player->inventory.find_equipped_item(EquipSlot::MAG)];
if (s->mag_evolution_table(c->version())->get_evolution_number(mag.data.data1[1]) < 4) {
uint8_t evolution_number = s->mag_evolution_table(c->version())->get_evolution_number(mag.data.data1[1]);
if (evolution_number < 4) {
switch (item.data.data1[2]) {
case 0x00: // Cell of MAG 502
mag.data.data1[1] = (player->disp.visual.section_id & 1) ? 0x1D : 0x21;
@@ -173,10 +170,9 @@ void player_use_item(shared_ptr<Client> c, size_t item_index, shared_ptr<RandomG
if (sum == 0) {
throw runtime_error("no unwrap results available for event");
}
// TODO: It seems that on non-BB, clients don't synchronize this at all, so
// they could end up thinking the unwrapped item is something completely
// different. (They don't even use a fixed random seed, like for rares;
// they just call rand().) How does this actually work on console PSO?
// TODO: It seems that on non-BB, clients don't synchronize this at all, so they could end up thinking the
// unwrapped item is something completely different. (They don't even use a fixed random seed, like for rares; they
// just call rand().) How does this actually work on console PSO?
size_t det = rand_crypt->next() % sum;
for (size_t z = 0; z < table.second; z++) {
const auto& entry = table.first[z];
@@ -264,8 +260,8 @@ void player_use_item(shared_ptr<Client> c, size_t item_index, shared_ptr<RandomG
}
if (should_delete_item) {
// Allow overdrafting meseta if the client is not BB, since the server isn't
// informed when meseta is added or removed from the bank.
// Allow overdrafting meseta if the client is not BB, since the server isn't informed when meseta is added or
// removed from the bank.
player->remove_item(item.data.id, 1, *s->item_stack_limits(c->version()));
}
}
@@ -323,8 +319,8 @@ void apply_mag_feed_result(
uint8_t evolution_number = mag_evolution_table->get_evolution_number(mag_item.data1[1]);
uint8_t mag_number = mag_item.data1[1];
// Note: Sega really did just hardcode all these rules into the client. There
// is no data file describing these evolutions, unfortunately.
// Note: Sega really did just hardcode all these rules into the client. There is no data file describing these
// evolutions, unfortunately.
if (mag_level < 10) {
// Nothing to do
@@ -408,9 +404,8 @@ void apply_mag_feed_result(
throw logic_error("char class is not any of the top-level classes");
}
// Note: The original code checks the class (hunter/ranger/force) again
// here, and goes into 3 branches that each do these same checks.
// However, the result of all 3 branches is exactly the same!
// Note: The original code checks the class (hunter/ranger/force) again here, and goes into 3 branches that
// each do these same checks. However, the result of all 3 branches is exactly the same!
if (((section_id_group == 0) && (pow + mind == def + dex)) ||
((section_id_group == 1) && (pow + dex == mind + def)) ||
((section_id_group == 2) && (pow + def == mind + dex))) {
@@ -443,54 +438,36 @@ void apply_mag_feed_result(
if (is_hunter) {
if (flags & 0x108) {
mag_item.data1[1] = (section_id & 1)
? ((dex < mind) ? 0x08 : 0x06)
: ((dex < mind) ? 0x0C : 0x05);
mag_item.data1[1] = (section_id & 1) ? ((dex < mind) ? 0x08 : 0x06) : ((dex < mind) ? 0x0C : 0x05);
} else if (flags & 0x010) {
mag_item.data1[1] = (section_id & 1)
? ((mind < pow) ? 0x12 : 0x10)
: ((mind < pow) ? 0x17 : 0x13);
mag_item.data1[1] = (section_id & 1) ? ((mind < pow) ? 0x12 : 0x10) : ((mind < pow) ? 0x17 : 0x13);
} else if (flags & 0x020) {
mag_item.data1[1] = (section_id & 1)
? ((pow < dex) ? 0x16 : 0x24)
: ((pow < dex) ? 0x07 : 0x1E);
mag_item.data1[1] = (section_id & 1) ? ((pow < dex) ? 0x16 : 0x24) : ((pow < dex) ? 0x07 : 0x1E);
}
} else if (is_ranger) {
if (flags & 0x110) {
mag_item.data1[1] = (section_id & 1)
? ((mind < pow) ? 0x0A : 0x05)
: ((mind < pow) ? 0x0C : 0x06);
mag_item.data1[1] = (section_id & 1) ? ((mind < pow) ? 0x0A : 0x05) : ((mind < pow) ? 0x0C : 0x06);
} else if (flags & 0x008) {
mag_item.data1[1] = (section_id & 1)
? ((dex < mind) ? 0x0A : 0x26)
: ((dex < mind) ? 0x0C : 0x06);
mag_item.data1[1] = (section_id & 1) ? ((dex < mind) ? 0x0A : 0x26) : ((dex < mind) ? 0x0C : 0x06);
} else if (flags & 0x020) {
mag_item.data1[1] = (section_id & 1)
? ((pow < dex) ? 0x18 : 0x1E)
: ((pow < dex) ? 0x08 : 0x05);
mag_item.data1[1] = (section_id & 1) ? ((pow < dex) ? 0x18 : 0x1E) : ((pow < dex) ? 0x08 : 0x05);
}
} else if (is_force) {
if (flags & 0x120) {
if (def < 45) {
mag_item.data1[1] = (section_id & 1)
? ((pow < dex) ? 0x17 : 0x09)
: ((pow < dex) ? 0x1E : 0x1C);
mag_item.data1[1] = (section_id & 1) ? ((pow < dex) ? 0x17 : 0x09) : ((pow < dex) ? 0x1E : 0x1C);
} else {
mag_item.data1[1] = 0x24;
}
} else if (flags & 0x008) {
if (def < 45) {
mag_item.data1[1] = (section_id & 1)
? ((dex < mind) ? 0x1C : 0x20)
: ((dex < mind) ? 0x1F : 0x25);
mag_item.data1[1] = (section_id & 1) ? ((dex < mind) ? 0x1C : 0x20) : ((dex < mind) ? 0x1F : 0x25);
} else {
mag_item.data1[1] = 0x23;
}
} else if (flags & 0x010) {
if (def < 45) {
mag_item.data1[1] = (section_id & 1)
? ((mind < pow) ? 0x12 : 0x0C)
: ((mind < pow) ? 0x15 : 0x11);
mag_item.data1[1] = (section_id & 1) ? ((mind < pow) ? 0x12 : 0x0C) : ((mind < pow) ? 0x15 : 0x11);
} else {
mag_item.data1[1] = 0x24;
}
+5 -6
View File
@@ -19,24 +19,23 @@ void LevelTable::reset_to_base(PlayerStats& stats, uint8_t char_class) const {
void LevelTable::advance_to_level(PlayerStats& stats, uint32_t level, uint8_t char_class) const {
for (; stats.level < level; stats.level++) {
const auto& level_stats = this->stats_delta_for_level(char_class, stats.level + 1);
// The original code clamps the resulting stat values to [0, max_stat]; we
// don't have max_stat handy so we just allow them to be unbounded
// The original code clamps the resulting stat values to [0, max_stat]; we don't have max_stat handy so we just
// allow them to be unbounded
stats.char_stats.atp += level_stats.atp;
stats.char_stats.mst += level_stats.mst;
stats.char_stats.evp += level_stats.evp;
stats.char_stats.hp += level_stats.hp;
stats.char_stats.dfp += level_stats.dfp;
stats.char_stats.ata += level_stats.ata;
// Note: It is not a bug that lck is ignored here; the original code
// ignores it too.
// Note: It is not a bug that lck is ignored here; the original code ignores it too.
stats.experience = level_stats.experience;
}
}
LevelTableV2::LevelTableV2(const string& data, bool compressed) {
struct Offsets {
// TODO: The overall format of this file on V2 has much more data than we
// actually use. What's known of the structure so far:
// TODO: The overall format of this file on V2 has much more data than we actually use. What's known of the
// structure so far:
le_uint32_t level_deltas; // (5468) -> u32[9] -> LevelStatsDelta[200]
le_uint32_t unknown_a1; // (548C) -> float[6]
le_uint32_t max_stats; // (54A4) -> PlayerStats[9]
+12 -20
View File
@@ -33,39 +33,35 @@ struct CharacterStatsT {
ret.lck = this->lck;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(CharacterStatsT, 0x0E);
using CharacterStats = CharacterStatsT<false>;
using CharacterStatsBE = CharacterStatsT<true>;
check_struct_size(CharacterStats, 0x0E);
check_struct_size(CharacterStatsBE, 0x0E);
template <bool BE>
struct PlayerStatsT {
/* 00 */ CharacterStatsT<BE> char_stats;
/* 0E */ U16T<BE> esp = 0;
/* 10 */ F32T<BE> height = 0.0;
/* 14 */ F32T<BE> unknown_a3 = 0.0;
/* 18 */ U32T<BE> level = 0;
/* 10 */ F32T<BE> attack_range = 0.0;
/* 14 */ F32T<BE> knockback_range = 0.0;
/* 18 */ U32T<BE> level = 0; // Qedit specifies this as tech level when used for enemies
/* 1C */ U32T<BE> experience = 0;
/* 20 */ U32T<BE> meseta = 0;
/* 20 */ U32T<BE> meseta = 0; // Qedit specifies this as TP when used for enemies
/* 24 */
operator PlayerStatsT<!BE>() const {
PlayerStatsT<!BE> ret;
ret.char_stats = this->char_stats;
ret.esp = this->esp;
ret.height = this->height;
ret.unknown_a3 = this->unknown_a3;
ret.attack_range = this->attack_range;
ret.knockback_range = this->knockback_range;
ret.level = this->level;
ret.experience = this->experience;
ret.meseta = this->meseta;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(PlayerStatsT, 0x24);
using PlayerStats = PlayerStatsT<false>;
using PlayerStatsBE = PlayerStatsT<true>;
check_struct_size(PlayerStats, 0x24);
check_struct_size(PlayerStatsBE, 0x24);
template <bool BE>
struct LevelStatsDeltaT {
@@ -89,18 +85,14 @@ struct LevelStatsDeltaT {
ps.mst += this->mst;
ps.lck += this->lck;
}
} __attribute__((packed));
} __packed_ws_be__(LevelStatsDeltaT, 0x0C);
using LevelStatsDelta = LevelStatsDeltaT<false>;
using LevelStatsDeltaBE = LevelStatsDeltaT<true>;
check_struct_size(LevelStatsDelta, 0x0C);
check_struct_size(LevelStatsDeltaBE, 0x0C);
class LevelTable {
// This is the base class for all the LevelTable implementations. The public
// interface here only defines functions that the server needs to handle
// requests, but some subclasses implement more functionality. See the
// comments and Offsets structures inside the subclasses' constructor
// implementations for more details on the file formats.
// This is the base class for all the LevelTable implementations. The public interface here only defines functions
// that the server needs to handle requests, but some subclasses implement more functionality. See the comments and
// Offsets structures inside the subclasses' constructor implementations for more details on the file formats.
public:
virtual ~LevelTable() = default;
virtual const CharacterStats& base_stats_for_class(uint8_t char_class) const = 0;
+66 -33
View File
@@ -145,6 +145,7 @@ uint32_t Lobby::FloorItemManager::reassign_all_item_ids(uint32_t next_item_id) {
Lobby::Lobby(shared_ptr<ServerState> s, uint32_t id, bool is_game)
: server_state(s),
log(std::format("[{}:{:X}] ", is_game ? "Game" : "Lobby", id), lobby_log.min_level),
creation_time(phosg::now()),
lobby_id(id),
random_seed(phosg::random_object<uint32_t>()),
rand_crypt(make_shared<DisabledRandomGenerator>()),
@@ -171,10 +172,10 @@ void Lobby::reset_next_item_ids() {
uint8_t Lobby::area_for_floor(Version version, uint8_t floor) const {
if (this->quest) {
return this->quest->meta.area_for_floor.at(floor);
return this->quest->meta.floor_assignments.at(floor).area;
}
auto sdt = this->require_server_state()->set_data_table(version, this->episode, this->mode, this->difficulty);
return sdt->default_area_for_floor(this->episode, floor);
return sdt->default_floor_to_area(this->episode).at(floor);
}
shared_ptr<ServerState> Lobby::require_server_state() const {
@@ -224,12 +225,19 @@ void Lobby::create_item_creator(Version logic_version) {
s->tekker_adjustment_set,
s->item_parameter_table(logic_version),
s->item_stack_limits(logic_version),
this->episode,
(this->mode == GameMode::SOLO) ? GameMode::NORMAL : this->mode,
this->difficulty,
effective_section_id,
rand_crypt,
this->quest ? this->quest->meta.battle_rules : nullptr);
if (this->blueballz_tier >= 0) {
double rare_mult = 1.25 + (static_cast<double>(this->blueballz_tier) * 0.25);
this->item_creator->set_rare_drop_rate_multiplier(rare_mult);
this->log.info_f("Blueballz +{} rare drop rate multiplier set to {:g}x", this->blueballz_tier, rare_mult);
}
if (s->use_legacy_item_random_behavior) {
this->item_creator->set_legacy_replay();
}
}
uint8_t Lobby::effective_section_id() const {
@@ -331,6 +339,12 @@ void Lobby::reassign_leader_on_client_departure(size_t leaving_client_index) {
}
if (this->clients[x]) {
this->leader_id = x;
// PSO GC's behavior is to reload the ItemPT and ItemRT tables only when the player returns to the city (Pioneer
// 2 or Lab). This means the game's effective section ID should only change after the new leader is assigned, and
// that new leader returns to the city. On BB, however, there is no evidence that this behavior was preserved;
// it's more likely that Sega's server either switched drop tables instantly when the leader changed, or never
// switched drop tables after game creation. We implement both of these behaviors (via the USE_CREATOR_SECTION_ID
// lobby flag), and we intentionally don't implement the more complex pre-BB behavior.
this->create_item_creator();
return;
}
@@ -425,8 +439,7 @@ void Lobby::add_client(shared_ptr<Client> c, ssize_t required_client_id) {
this->create_item_creator();
}
// If this is a lobby or no one was here before this, reassign all the floor
// item IDs and reset the next item IDs
// If this is a lobby or no one was here before this, reassign all the floor item IDs and reset the next item IDs
if (!this->is_game() || (leader_index >= this->max_clients)) {
this->reset_next_item_ids();
for (auto& m : this->floor_item_managers) {
@@ -434,19 +447,15 @@ void Lobby::add_client(shared_ptr<Client> c, ssize_t required_client_id) {
}
}
// If this is not a game or the joining client is the leader, they will assign
// their item IDs BEFORE they process any inbound commands (therefore a 6x6D
// command, which we will send during loading, should reflect the item state
// AFTER their IDs are assigned). If the joining client is not the leader,
// they will not assign their item IDs until they receive a 6x71 command,
// which is sent AFTER the 6x6D command, so the 6x6D should reflect the item
// state BEFORE their IDs are assigned. (In the latter case, we'll assign the
// IDs for real when they send a 6F command, or 6x1F equivalent in the case of
// DC NTE and 11/2000.)
// If this is not a game or the joining client is the leader, they will assign their item IDs BEFORE they process any
// inbound commands (therefore a 6x6D command, which we will send during loading, should reflect the item state AFTER
// their IDs are assigned). If the joining client is not the leader, they will not assign their item IDs until they
// receive a 6x71 command, which is sent AFTER the 6x6D command, so the 6x6D should reflect the item state BEFORE
// their IDs are assigned. (In the latter case, we'll assign the IDs for real when they send a 6F command, or 6x1F
// equivalent in the case of DC NTE and 11/2000.)
this->assign_inventory_and_bank_item_ids(c, (!this->is_game() || (c->lobby_client_id == this->leader_id)));
// On BB, we send artificial flag state to fix an Episode 2 bug where the
// CCA door lock state is overwritten by quests.
// On BB, we send flag state to fix an Episode 2 bug where the CCA door lock state is overwritten by quests.
if (this->is_game() && (c->version() == Version::BB_V4)) {
c->set_flag(Client::Flag::SHOULD_SEND_ARTIFICIAL_FLAG_STATE);
}
@@ -493,9 +502,8 @@ void Lobby::remove_client(shared_ptr<Client> c) {
}
this->clients[c->lobby_client_id] = nullptr;
// Unassign the client's lobby if it matches the current lobby (it may not
// match if the client was already added to another lobby - this can happen
// during the lobby change procedure)
// Unassign the client's lobby if it matches the current lobby (it may not match if the client was already added to
// another lobby - this can happen during the lobby change procedure)
{
auto c_lobby = c->lobby.lock();
if (c_lobby.get() == this) {
@@ -522,9 +530,8 @@ void Lobby::remove_client(shared_ptr<Client> c) {
}
}
// If there are still players left in the lobby, delete all items that only
// the leaving player could see. Don't do this if no one is left in the lobby,
// since that would mean items could not persist in empty lobbies.
// If there are still players left in the lobby, delete all items that only the leaving player could see. Don't do
// this if no one is left in the lobby, since that would mean items could not persist in empty lobbies.
uint16_t remaining_clients_mask = 0;
for (size_t z = 0; z < 12; z++) {
if (this->clients[z]) {
@@ -545,8 +552,7 @@ void Lobby::remove_client(shared_ptr<Client> c) {
this->check_flag(Flag::PERSISTENT) &&
!this->check_flag(Flag::DEFAULT) &&
(this->idle_timeout_usecs > 0)) {
// If the lobby is persistent but has an idle timeout, make it expire after
// the specified time
// If the lobby is persistent but has an idle timeout, make it expire after the specified time
this->idle_timeout_timer.expires_after(std::chrono::microseconds(this->idle_timeout_usecs));
this->idle_timeout_timer.async_wait([this](std::error_code ec) {
if (!ec) {
@@ -562,10 +568,7 @@ void Lobby::remove_client(shared_ptr<Client> c) {
}
}
void Lobby::move_client_to_lobby(
shared_ptr<Lobby> dest_lobby,
shared_ptr<Client> c,
ssize_t required_client_id) {
void Lobby::move_client_to_lobby(shared_ptr<Lobby> dest_lobby, shared_ptr<Client> c, ssize_t required_client_id) {
if (dest_lobby.get() == this) {
return;
}
@@ -649,8 +652,7 @@ Lobby::JoinError Lobby::join_error_for_client(std::shared_ptr<Client> c, const s
}
}
}
// Only prevent joining during loading if the client is actually trying to
// join (not just loading the game list)
// Only prevent joining during loading if the client is actually trying to join (not just loading the game list)
if (password && this->any_client_loading()) {
return JoinError::LOADING;
}
@@ -715,9 +717,8 @@ uint32_t Lobby::generate_item_id(uint8_t client_id) {
}
void Lobby::on_item_id_generated_externally(uint32_t item_id) {
// Note: The client checks for the range (0x00010000, 0x02010000) here, but
// server-side item drop logic uses 0x00810000 as its base ID, so we restrict
// the range further here.
// Note: The client checks for the range (0x00010000, 0x02010000) here, but server-side item drop logic uses
// 0x00810000 as its base ID, so we restrict the range further here.
if ((item_id > 0x00010000) && (item_id < 0x00810000)) {
uint16_t item_client_id = (item_id >> 21) & 0x7FF;
uint32_t& next_item_id = this->next_item_id_for_client.at(item_client_id);
@@ -839,3 +840,35 @@ bool Lobby::compare_shared(const shared_ptr<const Lobby>& a, const shared_ptr<co
return a->name < b->name;
}
template <>
const char* phosg::name_for_enum<Lobby::JoinError>(Lobby::JoinError value) {
switch (value) {
case Lobby::JoinError::ALLOWED:
return "ALLOWED";
case Lobby::JoinError::FULL:
return "FULL";
case Lobby::JoinError::VERSION_CONFLICT:
return "VERSION_CONFLICT";
case Lobby::JoinError::QUEST_SELECTION_IN_PROGRESS:
return "QUEST_SELECTION_IN_PROGRESS";
case Lobby::JoinError::QUEST_IN_PROGRESS:
return "QUEST_IN_PROGRESS";
case Lobby::JoinError::BATTLE_IN_PROGRESS:
return "BATTLE_IN_PROGRESS";
case Lobby::JoinError::LOADING:
return "LOADING";
case Lobby::JoinError::SOLO:
return "SOLO";
case Lobby::JoinError::INCORRECT_PASSWORD:
return "INCORRECT_PASSWORD";
case Lobby::JoinError::LEVEL_TOO_LOW:
return "LEVEL_TOO_LOW";
case Lobby::JoinError::LEVEL_TOO_HIGH:
return "LEVEL_TOO_HIGH";
case Lobby::JoinError::NO_ACCESS_TO_QUEST:
return "NO_ACCESS_TO_QUEST";
default:
throw runtime_error("invalid drop mode");
}
}
+21 -28
View File
@@ -30,12 +30,10 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
// At most one of the following will be non-null
std::shared_ptr<const MapState::ObjectState> from_obj;
std::shared_ptr<const MapState::EnemyState> from_ene;
// The low 12 bits of flags are visibility flags, specifying which clients
// can see the item. (In practice, only the lowest 4 of these bits are used,
// but the game has fields for 12 players so we do too.)
// The 13th bit (0x1000) specifies whether a rare item notification should
// be sent to all players when the item is picked up. This has no effect for
// non-rare items.
// The low 12 bits of flags are visibility flags, specifying which clients can see the item. (In practice, only the
// lowest 4 of these bits are used, but the game has fields for 12 players so we do too.) The 13th bit (0x1000)
// specifies whether a rare item notification should be sent to all players when the item is picked up. This has no
// effect for non-rare items.
uint16_t flags;
bool visible_to_client(uint8_t client_id) const;
@@ -43,8 +41,7 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
struct FloorItemManager {
phosg::PrefixedLogger log;
uint64_t next_drop_number;
// It's important that this is a map and not an unordered_map. See the
// comment in send_game_item_state for more details.
// It's important that this is a map and not an unordered_map. See the comment in send_game_item_state for details.
std::map<uint32_t, std::shared_ptr<FloorItem>> items; // Keyed on item_id
std::array<std::map<uint64_t, std::shared_ptr<FloorItem>>, 12> queue_for_client;
@@ -84,6 +81,7 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
START_BATTLE_PLAYER_IMMEDIATELY = 0x00010000,
CANNOT_CHANGE_CHEAT_MODE = 0x00020000,
USE_CREATOR_SECTION_ID = 0x00040000,
BLUEBALLZ_PLUS0 = 0x00080000,
// Flags used only for lobbies
PUBLIC = 0x01000000,
DEFAULT = 0x02000000,
@@ -94,6 +92,8 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
std::weak_ptr<ServerState> server_state;
phosg::PrefixedLogger log;
uint64_t creation_time;
uint32_t lobby_id;
uint32_t min_level = 0;
@@ -111,15 +111,15 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
std::unique_ptr<SwitchFlags> switch_flags;
// Game config
// Bits in allowed_versions specify who is allowed to join this game. The
// bits are indexed as (1 << version), where version is a value from the
// Version enum.
// Bits in allowed_versions specify who is allowed to join this game. The bits are indexed as (1 << version), where
// version is a value from the Version enum.
uint16_t allowed_versions = 0x0000;
uint8_t creator_section_id = 0xFF;
uint8_t override_section_id = 0xFF;
Episode episode = Episode::NONE;
GameMode mode = GameMode::NORMAL;
Difficulty difficulty = Difficulty::NORMAL;
int8_t blueballz_tier = -1; // -1 = disabled; 0..10 = Blueballz +0..+10
float base_exp_multiplier = 1.0f;
float exp_share_multiplier = 0.5f;
float challenge_exp_multiplier = 1.0f;
@@ -145,16 +145,14 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
std::shared_ptr<ChallengeParameters> challenge_params;
// Ep3 stuff
// There are three kinds of Episode 3 games. All of these types have episode
// set to EP3; types 2 and 3 additionally have the IS_SPECTATOR_TEAM flag.
// There are three kinds of Episode 3 games. All of these types have episode set to EP3; types 2 and 3 additionally
// have the IS_SPECTATOR_TEAM flag.
// 1. Primary games. These are the lobbies where battles may take place.
// 2. Watcher games. These lobbies receive all the battle and chat commands
// from a primary game. (This the implementation of spectator teams.)
// 3. Replay games. These lobbies replay a sequence of battle commands and
// chat commands from a previous primary game.
// Types 2 and 3 may be distinguished by the presence of the battle_record
// field - in replay games, it will be present; in watcher games it will be
// absent.
// 2. Watcher games. These lobbies receive all the battle and chat commands from a primary game. (This the
// implementation of spectator teams.)
// 3. Replay games. These lobbies replay a sequence of battle and chat commands from a previous primary game.
// Types 2 and 3 are distinguished by the presence of the battle_record field - in replay games, it will be present;
// in watcher games it will be absent.
std::shared_ptr<Episode3::Server> ep3_server; // Only used in primary games
std::weak_ptr<Lobby> watched_lobby; // Only used in watcher games
std::unordered_set<std::shared_ptr<Lobby>> watcher_lobbies; // Only used in primary games
@@ -174,8 +172,7 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
// Keys in this map are client_id
std::unordered_map<size_t, std::weak_ptr<Client>> clients_to_add;
// This is only used when the PERSISTENT flag is set and idle_timeout_usecs
// is not zero
// This is only used when the PERSISTENT flag is set and idle_timeout_usecs is not zero
uint64_t idle_timeout_usecs = 0;
asio::steady_timer idle_timeout_timer;
@@ -239,9 +236,7 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
void remove_client(std::shared_ptr<Client> c);
void move_client_to_lobby(
std::shared_ptr<Lobby> dest_lobby,
std::shared_ptr<Client> c,
ssize_t required_client_id = -1);
std::shared_ptr<Lobby> dest_lobby, std::shared_ptr<Client> c, ssize_t required_client_id = -1);
std::shared_ptr<Client> find_client(const std::string* identifier = nullptr, uint64_t account_id = 0);
@@ -286,6 +281,4 @@ struct Lobby : public std::enable_shared_from_this<Lobby> {
};
template <>
ServerDropMode phosg::enum_for_name<ServerDropMode>(const char* name);
template <>
const char* phosg::name_for_enum<ServerDropMode>(ServerDropMode value);
const char* phosg::name_for_enum<Lobby::JoinError>(Lobby::JoinError value);
+170
View File
@@ -0,0 +1,170 @@
#include "MagEvolutionTable.hh"
#include "CommonFileFormats.hh"
using namespace std;
struct MotionReference {
struct Side {
// This specifies which entry in ItemMagMotion.dat is used. The file is just a list of 0x64-byte structures.
// 0xFF = no TItemMagSub is created
uint8_t motion_table_entry = 0xFF;
parray<uint8_t, 5> unknown_a1 = 0;
} __packed_ws__(Side, 0x06);
parray<Side, 2> sides; // [0] = right side, [1] = left side
} __packed_ws__(MotionReference, 0x0C);
template <bool BE>
struct MotionReferenceTables {
// It seems that there are two definition tables, but only the first is used on any version of PSO. On v3 and later,
// the two offsets point to the same table, but on v2 they don't and the second table contains different data.
// TODO: Figure out what the deal is with the different v2 tables.
U32T<BE> ref_table; // -> MotionReference[num_mags]
U32T<BE> unused_ref_table; // -> MotionReference[num_mags]
} __packed_ws_be__(MotionReferenceTables, 0x08);
template <bool BE>
struct ColorEntry {
// Colors are specified as 4 floats, each in the range [0, 1], for each color channel. The default colors are:
// alpha red green blue color (see StaticGameData.cc)
// 1.0 1.0 0.2 0.1 red
// 1.0 0.2 0.2 1.0 blue
// 1.0 1.0 0.9 0.1 yellow
// 1.0 0.1 1.0 0.1 green
// 1.0 0.8 0.1 1.0 purple
// 1.0 0.1 0.1 0.2 black
// 1.0 0.9 1.0 1.0 white
// 1.0 0.1 0.9 1.0 cyan
// 1.0 0.5 0.3 0.2 brown
// 1.0 1.0 0.4 0.0 orange (v3+)
// 1.0 0.502 0.545 0.977 light-blue (v3+)
// 1.0 0.502 0.502 0.0 olive (v3+)
// 1.0 0.0 0.941 0.714 turquoise (v3+)
// 1.0 0.8 0.098 0.392 fuchsia (v3+)
// 1.0 0.498 0.498 0.498 grey (v3+)
// 1.0 0.996 0.996 0.832 cream (v3+)
// 1.0 0.996 0.498 0.784 pink (v3+)
// 1.0 0.0 0.498 0.322 dark-green (v3+)
F32T<BE> alpha;
F32T<BE> red;
F32T<BE> green;
F32T<BE> blue;
} __packed_ws_be__(ColorEntry, 0x10);
template <bool BE>
struct UnknownA3Entry {
uint8_t flags;
uint8_t unknown_a2;
U16T<BE> unknown_a3;
U16T<BE> unknown_a4;
U16T<BE> unknown_a5;
} __packed_ws_be__(UnknownA3Entry, 0x08);
template <bool BE>
struct RootV2V3V4 {
/* -- / 112K / V1 / V2 / V3 / BB */
/* 00 / 0438 / 0438 / 05BC / 0340 / 0400 */ U32T<BE> motion_tables; // -> MotionReferenceTables
/* 04 / 0440 / 0440 / 0594 / 0348 / 0408 */ U32T<BE> unknown_a2; // -> (uint8_t[2])[NumMags] (references into unknown_a3)
/* 08 / 0498 / 0498 / 0608 / 03CE / 04AE */ U32T<BE> unknown_a3; // -> UnknownA3Entry[max(unknown_a2) + 1]
/* 0C / 0510 / 0520 / 06B0 / 0476 / 0556 */ U32T<BE> unknown_a4; // -> uint8_t[NumMags]
/* 10 / 053C / 054C / 06EC / 04BC / 05AC */ U32T<BE> color_table; // -> ColorEntry[NumColors]
/* 14 / / / 077C / 05DC / 06CC */ U32T<BE> evolution_number_table; // -> uint8_t[NumMags]
} __packed_ws_be__(RootV2V3V4, 0x18);
struct RootV1 {
le_uint32_t motion_tables;
le_uint32_t unknown_a2;
le_uint32_t unknown_a3;
le_uint32_t unknown_a4;
le_uint32_t color_table;
} __packed_ws__(RootV1, 0x14);
static uint8_t get_v1_mag_evolution_number(uint8_t data1_1) {
static const std::array<uint8_t, 0x2C> v1_evolution_number_table{
/* 00 */ 0, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 2, 2,
/* 10 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 2, 2, 3, 4, 3, 3,
/* 20 */ 3, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 4};
if (data1_1 >= v1_evolution_number_table.size()) {
throw runtime_error("invalid mag number");
}
return v1_evolution_number_table[data1_1];
}
template <typename RootT, size_t NumMags, size_t NumColors, bool BE>
class MagEvolutionTableT : public MagEvolutionTable {
public:
explicit MagEvolutionTableT(std::shared_ptr<const std::string> data)
: data(data), r(*data), root(&r.pget<RootT>(this->r.pget_u32l(this->data->size() - 0x10))) {}
virtual ~MagEvolutionTableT() = default;
virtual VectorXYZTF get_color_rgba(size_t index) const {
if (index >= NumColors) {
throw runtime_error("invalid mag color index");
}
const auto& color = this->r.pget<ColorEntry<BE>>(this->root->color_table + sizeof(ColorEntry<BE>) * index);
return {color.red.load(), color.green.load(), color.blue.load(), color.alpha.load()};
}
virtual uint8_t get_evolution_number(uint8_t data1_1) const {
if constexpr (requires { this->root->evolution_number_table; }) {
return this->r.pget_u8(this->root->evolution_number_table + data1_1);
} else {
return get_v1_mag_evolution_number(data1_1);
}
}
protected:
std::shared_ptr<const std::string> data;
phosg::StringReader r;
const RootT* root;
};
class MagEvolutionTableDCNTE : public MagEvolutionTable {
public:
MagEvolutionTableDCNTE() = default;
virtual ~MagEvolutionTableDCNTE() = default;
virtual VectorXYZTF get_color_rgba(size_t) const {
throw runtime_error("mag colors not available on DC NTE");
}
virtual uint8_t get_evolution_number(uint8_t data1_1) const {
return get_v1_mag_evolution_number(data1_1);
}
};
using MagEvolutionTableDC112000 = MagEvolutionTableT<RootV2V3V4<false>, 0x28, 0x09, false>;
using MagEvolutionTableV1 = MagEvolutionTableT<RootV2V3V4<false>, 0x28, 0x09, false>;
using MagEvolutionTableV2 = MagEvolutionTableT<RootV2V3V4<false>, 0x3A, 0x09, false>;
using MagEvolutionTableGCNTE = MagEvolutionTableT<RootV2V3V4<true>, 0x3A, 0x09, true>;
using MagEvolutionTableGC = MagEvolutionTableT<RootV2V3V4<true>, 0x43, 0x12, true>;
using MagEvolutionTableXB = MagEvolutionTableT<RootV2V3V4<false>, 0x43, 0x12, false>;
using MagEvolutionTableV4 = MagEvolutionTableT<RootV2V3V4<false>, 0x53, 0x12, false>;
std::shared_ptr<MagEvolutionTable> MagEvolutionTable::create(
std::shared_ptr<const std::string> data, Version version) {
switch (version) {
case Version::DC_NTE:
return std::make_shared<MagEvolutionTableDCNTE>();
case Version::DC_11_2000:
return std::make_shared<MagEvolutionTableDC112000>(data);
case Version::DC_V1:
return std::make_shared<MagEvolutionTableV1>(data);
case Version::DC_V2:
case Version::PC_NTE:
case Version::PC_V2:
return std::make_shared<MagEvolutionTableV2>(data);
case Version::GC_NTE:
return std::make_shared<MagEvolutionTableGCNTE>(data);
case Version::GC_V3:
case Version::GC_EP3:
case Version::GC_EP3_NTE:
return std::make_shared<MagEvolutionTableGC>(data);
case Version::XB_V3:
return std::make_shared<MagEvolutionTableXB>(data);
case Version::BB_V4:
return std::make_shared<MagEvolutionTableV4>(data);
default:
throw std::logic_error("Cannot create mag evolution table for this version");
}
}
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include "WindowsPlatform.hh"
#include <stdint.h>
#include <memory>
#include <string>
#include "CommonFileFormats.hh"
#include "Text.hh"
#include "Types.hh"
#include "Version.hh"
class MagEvolutionTable {
public:
virtual ~MagEvolutionTable() = default;
static std::shared_ptr<MagEvolutionTable> create(std::shared_ptr<const std::string> data, Version version);
virtual VectorXYZTF get_color_rgba(size_t index) const = 0;
virtual uint8_t get_evolution_number(uint8_t data1_1) const = 0;
protected:
MagEvolutionTable() = default;
};
+635 -203
View File
File diff suppressed because it is too large Load Diff
+1119 -1074
View File
File diff suppressed because it is too large Load Diff
+129 -77
View File
@@ -16,7 +16,7 @@
#include "StaticGameData.hh"
#include "Text.hh"
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Game structures (used in 6x6B/6x6C/6x6E handlers, and here)
struct SyncEnemyStateEntry {
@@ -34,7 +34,7 @@ struct SyncObjectStateEntry {
le_uint16_t item_drop_id = 0;
} __packed_ws__(SyncObjectStateEntry, 0x04);
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set data table (variations index)
struct Variations {
@@ -67,8 +67,8 @@ public:
std::vector<std::string> map_filenames_for_variations(
Episode episode, GameMode mode, const Variations& variations, FilenameType type) const;
static uint8_t default_area_for_floor(Version version, Episode episode, uint8_t floor);
uint8_t default_area_for_floor(Episode episode, uint8_t floor) const;
static std::array<uint8_t, 0x12> default_floor_to_area(Version version, Episode episode);
std::array<uint8_t, 0x12> default_floor_to_area(Episode episode) const;
protected:
explicit SetDataTableBase(Version version);
@@ -98,8 +98,7 @@ private:
template <bool BE>
void load_table_t(const std::string& data);
// Indexes are [floor][variation1][variation2]
// floor is cumulative per episode, so Ep2 starts at floor=18.
// Indexes are [floor][variation1][variation2]; floor is cumulative per episode, so Ep2 starts at floor=18.
std::vector<std::vector<std::vector<SetEntry>>> entries;
};
@@ -131,12 +130,10 @@ private:
static const std::array<std::vector<std::vector<std::string>>, 0x12> NAMES;
};
////////////////////////////////////////////////////////////////////////////////
// Map (DAT) file parser. This class is responsible for parsing individual
// quest DAT files, or up to three individual free-play DAT files (object sets,
// enemy sets, and events, each of which are optional). In the free-play case,
// the MapFile represents entities for a single floor; in the quest case, it
// represents the lists for all floors.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Map (DAT) file parser. This class is responsible for parsing individual quest DAT files, or up to three individual
// free-play DAT files (object sets, enemy sets, and events, each of which are optional). In the free-play case, the
// MapFile represents entities for a single floor; in the quest case, it represents the lists for all floors.
class MapFile : public std::enable_shared_from_this<MapFile> {
public:
@@ -171,14 +168,12 @@ public:
/* 0A */ le_uint16_t group = 0;
/* 0C */ le_uint16_t room = 0;
/* 0E */ le_uint16_t unknown_a3 = 0;
// The position is relative to the room in which the object is placed; to
// get the actual world position, the object's position must be rotated
// around the room's origin by the room's angles, then translated by the
// room's offset. The room's angle and offset can be found in the area's
// n.rel file.
// The position is relative to the room in which the object is placed; to get the actual world position, the
// object's position must be rotated around the room's origin by the room's angles, then translated by the room's
// offset. The room's angle and offset can be found in the area's n.rel file.
/* 10 */ VectorXYZF pos;
// Angles are specified as 16-bit integers, where 0 is no rotation around
// the axis and FFFF is almost a complete counterclockwise rotation.
// Angles are specified as 16-bit integers, where 0 is no rotation around the axis and FFFF is almost a complete
// counterclockwise rotation.
/* 1C */ VectorXYZI angle;
// See notes in dat_object_definitions in Map.cc for how these are used
/* 28 */ le_float param1 = 0.0f;
@@ -198,7 +193,7 @@ public:
/* 00 */ le_uint16_t base_type = 0;
/* 02 */ le_uint16_t set_flags = 0; // Used by PSO at runtime, unused in DAT file
/* 04 */ le_uint16_t index = 0; // Used by PSO at runtime, unused in DAT file
/* 06 */ le_uint16_t num_children = 0; // If == 0, use the default child count from the constructor table (which is often also 0)
/* 06 */ le_uint16_t num_children = 0; // If == 0, use the default child count from the constructor table
/* 08 */ le_uint16_t floor = 0;
/* 0A */ le_uint16_t entity_id = 0; // == index + 0x1000; used by PSO at runtime, unused in DAT file
/* 0C */ le_uint16_t room = 0;
@@ -223,6 +218,9 @@ public:
} __packed_ws__(EnemySetEntry, 0x48);
struct EventsSectionHeader { // Section type 3 (EVENTS)
// The events section has three zones: the header (this structure), the event entries, and the action stream. The
// header specifies where to find each one in the section, and how many entries there are. The offsets here are
// relative to the beginning of the header.
/* 00 */ le_uint32_t action_stream_offset;
/* 04 */ le_uint32_t entries_offset;
/* 08 */ le_uint32_t entry_count;
@@ -235,17 +233,52 @@ public:
} __packed_ws__(EventsSectionHeader, 0x10);
struct Event1Entry { // Section type 3 (EVENTS) if format == 0
// A wave event consists of an event (this struct) and an action stream, which is a short script that runs when all
// enemies in the wave are killed. Generally, events work like this:
// 1. The event is triggered (e.g. via a quest script or trigger object). This sets flag 0004 on the wave event.
// 2. The client constructs a TSetEvtDestroy object, which despite its name, is also responsible for constructing
// enemies. This sets flag 0002 on the wave event. This object waits for the delay specified in this structure
// (in frames), then constructs the wave's enemies.
// 3. The player kills all the enemies.
// 4. The TSetEvtDestroy object sets flag 0010 on the event.
// 5. The TSetEvtDestroy object sets flag 0008 on the event and runs the post-wave actions. (This happens one
// frame after the above.) See the implementation of MapFile::disassemble_action_stream for details on the
// format of post-wave actions. It then clears flag 0004 (but not 0002).
// The event ID identifies this event on the current floor. It is not required that all wave events have unique
// IDs; if multiple events have the same ID, they will all trigger at the same time when any one of them is
// triggered (since wave events can only be triggered by ID).
/* 00 */ le_uint32_t event_id = 0;
// Bits in flags:
// 0004 = is active
// The flags field specifies the state of the event. This field is synced to a joining player as part of the 6x6E
// command during the game loading sequence. Known bits:
// 0002 = wave object constructor has been called (this flag is not synced via 6x6E)
// 0004 = is active (has been triggered)
// 0008 = post-wave actions have been run
// 0010 = all enemies killed
/* 04 */ le_uint16_t flags = 0; // Used by PSO at runtime, unused in DAT file
/* 06 */ le_uint16_t event_type = 0;
/* 04 */ le_uint16_t flags = 0; // Used by PSO at runtime, unused in file
// It seems Sega originally wanted to support multiple types of events, and the event_type field controls which
// constructor is called when the event is triggered by a 6x67 command. It seems they never actually used this
// though; there are only two valid values: 0 makes the event do nothing (no object is constructed at all) and 1
// uses the normal control object described above (TSetEvtDestroy). There is no bounds check here, so any other
// value causes undefined behavior.
/* 06 */ le_uint16_t event_type = 1;
// The room and wave_number fields specify which enemies should be constructed when this event triggers. All
// enemies whose room and wave_number fields match these two fields are constructed at the same time when the event
// triggers (or after the delay below).
/* 08 */ le_uint16_t room = 0;
/* 0A */ le_uint16_t wave_number = 0;
// The delay field specified how long (in frames) to wait after the event's trigger time before constructing all
// the enemies.
/* 0C */ le_uint32_t delay = 0;
// This field specifies where in the action stream data to start running commands for this event, when all enemies
// are defeated. This is relative to the beginning of the action stream, not the events section header.
/* 10 */ le_uint32_t action_stream_offset = 0;
/* 14 */
uint64_t semantic_hash(uint8_t floor) const;
@@ -270,20 +303,26 @@ public:
} __packed_ws__(Event2Entry, 0x18);
struct RandomEnemyLocationsHeader { // Section type 4 (RANDOM_ENEMY_LOCATIONS)
/* 00 */ le_uint32_t room_table_offset; // Offset to RandomEnemyLocationSegment structs, from start of this struct
/* 04 */ le_uint32_t entries_offset; // Offset to RandomEnemyLocationEntry structs, from start of this struct
// The room table specifies which locations are valid for each room, but these are specified indirectly as offsets
// into the entries table (pointed to by entries_offset). The entries in the room table must be sorted in
// increasing order of room_id; if they aren't, the client may fail to find a valid room during enemy placement,
// which can crash the client.
/* 00 */ le_uint32_t room_table_offset; // Offset to RandomEnemyRoom structs, from start of this struct
/* 04 */ le_uint32_t entries_offset; // Offset to RandomEnemyLocation structs, from start of this struct
/* 08 */ le_uint32_t num_rooms;
/* 0C */
} __packed_ws__(RandomEnemyLocationsHeader, 0x0C);
struct RandomEnemyLocationSection { // Section type 4 (RANDOM_ENEMY_LOCATIONS)
/* 00 */ le_uint16_t room;
struct RandomEnemyRoom { // Section type 4 (RANDOM_ENEMY_LOCATIONS)
/* 00 */ le_uint16_t room_id;
/* 02 */ le_uint16_t count;
/* 04 */ le_uint32_t offset;
/* 04 */ le_uint32_t offset; // Bytes from start of RandomEnemyLocation section
/* 08 */
} __packed_ws__(RandomEnemyLocationSection, 8);
struct RandomEnemyLocationEntry { // Section type 4 (RANDOM_ENEMY_LOCATIONS)
std::string str() const;
} __packed_ws__(RandomEnemyRoom, 8);
struct RandomEnemyLocation { // Section type 4 (RANDOM_ENEMY_LOCATIONS)
/* 00 */ VectorXYZF pos;
/* 0C */ VectorXYZI angle;
/* 18 */ le_uint16_t unknown_a9; // TODO: Verify these are actually little-endian
@@ -291,7 +330,7 @@ public:
/* 1C */
std::string str() const;
} __packed_ws__(RandomEnemyLocationEntry, 0x1C);
} __packed_ws__(RandomEnemyLocation, 0x1C);
struct RandomEnemyDefinitionsHeader { // Section type 5 (RANDOM_ENEMY_DEFINITIONS)
/* 00 */ le_uint32_t entries_offset; // Offset to RandomEnemyDefinition structs, from start of this struct
@@ -302,8 +341,8 @@ public:
} __packed_ws__(RandomEnemyDefinitionsHeader, 0x10);
struct RandomEnemyDefinition { // Section type 5 (RANDOM_ENEMY_DEFINITIONS)
// All fields through entry_num map to the corresponding fields in
// EnemySetEntry. Note that the order of param6 and param7 is switched!
// All fields through entry_index map to the corresponding fields in EnemySetEntry. Note that the order of param6
// and param7 is switched!
/* 00 */ le_float param1;
/* 04 */ le_float param2;
/* 08 */ le_float param3;
@@ -311,7 +350,8 @@ public:
/* 10 */ le_float param5;
/* 14 */ le_int16_t param7;
/* 16 */ le_int16_t param6;
/* 18 */ le_uint32_t entry_num;
/* 18 */ le_uint16_t entry_index;
/* 1A */ le_uint16_t unknown_a1;
/* 1C */ le_uint16_t min_children;
/* 1E */ le_uint16_t max_children;
/* 20 */
@@ -321,7 +361,7 @@ public:
struct RandomEnemyWeight { // Section type 5 (RANDOM_ENEMY_DEFINITIONS)
/* 00 */ uint8_t base_type_index;
/* 01 */ uint8_t def_entry_num;
/* 01 */ uint8_t def_entry_index;
/* 02 */ uint8_t weight;
/* 03 */ uint8_t unknown_a4;
/* 04 */
@@ -340,10 +380,13 @@ public:
explicit RandomState(uint32_t random_seed);
size_t rand_int_biased(size_t min_v, size_t max_v);
uint32_t next_location_index();
void generate_shuffled_location_table(const RandomEnemyLocationsHeader& header, phosg::StringReader r, uint16_t room);
void generate_shuffled_location_table(
const RandomEnemyLocationsHeader& header, phosg::StringReader r, uint16_t room_id);
};
struct FloorSections {
uint8_t floor = 0xFF;
size_t object_sets_file_offset = 0;
size_t object_sets_file_size = 0;
const ObjectSetEntry* object_sets = nullptr;
@@ -371,16 +414,24 @@ public:
size_t random_enemy_locations_file_size = 0;
const void* random_enemy_locations_data = nullptr;
size_t random_enemy_locations_data_size = 0;
const RandomEnemyRoom* random_enemy_rooms = nullptr;
size_t random_enemy_room_count = 0;
const RandomEnemyLocation* random_enemy_locations = nullptr;
size_t random_enemy_location_count = 0;
size_t random_enemy_definitions_file_offset = 0;
size_t random_enemy_definitions_file_size = 0;
const void* random_enemy_definitions_data = nullptr;
size_t random_enemy_definitions_data_size = 0;
const RandomEnemyDefinition* random_enemy_definitions = nullptr;
size_t random_enemy_definition_count = 0;
const RandomEnemyWeight* random_enemy_weights = nullptr;
size_t random_enemy_weight_count = 0;
};
// Quest constructor
MapFile(std::shared_ptr<const std::string> quest_data);
// Non-quest constructor
// Free-play constructor
MapFile(
uint8_t floor,
std::shared_ptr<const std::string> objects_data,
@@ -405,10 +456,9 @@ public:
return this->has_any_random_sections;
}
// If the map file has no random sections, does nothing and returns a
// shared_ptr to this. If it has any random sections, returns a new map with
// all non-random sections copied verbatim, and random sections replaced with
// non-random sections according to the challenge mode generation algorithm.
// If the map file has no random sections, does nothing and returns a shared_ptr to this. If it has any random
// sections, returns a new map with all non-random sections copied verbatim, and random sections replaced with
// non-random sections according to the challenge mode enemy generation algorithm.
std::shared_ptr<MapFile> materialize_random_sections(uint32_t random_seed);
std::shared_ptr<const MapFile> materialize_random_sections(uint32_t random_seed) const;
@@ -426,7 +476,11 @@ public:
static std::string disassemble_action_stream(const void* data, size_t size);
std::string disassemble(bool reassembly = false, Version version = Version::UNKNOWN) const;
std::string serialize() const;
protected:
static const std::array<uint32_t, 41> RAND_ENEMY_BASE_TYPES;
void link_data(std::shared_ptr<const std::string> data);
void set_object_sets_for_floor(uint8_t floor, size_t file_offset, const void* data, size_t size);
@@ -445,19 +499,15 @@ protected:
int64_t generated_with_random_seed = -1;
};
////////////////////////////////////////////////////////////////////////////////
// Super map. This class is responsible for collecting entity lists across PSO
// versions and diffing them to link together entities that don't line up
// across versions. This class also generates enemy lists from enemy set lists,
// which MapFile doesn't do. Like MapFile, a single SuperMap is either
// responsible for all entities on all floors in a quest, or all entities on a
// single floor in free play. Each entity is assigned a "super ID", which
// uniquely identifies the entity on all PSO versions. (These are the IDs which
// newserv formats as K-XXX, E-XXX, and W-XXX, though they are offset as needed
// for floors beyond the first.)
// There must not be any random enemy sections in any MapFile passed to
// SuperMap; to resolve them, materialize_random_sections must be called on all
// MapFiles first. This generally only is of concern in Challenge mode.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Super map. This class is responsible for collecting entity lists across PSO versions and diffing them to link
// together entities that don't line up across versions. This class also generates enemy lists from enemy set lists,
// which MapFile doesn't do. Like MapFile, a single SuperMap is either responsible for all entities on all floors in a
// quest, or all entities on a single floor in free play. Each entity is assigned a "super ID", which uniquely
// identifies the entity on all PSO versions. (These are the IDs which newserv formats as K-XXX, E-XXX, and W-XXX,
// though they are offset as needed for floors beyond the first.)
// There must not be any random enemy sections in any MapFile passed to SuperMap; to resolve them,
// materialize_random_sections must be called on all MapFiles first. This is generally only needed in Challenge mode.
class SuperMap {
public:
@@ -551,7 +601,9 @@ public:
std::multimap<uint64_t, std::shared_ptr<Event>> event_for_floor_and_event_id;
};
SuperMap(Episode episode, const std::array<std::shared_ptr<const MapFile>, NUM_VERSIONS>& map_files);
SuperMap(
const std::array<std::shared_ptr<const MapFile>, NUM_VERSIONS>& map_files,
const std::array<uint8_t, 0x12>& floor_to_area);
~SuperMap() = default;
inline EntitiesForVersion& version(Version v) {
@@ -561,9 +613,6 @@ public:
return this->entities_for_version.at(static_cast<size_t>(v));
}
inline Episode get_episode() const {
return this->episode;
}
inline int64_t get_random_seed() const {
return this->random_seed;
}
@@ -597,6 +646,10 @@ public:
std::unordered_map<EnemyType, size_t> count_enemy_sets_for_version(Version version) const;
uint8_t area_for_floor(uint8_t floor) const {
return this->floor_to_area.at(floor);
}
struct EfficiencyStats {
size_t filled_object_slots = 0;
size_t total_object_slots = 0;
@@ -613,9 +666,11 @@ public:
void print(FILE* stream) const;
protected:
friend class MapState;
phosg::PrefixedLogger log;
Episode episode;
std::array<uint8_t, 0x12> floor_to_area = {};
int64_t random_seed = -1;
std::vector<std::shared_ptr<Object>> objects;
std::vector<std::shared_ptr<Enemy>> enemies;
@@ -646,11 +701,10 @@ protected:
void add_map_file(Version v, std::shared_ptr<const MapFile> this_map_file);
};
////////////////////////////////////////////////////////////////////////////////
// Map state. This class is responsible for keeping track of the in-game state
// of objects, enemies, and events. This is the only class that's constructed
// for every game; the others are essentially immutable data once loaded, which
// this class refers to.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Map state. This class is responsible for keeping track of the in-game state of objects, enemies, and events. This is
// the only class that's constructed for every game; the others are essentially immutable data once loaded, and this
// class refers to them.
class MapState {
public:
@@ -683,12 +737,10 @@ public:
static const std::shared_ptr<const RareEnemyRates> DEFAULT_RARE_ENEMIES;
struct ObjectState {
// WARNING: super_obj CAN BE NULL! This is not the case for enemies and
// events; their super entities are never null. In the case of objects,
// dynamic objects like player-set traps have object IDs past the end of
// the map's object list, and when queried, the MapState will return a
// temporary ObjectState with a null super_obj. (In these cases, only k_id
// is needed for correctness.)
// WARNING: super_obj CAN BE NULL! This is not the case for enemies and events; their super entities are never
// null. In the case of objects, dynamic objects like player-set traps have object IDs past the end of the map's
// object list, and when queried, the MapState will return a temporary ObjectState with a null super_obj. (In these
// cases, only k_id is needed for correctness.)
std::shared_ptr<const SuperMap::Object> super_obj;
size_t k_id = 0;
uint16_t game_flags = 0;
@@ -746,7 +798,7 @@ public:
inline void set_mericarand_variant_flag(Version version) {
this->mericarand_variant_flags |= (1 << static_cast<size_t>(version));
}
inline EnemyType type(Version version, Episode episode, Difficulty difficulty, uint8_t event) const {
inline EnemyType type(Version version, uint8_t area, Difficulty difficulty, uint8_t event) const {
if (this->super_ene->type == EnemyType::MERICARAND) {
if (this->is_rare(version)) {
return ((this->mericarand_variant_flags >> static_cast<size_t>(version)) & 1)
@@ -759,10 +811,10 @@ public:
return ((difficulty == Difficulty::NORMAL) && !this->super_ene->alias_target_ene)
? EnemyType::DARK_FALZ_2
: EnemyType::DARK_FALZ_3;
} else if (this->is_rare(version)) {
return type_definition_for_enemy(this->super_ene->type).rare_type(area, event);
} else {
return this->is_rare(version)
? type_definition_for_enemy(this->super_ene->type).rare_type(episode, event, this->super_ene->floor)
: this->super_ene->type;
return this->super_ene->type;
}
}
inline bool ever_hit_by_client_id(uint8_t client_id) const {
@@ -878,6 +930,7 @@ public:
};
phosg::PrefixedLogger log;
std::array<uint8_t, 0x12> floor_to_area = {};
std::vector<FloorConfig> floor_config_entries;
Difficulty difficulty = Difficulty::NORMAL;
uint8_t event = 0;
@@ -923,8 +976,7 @@ public:
inline const FloorConfig& floor_config(uint8_t floor) const {
return this->floor_config_entries[std::min<uint8_t>(floor, this->floor_config_entries.size() - 1)];
}
// Resets states of all entities to their initial values. Used when
// restarting battles/challenges.
// Resets states of all entities to their initial values. Used when restarting battles/challenges.
void reset();
inline Range<ObjectIterator> iter_object_states(Version version) {
+21 -34
View File
@@ -7,11 +7,10 @@
#include <string>
#include <vector>
// Note: These aren't enums because neither enum nor enum class does what we
// want. Specifically, we need GO_BACK to be valid in multiple enums (and enums
// aren't namespaced unless they're enum classes), so we can't use enums. But we
// also want to be able to use non-enum values in switch statements without
// casting values all over the place, so we can't use enum classes either.
// Note: These aren't enums because neither enum nor enum class does what we want. Specifically, we need GO_BACK to be
// valid in multiple enums (and enums aren't namespaced unless they're enum classes), so we can't use enums. But we
// also want to be able to use non-enum values in switch statements without casting values all over the place, so we
// can't use enum classes either.
namespace MenuID {
constexpr uint32_t MAIN = 0x11000011;
@@ -22,8 +21,7 @@ constexpr uint32_t GAME = 0x44000044;
constexpr uint32_t QUEST_EP1 = 0x55010155;
constexpr uint32_t QUEST_EP2 = 0x55020255;
constexpr uint32_t QUEST_EP3 = 0x55030355;
// See the decsription of the A2 command in CommandFormats.hh for why these
// menu IDs don't fit the rest of the pattern.
// See the decsription of the A2 command in CommandFormats.hh for why these menu IDs don't fit the rest of the pattern.
constexpr uint32_t QUEST_CATEGORIES_EP1_EP3_EP4 = 0x01000001;
constexpr uint32_t QUEST_CATEGORIES_EP2 = 0x02000002;
constexpr uint32_t PROXY_DESTINATIONS = 0x77000077;
@@ -44,6 +42,12 @@ constexpr uint32_t PATCH_SWITCHES = 0x11666611;
constexpr uint32_t PROGRAMS = 0x11777711;
constexpr uint32_t DISCONNECT = 0x11888811;
constexpr uint32_t CLEAR_LICENSE = 0x11999911;
constexpr uint32_t BB_LIVE_SHIP = 0x11AAAA11;
constexpr uint32_t BB_TEST_SHIP = 0x11BBBB11;
constexpr uint32_t BB_VANILLA_SHIP = 0x11CCCC11;
constexpr uint32_t BB_HARDCORE_SHIP = 0x11F00D11;
constexpr uint32_t BB_DEV_SHIP = 0x11EEEE11;
constexpr uint32_t BLUEBALLZ_PLUS0 = 0x11DDDD11;
} // namespace MainMenuItemID
namespace ClearLicenseConfirmationMenuItemID {
@@ -75,13 +79,14 @@ constexpr uint32_t PLAYER_NOTIFICATIONS = 0xAA0202AA;
constexpr uint32_t DROP_NOTIFICATIONS = 0xAA0303AA;
constexpr uint32_t INFINITE_HP = 0xAA0404AA;
constexpr uint32_t INFINITE_TP = 0xAA0505AA;
constexpr uint32_t SWITCH_ASSIST = 0xAA0606AA;
constexpr uint32_t BLOCK_EVENTS = 0xAA0707AA;
constexpr uint32_t BLOCK_PATCHES = 0xAA0808AA;
constexpr uint32_t SAVE_FILES = 0xAA0909AA;
constexpr uint32_t EP3_INFINITE_MESETA = 0xAA0A0AAA;
constexpr uint32_t EP3_INFINITE_TIME = 0xAA0B0BAA;
constexpr uint32_t EP3_UNMASK_WHISPERS = 0xAA0C0CAA;
constexpr uint32_t FAST_KILLS = 0xAA0606AA;
constexpr uint32_t SWITCH_ASSIST = 0xAA0707AA;
constexpr uint32_t BLOCK_EVENTS = 0xAA0808AA;
constexpr uint32_t BLOCK_PATCHES = 0xAA0909AA;
constexpr uint32_t SAVE_FILES = 0xAA0A0AAA;
constexpr uint32_t EP3_INFINITE_MESETA = 0xAA0B0BAA;
constexpr uint32_t EP3_INFINITE_TIME = 0xAA0C0CAA;
constexpr uint32_t EP3_UNMASK_WHISPERS = 0xAA0D0DAA;
} // namespace ProxyOptionsMenuItemID
namespace TeamRewardMenuItemID {
@@ -91,20 +96,10 @@ constexpr uint32_t MEMBERS_20_LEADERS_3 = 0x03030303;
constexpr uint32_t MEMBERS_40_LEADERS_5 = 0x04040404;
constexpr uint32_t MEMBERS_70_LEADERS_8 = 0x05050505;
constexpr uint32_t MEMBERS_100_LEADERS_10 = 0x06060606;
// constexpr uint32_t POINT_OF_DISASTER = ...;
// constexpr uint32_t TOYS_TWILIGHT = ...;
// constexpr uint32_t COMMANDER_BLADE = ...;
// constexpr uint32_t UNION_GUARD = ...;
// constexpr uint32_t TEAM_POINTS_500 = ...;
// constexpr uint32_t TEAM_POINTS_1000 = ...;
// constexpr uint32_t TEAM_POINTS_5000 = ...;
// constexpr uint32_t TEAM_POINTS_10000 = ...;
} // namespace TeamRewardMenuItemID
struct MenuItem {
enum Flag {
// For menu items to be visible on DC NTE, they must not have either of the
// following two flags. (The INVISIBLE_ON_GC_NTE flag behaves similarly.)
INVISIBLE_ON_DC_PROTOS = 0x001,
INVISIBLE_ON_DC = 0x002,
INVISIBLE_ON_PC_NTE = 0x004,
@@ -130,16 +125,8 @@ struct MenuItem {
std::function<std::string()> get_description;
uint32_t flags;
MenuItem(
uint32_t item_id,
const std::string& name,
const std::string& description,
uint32_t flags);
MenuItem(
uint32_t item_id,
const std::string& name,
std::function<std::string()> get_description,
uint32_t flags);
MenuItem(uint32_t item_id, const std::string& name, const std::string& description, uint32_t flags);
MenuItem(uint32_t item_id, const std::string& name, std::function<std::string()> get_description, uint32_t flags);
};
struct Menu {
+1 -2
View File
@@ -103,8 +103,7 @@ uint32_t address_for_string(const char* address) {
}
uint64_t devolution_phone_number_for_netloc(uint32_t addr, uint16_t port) {
// It seems the address part of the number is fixed-width, but the port is
// not. Why did they do it this way?
// It seems the address part of the number is fixed-width, but the port is not. Why did they do it this way?
if (port & 0xF000) {
return (static_cast<uint64_t>(addr) << 16) | port;
} else if (port & 0x0F00) {
+1 -2
View File
@@ -6,8 +6,7 @@
#include <map>
#include <string>
// PSO is IPv4-only, so we just treat addresses as uint32_t everywhere because
// it's easier
// PSO is IPv4-only, so we just treat addresses as uint32_t everywhere because it's easier
std::map<std::string, uint32_t> get_local_addresses();
uint32_t get_connected_address(int fd);
+2 -3
View File
@@ -19,7 +19,7 @@ struct Entry {
le_uint32_t compressed_size;
le_uint32_t checksum;
// Data follows immediately here
// Trailer: le_uint32_t entry_size; //
// Trailer: le_uint32_t entry_size;
};
static void decrypt_ppk_data(std::string& data, const std::string& filename, const std::string& password) {
@@ -61,8 +61,7 @@ std::unordered_map<std::string, std::string> decode_ppk_file(const std::string&
uint32_t checksum = phosg::crc32(data.data(), data.size());
if (checksum != entry.checksum) {
throw runtime_error(std::format(
"incorrect checksum for file {} (expected {:08X}; received {:08X})",
filename, entry.checksum, checksum));
"incorrect checksum for file {} (expected {:08X}; received {:08X})", filename, entry.checksum, checksum));
}
if (entry.compressed_size < entry.decompressed_size) {
data = prs_decompress(data);
+42 -28
View File
@@ -11,8 +11,6 @@
using namespace std;
// TODO: fix style in this file, especially in psobb functions
RandomGenerator::RandomGenerator(uint32_t seed) : initial_seed(seed) {}
DisabledRandomGenerator::DisabledRandomGenerator() : RandomGenerator(0) {}
@@ -77,8 +75,7 @@ void PSOLFGEncryption::encrypt_both_endian(void* le_vdata, void* be_vdata, size_
}
}
PSOV2Encryption::PSOV2Encryption(uint32_t seed)
: PSOLFGEncryption(seed, STREAM_LENGTH + 1, STREAM_LENGTH) {
PSOV2Encryption::PSOV2Encryption(uint32_t seed) : PSOLFGEncryption(seed, STREAM_LENGTH + 1, STREAM_LENGTH) {
uint32_t a = 1, b = this->initial_seed;
this->stream[0x37] = b;
for (uint16_t virtual_index = 0x15; virtual_index <= 0x36 * 0x15; virtual_index += 0x15) {
@@ -106,8 +103,35 @@ PSOEncryption::Type PSOV2Encryption::type() const {
return Type::V2;
}
PSOV3Encryption::PSOV3Encryption(uint32_t seed)
: PSOLFGEncryption(seed, STREAM_LENGTH, STREAM_LENGTH) {
uint32_t PSOV2Encryption::single(uint32_t seed) {
// This function is an optimized implementation of `PSOV2Encryption(seed).next()`; that is, it allows the caller to
// get a single value from a PSOV2Encryption instance without actually constructing it. This method is 22x-100x
// faster (depending on build configuration) than constructing a PSOV2Encryption and calling .next() on it once.
// If fib(n) is the n'th Fibonacci number (starting with 1, 1, 2, 3, 5, etc.), then a closed form for the integer
// sequence generated by the first loop in PSOV2Encryption::PSOV2Encryption is:
// a(n) = (-1)^n * (fib(n) - fib(n-1) * seed)
// The sequence begins with a(-1) = seed (which is not generated by the loop but is used as an initial input, hence
// the negative index) and a(0) = 1, and the recurrence used in that loop is a(n) = a(n-2) - a(n-1). Assuming that
// a(n-2) and a(n-1) are described by this closed form, we can show that a(n) is as well:
// a(n) = a(n-2) - a(n-1)
// a(n) = (-1)^(n-2) * (fib(n-2) - fib(n-3) * seed) - ((-1)^(n-1) * (fib(n-1) - fib(n-2) * seed))
// a(n) = (-1)^(n-2) * (fib(n-2) - fib(n-3) * seed) + ((-1)^(n-2) * (fib(n-1) - fib(n-2) * seed))
// a(n) = (-1)^(n-2) * (fib(n-2) - fib(n-3) * seed + fib(n-1) - fib(n-2) * seed)
// a(n) = (-1)^(n-2) * (fib(n-2) + fib(n-1) - (fib(n-3) + fib(n-2)) * seed)
// a(n) = (-1)^(n-2) * (fib(n) - fib(n-1) * seed)
// a(n) = (-1)^(n) * (fib(n) - fib(n-1) * seed)
// This shows inductively that this closed form holds for all n >= 1 (since the sequence begins with a(-1)). Using
// the closed form and the values of a(-1) and a(0), we can eliminate all arithmetic done in the normal constructor
// that isn't necessary to produce the first result value. To do so, we trace backward from the result value, through
// the 5 update_stream calls and the initialization loop, to see which indexes within the stream are actually needed,
// and the expression to generate each one. We can then simplify the overall expression and truncate constants to 32
// bits (since it's a linear equation, overflow bits cannot affect the final 32-bit result). The full expression
// simplifies to:
return 0xC6DCAB76 * seed - 0x9E1977BA;
}
PSOV3Encryption::PSOV3Encryption(uint32_t seed) : PSOLFGEncryption(seed, STREAM_LENGTH, STREAM_LENGTH) {
uint32_t x, y, basekey, source1, source2, source3;
basekey = 0;
@@ -154,9 +178,7 @@ PSOEncryption::Type PSOV3Encryption::type() const {
return Type::V3;
}
PSOBBEncryption::PSOBBEncryption(
const KeyFile& key, const void* original_seed, size_t seed_size)
: state(key) {
PSOBBEncryption::PSOBBEncryption(const KeyFile& key, const void* original_seed, size_t seed_size) : state(key) {
this->apply_seed(original_seed, seed_size);
}
@@ -361,11 +383,10 @@ void PSOBBEncryption::tfs1_scramble(uint32_t* out1, uint32_t* out2) const {
}
void PSOBBEncryption::apply_seed(const void* original_seed, size_t seed_size) {
// Note: This part is done in the 03 command handler in the BB client, and
// isn't actually part of the encryption library. (Why did they do this?)
// Note: This part is done in the 03 command handler in the BB client, and isn't actually part of the encryption
// library. (Why did they do this?)
string seed;
const uint8_t* original_seed_data = reinterpret_cast<const uint8_t*>(
original_seed);
const uint8_t* original_seed_data = reinterpret_cast<const uint8_t*>(original_seed);
for (size_t x = 0; x < seed_size; x += 3) {
seed.push_back(original_seed_data[x] ^ 0x19);
seed.push_back(original_seed_data[x + 1] ^ 0x16);
@@ -614,12 +635,8 @@ void PSOBBEncryption::apply_seed(const void* original_seed, size_t seed_size) {
}
PSOV2OrV3DetectorEncryption::PSOV2OrV3DetectorEncryption(
uint32_t key,
const std::unordered_set<uint32_t>& v2_matches,
const std::unordered_set<uint32_t>& v3_matches)
: key(key),
v2_matches(v2_matches),
v3_matches(v3_matches) {}
uint32_t key, const std::unordered_set<uint32_t>& v2_matches, const std::unordered_set<uint32_t>& v3_matches)
: key(key), v2_matches(v2_matches), v3_matches(v3_matches) {}
void PSOV2OrV3DetectorEncryption::encrypt(void* data, size_t size) {
if (!this->active_crypt) {
@@ -641,7 +658,8 @@ void PSOV2OrV3DetectorEncryption::encrypt(void* data, size_t size) {
bool v3_match = this->v3_matches.count(decrypted_v3);
if (!v2_match && !v3_match) {
throw runtime_error(std::format(
"unable to determine crypt version (input={:08X}, v2={:08X}, v3={:08X})", encrypted, decrypted_v2, decrypted_v3));
"unable to determine crypt version (input={:08X}, v2={:08X}, v3={:08X})",
encrypted, decrypted_v2, decrypted_v3));
} else if (v2_match && v3_match) {
throw runtime_error(std::format("ambiguous crypt version (v2={:08X}, v3={:08X})", decrypted_v2, decrypted_v3));
} else if (v2_match) {
@@ -665,8 +683,7 @@ PSOEncryption::Type PSOV2OrV3DetectorEncryption::type() const {
PSOV2OrV3ImitatorEncryption::PSOV2OrV3ImitatorEncryption(
uint32_t key, std::shared_ptr<PSOV2OrV3DetectorEncryption> detector_crypt)
: key(key),
detector_crypt(detector_crypt) {}
: key(key), detector_crypt(detector_crypt) {}
void PSOV2OrV3ImitatorEncryption::encrypt(void* data, size_t size) {
if (!this->active_crypt) {
@@ -761,9 +778,8 @@ shared_ptr<PSOBBEncryption> PSOBBMultiKeyImitatorEncryption::ensure_crypt() {
if (!key.get()) {
throw logic_error("server crypt cannot be initialized because client crypt is not ready");
}
// Hack: JSD1 uses the client seed for both ends of the connection and
// ignores the server seed (though each end has its own state after that).
// To handle this, we use the other crypt's seed if the type is JSD1.
// Hack: JSD1 uses the client seed for both ends of the connection and ignores the server seed (though each end has
// its own state after that). To handle this, we use the other crypt's seed if the type is JSD1.
if ((key->subtype == PSOBBEncryption::Subtype::JSD1) && this->jsd1_use_detector_seed) {
const auto& detector_seed = this->detector_crypt->get_seed();
this->active_crypt = make_shared<PSOBBEncryption>(*key, detector_seed.data(), detector_seed.size());
@@ -837,9 +853,7 @@ uint32_t encrypt_challenge_time(uint16_t value) {
uint16_t decrypt_challenge_time(uint32_t value) {
uint16_t mask = (value >> 0x10);
uint8_t mask_one_bits = count_one_bits(mask);
return ((mask_one_bits < 4) || (mask_one_bits > 12))
? 0xFFFF
: ((mask ^ value) & 0xFFFF);
return ((mask_one_bits < 4) || (mask_one_bits > 12)) ? 0xFFFF : ((mask ^ value) & 0xFFFF);
}
string decrypt_v2_registry_value(const void* data, size_t size) {
+13 -18
View File
@@ -132,6 +132,9 @@ public:
explicit PSOV2Encryption(uint32_t seed);
virtual Type type() const;
// Optimized implementation of `PSOV2Encryption(seed).next()` for when the caller needs only the first value
static uint32_t single(uint32_t seed);
protected:
virtual void update_stream();
@@ -159,8 +162,7 @@ public:
};
struct KeyFile {
// initial_keys are actually a stream of uint32_ts, but we treat them as
// bytes for code simplicity
// initial_keys are actually a stream of uint32_ts, but we treat them as bytes for code simplicity
union InitialKeys {
uint8_t jsd1_stream_offset;
parray<uint8_t, 0x48> as8;
@@ -176,11 +178,9 @@ public:
} __packed_ws__(PrivateKeys, 0x1000);
InitialKeys initial_keys;
PrivateKeys private_keys;
// This field only really needs to be one byte, but annoyingly, some
// compilers pad this structure to a longer alignment, presumably because
// the unions above contain structures with 32-bit alignment. To prevent
// this structure's size from not matching the .nsk files' sizes, we use
// an unnecessarily large size for this field.
// This field only really needs to be one byte, but annoyingly, some compilers pad this structure to a longer
// alignment, presumably because the unions above contain structures with 32-bit alignment. To prevent this
// structure's size from not matching the .nsk files' sizes, we use an unnecessarily large size for this field.
le_uint64_t subtype;
} __packed_ws__(KeyFile, 0x1050);
@@ -198,8 +198,8 @@ protected:
void apply_seed(const void* original_seed, size_t seed_size);
};
// The following classes provide support for automatically detecting which type
// of encryption a client is using based on their initial response to the server
// The following classes provide support for automatically detecting which type of encryption a client is using based
// on their initial response to the server
class PSOV2OrV3DetectorEncryption : public PSOEncryption {
public:
@@ -234,9 +234,8 @@ protected:
std::shared_ptr<PSOEncryption> active_crypt;
};
// The following classes provide support for multiple PSOBB private keys, and
// the ability to automatically detect which key the client is using based on
// the first 8 bytes they send
// The following classes provide support for multiple PSOBB private keys, and the ability to automatically detect which
// key the client is using based on the first 8 bytes they send
class PSOBBMultiKeyDetectorEncryption : public PSOEncryption {
public:
@@ -344,11 +343,9 @@ public:
ret.store_raw(this->value);
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(ChallengeTimeT, 4);
using ChallengeTime = ChallengeTimeT<false>;
using ChallengeTimeBE = ChallengeTimeT<true>;
check_struct_size(ChallengeTime, 4);
check_struct_size(ChallengeTimeBE, 4);
std::string decrypt_v2_registry_value(const void* data, size_t size);
@@ -397,9 +394,7 @@ DecryptedPR2 decrypt_pr2_data(const std::string& data) {
throw std::runtime_error("not enough data for PR2 header");
}
phosg::StringReader r(data);
DecryptedPR2 ret = {
.compressed_data = data.substr(8),
.decompressed_size = r.get<U32T<BE>>()};
DecryptedPR2 ret = {.compressed_data = data.substr(8), .decompressed_size = r.get<U32T<BE>>()};
PSOV2Encryption crypt(r.get<U32T<BE>>());
if (BE) {
crypt.encrypt_big_endian(ret.compressed_data.data(), ret.compressed_data.size());
+3 -9
View File
@@ -189,25 +189,19 @@ void PSOCommandHeader::set_flag(Version version, uint32_t flag) {
void check_size_v(size_t size, size_t min_size, size_t max_size) {
if (size < min_size) {
throw std::runtime_error(std::format(
"command too small (expected at least 0x{:X} bytes, received 0x{:X} bytes)",
min_size, size));
"command too small (expected at least 0x{:X} bytes, received 0x{:X} bytes)", min_size, size));
}
if (max_size < min_size) {
max_size = min_size;
}
if (size > max_size) {
throw std::runtime_error(std::format(
"command too large (expected at most 0x{:X} bytes, received 0x{:X} bytes)",
max_size, size));
"command too large (expected at most 0x{:X} bytes, received 0x{:X} bytes)", max_size, size));
}
}
std::string prepend_command_header(
Version version,
bool encryption_enabled,
uint16_t cmd,
uint32_t flag,
const std::string& data) {
Version version, bool encryption_enabled, uint16_t cmd, uint32_t flag, const std::string& data) {
phosg::StringWriter ret;
switch (version) {
case Version::DC_NTE:
+5 -16
View File
@@ -46,23 +46,16 @@ union PSOCommandHeader {
PSOCommandHeader();
} __packed_ws__(PSOCommandHeader, 8);
// This function is used in a lot of places to check received command sizes and
// cast them to the appropriate type
// This function is used in a lot of places to check received command sizes and cast them to the appropriate type
template <typename RetT, typename PtrT>
RetT& check_size_generic(
PtrT data,
size_t size,
size_t min_size,
size_t max_size) {
RetT& check_size_generic(PtrT data, size_t size, size_t min_size, size_t max_size) {
if (size < min_size) {
throw std::runtime_error(std::format(
"command too small (expected at least 0x{:X} bytes, received 0x{:X} bytes)",
min_size, size));
"command too small (expected at least 0x{:X} bytes, received 0x{:X} bytes)", min_size, size));
}
if (size > max_size) {
throw std::runtime_error(std::format(
"command too large (expected at most 0x{:X} bytes, received 0x{:X} bytes)",
max_size, size));
"command too large (expected at most 0x{:X} bytes, received 0x{:X} bytes)", max_size, size));
}
return *reinterpret_cast<RetT*>(data);
}
@@ -128,8 +121,4 @@ T* check_size_vec_t(std::string& data, size_t count, bool allow_extra = false) {
void check_size_v(size_t size, size_t min_size, size_t max_size = 0);
std::string prepend_command_header(
Version version,
bool encryption_enabled,
uint16_t cmd,
uint32_t flag,
const std::string& data);
Version version, bool encryption_enabled, uint16_t cmd, uint32_t flag, const std::string& data);
+6 -10
View File
@@ -51,8 +51,8 @@ PatchFileIndex::PatchFileIndex(const string& root_dir)
patch_index_log.warning_f("Cannot load patch metadata cache from {}: {}", metadata_cache_filename, e.what());
}
// Assuming it's rare for patch files to change, we skip writing the metadata
// cache if no files were changed at all (which should usually be the case)
// Assuming it's rare for patch files to change, we skip writing the metadata cache if no files were changed at all
// (which should usually be the case)
bool should_write_metadata_cache = false;
phosg::JSON new_metadata_cache_json = phosg::JSON::dict();
@@ -124,10 +124,8 @@ PatchFileIndex::PatchFileIndex(const string& root_dir)
should_write_metadata_cache = true;
} else {
// File was not modified and cache item was valid; just use the
// existing cache item
new_metadata_cache_json.emplace(
relative_item_path, std::move(cache_item_json));
// File was not modified and cache item was valid; just use the existing cache item
new_metadata_cache_json.emplace(relative_item_path, std::move(cache_item_json));
}
this->files_by_patch_order.emplace_back(f);
@@ -159,12 +157,10 @@ PatchFileIndex::PatchFileIndex(const string& root_dir)
}
}
const vector<shared_ptr<PatchFileIndex::File>>&
PatchFileIndex::all_files() const {
const vector<shared_ptr<PatchFileIndex::File>>& PatchFileIndex::all_files() const {
return this->files_by_patch_order;
}
shared_ptr<PatchFileIndex::File> PatchFileIndex::get(
const string& filename) const {
shared_ptr<PatchFileIndex::File> PatchFileIndex::get(const string& filename) const {
return this->files_by_name.at(filename);
}
+1 -3
View File
@@ -47,8 +47,6 @@ struct PatchFileChecksumRequest {
size(0),
response_received(false) {}
inline bool needs_update() const {
return !this->response_received ||
(this->crc32 != this->file->crc32) ||
(this->size != this->file->size);
return !this->response_received || (this->crc32 != this->file->crc32) || (this->size != this->file->size);
}
};
+22 -35
View File
@@ -21,27 +21,22 @@
class Client;
class ItemParameterTable;
// PSO V2 stored some extra data in the character structs in a format that I'm
// sure Sega thought was very clever for backward compatibility, but for us is
// just plain annoying. Specifically, they used the third and fourth bytes of
// the InventoryItem struct to store some things not present in V1. The game
// stores arrays of bytes striped across these structures. In newserv, we call
// those fields extension_data. They contain:
// PSO V2 stored some extra data in the character structs in a format that I'm sure Sega thought was very clever for
// backward compatibility, but for us is just plain annoying. Specifically, they used the third and fourth bytes of the
// InventoryItem struct to store some things not present in V1. The game stores arrays of bytes striped across these
// structures. In newserv, we call those fields extension_data. They contain:
// items[0].extension_data1 through items[19].extension_data1:
// Extended technique levels. The values in the technique_levels_v1 array
// only go up to 14 (tech level 15); if the player has a technique above
// level 15, the corresponding extension_data1 field holds the remaining
// levels (so a level 20 tech would have 14 in technique_levels_v1 and 5
// in the corresponding item's extension_data1 field).
// Extended technique levels. The values in the technique_levels_v1 array only go up to 14 (tech level 15); if
// the player has a technique above level 15, the extension_data1 field holds the remaining levels (so a level 20
// technique would have 14 in technique_levels_v1 and 5 in the corresponding item's extension_data1 field).
// items[0].extension_data2 through items[3].extension_data2:
// The flags field from the PSOGCCharacterFile::Character struct; see
// SaveFileFormats.hh for details.
// The flags field from the PSOGCCharacterFile::Character struct; see SaveFileFormats.hh for details.
// items[4].extension_data2 through items[7].extension_data2:
// The timestamp when the character was last saved, in seconds since
// January 1, 2000. Stored little-endian, so items[4] contains the LSB.
// The timestamp when the character was last saved, in seconds since January 1, 2000. Stored little-endian, so
// items[4] contains the LSB.
// items[8].extension_data2 through items[12].extension_data2:
// Number of power materials, mind materials, evade materials, def
// materials, and luck materials (respectively) used by the player.
// Number of power materials, mind materials, evade materials, def materials, and luck materials (respectively)
// used by the player.
// items[13].extension_data2 through items[15].extension_data2:
// Unknown. These are not an array, but do appear to be related.
@@ -81,11 +76,9 @@ struct PlayerInventoryItemT {
bool is_equipped() const {
return (this->flags & 8);
}
} __attribute__((packed));
} __packed_ws_be__(PlayerInventoryItemT, 0x1C);
using PlayerInventoryItem = PlayerInventoryItemT<false>;
using PlayerInventoryItemBE = PlayerInventoryItemT<true>;
check_struct_size(PlayerInventoryItem, 0x1C);
check_struct_size(PlayerInventoryItemBE, 0x1C);
template <bool BE>
struct PlayerBankItemT {
@@ -105,11 +98,9 @@ struct PlayerBankItemT {
ret.present = this->present;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(PlayerBankItemT, 0x18);
using PlayerBankItem = PlayerBankItemT<false>;
using PlayerBankItemBE = PlayerBankItemT<true>;
check_struct_size(PlayerBankItem, 0x18);
check_struct_size(PlayerBankItemBE, 0x18);
template <bool BE>
struct PlayerInventoryT {
@@ -149,8 +140,7 @@ struct PlayerInventoryT {
continue;
}
// Units can be equipped in multiple slots, so the currently-equipped slot
// is stored in the item data itself.
// Units can be equipped in multiple slots, so the currently-equipped slot is stored in the item data itself.
if (((slot == EquipSlot::UNIT_1) && (i.data.data1[4] != 0x00)) ||
((slot == EquipSlot::UNIT_2) && (i.data.data1[4] != 0x01)) ||
((slot == EquipSlot::UNIT_3) && (i.data.data1[4] != 0x02)) ||
@@ -258,11 +248,10 @@ struct PlayerInventoryT {
void encode_for_client(Version v, std::shared_ptr<const ItemParameterTable> item_parameter_table) {
if (v == Version::DC_NTE) {
// DC NTE has the item count as a 32-bit value here, whereas every other
// version uses a single byte. To stop DC NTE from crashing by trying to
// construct far more than 30 TItem objects, we clear the fields DC NTE
// doesn't know about. Note that the 11/2000 prototype does not have this
// issue - its inventory format matches the rest of the versions.
// DC NTE has the item count as a 32-bit value here, whereas every other version uses a single byte. To stop DC
// NTE from crashing by trying to construct far more than 30 TItem objects, we clear the fields DC NTE doesn't
// know about. Note that the 11/2000 prototype does not have this issue - its inventory format matches the rest
// of the versions.
this->hp_from_materials = 0;
this->tp_from_materials = 0;
this->language = Language::JAPANESE;
@@ -276,8 +265,8 @@ struct PlayerInventoryT {
}
}
// For pre-V2 clients, use the V2 parameter table, since the V1 table
// doesn't have correct encodings for backward-compatible V2 items.
// For pre-V2 clients, use the V2 parameter table, since the V1 table doesn't have correct encodings for backward-
// compatible V2 items.
for (size_t z = 0; z < this->items.size(); z++) {
this->items[z].data.encode_for_version(v, item_parameter_table);
}
@@ -298,11 +287,9 @@ struct PlayerInventoryT {
ret.items = this->items;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(PlayerInventoryT, 0x34C);
using PlayerInventory = PlayerInventoryT<false>;
using PlayerInventoryBE = PlayerInventoryT<true>;
check_struct_size(PlayerInventory, 0x34C);
check_struct_size(PlayerInventoryBE, 0x34C);
template <size_t SlotCount, bool BE>
struct PlayerBankT {
+15 -23
View File
@@ -330,27 +330,19 @@ const QuestFlagsForDifficulty BB_QUEST_FLAG_APPLY_MASK{{
// clang-format on
// The flags in the above mask are:
// 000A 000B 000C 000D 000E 000F 0010 0011 0012 0013 0014 0015 0016 0017
// 0018 0019 001A 001E 001F 0020 0021 0022 0028 0029 002A 002B 002C 002D
// 002E 002F 0030 0031 0032 0033 0034 0035 0036 0037 0046 0047 0048 0049
// 004A 004B 004C 004D 004E 004F 0050 0051 0052 0053 0054 0055 0056 0057
// 0058 0059 005A 005B 005C 005D 005E 005F 0060 0061 0062 0063 0097 0098
// 0099 009A 012D 012E 012F 0130 0131 0132 0133 0134 0135 0140 0141 0142
// 0143 0144 0145 0146 0147 0148 0149 014A 014B 014C 014D 014E 014F 0150
// 0151 0152 0153 0154 0155 0156 0157 0158 0159 015A 015B 015C 015D 015E
// 015F 0160 0161 0162 0163 0164 0165 0166 0167 0168 0169 016A 016B 016C
// 016D 016E 016F 0170 0171 0172 0173 0174 0175 0176 0177 0178 0179 017A
// 017B 017C 017D 017E 017F 0180 0181 0182 0183 0184 0185 0186 0191 0192
// 0193 0194 0195 0196 0197 0198 0199 019A 019B 019C 019D 019E 01A4 01A5
// 01A6 01A7 01A8 01A9 01AA 01AB 01AC 01AD 01AE 01AF 01B0 01B1 01B2 01B3
// 01B4 01B5 01B6 01B7 01B8 01C2 01C3 01C4 01C5 01C6 01C7 01C8 01C9 01CA
// 01CB 01CC 01CD 01CE 01CF 01D0 01D1 01D2 01D3 01D4 01D5 01D6 01F4 01F5
// 01F6 01F7 01F8 01F9 01FA 01FB 01FC 01FD 01FE 01FF 0200 0201 0202 0203
// 0204 0205 0206 0207 0208 0209 020A 020B 020C 020D 020E 020F 0210 0211
// 0212 0213 0214 0215 0216 0217 0218 0219 021A 021B 021C 021D 021E 021F
// 0220 0221 0222 0223 0224 0225 0226 0227 0228 0229 022A 022B 022C 022D
// 022E 022F 0230 0231 0232 0233 0234 0235 02BD 02BE 02BF 02C0 02C1 02C2
// 02C3 02C4
// 000A 000B 000C 000D 000E 000F 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 001A 001E 001F 0020 0021 0022
// 0028 0029 002A 002B 002C 002D 002E 002F 0030 0031 0032 0033 0034 0035 0036 0037 0046 0047 0048 0049 004A 004B
// 004C 004D 004E 004F 0050 0051 0052 0053 0054 0055 0056 0057 0058 0059 005A 005B 005C 005D 005E 005F 0060 0061
// 0062 0063 0097 0098 0099 009A 012D 012E 012F 0130 0131 0132 0133 0134 0135 0140 0141 0142 0143 0144 0145 0146
// 0147 0148 0149 014A 014B 014C 014D 014E 014F 0150 0151 0152 0153 0154 0155 0156 0157 0158 0159 015A 015B 015C
// 015D 015E 015F 0160 0161 0162 0163 0164 0165 0166 0167 0168 0169 016A 016B 016C 016D 016E 016F 0170 0171 0172
// 0173 0174 0175 0176 0177 0178 0179 017A 017B 017C 017D 017E 017F 0180 0181 0182 0183 0184 0185 0186 0191 0192
// 0193 0194 0195 0196 0197 0198 0199 019A 019B 019C 019D 019E 01A4 01A5 01A6 01A7 01A8 01A9 01AA 01AB 01AC 01AD
// 01AE 01AF 01B0 01B1 01B2 01B3 01B4 01B5 01B6 01B7 01B8 01C2 01C3 01C4 01C5 01C6 01C7 01C8 01C9 01CA 01CB 01CC
// 01CD 01CE 01CF 01D0 01D1 01D2 01D3 01D4 01D5 01D6 01F4 01F5 01F6 01F7 01F8 01F9 01FA 01FB 01FC 01FD 01FE 01FF
// 0200 0201 0202 0203 0204 0205 0206 0207 0208 0209 020A 020B 020C 020D 020E 020F 0210 0211 0212 0213 0214 0215
// 0216 0217 0218 0219 021A 021B 021C 021D 021E 021F 0220 0221 0222 0223 0224 0225 0226 0227 0228 0229 022A 022B
// 022C 022D 022E 022F 0230 0231 0232 0233 0234 0235 02BD 02BE 02BF 02C0 02C1 02C2 02C3 02C4
}};
BattleRules::BattleRules(const phosg::JSON& json) {
@@ -729,7 +721,7 @@ const ChallengeTemplateDefinition& get_challenge_template_definition(Version ver
}
PlayerHoldState::PlayerHoldState(const PlayerHoldState_DCProtos& proto)
: unknown_a1(proto.unknown_a1),
: expiration_frames(proto.expiration_frames),
unknown_a2(proto.unknown_a2),
unknown_a3(0),
trigger_radius2(proto.trigger_radius2),
@@ -738,7 +730,7 @@ PlayerHoldState::PlayerHoldState(const PlayerHoldState_DCProtos& proto)
PlayerHoldState::operator PlayerHoldState_DCProtos() const {
PlayerHoldState_DCProtos ret;
ret.unknown_a1 = this->unknown_a1;
ret.expiration_frames = this->expiration_frames;
ret.unknown_a2 = this->unknown_a2;
ret.trigger_radius2 = this->trigger_radius2;
ret.x = this->x;
+36 -68
View File
@@ -32,10 +32,9 @@ struct PlayerVisualConfigT {
/* 10 */ parray<uint8_t, 8> unknown_a2;
/* 18 */ U32T<BE> name_color = 0xFFFFFFFF; // ARGB
/* 1C */ uint8_t extra_model = 0;
// Some NPCs can crash the client if the character's class is incorrect. To
// handle this, we save the affected fields in the unused bytes after
// extra_model. This is a newserv-specific extension; it appears the
// following 15 bytes were simply never used by Sega.
// Some NPCs can crash the client if the character's class is incorrect. To handle this, we save the affected fields
// in the unused bytes after extra_model. This is a newserv-specific extension; it appears the following 15 bytes
// were simply never used by Sega.
/* 1D */ uint8_t npc_saved_data_type = 0;
/* 1E */ uint8_t npc_saved_costume = 0;
/* 1F */ uint8_t npc_saved_skin = 0;
@@ -47,16 +46,13 @@ struct PlayerVisualConfigT {
/* 25 */ uint8_t npc_saved_hair_b = 0;
/* 26 */ parray<uint8_t, 2> unused;
/* 28 */ F32T<BE> npc_saved_proportion_y = 0.0;
// See compute_name_color_checksum for details on how this is computed. If the
// value is incorrect, V1 and V2 will ignore the name_color field and use the
// default color instead. This field is ignored on GC; on BB (and presumably
// Xbox), if this has a nonzero value, the "Change Name" option appears in the
// character selection menu.
// See compute_name_color_checksum for details on how this is computed. If the value is incorrect, V1 and V2 will
// ignore the name_color field and use the default color instead. This field is ignored on GC; on BB (and presumably
// Xbox), if this has a nonzero value, the "Change Name" option appears in the character selection menu.
/* 2C */ U32T<BE> name_color_checksum = 0;
/* 30 */ uint8_t section_id = 0;
/* 31 */ uint8_t char_class = 0;
// validation_flags specifies that some parts of this structure are not valid
// and should be ignored. The bits are:
// validation_flags specifies that some parts of this structure are not valid and should be ignored. The bits are:
// -----FCS
// F = class_flags is incorrect for the character's char_class value
// C = char_class is out of range
@@ -68,6 +64,12 @@ struct PlayerVisualConfigT {
// F = force, R = ranger, H = hunter
// A = android, N = newman, M = human
// f = female, m = male
// Enemies also have a class_flags field, though it isn't part of PlayerVisualConfig. The bits for enemies are:
// -------- -------- -------- ----DMAN
// D = Dark attribute
// M = Machine attribute
// A = Altered Beast attribute
// N = Native attribute
/* 34 */ U32T<BE> class_flags = 0;
/* 38 */ U16T<BE> costume = 0;
/* 3A */ U16T<BE> skin = 0;
@@ -310,11 +312,9 @@ struct PlayerVisualConfigT {
ret.proportion_y = this->proportion_y;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(PlayerVisualConfigT, 0x50);
using PlayerVisualConfig = PlayerVisualConfigT<false>;
using PlayerVisualConfigBE = PlayerVisualConfigT<true>;
check_struct_size(PlayerVisualConfig, 0x50);
check_struct_size(PlayerVisualConfigBE, 0x50);
template <bool BE>
struct PlayerDispDataDCPCV3T {
@@ -329,17 +329,15 @@ struct PlayerDispDataDCPCV3T {
}
PlayerDispDataBB to_bb(Language to_language, Language from_language) const;
} __attribute__((packed));
} __packed_ws_be__(PlayerDispDataDCPCV3T, 0xD0);
using PlayerDispDataDCPCV3 = PlayerDispDataDCPCV3T<false>;
using PlayerDispDataDCPCV3BE = PlayerDispDataDCPCV3T<true>;
check_struct_size(PlayerDispDataDCPCV3, 0xD0);
check_struct_size(PlayerDispDataDCPCV3BE, 0xD0);
struct PlayerDispDataBBPreview {
/* 00 */ le_uint32_t experience = 0;
/* 04 */ le_uint32_t level = 0;
// The name field in this structure is used for the player's Guild Card
// number, apparently (possibly because it's a char array and this is BB)
// The name field in this structure is used for the player's Guild Card number, apparently (possibly because it's a
// char array and this is BB)
/* 08 */ PlayerVisualConfig visual;
/* 58 */ pstring<TextEncoding::UTF16_ALWAYS_MARKED, 0x10> name;
/* 78 */ uint32_t play_time_seconds = 0;
@@ -436,18 +434,6 @@ struct GuildCardPC {
operator GuildCardBB() const;
} __packed_ws__(GuildCardPC, 0xF0);
// 0000 | 62 00 AC 00 06 2A 00 00 00 00 01 00 90 96 66 8C | b * f
// 0010 | 31 31 31 31 00 00 00 00 00 00 00 00 00 00 00 00 | 1111
// 0020 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0030 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0040 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0050 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0060 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0070 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0080 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 0090 | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
// 00A0 | 00 00 00 00 00 00 00 00 01 00 06 00 |
template <bool BE, size_t DescriptionLength>
struct GuildCardGCT {
/* NTE:Final */
@@ -536,11 +522,9 @@ GuildCardGCT<BE, DescriptionLength>::operator GuildCardBB() const {
struct PlayerLobbyDataPC {
le_uint32_t player_tag = 0;
le_uint32_t guild_card_number = 0;
// There's a strange behavior (bug? "feature"?) in Episode 3 where the start
// button does nothing in the lobby (hence you can't "quit game") if the
// client's IP address is zero. So, we fill it in with a fake nonzero value to
// avoid this behavior, and to be consistent, we make IP addresses fake and
// nonzero on all other versions too.
// There's a strange behavior (bug? "feature"?) in Episode 3 where the start button does nothing in the lobby (hence
// you can't "quit game") if the client's IP address is zero. So, we fill it in with a fake nonzero value to avoid
// this behavior, and to be consistent, we make IP addresses fake and nonzero on all other versions too.
be_uint32_t ip_address = 0x7F000001;
le_uint32_t client_id = 0;
pstring<TextEncoding::UTF16, 0x10> name;
@@ -563,8 +547,7 @@ struct XBNetworkLocation {
/* 04 */ le_uint32_t external_ipv4_address = 0x23232323;
/* 08 */ le_uint16_t port = 9500;
/* 0A */ parray<uint8_t, 6> mac_address = 0x77;
// The remainder of this struct appears to be private/opaque in the XDK (and
// newserv doesn't use it either)
// The remainder of this struct appears to be private/opaque in the XDK (and newserv doesn't use it either)
/* 10 */ le_uint32_t sg_ip_address = 0x0B0B0B0B;
/* 14 */ le_uint32_t spi = 0xCCCCCCCC;
/* 18 */ le_uint64_t account_id = 0xFFFFFFFFFFFFFFFF;
@@ -593,8 +576,7 @@ struct PlayerLobbyDataBB {
/* 10 */ parray<uint8_t, 0x0C> unknown_a1;
/* 1C */ le_uint32_t client_id = 0;
/* 20 */ pstring<TextEncoding::UTF16_ALWAYS_MARKED, 0x10> name;
// If this field is zero, the "Press F1 for help" prompt appears in the corner
// of the screen in the lobby and on Pioneer 2.
// If this is zero, the "Press F1 for help" prompt appears in the corner of the screen in the lobby and Pioneer 2.
/* 40 */ le_uint32_t hide_help_prompt = 1;
/* 44 */
@@ -612,11 +594,9 @@ struct ChallengeAwardStateT {
ret.maximum_rank = this->maximum_rank;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(ChallengeAwardStateT, 8);
using ChallengeAwardState = ChallengeAwardStateT<false>;
using ChallengeAwardStateBE = ChallengeAwardStateT<true>;
check_struct_size(ChallengeAwardState, 8);
check_struct_size(ChallengeAwardStateBE, 8);
template <TextEncoding UnencryptedEncoding, TextEncoding EncryptedEncoding>
struct PlayerRecordsChallengeDCPCT {
@@ -653,8 +633,7 @@ check_struct_size(PlayerRecordsChallengePC, 0xD8);
template <bool BE>
struct PlayerRecordsChallengeV3T {
// Offsets are (1) relative to start of C5 entry, and (2) relative to start
// of save file structure
// Offsets are (1) relative to start of C5 entry, and (2) relative to start of save file structure
/* 0000:001C */ U16T<BE> title_color = 0x7FFF; // XRGB1555
/* 0002:001E */ parray<uint8_t, 2> unknown_u0;
/* 0004:0020 */ parray<ChallengeTimeT<BE>, 9> times_ep1_online;
@@ -679,9 +658,8 @@ struct PlayerRecordsChallengeV3T {
/* 00C8:00E4 */ ChallengeAwardStateT<BE> ep2_online_award_state;
/* 00D0:00EC */ ChallengeAwardStateT<BE> ep1_offline_award_state;
/* 00D8:00F4 */
// On Episode 3, there are special cases that apply to this field - if the
// text ends with certain strings, the player will have particle effects
// emanate from their character in the lobby every 2 seconds. The effects are:
// On Episode 3, there are special cases that apply to this field - if the text ends with certain strings, the player
// will have particle effects emanate from their character in the lobby every 2 seconds. The effects are:
// Ends with ":GOD" => blue circle
// Ends with ":KING" => white particles
// Ends with ":LORD" => rising yellow sparkles
@@ -689,11 +667,9 @@ struct PlayerRecordsChallengeV3T {
/* 00D8:00F4 */ pstring<TextEncoding::CHALLENGE8, 0x0C> rank_title;
/* 00E4:0100 */ parray<uint8_t, 0x1C> unknown_l7;
/* 0100:011C */
} __attribute__((packed));
} __packed_ws_be__(PlayerRecordsChallengeV3T, 0x100);
using PlayerRecordsChallengeV3 = PlayerRecordsChallengeV3T<false>;
using PlayerRecordsChallengeV3BE = PlayerRecordsChallengeV3T<true>;
check_struct_size(PlayerRecordsChallengeV3, 0x100);
check_struct_size(PlayerRecordsChallengeV3BE, 0x100);
struct PlayerRecordsChallengeEp3 {
/* 00:1C */ be_uint16_t title_color = 0x7FFF; // XRGB1555
@@ -720,8 +696,7 @@ struct PlayerRecordsChallengeEp3 {
/* C8:E4 */ ChallengeAwardStateT<true> ep2_online_award_state;
/* D0:EC */ ChallengeAwardStateT<true> ep1_offline_award_state;
/* D8:F4 */
} __attribute__((packed));
check_struct_size(PlayerRecordsChallengeEp3, 0xD8);
} __packed_ws__(PlayerRecordsChallengeEp3, 0xD8);
struct PlayerRecordsChallengeBB {
/* 0000 */ le_uint16_t title_color = 0x7FFF; // XRGB1555
@@ -849,11 +824,9 @@ struct PlayerRecordsBattleT {
}
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(PlayerRecordsBattleT, 0x18);
using PlayerRecordsBattle = PlayerRecordsBattleT<false>;
using PlayerRecordsBattleBE = PlayerRecordsBattleT<true>;
check_struct_size(PlayerRecordsBattle, 0x18);
check_struct_size(PlayerRecordsBattleBE, 0x18);
template <typename DestT, typename SrcT = DestT>
DestT convert_player_disp_data(const SrcT&, Language, Language) {
@@ -862,7 +835,8 @@ DestT convert_player_disp_data(const SrcT&, Language, Language) {
}
template <>
inline PlayerDispDataDCPCV3 convert_player_disp_data<PlayerDispDataDCPCV3>(const PlayerDispDataDCPCV3& src, Language, Language) {
inline PlayerDispDataDCPCV3 convert_player_disp_data<PlayerDispDataDCPCV3>(
const PlayerDispDataDCPCV3& src, Language, Language) {
return src;
}
@@ -879,8 +853,7 @@ inline PlayerDispDataBB convert_player_disp_data<PlayerDispDataBB, PlayerDispDat
}
template <>
inline PlayerDispDataBB convert_player_disp_data<PlayerDispDataBB>(
const PlayerDispDataBB& src, Language, Language) {
inline PlayerDispDataBB convert_player_disp_data<PlayerDispDataBB>(const PlayerDispDataBB& src, Language, Language) {
return src;
}
@@ -1117,10 +1090,7 @@ struct SymbolChatT {
/* 0C */ parray<SymbolChatFacePart, 12> face_parts;
/* 3C */
SymbolChatT()
: spec(0),
corner_objects(0x00FF),
face_parts() {}
SymbolChatT() : spec(0), corner_objects(0x00FF), face_parts() {}
operator SymbolChatT<!BE>() const {
SymbolChatT<!BE> ret;
@@ -1131,11 +1101,9 @@ struct SymbolChatT {
ret.face_parts = this->face_parts;
return ret;
}
} __attribute__((packed));
} __packed_ws_be__(SymbolChatT, 0x3C);
using SymbolChat = SymbolChatT<false>;
using SymbolChatBE = SymbolChatT<true>;
check_struct_size(SymbolChat, 0x3C);
check_struct_size(SymbolChatBE, 0x3C);
struct TelepipeState {
/* 00 */ le_uint16_t owner_client_id = 0xFFFF;
@@ -1148,7 +1116,7 @@ struct TelepipeState {
struct PlayerHoldState_DCProtos {
// This is used in all versions of this command except DCNTE and 11/2000.
/* 00 */ le_uint16_t unknown_a1 = 0;
/* 00 */ le_uint16_t expiration_frames = 0;
/* 02 */ le_uint16_t unknown_a2 = 0;
// unknown_a3 is missing in this format, unlike the v1+ format below
/* 04 */ le_float trigger_radius2 = 0.0f;
@@ -1159,7 +1127,7 @@ struct PlayerHoldState_DCProtos {
struct PlayerHoldState {
// This is used in all versions of this command except DCNTE and 11/2000.
/* 00 */ le_uint16_t unknown_a1 = 0;
/* 00 */ le_uint16_t expiration_frames = 0;
/* 02 */ le_uint16_t unknown_a2 = 0;
/* 04 */ le_uint32_t unknown_a3 = 0;
/* 08 */ le_float trigger_radius2 = 0.0f;
+894 -485
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More