Compare commits

..

330 Commits

Author SHA1 Message Date
Martin Michelsen 2bab3f2f8f fix episode 4 boss drops
Docker / Build (push) Has been cancelled
2025-09-30 23:19:44 -07:00
Martin Michelsen fdd0bfea08 rewrite quest metadata indexing
- split ep3 download quests from quest index
- fix Ep3 NTE download quests
- automatically detect battle/challenge params and area remaps
2025-09-28 23:26:14 -07:00
Martin Michelsen 48c225366f rewrite trade sequence 2025-09-26 21:45:24 -07:00
Martin Michelsen 0d88253334 add deadzone hint to font bitmap decoder 2025-09-26 21:45:04 -07:00
Martin Michelsen d7b17aa383 update some notes 2025-09-26 21:44:44 -07:00
Martin Michelsen ba131ab94a handle 6xE2 full inventory case 2025-09-25 21:20:48 -07:00
Martin Michelsen 648d9c5164 remove leader check on 6x17 2025-09-25 09:06:53 -07:00
Martin Michelsen 60487daf6f fix 6x17 checks for Vol Opt arena 2025-09-24 21:02:05 -07:00
Martin Michelsen e0c43836b3 add English AR code for Ep1&2 Trial 2025-09-22 18:05:42 -07:00
Martin Michelsen 719a403b1d show dmc patch in patches menu 2025-09-22 18:05:42 -07:00
Martin Michelsen 6f88c3d31a fix size field in 6xDD 2025-09-22 09:20:45 -07:00
Martin Michelsen 7114798e69 fix size check on 6xDD extension 2025-09-21 17:18:42 -07:00
Martin Michelsen 65384435a3 add extension for fractional EXP multipliers on BB 2025-09-21 13:16:28 -07:00
Martin Michelsen 4236ff62b1 add ep1 boss rush test 2025-09-19 09:16:28 -07:00
Martin Michelsen 277be9bcd6 obscure security updates 2025-09-18 23:48:14 -07:00
Martin Michelsen 9493e2d3e7 add some ar codes 2025-09-18 21:51:55 -07:00
Martin Michelsen 16b15162d5 add decrypt_pr1_data 2025-09-16 08:39:19 -07:00
Martin Michelsen 9854b93d02 support AFS tables in convert-common-item-set 2025-09-16 08:39:12 -07:00
Martin Michelsen d02ab1e7a5 add node about D5 non-repeatability on BB 2025-09-16 08:38:49 -07:00
Martin Michelsen e0c8ca677f add Windows build outline 2025-09-14 21:03:42 -07:00
Martin Michelsen 2cea44f790 add Ep3 JP subcommands in handler-tables 2025-09-14 13:37:39 -07:00
Martin Michelsen fb783034bc handle incorrect flags in 10 command 2025-09-14 13:04:42 -07:00
Martin Michelsen 40a6f49b29 fix crossplay challenge restart logic 2025-09-13 22:38:32 -07:00
Martin Michelsen dea0ac99c3 update some command notes 2025-09-13 22:38:27 -07:00
Martin Michelsen 24cf8e73c6 fix incorrect symlink on q080-gcn 2025-09-12 23:50:47 -07:00
Martin Michelsen c301a921e6 assume all GC NTE quests are Episode 1 2025-09-12 23:50:47 -07:00
Martin Michelsen 22d7825ba3 handle devil's/demon's in EnemyDamageSync 2025-09-12 23:45:51 -07:00
Martin Michelsen 526bfb64e5 fix memcpy call that gcc is unhappy with 2025-09-11 16:17:38 -07:00
Martin Michelsen 55cbf6e20b fix out-of-bounds access in 6x46, etc. 2025-09-11 10:14:39 -07:00
Martin Michelsen 0b86ffb227 fix use-after-free in AsyncPromise 2025-09-11 10:14:39 -07:00
Matt Swift e28596c825 Add Aberrant Grove custom quest 2025-09-11 09:31:14 -07:00
Matt Swift 716676b87d Add GC NTE quest symlinks 2025-09-11 09:31:14 -07:00
Martin Michelsen 5ca0265c37 remove unused argument 2025-09-10 22:10:47 -07:00
Martin Michelsen c7a0873ca8 fix cross-floor commands in EnemyDamageSync 2025-09-10 21:15:22 -07:00
Martin Michelsen b1d51cdbbe fix visibility for some patches 2025-09-09 23:18:09 -07:00
Martin Michelsen 5a7151bc63 minor proxy bugfixes 2025-09-09 23:18:01 -07:00
Martin Michelsen 49d861919f update some notes 2025-09-06 22:53:59 -07:00
Martin Michelsen 3f20c4239f remove cmake from explicit-install list in GH Actions script 2025-09-02 21:37:58 -07:00
Martin Michelsen 038f306661 update notes on some 6xB5 subcommands 2025-09-02 21:34:39 -07:00
Martin Michelsen 0575f3c9cf fix windows build 2025-09-02 21:34:19 -07:00
Martin Michelsen e37307acb3 fix bank load function when index not set 2025-08-29 18:49:32 -07:00
Martin Michelsen 4b32b41183 add note in readme about xbox connectivity 2025-08-29 10:33:51 -07:00
Martin Michelsen c8f8a6f65b clean up legacy format notes 2025-08-26 23:54:56 -07:00
Martin Michelsen 0c93275e88 describe some esoteric NTE and 11/2000 commands 2025-08-24 22:47:33 -07:00
Martin Michelsen c44ab27c7e update some command notes 2025-08-24 18:17:39 -07:00
Martin Michelsen 3f09a7b57b add version checks around bank access 2025-08-24 17:28:26 -07:00
Martin Michelsen 0b4d5b2f89 add BB BankSize patch 2025-08-22 22:39:32 -07:00
Martin Michelsen 45824b46fe support per-quest common and rare tables 2025-08-22 14:09:41 -07:00
Martin Michelsen e78f3142e3 update comment on send_lobby_list 2025-08-21 10:37:35 -07:00
Martin Michelsen 4166149841 add player check in HungryMagSound 2025-08-19 23:18:03 -07:00
Martin Michelsen 45131dabc0 fix dice range parsing in create-tournament 2025-08-19 20:22:41 -07:00
Martin Michelsen b235644575 expand leaf containers in text set serialization 2025-08-15 12:54:13 -07:00
Martin Michelsen 377d8beac3 implement $switchchar command 2025-08-14 23:44:16 -07:00
Martin Michelsen 16bff52575 update comments in expand_rate 2025-08-13 11:51:35 -07:00
Martin Michelsen 49fb7eba60 fix $bank when used with MoreSaveSlots 2025-08-13 11:42:20 -07:00
Martin Michelsen 00b46d7161 update game_flags notes 2025-08-13 11:42:07 -07:00
Martin Michelsen 5bea9d3a2b add warning about crossplay + stack limits 2025-08-07 00:00:25 -07:00
Martin Michelsen a9dcd4b87e enforce stack limits when loading BB character data
Docker / Build (push) Has been cancelled
2025-08-06 21:23:30 -07:00
Martin Michelsen 5c84581978 add names in show-battle-params 2025-08-06 21:03:20 -07:00
Martin Michelsen ab38a58e39 mention address config in readme 2025-08-06 21:02:30 -07:00
Martin Michelsen d430112a94 support chat shell command for non-proxy clients 2025-07-27 14:18:48 -07:00
Martin Michelsen 0cf59f874d use remote_addr for SocketChannel in send_reconnect 2025-07-26 16:54:13 -07:00
Martin Michelsen bf028ed0f6 fix data2 handling in 30 command from GetExtendedPlayerInfo 2025-07-24 21:37:36 -07:00
Martin Michelsen 1ecc41dea9 format show-item-tables output more cleanly 2025-07-24 18:38:14 -07:00
Justin Schwartz 648e15a016 document the original unit stars random state 2025-07-22 23:18:53 -07:00
Martin Michelsen 1729edc1d2 add dynamic switching in EnemyDamageSync 2025-07-22 00:27:21 -07:00
Martin Michelsen bbcc03f832 improve CommonItemSet JSON parser/serializer 2025-07-20 22:30:04 -07:00
Martin Michelsen 6827229c83 refine 6x79 a bit 2025-07-20 22:30:01 -07:00
Martin Michelsen 60291993b6 add configurable min levels for non-BB; closes #666 2025-07-11 17:57:39 -07:00
Martin Michelsen 118512ebb2 fix websocket timeout 2025-07-10 09:38:31 -07:00
Martin Michelsen ae9eaccd29 fix disconnect for websocket clients 2025-07-08 20:09:20 -07:00
Martin Michelsen 3025420aea fix headers in show-item-tables 2025-07-08 20:09:04 -07:00
Martin Michelsen 3c4ad43e71 add belra arm bug fix 2025-07-06 23:25:03 -07:00
Martin Michelsen 9e02b6c666 add $sound command 2025-07-06 21:41:31 -07:00
Martin Michelsen fe435c13d3 fix local address detection 2025-07-06 20:48:44 -07:00
Martin Michelsen 3b5145880c fix $loadchar description in readme 2025-07-06 15:35:56 -07:00
Martin Michelsen d965ff5031 add stat boosts to ItemPMT formatting 2025-07-06 13:57:31 -07:00
Martin Michelsen 22a89deb8b fix save game data timer 2025-07-05 20:27:24 -07:00
Martin Michelsen c9ba61a4b0 fix NAME_ONLY for units with kill counts 2025-07-05 19:54:30 -07:00
Martin Michelsen 0cdf2784cc fix text alignment in MoreSaveSlots 2025-07-05 19:49:20 -07:00
Martin Michelsen 76a948a45d fix unused variable 2025-07-03 00:27:38 -07:00
Martin Michelsen fd39a89957 fix BB proxy bugs 2025-07-02 21:14:32 -07:00
Martin Michelsen 0a5065707c use new phosg::Image class 2025-07-01 09:56:42 -07:00
Martin Michelsen 072e647c7b update readme 2025-06-29 11:22:40 -07:00
Martin Michelsen 148db03a9a fix copy-paste error in MoreSaveSlots patch 2025-06-24 20:53:33 -07:00
Martin Michelsen cff5ad23fc fix scroll bar setup in MoreSaveSlots 2025-06-24 20:12:49 -07:00
Martin Michelsen 3e174b7397 add notes on TObjSinBoard 2025-06-24 20:12:33 -07:00
Martin Michelsen e9bf51f3f7 save all fields when applying npc skins 2025-06-24 20:12:24 -07:00
Martin Michelsen 28ab1bea9c add IPv6 support in proxy 2025-06-17 01:19:26 -07:00
Martin Michelsen 923cc4ebb0 add missing xbox includes 2025-06-16 19:22:38 -07:00
Martin Michelsen e24a0e3c40 decrypt Ep3 player config at load time 2025-06-16 00:30:53 -07:00
Martin Michelsen a857cc9d03 update some notes 2025-06-16 00:10:50 -07:00
Martin Michelsen 8746b544b6 describe the PCv2-exclusive quest opcodes 2025-06-14 20:40:53 -07:00
Martin Michelsen ccd5baedf1 add notes from BB trial edition 2025-06-14 12:00:36 -07:00
Martin Michelsen 9621e89cd7 add notes and support for final PCv2 version 2025-06-14 00:35:56 -07:00
Martin Michelsen 3844c9881c add AccurateKillCount patch 2025-06-12 18:49:38 -07:00
Martin Michelsen 6999694f89 rewrite 6xE4 logic 2025-06-12 01:27:54 -07:00
Martin Michelsen 54acd931da use .label/.address in xbox client functions 2025-06-09 10:00:38 -07:00
Martin Michelsen 9bc9e219b5 add patch for disabling Xbox save signature validation 2025-06-07 19:32:21 -07:00
Martin Michelsen e8b2765a71 add xbox disk file formats 2025-06-07 19:26:34 -07:00
Martin Michelsen d4bc880018 make $killcount work for units too 2025-06-07 09:53:56 -07:00
Martin Michelsen c1a2742617 update readme 2025-06-07 09:53:35 -07:00
Martin Michelsen ebaeb2f70a update docs for find_inventory_item quest opcode 2025-06-05 21:33:51 -07:00
Martin Michelsen 0366e36edb add Xbox-US1 quest handlers 2025-06-05 20:59:41 -07:00
Martin Michelsen a0f52f01bb use 6x2F for infinite HP 2025-06-04 00:18:57 -07:00
Martin Michelsen bee4c55446 make client functions parameterizable by version 2025-06-04 00:16:43 -07:00
Martin Michelsen 1a6b26e56b add text-only matching in AddressTranslator 2025-06-03 09:59:19 -07:00
Martin Michelsen 1047d089d5 fix 6x0B error message 2025-05-31 23:15:23 -07:00
Martin Michelsen 2d6096cfda fix $savechar on BB 2025-05-31 23:15:00 -07:00
Martin Michelsen 7cbd9402d0 fix CallNativeFunctionGC
Docker / Build (push) Has been cancelled
2025-05-31 15:15:03 -07:00
Martin Michelsen 0396337994 fix inventory/bank debug messages 2025-05-31 15:14:04 -07:00
Martin Michelsen 6fbc0829ae add patch to replace Pinz shop cards 2025-05-31 10:56:01 -07:00
Martin Michelsen 4f41cbc9ce fix description generated in $item command 2025-05-31 10:07:11 -07:00
Martin Michelsen d1e6d75d70 fix TethVer detection hack 2025-05-31 10:04:09 -07:00
Martin Michelsen 067f2439ca make redirect wait apply to SocketChannels as well 2025-05-31 09:34:09 -07:00
Martin Michelsen 2d2edbd7be fix ping exception handler 2025-05-31 09:29:01 -07:00
Vargur f5f457aa6f Fix HTTP endpoint logic: remove incorrect negation in rare-tables path check
The !req.path.starts_with( was causing every subsequent command to be processed as a rare-tables substring command.
2025-05-30 19:29:52 -07:00
Martin Michelsen aabbafb749 fix game flag translation across v2/v3 boundary 2025-05-28 22:01:54 -07:00
Martin Michelsen e72e37f713 implement extended $infhp features on proxy server; closes #501 2025-05-27 19:34:47 -07:00
Martin Michelsen f884893b18 reprioritize to-do list 2025-05-27 19:34:25 -07:00
Martin Michelsen c74c0e2250 fix conditions 2025-05-26 23:52:43 -07:00
Martin Michelsen 5f4d2ec891 complete implementation of $checkchar and make slot count configurable; closes #645 2025-05-26 21:55:19 -07:00
Martin Michelsen 33b0ab3ed3 improve BB proxy functionality 2025-05-26 18:56:23 -07:00
Martin Michelsen 2e158a1df8 fix Programs menu item in tests
Docker / Build (push) Has been cancelled
2025-05-26 15:08:26 -07:00
Martin Michelsen 6a89f18580 make logging less verbose 2025-05-26 14:51:43 -07:00
Martin Michelsen b3e757dcdc add Windows platform wrapper 2025-05-26 14:20:20 -07:00
Martin Michelsen 9c675a14ab fix CI build steps 2025-05-26 14:17:47 -07:00
Martin Michelsen cc99050964 switch to coroutine execution model 2025-05-26 14:11:38 -07:00
Martin Michelsen f65b1f1c14 make login faster with MoreSaveSlots 2025-04-25 08:56:19 -07:00
Martin Michelsen 1ad2c47444 make $exit work without a quest loaded on most versions 2025-04-24 18:58:20 -07:00
Martin Michelsen ebef2f2bd1 add aliases for $arrow command 2025-04-21 19:51:00 -07:00
Martin Michelsen afa23f03c7 describe how TObjNpcEnemy works 2025-04-19 11:01:31 -07:00
Martin Michelsen 9d7b6c6341 update some notes 2025-04-19 11:00:33 -07:00
Martin Michelsen 4199f7bb23 update comments on MoreSaveSlots patch 2025-04-13 19:11:12 -07:00
Martin Michelsen 140d488239 support more BB save slots; add client patch 2025-04-12 23:35:00 -07:00
Martin Michelsen 22e9314e18 fix some notes 2025-04-07 23:49:08 -07:00
anzz1 c8a3b3ba31 add 59NL version of Palette client patch
Enables the alternate action palette for number keys
Credits to Soly from Blue Burst Patch Project
2025-04-05 21:42:09 -07:00
Martin Michelsen 8b7e4014ae fix quest max players check; closes #636 2025-04-05 14:11:21 -07:00
Martin Michelsen 13b94e7ba1 minor cleanup in map entity notes 2025-04-05 11:38:04 -07:00
Martin Michelsen ab2a8d5fa9 document item/level table format commands 2025-04-05 11:38:04 -07:00
Martin Michelsen a01d8206e1 add outline of ep4 enemy args 2025-04-04 14:23:43 -07:00
Martin Michelsen 61570a2563 add version/area flags to object/enemy defs 2025-04-04 00:39:57 -07:00
Martin Michelsen 822c0e0670 more ep2 enemy notes 2025-04-03 10:39:40 -07:00
Martin Michelsen c5b5ab3815 fixes after compiler upgrade 2025-04-03 10:38:55 -07:00
anzz1 b28e9a5d54 [BB] unitxt_shop_e typo fix
"This item will be delete. OK?" -> "This item will be deleted. OK?"
2025-03-31 20:19:30 -07:00
anzz1 e5e61d189c [BB] Correct unitxt_shop_e.prs, add WS files for reference
Corrected unitxt_shop_e.prs: Fixed typo 'Mestea' -> 'Meseta', added missing Present Counter text lines.
Added WS files to notes for reference (from gsl)
2025-03-31 20:19:30 -07:00
anzz1 8b35d07fc9 59NL DrawDistance client function (beta)
Currently beta quality, map objects that fade like boxes, and Pioneer's
background billboards and elevators still have regular draw distance.
TODO: 90% of stuff is included, bring home the last 10%.
2025-03-31 20:18:39 -07:00
anzz1 2f462d391e Update HungryMagSound.59NL.patch.s
Change the hungry mag sound effect from "message received" to "mag feed"
2025-03-31 20:15:38 -07:00
Martin Michelsen 09d3b90169 describe some Ep2 enemies 2025-03-30 16:21:02 -07:00
Martin Michelsen a329db3036 use new phosg hash interface 2025-03-30 12:57:55 -07:00
Martin Michelsen 711fa742be describe ep1/ep2 bosses 2025-03-29 21:51:05 -07:00
Martin Michelsen d9c549bef5 add $whatene command 2025-03-29 21:50:11 -07:00
Martin Michelsen e0d1db0363 handle DARK_GUNNER_CONTROL properly 2025-03-29 16:32:53 -07:00
Martin Michelsen 1723a4152c describe Ruins enemies 2025-03-29 16:19:35 -07:00
Martin Michelsen c212b2987c describe Mines enemies 2025-03-28 22:36:19 -07:00
Martin Michelsen 488a5b201e more enemy type docs 2025-03-27 23:38:46 -07:00
Martin Michelsen 4770297cd0 document some things in ItemPMT 2025-03-27 23:38:37 -07:00
Martin Michelsen 3297df580a port the menu code to all versions 2025-03-26 23:22:03 -07:00
Martin Michelsen 936b914cbc start describing enemy types 2025-03-26 23:07:39 -07:00
Martin Michelsen ad51dcf16f describe remaining object types 2025-03-25 17:37:03 -07:00
Martin Michelsen c8f330e2c8 describe some ep4 objects 2025-03-25 11:30:11 -07:00
Martin Michelsen 6467693df9 describe a few Ep4 objects 2025-03-24 23:45:22 -07:00
Martin Michelsen 07716fd301 describe Ep3 map objects 2025-03-24 18:33:59 -07:00
Martin Michelsen b30cd3bb8e load Ep3 Morgue map 2025-03-24 18:29:09 -07:00
Martin Michelsen a4a8389add describe remaining Ep2 objects 2025-03-24 15:24:19 -07:00
Martin Michelsen 7f2fca3a79 add notes for lobby, temple, and spaceship objects 2025-03-23 21:58:37 -07:00
Martin Michelsen cfea8a2712 more object notes 2025-03-22 12:52:31 -07:00
Martin Michelsen 3e59f9a91e brace-init in vector math 2025-03-22 00:05:50 -07:00
Martin Michelsen 69edba036e add $whatobj command 2025-03-21 23:58:49 -07:00
Martin Michelsen ca1dc6ad7d more object notes 2025-03-21 23:58:49 -07:00
Martin Michelsen dcd8d3b650 more object notes 2025-03-18 23:45:38 -07:00
Martin Michelsen 1bc668f72f disable non-resource-file CI build 2025-03-18 20:58:44 -07:00
Martin Michelsen 52d019a321 make BB proxy's Save Files option generate .psochar files 2025-03-18 20:55:04 -07:00
Martin Michelsen 02c3d35d78 more object comments 2025-03-18 20:55:04 -07:00
Martin Michelsen 6328453d38 make resource_file required 2025-03-18 18:59:16 -07:00
Martin Michelsen 595675df20 refine object comments 2025-03-18 00:49:55 -07:00
Martin Michelsen 4489bca037 document more map object types 2025-03-17 22:57:24 -07:00
Martin Michelsen 333b62b884 rewrite dat constructor tables 2025-03-16 23:09:49 -07:00
Martin Michelsen f06b07a7c4 add note on F829 2025-03-16 12:20:13 -07:00
Martin Michelsen b52a2e4a5b refine some ItemPMT structures 2025-03-16 12:20:13 -07:00
Martin Michelsen 26c3a87a73 distinguish hidden-name ES weapons 2025-03-16 12:20:13 -07:00
Martin Michelsen 73eef4815b update 6x9A description 2025-03-16 12:20:13 -07:00
Martin Michelsen d85737b1a7 update release instructions; closes #621 2025-03-14 23:36:03 -07:00
Martin Michelsen ed05bbe2e3 write gc/xbox versions of NoRareSelling 2025-03-14 23:23:39 -07:00
Martin Michelsen f0c492abea remove patches menu in favor of patch switches; closes #623 2025-03-14 23:20:09 -07:00
Martin Michelsen 2cff04943f add player_count in 83 command struct 2025-03-14 23:20:09 -07:00
anzz1 1df7b821e8 cleanup 59NL NoSellRare client patch 2025-03-14 21:17:54 -07:00
anzz1 5fb842761d add 59NL version of NoSellRare client patch
Prevents you from accidentally selling rares and untekked weapons to vendor
Credits to Soly from Blue Burst Patch Project
2025-03-14 21:17:54 -07:00
Martin Michelsen 3cddb99c20 use IP stack sim address in HTTP responses if client is on tapserver 2025-03-09 23:27:07 -07:00
Martin Michelsen e27426dc16 delete unverified BB HTML drop tables
Docker / Build (push) Has been cancelled
2025-03-09 20:40:07 -07:00
Martin Michelsen 4cf650fb98 fix team member remove bug 2025-03-09 17:36:08 -07:00
Martin Michelsen 3857cda4e5 fix team member count updates 2025-03-09 16:11:34 -07:00
Martin Michelsen 99ebf96cb0 fix allowed version flags on Ep2 BB games; closes #619 2025-03-09 16:11:09 -07:00
Martin Michelsen 311af36632 add HTML drop tables 2025-03-09 00:55:32 -08:00
Martin Michelsen cf46a2cfc1 make salvage-gci --round2 21000x faster 2025-03-08 23:44:57 -08:00
Martin Michelsen 002a504418 describe a few more object params 2025-03-08 23:44:57 -08:00
Martin Michelsen ff9ff218bb fix help text 2025-03-08 23:04:48 -08:00
Martin Michelsen 5f838815ab fix team membership struct 2025-03-08 23:04:48 -08:00
Martin Michelsen c7d606247f describe some more object types 2025-03-05 22:37:50 -08:00
Martin Michelsen 546e8a3801 gcc should be able to handle this 2025-03-01 20:02:39 -08:00
Martin Michelsen f53604f49c start documenting map object types 2025-03-01 19:50:36 -08:00
Martin Michelsen 84c62b33a4 update comments on 6x93 and 6xB2 2025-03-01 19:50:36 -08:00
Martin Michelsen ddc52c06ae fix $where in the lobby 2025-03-01 19:50:36 -08:00
Martin Michelsen d02a3d7d64 add extract-ppk action 2025-03-01 19:50:36 -08:00
Martin Michelsen 21a0efa8ac update comment on get_random quest opcode 2025-03-01 19:50:36 -08:00
Martin Michelsen 4d7a3395ba refine quest header format; use metadata from .bin.txt file if present 2025-03-01 19:50:36 -08:00
Martin Michelsen 78fe4ebf98 refine 24 and 25 command structs 2025-02-27 23:14:46 -08:00
Martin Michelsen c596a18b3a support .include in quest scripts 2025-02-26 21:01:55 -08:00
Martin Michelsen f3b547f93c fix v1 itemrt conversion 2025-02-25 14:51:52 -08:00
Martin Michelsen ef53a3b269 fix signed comparison 2025-02-24 10:20:20 -08:00
Martin Michelsen 4f364f56d0 update html rare table generator 2025-02-24 10:14:37 -08:00
Martin Michelsen 4e77ff7ab1 add --decompress option in decode-qst 2025-02-24 10:14:15 -08:00
Martin Michelsen 81ad01891a update version code notes 2025-02-24 10:13:33 -08:00
Martin Michelsen 03d303b2bb add encode/decode options for bitmap fonts 2025-02-23 17:05:16 -08:00
Martin Michelsen 52bca977c3 fix enemy type conditions to match what the client does 2025-02-23 11:24:43 -08:00
Martin Michelsen f9cac45996 allow including shared files via .include_native 2025-02-23 11:20:55 -08:00
Martin Michelsen 04dbcef2cf recompile extended item info AR code for v1.2 2025-02-22 20:53:08 -08:00
Martin Michelsen 66e00d5136 add $nativecall command 2025-02-22 20:52:47 -08:00
Martin Michelsen 11d539042c fix ExtendedItemInfo patch and add AR code 2025-02-22 17:18:30 -08:00
Martin Michelsen 104e31028b fix incorrect box drop areas in rare tables 2025-02-22 16:50:18 -08:00
Martin Michelsen fa22c3563d add HTML rare table generator 2025-02-22 14:01:33 -08:00
Martin Michelsen 2cd4e5cf27 add file caches in non-server ServerState constructor 2025-02-20 22:31:39 -08:00
Martin Michelsen d9744a696e implement item translation table 2025-02-20 22:31:26 -08:00
Martin Michelsen 813bd2e0fa fix definition of give_s_rank_weapon opcode 2025-02-20 21:29:57 -08:00
Martin Michelsen 2d42d1ce07 update some item-related notes 2025-02-20 21:29:45 -08:00
Martin Michelsen 9001af38cd fix patch flags on BB 2025-02-20 21:29:02 -08:00
Martin Michelsen 67a56a369f fix corruption loader AR code 2025-02-17 23:16:18 -08:00
Martin Michelsen f4da9c8cb2 add enemy count generator 2025-02-17 19:34:36 -08:00
Martin Michelsen 963788af33 add enemy count computation in load-maps-test 2025-02-17 18:13:44 -08:00
Martin Michelsen d0e0e59762 add ReturnTokenX86 function 2025-02-17 10:36:53 -08:00
Martin Michelsen caf41c99de add stub for new address translator function 2025-02-17 00:19:03 -08:00
Martin Michelsen 9185dc0b62 fix overly long option names 2025-02-17 00:14:58 -08:00
Martin Michelsen 83990c6d5f construct supermaps on-demand instead of at startup 2025-02-17 00:14:58 -08:00
Martin Michelsen f53ca31b22 update 6x61 description 2025-02-17 00:14:58 -08:00
Martin Michelsen 44ea82771b update client functions for eventual pc v2 semantics 2025-02-17 00:14:58 -08:00
Martin Michelsen 984d8f0f31 update executable diff action 2025-02-17 00:14:58 -08:00
Martin Michelsen 7570c3ce34 add more ar codes 2025-02-17 00:14:58 -08:00
Martin Michelsen d24a535cd6 write 59NJ version of DisableIdleDisconnect patch 2025-02-17 00:14:58 -08:00
Martin Michelsen f2d36d589b add v1 ports of RaresInQuests patch 2025-02-17 00:14:58 -08:00
Martin Michelsen 2b31656661 update write opcode comments in QuestScript.cc 2025-02-17 00:14:54 -08:00
Martin Michelsen 6e8eecda8b document more of ItemMagEdit.prs format 2025-02-14 22:39:15 -08:00
Martin Michelsen 9ed01ede2d use mag evolution table for fixed-type cell evolution; fixes #608 2025-02-13 21:59:00 -08:00
Martin Michelsen 5ed2503491 fix ExtendedItemInfo in city 2025-02-13 21:00:34 -08:00
Martin Michelsen 2a34d64f00 add 2OJ5 version of RaresInQuests 2025-02-13 07:38:13 -08:00
Martin Michelsen fe4bd3d495 fix print-item-tables 2025-02-13 07:36:52 -08:00
Blst34 7ad5cbd28b Add files via upload 2025-02-13 07:36:36 -08:00
Martin Michelsen 775369345c use semantic hash index to fill in gaps in supermap 2025-02-11 09:37:53 -08:00
Martin Michelsen 17fe80cf85 abstract supermap construction across entity types 2025-02-10 22:44:13 -08:00
Martin Michelsen a3428d33ae update Ep3 Plus description 2025-02-09 23:32:37 -08:00
Martin Michelsen 4a1561ec55 add Ep3 Plus as a client function 2025-02-09 23:22:58 -08:00
Martin Michelsen 405399682f improve diff-dol-files 2025-02-09 23:08:16 -08:00
Martin Michelsen 01e6c5a8fb shorter version of ep3 chat filter code 2025-02-09 23:08:09 -08:00
Martin Michelsen 048b8ba09c fix mericarol type logic; closes #607 2025-02-09 10:40:57 -08:00
Martin Michelsen b451c82943 add GSL archive generation 2025-02-09 08:55:59 -08:00
Martin Michelsen 9d7c71fb26 rewrite common bank patch 2025-02-08 22:47:23 -08:00
Martin Michelsen 07c5a8a4b6 rewrite chat patch 2025-02-08 22:05:44 -08:00
Martin Michelsen 15f923a639 rewrite palette patch 2025-02-08 14:59:24 -08:00
Martin Michelsen 4c55551e12 fix 6xA4 and 6xA5 sizes; closes #605 2025-02-07 08:56:29 -08:00
Martin Michelsen 81d5b23d80 fix $next on proxy server 2025-02-06 22:59:52 -08:00
Martin Michelsen fa7c76b75b add more door types 2025-02-06 22:53:21 -08:00
Martin Michelsen 1a7f219158 write other versions of ExtendedItemInfo patch 2025-02-01 09:29:45 -08:00
Martin Michelsen 4b3bde01e4 add extended item info patch 2025-01-31 22:25:11 -08:00
Martin Michelsen a7fdfbf732 don't print supermap at lobby creation; closes #601 2025-01-31 21:53:43 -08:00
Martin Michelsen c0994b49e5 add change marker AR code 2025-01-31 21:51:17 -08:00
Martin Michelsen 03fc351a35 add 59NJ versions of some patches; closes #598 2025-01-29 23:20:51 -08:00
Martin Michelsen 24722f0a27 more patches 2025-01-28 23:26:12 -08:00
Martin Michelsen b7293e7cb0 write more patches 2025-01-27 23:29:07 -08:00
Martin Michelsen b5104a7bda document many unknown fields 2025-01-26 15:41:54 -08:00
Martin Michelsen 78b7bfac70 refine many subcommand formats 2025-01-26 09:47:19 -08:00
Martin Michelsen 65a1b97093 refine more commands 2025-01-23 09:51:48 -08:00
Martin Michelsen 2e6e1adcf3 refine more commands 2025-01-22 23:26:12 -08:00
Martin Michelsen 7da0da66f1 refine some command formats 2025-01-22 00:41:17 -08:00
Martin Michelsen 4038221d8c fix telepipe desync during BB joinable quest load 2025-01-22 00:00:06 -08:00
Martin Michelsen 5c807fa655 refine some xb voice chat structs 2025-01-22 00:00:03 -08:00
Martin Michelsen aa9e1e7305 enable dcv1 native battle mode 2025-01-20 21:27:09 -08:00
Martin Michelsen 721b01a294 rename section to room 2025-01-19 23:21:56 -08:00
Martin Michelsen aa08e3c183 write xbox draw distance patch 2025-01-19 14:56:53 -08:00
Martin Michelsen 63fb78cc9e use original draw distance patch with fixed callback 2025-01-18 22:54:32 -08:00
Martin Michelsen a39adc593b update link on draw distance patch 2025-01-18 20:25:06 -08:00
Martin Michelsen afc6c44bc6 fix incorrect proxy handler on BB 2025-01-18 11:02:00 -08:00
Martin Michelsen 6f26cf87b1 add comment in SuperMap::add_enemy_and_children 2025-01-18 11:02:00 -08:00
Martin Michelsen 6e9d86a6ca use disconnect_client for the kick and ban commands 2025-01-17 21:05:40 -08:00
Martin Michelsen e2caf81e4b use scrolling message for BB client announcements; closes #593 2025-01-17 10:03:44 -08:00
Martin Michelsen 823fb17f60 replace draw distance patch; fixes #470 2025-01-16 23:42:54 -08:00
Martin Michelsen a30e7438ff fix status icons in enemy HP bars patch 2025-01-16 22:00:12 -08:00
Martin Michelsen 269d2178fb add /y/accounts and /y/data/quests in API 2025-01-15 20:34:56 -08:00
Martin Michelsen 6564db437a update HTTP server section in readme 2025-01-13 10:47:48 -08:00
Martin Michelsen 732f1d5eb6 update cc shell command help text 2025-01-12 16:37:25 -08:00
Martin Michelsen 9033fb6a5d rewrite chat command system 2025-01-12 16:27:02 -08:00
Martin Michelsen b028532db3 add /y/shell-exec in HTTP server 2025-01-11 22:16:26 -08:00
Martin Michelsen 80dda2e1f9 fix slime child count in challenge mode 2025-01-11 20:47:09 -08:00
Martin Michelsen 4d3595640a document hardware_id in login commands 2025-01-10 22:13:57 -08:00
Martin Michelsen 0704590238 add kick command in shell 2025-01-09 20:39:45 -08:00
Martin Michelsen 7c48dc1ff5 add notes about interaction mode 2025-01-08 23:49:03 -08:00
Martin Michelsen 68003b2e2f unify menu item format 2025-01-08 23:35:12 -08:00
Martin Michelsen f6fbba5638 run the HTTP server on the event thread on Windows 2025-01-06 22:38:19 -08:00
Martin Michelsen 4bfe7218f7 update readme 2025-01-06 08:14:16 -08:00
Martin Michelsen 5dbb6c3a27 allow concurrent proxy sessions on the same account 2025-01-06 00:12:00 -08:00
Martin Michelsen 0be056adce factor out shell command execution 2025-01-06 00:12:00 -08:00
Martin Michelsen d51f7a0fe7 fix v2/v3 crossplay quest loading 2025-01-05 10:51:59 -08:00
Martin Michelsen a7b5ea5562 allow v2 and v3 clients to load quests in the same game 2025-01-04 22:53:54 -08:00
Martin Michelsen d833727074 fix issue that caused v3 players to be temporarily invisible to v2 players after joining 2025-01-04 22:53:54 -08:00
Martin Michelsen 149e746e3a support dynamic objects in map state; closes #589 2025-01-04 22:53:54 -08:00
Martin Michelsen 1c5b0e4667 make name-all-items more useful 2025-01-04 19:01:16 -08:00
Martin Michelsen 8508607c87 rename DC_V1_11_2000_PROTOTYPE to DC_11_2000 2025-01-01 20:58:28 -08:00
Martin Michelsen 0862b01770 add missing includes on linux 2025-01-01 18:03:35 -08:00
Martin Michelsen 72ac20e574 rewrite map data model 2025-01-01 17:47:50 -08:00
Martin Michelsen 69f7bb3db9 always send server time at login; closes #586 2024-12-26 16:17:47 -08:00
Martin Michelsen dc7368e4af fix qst file format bug 2024-12-23 00:03:38 -08:00
Martin Michelsen 79c7e5dcb4 add inventory items to API response 2024-12-15 21:44:03 -08:00
Martin Michelsen 56ac0a5057 add offline seasonal rappies code 2024-12-14 19:06:13 -08:00
Martin Michelsen 183e7dbf8a fix incorrect CharClass in API server 2024-12-14 19:06:13 -08:00
Martin Michelsen e3097c5578 update ep3 battle setup debug messages 2024-12-14 19:06:13 -08:00
Martin Michelsen aebc9293ad document api endpoints 2024-12-11 19:38:36 -08:00
Martin Michelsen 4b3dcbb6f4 add item pickup patch 2024-12-07 17:29:10 -08:00
Martin Michelsen 3424d6481b add more log messages around login commands; closes #583 2024-12-03 22:21:12 -08:00
Martin Michelsen 760cec9d1e don't check auxiliary data on XB accounts; fixes #584 2024-12-03 21:37:27 -08:00
Martin Michelsen 0196c866f6 fix namespace 2024-12-01 13:19:34 -08:00
Martin Michelsen 13ee74945b refine option_flags notes 2024-12-01 10:07:21 -08:00
Martin Michelsen c6266ff624 fix checksum in 6xBB/6xBC 2024-11-30 22:13:17 -08:00
Martin Michelsen 9a15433fbf fix error in item comments 2024-11-30 10:21:46 -08:00
Martin Michelsen db2bd9d08f refine quest opcode notes 2024-11-29 23:33:44 -08:00
Martin Michelsen f5ed347734 convert private word select messages to text chat messages 2024-11-29 22:19:05 -08:00
Martin Michelsen 483f6dd3fc add conversion functions for proto and v1 save files 2024-11-24 12:26:12 -08:00
Martin Michelsen 0e5837f79a more quest opcode notes 2024-11-17 18:53:57 -08:00
Martin Michelsen ab1a2373b9 refine quest opcode notes 2024-11-17 13:49:10 -08:00
Martin Michelsen aa2b94b7f5 refine more quest opcodes 2024-11-15 19:30:10 -08:00
Martin Michelsen 55a8207932 refine quest opcode docs 2024-11-14 23:07:04 -08:00
Martin Michelsen 484feed314 update some notes 2024-11-13 23:17:15 -08:00
Martin Michelsen 04a42dc627 update readme 2024-11-13 22:42:10 -08:00
988 changed files with 364896 additions and 260767 deletions
+2 -4
View File
@@ -16,19 +16,18 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
with_resource_file: ["true", "false"]
steps:
- uses: actions/checkout@v4
- name: Install libraries (Linux)
if: ${{ matrix.os == 'ubuntu-latest' }}
run: sudo apt-get install -y libevent-dev
run: sudo apt-get install -y cmake libasio-dev
- name: Install libraries (macOS)
if: ${{ matrix.os == 'macos-latest' }}
run: |
brew install libevent
brew install asio libiconv
cat << EOF > nproc
#!/bin/sh
@@ -47,7 +46,6 @@ jobs:
sudo make install
- name: Install resource_file
if: ${{ matrix.with_resource_file == 'true' }}
run: |
git clone https://github.com/fuzziqersoftware/resource_dasm.git
cd resource_dasm
+2
View File
@@ -14,6 +14,7 @@ CTestTestfile.cmake
install_manifest.txt
Makefile
Testing
build
# Files modified by the user and/or server that don't have defaults
system/config.json
@@ -35,6 +36,7 @@ system/patch-bb/.metadata-cache.json
# repository
files
make_release.py
notes-private
old-khyller
old-newserv
release
+26 -42
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.10)
cmake_minimum_required(VERSION 3.22)
set(CMAKE_POLICY_DEFAULT_CMP0110 NEW)
@@ -19,19 +19,15 @@ endif()
# Library search
find_path (LIBEVENT_INCLUDE_DIR NAMES event.h)
find_library (LIBEVENT_LIBRARY NAMES event)
find_library (LIBEVENT_CORE NAMES event_core)
find_library (LIBEVENT_PTHREADS NAMES event_pthreads)
set (LIBEVENT_INCLUDE_DIRS ${LIBEVENT_INCLUDE_DIR})
set (LIBEVENT_LIBRARIES
${LIBEVENT_LIBRARY}
${LIBEVENT_CORE}
${LIBEVENT_PTHREADS})
find_path(ASIO_INCLUDE_DIR NAMES asio.hpp HINTS "${WINDOWS_ENV}/include" REQUIRED)
if(WIN32)
find_path(Iconv_INCLUDE_DIRS NAMES iconv.h HINTS "${WINDOWS_ENV}/include" REQUIRED)
find_library(Iconv_LIBRARIES NAMES iconv HINTS "${WINDOWS_ENV}/lib" REQUIRED)
else()
find_package(Iconv REQUIRED)
endif()
find_package(phosg REQUIRED)
find_package(Iconv REQUIRED)
find_package(resource_file QUIET)
find_package(resource_file REQUIRED)
@@ -54,10 +50,12 @@ add_custom_target(
set(SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/Revision.cc
src/Account.cc
src/AddressTranslator.cc
src/AFSArchive.cc
src/AsyncHTTPServer.cc
src/AsyncUtils.cc
src/BattleParamsIndex.cc
src/BMLArchive.cc
src/CatSession.cc
src/Channel.cc
src/ChatCommands.cc
src/ChoiceSearch.cc
@@ -80,12 +78,12 @@ set(SOURCES
src/Episode3/RulerServer.cc
src/Episode3/Server.cc
src/Episode3/Tournament.cc
src/EventUtils.cc
src/FileContentsCache.cc
src/FunctionCompiler.cc
src/GameServer.cc
src/GSLArchive.cc
src/GVMEncoder.cc
src/HTTPServer.cc
src/ImageEncoder.cc
src/IntegralExpression.cc
src/IPFrameInfo.cc
src/IPStackSimulator.cc
@@ -95,6 +93,7 @@ set(SOURCES
src/ItemNameIndex.cc
src/ItemParameterTable.cc
src/Items.cc
src/ItemTranslationTable.cc
src/LevelTable.cc
src/Lobby.cc
src/Loggers.cc
@@ -103,26 +102,26 @@ set(SOURCES
src/Menu.cc
src/NetworkAddresses.cc
src/PatchFileIndex.cc
src/PatchServer.cc
src/PlayerFilesManager.cc
src/PlayerInventory.cc
src/PlayerSubordinates.cc
src/PPKArchive.cc
src/ProxyCommands.cc
src/ProxyServer.cc
src/ProxySession.cc
src/PSOEncryption.cc
src/PSOGCObjectGraph.cc
src/PSOProtocol.cc
src/Quest.cc
src/QuestMetadata.cc
src/QuestScript.cc
src/RareItemSet.cc
src/ReceiveCommands.cc
src/ReceiveSubcommands.cc
src/ReplaySession.cc
src/Revision.cc
src/SaveFileFormats.cc
src/SendCommands.cc
src/Server.cc
src/ServerShell.cc
src/ServerState.cc
src/ShellCommands.cc
src/SignalWatcher.cc
src/StaticGameData.cc
src/TeamIndex.cc
@@ -132,19 +131,13 @@ set(SOURCES
src/WordSelectTable.cc
)
if(resource_file_FOUND)
set(SOURCES ${SOURCES} src/AddressTranslator.cc)
endif()
add_executable(newserv ${SOURCES})
target_include_directories(newserv PUBLIC ${LIBEVENT_INCLUDE_DIR} ${Iconv_INCLUDE_DIRS})
target_link_libraries(newserv phosg::phosg ${LIBEVENT_LIBRARIES} ${Iconv_LIBRARIES} pthread)
if(resource_file_FOUND)
target_compile_definitions(newserv PUBLIC HAVE_RESOURCE_FILE)
target_link_libraries(newserv resource_file::resource_file)
message(STATUS "resource_file found; enabling patch support")
else()
message(WARNING "resource_file not found; disabling patch support")
target_include_directories(newserv PUBLIC ${ASIO_INCLUDE_DIR} ${Iconv_INCLUDE_DIRS})
target_link_libraries(newserv phosg::phosg ${Iconv_LIBRARIES} pthread 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)
endif()
add_dependencies(newserv newserv-Revision-cc)
@@ -167,15 +160,6 @@ foreach(LogTestCase IN ITEMS ${LogTestCases})
COMMAND ${CMAKE_BINARY_DIR}/newserv --replay-log=${LogTestCase} --config=${CMAKE_SOURCE_DIR}/tests/config.json)
endforeach()
if(resource_file_FOUND)
foreach(LogRDTestCase IN ITEMS ${LogRDTestCases})
add_test(
NAME ${LogRDTestCase}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMAND ${CMAKE_BINARY_DIR}/newserv --replay-log=${LogRDTestCase} --config=${CMAKE_SOURCE_DIR}/tests/config.json)
endforeach()
endif()
file(GLOB ScriptTestCases ${CMAKE_SOURCE_DIR}/tests/*.test.sh)
foreach(ScriptTestCase IN ITEMS ${ScriptTestCases})
+8 -8
View File
@@ -11,7 +11,7 @@ RUN apt update && apt install -y --no-install-recommends \
make \
cmake \
g++ \
libevent-dev \
libasio-dev \
zlib1g-dev
# ---
@@ -29,13 +29,13 @@ RUN git clone --depth 1 -b ${PHOSG_TARGET} https://github.com/fuzziqersoftware/p
sudo make install
RUN \
if [ "$BUILD_RESOURCE_DASM" = "true" ] ; then \
if [ "$BUILD_RESOURCE_DASM" = "true" ] ; then \
git clone --depth 1 -b ${RESOURCE_DASM_TARGET} https://github.com/fuzziqersoftware/resource_dasm.git && \
cd resource_dasm && \
cmake . && \
make -j$(nproc) && \
sudo make install \
; fi
; fi
# ---
@@ -53,10 +53,10 @@ RUN cmake -B $PWD/build -DCMAKE_BUILD_TYPE=${BUILD_TYPE} && \
sudo make -C build install
RUN \
if [ "$BUILD_STRIP" = "true" ] ; then \
strip /usr/local/lib/*.a && \
strip /usr/local/bin/* \
; fi
if [ "$BUILD_STRIP" = "true" ] ; then \
strip /usr/local/lib/*.a && \
strip /usr/local/bin/* \
; fi
# ---
@@ -72,7 +72,7 @@ RUN cp -f system/config.example.json system/config.json && \
FROM ${BASE_IMAGE} AS final
RUN apt update && apt install -y --no-install-recommends \
libevent-dev \
libasio-dev \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/*
WORKDIR /newserv
+292 -199
View File
@@ -13,7 +13,7 @@ See TODO.md for a list of known issues and future work I've curated, or go to th
* [History](#history)
* [Other server projects](#other-server-projects)
* [Using newserv in other projects](#using-newserv-in-other-projects)
* [Developer information](#developer-information)
* [Contributing to newserv](#contributing-to-newserv)
* [Compatibility](#compatibility)
* Setup
* [Server setup](#server-setup)
@@ -26,9 +26,10 @@ See TODO.md for a list of known issues and future work I've curated, or go to th
* [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-client-functions-and-dol-files)
* [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
@@ -45,7 +46,7 @@ For a while it was essentially necessary to use a proxy to go online at all, so
<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 a bit tedious to compile on Windows but does work.)
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).
@@ -53,70 +54,79 @@ At the time of its inception, Aeon was also called newserv, and you may find som
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. Still active and popular as of this writing (early 2024). Schtserv is also the only other unofficial server to support all versions of PSO, including Episode 3.
* (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/), currently the most popular PSOBB server, 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. Still active and popular as of this writing (early 2024).
* (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 written in C# by Soly. It seems this was planned to be open-source at some point, but that has not (yet) happened.
* (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.
## Developer information
There is a lot of code in this project that could be useful as a reference. Some of the more notable files are:
* **src/CommandFormats.hh**: Complete listing of all network commands used in all known versions of the game, and their formats
* **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 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/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
## Using newserv in other projects
There is a fair amount of code in this project that could potentially be useful to 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.
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 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.)
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 | No |
| DC 11/2000 | Yes | Yes | No |
| 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 (3) | Yes | No |
| 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 (1) | Yes |
| GC Ep3 NTE | Yes | Yes (2) | Yes |
| GC Ep3 | Yes | Yes | Yes |
| Xbox Ep1&2 Beta | Yes | Yes | Yes |
| Xbox Ep1&2 | Yes | Yes | Yes |
| BB (vanilla) | Yes | Yes (2) | Yes |
| BB (Tethealla) | Yes | Yes (2) | 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. *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.*
2. *Some BB-specific features are not well-tested (for example, some quests that use rare commands may not work properly). Please submit a GitHub issue if you find something that doesn't work.*
3. *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.*
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
@@ -126,27 +136,27 @@ Currently newserv works on macOS, Windows, and Ubuntu Linux. It will likely work
### Windows/macOS
1. Download the latest release-windows-amd64.zip or release-macos-arm64.zip file from the [releases page](https://github.com/fuzziqersoftware/newserv/releases).
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. (Optional) If you want to change any config options, 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.
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 "Building from source" section below.
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
### Building from source (macOS/Linux)
1. Install the packages newserv depends on.
* If you're on Windows, install [Cygwin](https://www.cygwin.com/). While doing so, install the `cmake`, `gcc-core`, `gcc-g++`, `git`, `libevent2.1_7`, `libevent-devel`, `make`, `libiconv-devel`, and `zlib` packages. Do the rest of these steps inside a Cygwin shell (not a Windows cmd shell or PowerShell).
* If you're on macOS, run `brew install cmake libevent libiconv`.
* If you're on Linux, run `sudo apt-get install cmake libevent-dev` (or use your Linux distribution's package manager).
3. Build and install [phosg](https://github.com/fuzziqersoftware/phosg).
4. Optionally, install [resource_dasm](https://github.com/fuzziqersoftware/resource_dasm). This will enable newserv to send memory patches and load DOL files on PSO GC clients. PSO GC clients can play PSO normally on newserv without this.
5. Run `cmake . && make` in the newserv directory.
To build on macOS or Linux:
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.
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.
@@ -154,6 +164,16 @@ On Linux and macOS, the server also responds to SIGUSR1 and SIGUSR2. SIGUSR1 doe
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.
@@ -233,28 +253,32 @@ Devolution includes modem emulation and is compatible with all PSO GameCube vers
### 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 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 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 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. Set IPStackListen (for BBA) or PPPStackListen (for modem) according to the comments in config.json and start newserv.
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 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" section for instructions on setting this up.)
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).
* Modify your hosts file to redirect the client's destination address to localhost or your server's address.
* 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 0x56D724 in psobb.exe. Overwrite these addresses with your server's hostname or IP address, and you should be able to connect.
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.
### Connecting external clients
### 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.
@@ -273,7 +297,8 @@ A license is a set of credentials that a player can use to log in. There are six
* *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 account, use `add-license` in the shell.
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.
@@ -291,12 +316,15 @@ Within the category directories, quest files should be named like `q###-VERSION-
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.
Some quests (mostly battle and challenge mode quests) have additional JSON metadata files that describe how the server should handle them. This includes flags that can be used to hide the quest unless a preceding quest has been cleared, or to hide the quest unless purchased as a team reward. 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 system/quests/battle/b88001.json for documentation on the exact format of the JSON file.
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.
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/.
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:
@@ -324,7 +352,7 @@ There are multiple PSO quest formats out there; newserv supports all of them. It
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 below.*
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/). These files can be encoded in any of the formats described above, except .qst.
@@ -338,13 +366,13 @@ Quest contents are cached in memory, but if you've changed the contents of the q
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 on BB.
* `SERVER_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 for BB.
* `SERVER_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.
* `SERVER_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.
* `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 `SERVER_PRIVATE` and `SERVER_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.
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.
@@ -352,13 +380,18 @@ In the server drop modes, the item tables used to generate common items are in t
## Cross-version play
All versions of PSO can see and interact with each other in the lobby. newserv also allows some versions to play in-game with each other:
* DC V1 players can join DC V2 games if the difficulty level isn't set to Ultimate and the creator chose to allow V1 players.
* DC V2 players can join DC V1 games.
* If AllowDCPCGames is enabled in config.json, PC and DC players can join each other's games. DC V1 players cannot join PC games with the Ultimate difficulty level.
* If AllowGCXBGames is enabled in config.json, GC and Xbox players can join each other's games.
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.
In V1/V2 cross-version play, when any of the server drop modes are used, the server uses the drop table corresponding to the version the game was created with. (For example, if a DC V1 player created the game, rare-table-v1.json will be used, even after V2 players join.)
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
@@ -366,11 +399,13 @@ newserv has the ability to save character data on the server side. For PSO BB, t
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.
There is a third 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.
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 |
| 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 |
@@ -426,59 +461,61 @@ There is no public editor for Episode 3 maps and quests, but the format is descr
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, client functions, and DOL files
## Memory patches and client functions
*Everything in this section requires resource_dasm to be installed, so newserv can use the assemblers and disassemblers from its libresource_file library. If resource_dasm is not installed, newserv will still build and run, but these features will not be available.*
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/WriteMemory.ppc.s.
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 | Architecture |
|-------------------|------|---------------|
| PSO DC NTE | 1OJ1 | Not supported |
| PSO DC 11/2000 | 1OJ2 | Not supported |
| PSO DC 12/2000 | 1OJ3 | Not supported |
| PSO DC 01/2001 | 1OJ4 | Not supported |
| PSO DC v1 JP | 1OJF | Not supported |
| PSO DC v1 US | 1OEF | Not supported |
| PSO DC v1 EU | 1OPF | Not supported |
| PSO DC 08/2001 | 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) | 2OJW | Not supported |
| PSO GC NTE | 3OJT | PowerPC |
| PSO GC v1.2 JP | 3OJ2 | PowerPC |
| PSO GC v1.3 JP | 3OJ3 | PowerPC |
| PSO GC v1.4 JP | 3OJ4 | PowerPC |
| PSO GC v1.5 JP | 3OJ5 | PowerPC (1) |
| PSO GC v1.0 US | 3OE0 | PowerPC |
| PSO GC v1.1 US | 3OE1 | PowerPC |
| PSO GC v1.2 US | 3OE2 | PowerPC (1) |
| PSO GC v1.0 EU | 3OP0 | PowerPC |
| PSO GC Ep3 NTE | 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.13 | 59NL | x86 |
| PSO BB Tethealla | 59NL | x86 |
| 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) 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, based on AR codes originally made by Ralf at GC-Forever and Aleron Ives. Many of them were originally posted in [this thread](https://www.gc-forever.com/forums/viewtopic.php?f=38&t=2050).
newserv comes with a set of patches for many of the above versions. These are organized in subdirectories within system/client-functions/.
You can also 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, ReadMemoryWord.ppc.s, WriteMemory.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.
### 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.
@@ -490,9 +527,9 @@ If you want to play online on remote servers rather than running your own server
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 PSO BB clients - all 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.
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, or GC 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.
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).
@@ -505,95 +542,102 @@ There are many options available when starting a proxy session. All options are
* **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). These kinds of files can be saved:
* **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 into PowerPC assembly if newserv is built with patch support)
* Player data from BB sessions (saved as .bin files, which are not the same format as .nsc 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. On PSO DC, PC and GC, the proxy server 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.
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 server 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 LinkedSession:17205AE4, for example, you would run `on 17205AE4 chat ...`.
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 on the game server and not on the proxy server. The chat commands are:
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 server, show information about your connection instead (remote Guild Card number, client ID, etc.).
* `$si` (game server only): Show basic information about the server.
* `$ping`: Show round-trip ping time from the server to you. On the proxy server, show the ping time from you to the proxy and from the proxy to the server.
* `$matcount` (game server only): Show how many of each type of material you've used.
* `$killcount` (game server 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.
* `$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` (game server only): Show the type, name, and stats of the nearest item on the ground.
* `$where` (game server only): Show your current floor number and coordinates. Mainly useful for debugging.
* `$qfread <field-name>` (game server only): Show the value of a quest counter in your player data. The field names are defined in config.json.
* `$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.
* Debugging commands
* `$debug` (game server only): Enable or disable debug. You need the DEBUG flag in your user account to use this command. Enabling debug does several things:
* You'll see in-game messages from the server when you take certain actions, like killing an enemy in BB.
* 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 crossplay is normally supported. Be prepared for client crashes and other client-side brokenness if you do this. Do not submit any issues for broken behaviors in crossplay, unless the situation is explicitly supported (see the "Cross-version play" section above).
* The rest of the commands in this section are enabled on the game server. (They are always enabled on the proxy server.)
* `$quest <number>` (game server 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 to be enabled if the specified quest has the AllowStartFromChatCommand field set in its metadata file.
* 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.
* `$qcheck <flag-num>` (game server only): Show the value of a quest flag. This command can be used without debug mode enabled. 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).
* `$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.
* `$qgread <flag-num>` (game server only): Show the value of a quest counter ("global flag"). This command can be used without debug mode enabled.
* `$qgwrite <flag-num> <value>` (game server only): Set the value of a quest counter ("global flag") for yourself.
* `$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` (game server only): Send your own Guild Card to yourself.
* `$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.
* `$meseta <amount>` (game server only; Episode 3 only): Add the given amount to your Meseta total.
* `$auction` (Episode 3 only): Bring up the CARD Auction menu, regardless of how many players are in the game or if you have a VIP card.
* `$ep3battledebug` (game server only; Episode 3 only): Enable or disable TCard00_Select. If enabled, the game will enter the debug menu when you start a battle.
* `$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.
* Personal state commands
* `$arrow <color-id>`: Change your lobby arrow color.
* `$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 server, this will not work if the remote server controls item drops (e.g. on BB, or on Schtserv with server drops enabled). If the server does not allow cheat mode anywhere (that is, "CheatModeBehavior" is "Off" in config.json), this command does nothing.
* `$battle` (game server only; DC v1 only): After using this command, the next game you create will be in battle mode. (A chat command is required for this because DCv1 doesn't allow this natively.) On DCv1, the battle quests are not available, but free-roam is.
* `$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. This also makes item drops deterministic in Blue Burst games hosted by newserv. On the proxy server, 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 server, 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.
* `$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 (game server only)
* `$savechar <slot>`: Save your current character data on the server in the specified slot. See the "Server-side saves" section for more details.
* `$loadchar <slot>`: Save your current character data on the server in the specified slot. See the "Server-side saves" section 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 for more details.
* `$edit <stat> <value>`: Modify your character data. See "Using $edit" below for details.
* 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 (game server only)
* 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 (game server only)
* 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 for more information.
* `$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 (game server only)
* 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.
@@ -603,25 +647,24 @@ Some commands only work on the game server and not on the proxy server. The chat
* `$playrec <name>`: Play a battle recording. This command creates a spectator team immediately but the replay does not start automatically, to give other players a chance to join. To start the battle replay within the spectator team, run `$playrec` again (with no name). There is a bug in Dolphin that makes this command unstable in emulation (see the "Battle records" section above).
* Cheat mode commands
* `$cheat` (game server 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 server, 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 (not DCv1, GC US 1.2, or GC JP 1.5), the server will automatically revive you if you die. On all versions except GC US 1.2 and GC JP 1.5, infinite HP also automatically cures status ailments.
* `$inftp`: Enable or disable infinite TP mode. Applies to only you; does not affect other players.
* `$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 server.
* `$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 (e.g. "Hell Saber +5 0/10/25/0/10") 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 server, you must not be using Blue Burst for this command to work. On the game server, this command works for all versions.
* `$unset <index>` (game server 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.
* `$dropmode [mode]` (proxy server): 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 server 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.
* `$item <desc>` (or `$i <desc>`): Create an item. `desc` may be a description of the item (e.g. "Hell Saber +5 0/10/25/0/10") 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.
* `$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.
* `$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 server, this applies to all lobbies and games you join, but only you will see the new event - other players will not.
* `$allevent <event>` (game server only): Set the current holiday event in all lobbies.
* `$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 (game server only)
* 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.
* `$ax <message>`: Send a message to the server's terminal. This cannot be used to run server shell commands; it only prints text to stderr.
* `$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.
@@ -647,7 +690,7 @@ Some subcommands are always available. They 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 for this unless your character is Level 1)
* `$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)
@@ -656,45 +699,95 @@ The remaining subcommands are only available if cheat mode is enabled on the ser
* `$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 MST 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 and proxy server. Run `newserv help` to see a full list of the options and how to use each one.
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 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 | None | `extract-afs` |
| BML archive | None | `extract-bml` |
| GSL archive | None | `extract-gsl` |
| GVM texture | `encode-gvm` | None |
| 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) | `convert-rare-item-set` | `convert-rare-item-set` |
| 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:
@@ -703,8 +796,8 @@ There are several actions that don't fit well into the table above, which let yo
* 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`)
* Search for rare enemy seeds that result in rare enemies on console versions (`find-rare-enemy-seeds`)
* 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`)
+11 -3
View File
@@ -1,13 +1,19 @@
## General
- Make UI strings localizable (e.g. entries in menus, welcome message, etc.)
- Add an idle connection timeout for proxy sessions
- Make a server patch version of story flag fixer quest
- Fix enemy flag mapping in v2/v3 crossplay and test
- Handle items in crossplay - use the replacement table
- Make proxy server handle all login commands on non-BB, including sending 9C when needed
- Add $switchit command (activates switch flag(s) for nearest object, e.g. laser fence, door, fog collision)
- Add a way to persist flags across connections, at least on v3, because of Meet User + B2 enable quest interactions - maybe update the quest to patch one of the login commands so the server can tell it's enabled
- Handle MeetUserExtensions properly in 41 and C4 commands on the proxy (rewrite the embedded 19 command and put some metadata in the persistent config, perhaps)
- Clean up ItemParameterTable implementation (see comment at the top of the class definition)
- Handle MeetUserExtensions properly in 41 and C4 commands on the proxy (rewrite the embedded 19 command and store a map of received destinations)
- Make UI strings localizable (e.g. entries in menus, welcome message, etc.)
## PSO DC
- Investigate if https://crates.io/crates/blaze-ssl-async can be used to implement the HL check server
- v2 challenge data in $savechar/$loadchar doesn't work properly
## Episode 3
@@ -27,3 +33,5 @@
- 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
+734 -322
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+5 -5
View File
@@ -1,5 +1,5 @@
DC NTE: pso02.dricas.ne.jp
Nov 2000 proto: test1.st-pso.games.sega.net
Dec 2000 proto: sg107634.csrd.sega.co.jp OR master.pso.dream-key.com
Jan 2001 proto: master.pso.dream-key.com
Aug 2001 proto (v2): game01.st-pso.games.sega.net
1OJ1 (DC NTE): pso02.dricas.ne.jp
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
+3 -1
View File
@@ -1,4 +1,6 @@
List of differences in Ep3 NTE compared to Final:
- COMs can play more than one defense card per turn
- The battle setup menu allows 1v2 battles
- Assist cards
- - Dice Fever sets dice to 6, not 5, and there is no Dice Fever +
- - Rich + and Charity + also don't exist
@@ -27,7 +29,7 @@ List of differences in Ep3 NTE compared to Final:
- - Ability Trap prevents all abnormal conditions
- Traps
- - Traps trigger as soon as you move into their tile; on Final, they trigger at the end of the Move phase
- - Traps may use any assist card, and this can be configured in the map definition (TODO: verify this last part)
- - Traps may use any assist card, and this can be configured in the map definition
- Rules
- - Dice Boost does not exist
- - ATK and DEF dice ranges can be set independently, but there are only 7 options for each: 1-6, 1-1, 2-2, 3-3, 4-4, 5-5, 6-6
+3 -13
View File
@@ -5,17 +5,7 @@ import sys
from dataclasses import dataclass
version_tokens = ("JP12", "JP13", "JP14", "JP15", "US10", "US11", "US12", "EU")
version_to_specific_version = {
"JP12": "3OJ2",
"JP13": "3OJ3",
"JP14": "3OJ4",
"JP15": "3OJ5",
"US10": "3OE0",
"US11": "3OE1",
"US12": "3OE2",
"EU": "3OP0",
}
version_tokens = ("3OJ2", "3OJ3", "3OJ4", "3OJ5", "3OE0", "3OE1", "3OE2", "3OP0")
@dataclass
@@ -60,7 +50,7 @@ def write_patches_for_code(
if write_regions:
filename = os.path.join(
out_dir,
f'{name.replace(" ", "")}.{version_to_specific_version[v]}.patch.s',
f'{name.replace(" ", "")}.{v}.patch.s',
)
with open(filename, "wt") as f:
if long_name is not None:
@@ -144,7 +134,7 @@ def main():
| (data[z + 2] << 8)
| (data[z + 3] << 0)
)
elif line.startswith("JP12------------"):
elif line.startswith("3OJ2------------"):
reading_code = True
else:
code_name = line
+942 -937
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,7 +1,7 @@
patch required in TethVer12513 to get this to work: 0048210D EB
patch required in 59NL to get this to work: 0048210D EB
is_hangame callsites:
0040457C - ??? (something in TDataProtocol?)
is_hangame callsites in 59NL:
0040457C - don't save password on disconnect
004820F4 - client version check (use patch above to bypass)
00708318 - patch server domain name
00708348 - patch server port
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+69 -69
View File
@@ -21,7 +21,7 @@ Common Bank Patch
CommonBank
*** name=Common bank
*** desc=Hold L and open\nthe bank to use a\ncommon bank stored\nin temp character\n3's data
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000BAB4 281B0002 8000BAB4 281B0002 8000BAB4 281B0002 8000BAB4 281B0002 8000BAB4 281B0002 8000BAB4 281B0002 8000BAB4 281B0002 8000BAB4 281B0002 cmplwi r27, 2
8000BAB8 40820018 8000BAB8 40820018 8000BAB8 40820018 8000BAB8 40820018 8000BAB8 40820018 8000BAB8 40820018 8000BAB8 40820018 8000BAB8 40820018 bne +0x00000018 /* 8000BAD0 */
8000BABC 3C008000 8000BABC 3C008000 8000BABC 3C008000 8000BABC 3C008000 8000BABC 3C008000 8000BABC 3C008000 8000BABC 3C008000 8000BABC 3C008000 lis r0, 0x8000
@@ -71,7 +71,7 @@ Item Loss Prevention
ItemLossPrevention
*** name=No item loss
*** desc=Don't lose items if\nyou don't log off\nnormally
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801D33E4 4800004C 801D38EC 4800004C 801D3CC4 4800004C 801D39B8 4800004C 801D381C 4800004C 801D381C 4800004C 801D3A1C 4800004C 801D3ED8 4800004C b +0x0000004C /* 801D3868 */
801FE900 60000000 801FF174 60000000 8020010C 60000000 801FF710 60000000 801FF0FC 60000000 801FF0FC 60000000 801FFA44 60000000 801FF9E0 60000000 nop
801FFE5C 60000000 802006D0 60000000 802016CC 60000000 80200C9C 60000000 80200658 60000000 80200658 60000000 80200FD0 60000000 80200F3C 60000000 nop
@@ -83,7 +83,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Palette
*** name=Palette
*** desc=Press Z to cycle\nthrough 4 customize\nconfigs instead of of\njust one
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000CD00 3C808000 8000CD00 3C808000 8000CD00 3C808000 8000CD00 3C808000 8000CD00 3C808000 8000CD00 3C808000 8000CD00 3C808000 8000CD00 3C808000 lis r4, 0x8000
8000CD04 6084CF3E 8000CD04 6084CF3E 8000CD04 6084CF3E 8000CD04 6084CF3E 8000CD04 6084CF3E 8000CD04 6084CF3E 8000CD04 6084CF3E 8000CD04 6084CF3E ori r4, r4, 0xCF3E
8000CD08 3BE00000 8000CD08 3BE00000 8000CD08 3BE00000 8000CD08 3BE00000 8000CD08 3BE00000 8000CD08 3BE00000 8000CD08 3BE00000 8000CD08 3BE00000 li r31, 0x0000
@@ -123,7 +123,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
"Palette Patch" Part 2
Palette
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000CD8C 38600003 8000CD8C 38600003 8000CD8C 38600003 8000CD8C 38600003 8000CD8C 38600003 8000CD8C 38600003 8000CD8C 38600003 8000CD8C 38600003 li r3, 0x0003
8000CD90 3C808001 8000CD90 3C808001 8000CD90 3C808001 8000CD90 3C808001 8000CD90 3C808001 8000CD90 3C808001 8000CD90 3C808001 8000CD90 3C808001 lis r4, 0x8001
8000CD94 B064CF78 8000CD94 B064CF78 8000CD94 B064CF78 8000CD94 B064CF78 8000CD94 B064CF78 8000CD94 B064CF78 8000CD94 B064CF78 8000CD94 B064CF78 sth [r4 - 0x3088], r3
@@ -159,7 +159,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
"Palette Patch" Part 3 (this part adds PBs to the customize list)
Palette
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000CA40 28030000 8000CA40 28030000 8000CA40 28030000 8000CA40 28030000 8000CA40 28030000 8000CA40 28030000 8000CA40 28030000 8000CA40 28030000 cmplwi r3, 0
8000CA44 40820008 8000CA44 40820008 8000CA44 40820008 8000CA44 40820008 8000CA44 40820008 8000CA44 40820008 8000CA44 40820008 8000CA44 40820008 bne +0x00000008 /* 8000CA4C */
8000CA48 3BE00000 8000CA48 3BE00000 8000CA48 3BE00000 8000CA48 3BE00000 8000CA48 3BE00000 8000CA48 3BE00000 8000CA48 3BE00000 8000CA48 3BE00000 li r31, 0x0000
@@ -195,12 +195,12 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
"Palette Patch" Part 4 (this disables PBs from overtaking the back palette)
Palette
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801B55F8 38600000 801B5A4C 38600000 801B7BB8 38600000 801B5B18 38600000 801B59E4 38600000 801B59E4 38600000 801B5B7C 38600000 801B6038 38600000 li r3, 0x0000
"Palette Patch" Part 5 (saves palettes to temp slot 3)
Palette
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000B958 906DB93C 8000B958 906DB944 8000B958 906DB964 8000B958 906DB964 8000B958 906DB954 8000B958 906DB954 8000B958 906DB974 8000B958 906DB9B4 stw [r13 - 0x46AC], r3
8000B95C 1C63003C 8000B95C 1C63003C 8000B95C 1C63003C 8000B95C 1C63003C 8000B95C 1C63003C 8000B95C 1C63003C 8000B95C 1C63003C 8000B95C 1C63003C mulli r3, r3, 60
8000B960 808DB920 8000B960 808DB928 8000B960 808DB948 8000B960 808DB948 8000B960 808DB938 8000B960 808DB938 8000B960 808DB958 8000B960 808DB998 lwz r4, [r13 - 0x46C8]
@@ -244,7 +244,7 @@ Decoction Patch (makes the Decoction item wipe non-HP/TP materials)
Decoction
*** name=Decoction
*** desc=Make the Decoction\nitem reset your\nmaterial usage
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80350740 880300EE 80351B44 880300EE 803530A0 880300EE 80352E54 880300EE 803515F4 880300EE 80351638 880300EE 80353220 880300EE 80352614 880300EE lbz r0, [r3 + 0x00EE]
80350744 2800000B 80351B48 2800000B 803530A4 2800000B 80352E58 2800000B 803515F8 2800000B 8035163C 2800000B 80353224 2800000B 80352618 2800000B cmplwi r0, 11
80350748 40820144 80351B4C 40820144 803530A8 40820144 80352E5C 40820144 803515FC 40820144 80351640 40820144 80353228 40820144 8035261C 40820144 bne +0x00000144 /* 80351740 */
@@ -288,19 +288,19 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Movement
*** name=Movement
*** desc=Allow backsteps and\nmovement when\nenemies are\nnearby
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801CF69C 48000014 801CFBB0 48000014 801D1CEC 48000014 801CFC7C 48000014 801CFAE0 48000014 801CFAE0 48000014 801CFCE0 48000014 801D019C 48000014 b +0x00000014 /* 801CFAF4 */
"Movement Patch" Part 2 (restores backstep functionality on certain movements)
Movement
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801CE7AC 4800000C 801CECC0 4800000C 801D0D10 4800000C 801CED8C 4800000C 801CEBF0 4800000C 801CEBF0 4800000C 801CEDF0 4800000C 801CF2AC 4800000C b +0x0000000C /* 801CEBFC */
Olga Flow Barta Bug Fix (makes barta work on ice weakness Olga Flow instead of damaging player)
BugFixes
*** name=Bug fixes
*** desc=Fix many minor\ngameplay, sound,\nand graphical bugs
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000D980 807C0000 8000D980 807C0000 8000D980 807C0000 8000D980 807C0000 8000D980 807C0000 8000D980 807C0000 8000D980 807C0000 8000D980 807C0000 lwz r3, [r28]
8000D984 2C030013 8000D984 2C030013 8000D984 2C030013 8000D984 2C030013 8000D984 2C030013 8000D984 2C030013 8000D984 2C030013 8000D984 2C030013 cmpwi r3, 19
8000D988 40820008 8000D988 40820008 8000D988 40820008 8000D988 40820008 8000D988 40820008 8000D988 40820008 8000D988 40820008 8000D988 40820008 bne +0x00000008 /* 8000D990 */
@@ -310,7 +310,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Morfos Frozen Player Bug Fix (stops Morfos Laser multi-hitting when player is frozen)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000D9A0 C042FC78 8000D9A0 C042FC80 8000D9A0 C042FC80 8000D9A0 C042FC80 8000D9A0 C042FC88 8000D9A0 C042FC88 8000D9A0 C042FC88 8000D9A0 C042FC88 lfs f2, [r2 - 0x0378]
8000D9A4 807E0030 8000D9A4 807E0030 8000D9A4 807E0030 8000D9A4 807E0030 8000D9A4 807E0030 8000D9A4 807E0030 8000D9A4 807E0030 8000D9A4 807E0030 lwz r3, [r30 + 0x0030]
8000D9A8 70630020 8000D9A8 70630020 8000D9A8 70630020 8000D9A8 70630020 8000D9A8 70630020 8000D9A8 70630020 8000D9A8 70630020 8000D9A8 70630020 andi. r3, r3, 0x0020
@@ -321,18 +321,18 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Tiny Grass Assassins Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
800BC750 48000010 800BCA58 48000010 800BCBD0 48000010 800BCB80 48000010 800BC9E8 48000010 800BC9E8 48000010 800BCB90 48000010 800BCB58 48000010 b +0x00000010 /* 800BC9F8 */
Bulclaw HP Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80091528 4800024D 80091814 4800024D 8009198C 4800024D 8009193C 4800024D 800917B4 4800024D 800917B4 4800024D 8009194C 4800024D 80091914 4800024D bl +0x0000024C /* 80091A00 */
8009152C B3C3032C 80091818 B3C3032C 80091990 B3C3032C 80091940 B3C3032C 800917B8 B3C3032C 800917B8 B3C3032C 80091950 B3C3032C 80091918 B3C3032C sth [r3 + 0x032C], r30
Control Tower: Delbiter Death SFX Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80301600 48000020 803025CC 48000020 80303A1C 48000020 803037D0 48000020 80301F58 48000020 80301F9C 48000020 8030398C 48000020 80302D64 48000020 b +0x00000020 /* 80301F78 */
80301604 3863A830 803025D0 3863A830 80303A20 3863A830 803037D4 3863A830 80301F5C 3863A830 80301FA0 3863A830 80303990 3863A830 80302D68 3863A830 subi r3, r3, 0x57D0
80301608 800DB98C 803025D4 800DB994 80303A24 800DB9B4 803037D8 800DB9B4 80301F60 800DB9A4 80301FA4 800DB9A4 80303994 800DB9C4 80302D6C 800DBA04 lwz r0, [r13 - 0x465C]
@@ -344,7 +344,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Weapon Attributes Patch (allows attributes to work on minibosses and Olga Flow)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000C8C0 7000000F 8000C8C0 7000000F 8000C8C0 7000000F 8000C8C0 7000000F 8000C8C0 7000000F 8000C8C0 7000000F 8000C8C0 7000000F 8000C8C0 7000000F andi. r0, r0, 0x000F
8000C8C4 7000004F 8000C8C4 7000004F 8000C8C4 7000004F 8000C8C4 7000004F 8000C8C4 7000004F 8000C8C4 7000004F 8000C8C4 7000004F 8000C8C4 7000004F andi. r0, r0, 0x004F
8000C8C8 2C000004 8000C8C8 2C000004 8000C8C8 2C000004 8000C8C8 2C000004 8000C8C8 2C000004 8000C8C8 2C000004 8000C8C8 2C000004 8000C8C8 2C000004 cmpwi r0, 4
@@ -354,34 +354,34 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Ruins Laser Fence SFX Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80166324 3C604005 801666D8 3C604005 80166848 3C604005 8016679C 3C604005 801666E0 3C604005 801666E0 3C604005 80166800 3C604005 80166CC4 3C604005 lis r3, 0x4005
80166328 4800009C 801666DC 4800009C 8016684C 4800009C 801667A0 4800009C 801666E4 4800009C 801666E4 4800009C 80166804 4800009C 80166CC8 4800009C b +0x0000009C /* 80166780 */
801663C0 4800001C 80166774 4800001C 801668E4 4800001C 80166838 4800001C 8016677C 4800001C 8016677C 4800001C 8016689C 4800001C 80166D60 4800001C b +0x0000001C /* 80166798 */
SFX Cancellation Distance Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
805CB608 46AFC800 805D5C08 46AFC800 805DD0A8 46AFC800 805DCE48 46AFC800 805CBF10 46AFC800 805D2F30 46AFC800 805DC750 46AFC800 805D8990 46AFC800 .invalid sc
805CB8A8 43480000 805D5EA8 43480000 805DD348 43480000 805DD0E8 43480000 805CC1B0 43480000 805D31D0 43480000 805DC9F0 43480000 805D8C30 43480000 bc 26, 8, +0x00000000 /* 805CC1B0 */
Foie SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8022E2A8 3880FF00 8022EC44 3880FF00 8022FB30 3880FF00 8022F8E4 3880FF00 8022EB64 3880FF00 8022EB64 3880FF00 8022FC18 3880FF00 8022F4B0 3880FF00 li r4, 0xFFFFFF00
8022E2D8 3880FE80 8022EC74 3880FE80 8022FB60 3880FE80 8022F914 3880FE80 8022EB94 3880FE80 8022EB94 3880FE80 8022FC48 3880FE80 8022F4E0 3880FE80 li r4, 0xFFFFFE80
8022E308 3880FDB0 8022ECA4 3880FDB0 8022FB90 3880FDB0 8022F944 3880FDB0 8022EBC4 3880FDB0 8022EBC4 3880FDB0 8022FC78 3880FDB0 8022F510 3880FDB0 li r4, 0xFFFFFDB0
Gifoie SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802300B8 3880FF00 80230A54 3880FF00 80231940 3880FF00 802316F4 3880FF00 80230974 3880FF00 80230974 3880FF00 80231A28 3880FF00 802312C0 3880FF00 li r4, 0xFFFFFF00
802300E8 3880FE80 80230A84 3880FE80 80231970 3880FE80 80231724 3880FE80 802309A4 3880FE80 802309A4 3880FE80 80231A58 3880FE80 802312F0 3880FE80 li r4, 0xFFFFFE80
80230118 3880FDB0 80230AB4 3880FDB0 802319A0 3880FDB0 80231754 3880FDB0 802309D4 3880FDB0 802309D4 3880FDB0 80231A88 3880FDB0 80231320 3880FDB0 li r4, 0xFFFFFDB0
Rafoie SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802365AC 3880FF00 80236F68 3880FF00 80237E54 3880FF00 80237C08 3880FF00 80236E88 3880FF00 80236E88 3880FF00 80237F3C 3880FF00 802377D4 3880FF00 li r4, 0xFFFFFF00
802365DC 3880FE80 80236F98 3880FE80 80237E84 3880FE80 80237C38 3880FE80 80236EB8 3880FE80 80236EB8 3880FE80 80237F6C 3880FE80 80237804 3880FE80 li r4, 0xFFFFFE80
8023660C 3880FDB0 80236FC8 3880FDB0 80237EB4 3880FDB0 80237C68 3880FDB0 80236EE8 3880FDB0 80236EE8 3880FDB0 80237F9C 3880FDB0 80237834 3880FDB0 li r4, 0xFFFFFDB0
@@ -391,79 +391,79 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Barta SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80229B54 3880FF00 8022A4F0 3880FF00 8022B3E0 3880FF00 8022B190 3880FF00 8022A410 3880FF00 8022A410 3880FF00 8022B4C4 3880FF00 8022AD5C 3880FF00 li r4, 0xFFFFFF00
80229B84 3880FE80 8022A520 3880FE80 8022B410 3880FE80 8022B1C0 3880FE80 8022A440 3880FE80 8022A440 3880FE80 8022B4F4 3880FE80 8022AD8C 3880FE80 li r4, 0xFFFFFE80
80229BB4 3880FDB0 8022A550 3880FDB0 8022B440 3880FDB0 8022B1F0 3880FDB0 8022A470 3880FDB0 8022A470 3880FDB0 8022B524 3880FDB0 8022ADBC 3880FDB0 li r4, 0xFFFFFDB0
Gibarta SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8022EAB4 3880FF00 8022F450 3880FF00 80230340 3880FF00 802300F0 3880FF00 8022F370 3880FF00 8022F370 3880FF00 80230424 3880FF00 8022FCBC 3880FF00 li r4, 0xFFFFFF00
8022EAE4 3880FE80 8022F480 3880FE80 80230370 3880FE80 80230120 3880FE80 8022F3A0 3880FE80 8022F3A0 3880FE80 80230454 3880FE80 8022FCEC 3880FE80 li r4, 0xFFFFFE80
8022EB14 3880FDB0 8022F4B0 3880FDB0 802303A0 3880FDB0 80230150 3880FDB0 8022F3D0 3880FDB0 8022F3D0 3880FDB0 80230484 3880FDB0 8022FD1C 3880FDB0 li r4, 0xFFFFFDB0
Rabarta SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80235DD4 3880FF00 80236790 3880FF00 8023767C 3880FF00 80237430 3880FF00 802366B0 3880FF00 802366B0 3880FF00 80237764 3880FF00 80236FFC 3880FF00 li r4, 0xFFFFFF00
80235E10 3880FE80 802367CC 3880FE80 802376B8 3880FE80 8023746C 3880FE80 802366EC 3880FE80 802366EC 3880FE80 802377A0 3880FE80 80237038 3880FE80 li r4, 0xFFFFFE80
80235E4C 3880FDB0 80236808 3880FDB0 802376F4 3880FDB0 802374A8 3880FDB0 80236728 3880FDB0 80236728 3880FDB0 802377DC 3880FDB0 80237074 3880FDB0 li r4, 0xFFFFFDB0
Zonde SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8023B2C8 3880FF00 8023BC84 3880FF00 8023CB70 3880FF00 8023C924 3880FF00 8023BBA4 3880FF00 8023BBA4 3880FF00 8023CC58 3880FF00 8023C4F0 3880FF00 li r4, 0xFFFFFF00
8023B2F8 3880FE80 8023BCB4 3880FE80 8023CBA0 3880FE80 8023C954 3880FE80 8023BBD4 3880FE80 8023BBD4 3880FE80 8023CC88 3880FE80 8023C520 3880FE80 li r4, 0xFFFFFE80
8023B328 3880FDB0 8023BCE4 3880FDB0 8023CBD0 3880FDB0 8023C984 3880FDB0 8023BC04 3880FDB0 8023BC04 3880FDB0 8023CCB8 3880FDB0 8023C550 3880FDB0 li r4, 0xFFFFFDB0
Gizonde SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80230E08 3880FF00 802317C4 3880FF00 802326B0 3880FF00 80232464 3880FF00 802316E4 3880FF00 802316E4 3880FF00 80232798 3880FF00 80232030 3880FF00 li r4, 0xFFFFFF00
80230E38 3880FE80 802317F4 3880FE80 802326E0 3880FE80 80232494 3880FE80 80231714 3880FE80 80231714 3880FE80 802327C8 3880FE80 80232060 3880FE80 li r4, 0xFFFFFE80
80230E68 3880FDB0 80231824 3880FDB0 80232710 3880FDB0 802324C4 3880FDB0 80231744 3880FDB0 80231744 3880FDB0 802327F8 3880FDB0 80232090 3880FDB0 li r4, 0xFFFFFDB0
Razonde SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80237998 3880FF00 80238354 3880FF00 80239240 3880FF00 80238FF4 3880FF00 80238274 3880FF00 80238274 3880FF00 80239328 3880FF00 80238BC0 3880FF00 li r4, 0xFFFFFF00
802379C8 3880FE80 80238384 3880FE80 80239270 3880FE80 80239024 3880FE80 802382A4 3880FE80 802382A4 3880FE80 80239358 3880FE80 80238BF0 3880FE80 li r4, 0xFFFFFE80
802379F8 3880FDB0 802383B4 3880FDB0 802392A0 3880FDB0 80239054 3880FDB0 802382D4 3880FDB0 802382D4 3880FDB0 80239388 3880FDB0 80238C20 3880FDB0 li r4, 0xFFFFFDB0
Grants SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802316FC 3880FF00 802320B8 3880FF00 80232FA4 3880FF00 80232D58 3880FF00 80231FD8 3880FF00 80231FD8 3880FF00 8023308C 3880FF00 80232924 3880FF00 li r4, 0xFFFFFF00
80231734 3880FE80 802320F0 3880FE80 80232FDC 3880FE80 80232D90 3880FE80 80232010 3880FE80 80232010 3880FE80 802330C4 3880FE80 8023295C 3880FE80 li r4, 0xFFFFFE80
8023176C 3880FDB0 80232128 3880FDB0 80233014 3880FDB0 80232DC8 3880FDB0 80232048 3880FDB0 80232048 3880FDB0 802330FC 3880FDB0 80232994 3880FDB0 li r4, 0xFFFFFDB0
Megid SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802337A8 3880FF00 80234164 3880FF00 80235050 3880FF00 80234E04 3880FF00 80234084 3880FF00 80234084 3880FF00 80235138 3880FF00 802349D0 3880FF00 li r4, 0xFFFFFF00
802337D8 3880FE80 80234194 3880FE80 80235080 3880FE80 80234E34 3880FE80 802340B4 3880FE80 802340B4 3880FE80 80235168 3880FE80 80234A00 3880FE80 li r4, 0xFFFFFE80
80233808 3880FDB0 802341C4 3880FDB0 802350B0 3880FDB0 80234E64 3880FDB0 802340E4 3880FDB0 802340E4 3880FDB0 80235198 3880FDB0 80234A30 3880FDB0 li r4, 0xFFFFFDB0
Anti SFX Pitch Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80229354 2C000001 80229CF0 2C000001 8022ABDC 2C000001 8022A990 2C000001 80229C10 2C000001 80229C10 2C000001 8022ACC4 2C000001 8022A55C 2C000001 cmpwi r0, 1
Shield DFP/EVP Bug Fix (allows shields to reach true max DFP/EVP values)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801185B0 88040016 801187CC 88040016 8011885C 88040016 80118764 88040016 80118854 88040016 80118854 88040016 80118774 88040016 8011894C 88040016 lbz r0, [r4 + 0x0016]
801185BC 88040017 801187D8 88040017 80118868 88040017 80118770 88040017 80118860 88040017 80118860 88040017 80118780 88040017 80118958 88040017 lbz r0, [r4 + 0x0017]
VR Spaceship Item Drop Bug Fix (allows items to drop from enemies above a certain Y position)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
805C996C 435C0000 805D3F6C 435C0000 805DB40C 435C0000 805DB1AC 435C0000 805CA274 435C0000 805D1294 435C0000 805DAAB4 435C0000 805D6CF4 435C0000 bc 26, 28, +0x00000000 /* 805CA274 */
Invalid Items Bug Fix (something to do with making invalid items correctly display as ???? I think)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8011CA90 7C030378 8011CCD4 7C030378 8011CD0C 7C030378 8011CC6C 7C030378 8011CD34 7C030378 8011CD34 7C030378 8011CC7C 7C030378 8011CE54 7C030378 mr r3, r0
8011CA94 3863FFFF 8011CCD8 3863FFFF 8011CD10 3863FFFF 8011CC70 3863FFFF 8011CD38 3863FFFF 8011CD38 3863FFFF 8011CC80 3863FFFF 8011CE58 3863FFFF subi r3, r3, 0x0001
8011CA98 4BFFFFE8 8011CCDC 4BFFFFE8 8011CD14 4BFFFFE8 8011CC74 4BFFFFE8 8011CD3C 4BFFFFE8 8011CD3C 4BFFFFE8 8011CC84 4BFFFFE8 8011CE5C 4BFFFFE8 b -0x00000018 /* 8011CD24 */
@@ -476,7 +476,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Item Removal Maxed Stats Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000B088 7FA3EB78 8000B088 7FA3EB78 8000B088 7FA3EB78 8000B088 7FA3EB78 8000B088 7FA3EB78 8000B088 7FA3EB78 8000B088 7FA3EB78 8000B088 7FA3EB78 mr r3, r29
8000B08C 38800000 8000B08C 38800000 8000B08C 38800000 8000B08C 38800000 8000B08C 38800000 8000B08C 38800000 8000B08C 38800000 8000B08C 38800000 li r4, 0x0000
8000B090 481AE725 8000B090 481AEB91 8000B090 481B1C09 8000B090 481AEC5D 8000B090 481AEB11 8000B090 481AEB11 8000B090 481AECC1 8000B090 481AF17D bl +0x001AEB10 /* 801B9BA0 */
@@ -537,7 +537,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Unit Present Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000C640 54800673 8000C640 54800673 8000C640 54800673 8000C640 54800673 8000C640 54800673 8000C640 54800673 8000C640 54800673 8000C640 54800673 rlwinm. r0, r4, 0, 25, 25
8000C644 41820008 8000C644 41820008 8000C644 41820008 8000C644 41820008 8000C644 41820008 8000C644 41820008 8000C644 41820008 8000C644 41820008 beq +0x00000008 /* 8000C64C */
8000C648 38800000 8000C648 38800000 8000C648 38800000 8000C648 38800000 8000C648 38800000 8000C648 38800000 8000C648 38800000 8000C648 38800000 li r4, 0x0000
@@ -547,7 +547,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Bank Item Stacking Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000C6D0 38000001 8000C6D0 38000001 8000C6D0 38000001 8000C6D0 38000001 8000C6D0 38000001 8000C6D0 38000001 8000C6D0 38000001 8000C6D0 38000001 li r0, 0x0001
8000C6D4 901D0054 8000C6D4 901D0054 8000C6D4 901D0054 8000C6D4 901D0054 8000C6D4 901D0054 8000C6D4 901D0054 8000C6D4 901D0054 8000C6D4 901D0054 stw [r29 + 0x0054], r0
8000C6D8 807D0024 8000C6D8 807D0024 8000C6D8 807D0024 8000C6D8 807D0024 8000C6D8 807D0024 8000C6D8 807D0024 8000C6D8 807D0024 8000C6D8 807D0024 lwz r3, [r29 + 0x0024]
@@ -561,28 +561,28 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Dropped Mag Colour Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80114378 38000012 8011458C 38000012 80114634 38000012 80114524 38000012 8011461C 38000012 8011461C 38000012 80114534 38000012 8011470C 38000012 li r0, 0x0012
Meseta Drop System Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80107478 4800000C 80107654 4800000C 80107708 4800000C 801075D4 4800000C 8010771C 4800000C 8010771C 4800000C 801075E4 4800000C 801077D4 4800000C b +0x0000000C /* 80107728 */
8010748C 7C030378 80107668 7C030378 8010771C 7C030378 801075E8 7C030378 80107730 7C030378 80107730 7C030378 801075F8 7C030378 801077E8 7C030378 mr r3, r0
Present Colour Bug Fix (TODO: which versions need this?)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80101C14 60000000 60000000 60000000 60000000 80101EB8 60000000 80101EB8 60000000 60000000 60000000 nop
Offline Quests Drop Table Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80104B48 4182000C 80104D24 4182000C 80104DE0 4182000C 80104CA4 4182000C 80104DEC 4182000C 80104DEC 4182000C 80104CB4 4182000C 80104EA4 4182000C beq +0x0000000C /* 80104DF8 */
Mag Revival Priority Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000C8A0 1C00000A 8000C8A0 1C00000A 8000C8A0 1C00000A 8000C8A0 1C00000A 8000C8A0 1C00000A 8000C8A0 1C00000A 8000C8A0 1C00000A 8000C8A0 1C00000A mulli r0, r0, 10
8000C8A4 57E407BD 8000C8A4 57E407BD 8000C8A4 57E407BD 8000C8A4 57E407BD 8000C8A4 57E407BD 8000C8A4 57E407BD 8000C8A4 57E407BD 8000C8A4 57E407BD rlwinm. r4, r31, 0, 30, 30
8000C8A8 41820008 8000C8A8 41820008 8000C8A8 41820008 8000C8A8 41820008 8000C8A8 41820008 8000C8A8 41820008 8000C8A8 41820008 8000C8A8 41820008 beq +0x00000008 /* 8000C8B0 */
@@ -592,22 +592,22 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Mag Revival Challenge & Quest Mode Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801CA1F4 48000010 801CA6E0 48000010 801CB5EC 48000010 801CA7AC 48000010 801CA610 48000010 801CA610 48000010 801CA810 48000010 801CACCC 48000010 b +0x00000010 /* 801CA620 */
Chat Bubble Window TAB Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80250264 60000000 80250CB0 60000000 80251CA4 60000000 802519A4 60000000 80250AEC 60000000 80250AEC 60000000 80251C68 60000000 802514B0 60000000 nop
Chat Log Window LF/Tab Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80267DDC 60000000 80268A88 60000000 80269AE4 60000000 80269898 60000000 80268788 60000000 80268788 60000000 80269B5C 60000000 802693A4 60000000 nop
Dark/Hell Special GFX Bug Fix (makes Dark/Hell display graphic on success like in PSO BB)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000E1E0 7FC802A6 8000E1E0 7FC802A6 8000E1E0 7FC802A6 8000E1E0 7FC802A6 8000E1E0 7FC802A6 8000E1E0 7FC802A6 8000E1E0 7FC802A6 8000E1E0 7FC802A6 mflr r30
8000E1E4 38A00000 8000E1E4 38A00000 8000E1E4 38A00000 8000E1E4 38A00000 8000E1E4 38A00000 8000E1E4 38A00000 8000E1E4 38A00000 8000E1E4 38A00000 li r5, 0x0000
8000E1E8 38C0001E 8000E1E8 38C0001E 8000E1E8 38C0001E 8000E1E8 38C0001E 8000E1E8 38C0001E 8000E1E8 38C0001E 8000E1E8 38C0001E 8000E1E8 38C0001E li r6, 0x001E
@@ -622,18 +622,18 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Gol Dragon Camera Bug Fix (makes the camera after Gol Dragon display "normally")
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802FB99C 2C030001 802FC968 2C030001 802FDE60 2C030001 802FDB6C 2C030001 802FC2F4 2C030001 802FC338 2C030001 802FDD28 2C030001 802FD100 2C030001 cmpwi r3, 1
Box/Fence Fadeout Bug Fix (stops boxes and other environmental objects fading in and out as you approach)
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80189A54 60000000 80189E2C 60000000 80189F90 60000000 80189EF0 60000000 80189E20 60000000 80189E20 60000000 80189F54 60000000 8018A418 60000000 nop
801933DC 60000000 801937B0 60000000 80193914 60000000 80193874 60000000 801937A8 60000000 801937A8 60000000 801938D8 60000000 80193D9C 60000000 nop
TP Bar Colour Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8026DA74 3884AAFA 8026E738 3884AAFA 8026F794 3884AAFA 8026F548 3884AAFA 8026E2D4 3884AAFA 8026E2D4 3884AAFA 8026F6FC 3884AAFA 8026EF44 3884AAFA subi r4, r4, 0x5506
8026DB88 3863AAFA 8026E84C 3863AAFA 8026F8A8 3863AAFA 8026F65C 3863AAFA 8026E3E8 3863AAFA 8026E3E8 3863AAFA 8026F810 3863AAFA 8026F058 3863AAFA subi r3, r3, 0x5506
8026DC10 3883AAFA 8026E8D4 3883AAFA 8026F930 3883AAFA 8026F6E4 3883AAFA 8026E470 3883AAFA 8026E470 3883AAFA 8026F898 3883AAFA 8026F0E0 3883AAFA subi r4, r3, 0x5506
@@ -641,12 +641,12 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Devil's and Demon's Special Damage Display Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8001306C 4BFFFCC0 8001309C 4BFFFCC0 80013364 4BFFFCC0 8001304C 4BFFFCC0 80013084 4BFFFCC0 80013084 4BFFFCC0 8001304C 4BFFFCC0 800130C4 4BFFFCC0 b -0x00000340 /* 80012D44 */
Christmas Trees Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000B5C8 80630098 8000B5C8 80630098 8000B5C8 80630098 8000B5C8 80630098 8000B5C8 80630098 8000B5C8 80630098 8000B5C8 80630098 8000B5C8 80630098 lwz r3, [r3 + 0x0098]
8000B5CC 483D46F5 8000B5CC 483D70D1 8000B5CC 483D8F71 8000B5CC 483D8D21 8000B5CC 483D5999 8000B5CC 483D59F1 8000B5CC 483D90F1 8000B5CC 483D7BE1 bl +0x003D5998 /* 803E0F64 */
8000B5D0 807F042C 8000B5D0 807F042C 8000B5D0 807F042C 8000B5D0 807F042C 8000B5D0 807F042C 8000B5D0 807F042C 8000B5D0 807F042C 8000B5D0 807F042C lwz r3, [r31 + 0x042C]
@@ -657,25 +657,25 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Rain Drops Colour Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
804B3738 70808080 804B6E58 70808080 804B92F8 70808080 804B90B8 70808080 804B3EF0 70808080 804B43D0 70808080 804B8990 70808080 804B8E10 70808080 andi. r0, r4, 0x8080
804B373C 60707070 804B6E5C 60707070 804B92FC 60707070 804B90BC 60707070 804B3EF4 60707070 804B43D4 60707070 804B8994 60707070 804B8E14 60707070 ori r16, r3, 0x7070
Reverser Target Lock Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
801C5EA4 389F02FC 801C6360 389F02FC 801C6604 389F02FC 801C642C 389F02FC 801C62C0 389F02FC 801C62C0 389F02FC 801C6490 389F02FC 801C694C 389F02FC addi r4, r31, 0x02FC
Deband/Shifta/Resta Target Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8022CF84 41810630 8022D920 41810630 8022E85C 41810630 8022E5C0 41810630 8022D840 41810630 8022D840 41810630 8022E8F4 41810630 8022E18C 41810630 bgt +0x00000630 /* 8022DE70 */
8022D278 4181033C 4181033C 4181033C 4181033C 8022DB34 4181033C 8022DB34 4181033C 4181033C 4181033C bgt +0x0000033C /* 8022DE70 */
8022D36C 41810248 41810248 41810248 41810248 8022DC28 41810248 8022DC28 41810248 41810248 41810248 bgt +0x00000248 /* 8022DE70 */
Tech Auto Targetting Bug Fix
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8022C850 60000000 8022D1EC 60000000 8022E128 60000000 8022DE8C 60000000 8022D10C 60000000 8022D10C 60000000 8022E1C0 60000000 8022DA58 60000000 nop
804C6EE4 0000001E 804CA61C 0000001E 804CCB6C 0000001E 804CC90C 0000001E 804C76B4 0000001E 804C7B94 0000001E 804CC1E4 0000001E 804CC5D4 0000001E .invalid
804C6F3C 00000028 804CA674 00000028 804CCBC4 00000028 804CC964 00000028 804C770C 00000028 804C7BEC 00000028 804CC23C 00000028 804CC62C 00000028 .invalid
@@ -686,7 +686,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Enable Trap Animations
BugFixes
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000BBD0 809F0370 8000BBD0 809F0370 8000BBD0 809F0370 8000BBD0 809F0370 8000BBD0 809F0370 8000BBD0 809F0370 8000BBD0 809F0370 8000BBD0 809F0370 lwz r4, [r31 + 0x0370]
8000BBD4 3884FC00 8000BBD4 3884FC00 8000BBD4 3884FC00 8000BBD4 3884FC00 8000BBD4 3884FC00 8000BBD4 3884FC00 8000BBD4 3884FC00 8000BBD4 3884FC00 subi r4, r4, 0x0400
8000BBD8 909F0370 8000BBD8 909F0370 8000BBD8 909F0370 8000BBD8 909F0370 8000BBD8 909F0370 8000BBD8 909F0370 8000BBD8 909F0370 8000BBD8 909F0370 stw [r31 + 0x0370], r4
@@ -702,12 +702,12 @@ Extended Word Select
ChatFeatures
*** name=Chat
*** desc=Enable extended\nWord Select and\nstop the Log Window\nfrom scrolling by\nholding L+R
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8034445C 38600000 803457AC 38600000 80346CCC 38600000 80346A80 38600000 8034525C 38600000 803452A0 38600000 80346E4C 38600000 8034627C 38600000 li r3, 0x0000
Chat Log Window: Lock Scrolling with L+R
ChatFeatures
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000D6A0 3C608051 8000D6A0 3C608051 8000D6A0 3C608051 8000D6A0 3C608051 8000D6A0 3C608051 8000D6A0 3C608051 8000D6A0 3C608051 8000D6A0 3C608051 lis r3, 0x8051
8000D6A4 A0638AD0 8000D6A4 A063C590 8000D6A4 A063EBD0 8000D6A4 A063E970 8000D6A4 A06393B0 8000D6A4 A0639890 8000D6A4 A063E270 8000D6A4 A063F290 lhz r3, [r3 - 0x6C50]
8000D6A8 70600003 8000D6A8 70600003 8000D6A8 70600003 8000D6A8 70600003 8000D6A8 70600003 8000D6A8 70600003 8000D6A8 70600003 8000D6A8 70600003 andi. r0, r3, 0x0003
@@ -721,7 +721,7 @@ Improved Draw Distance of most objects
Draw Distance
*** name=Draw Distance
*** desc=Extend the draw\ndistance of many\nobjects
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000DFA0 C3C2C1F8 8000DFA0 C3C2C1F8 8000DFA0 C3C2C1F8 8000DFA0 C3C2C1F8 8000DFA0 C3C2C200 8000DFA0 C3C2C200 8000DFA0 C3C2C200 8000DFA0 C3C2C200 lfs f30, [r2 - 0x3E00]
8000DFA4 EFDE0072 8000DFA4 EFDE0072 8000DFA4 EFDE0072 8000DFA4 EFDE0072 8000DFA4 EFDE0072 8000DFA4 EFDE0072 8000DFA4 EFDE0072 8000DFA4 EFDE0072 fmuls f30, f30, f1
8000DFA8 4E800020 8000DFA8 4E800020 8000DFA8 4E800020 8000DFA8 4E800020 8000DFA8 4E800020 8000DFA8 4E800020 8000DFA8 4E800020 8000DFA8 4E800020 blr
@@ -739,7 +739,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
8000DFD8 3C60804C 8000DFD8 3C60804C 8000DFD8 3C60804D 8000DFD8 3C60804D 8000DFD8 3C60804C 8000DFD8 3C60804C 8000DFD8 3C60804D 8000DFD8 3C60804D lis r3, 0x804C
8000DFDC 4E800020 8000DFDC 4E800020 8000DFDC 4E800020 8000DFDC 4E800020 8000DFDC 4E800020 8000DFDC 4E800020 8000DFDC 4E800020 8000DFDC 4E800020 blr
801008E8 4BF0D6B9 80100AD0 4BF0D4D1 80100B74 4BF0D42D 80100A50 4BF0D551 80100B8C 4BF0D415 80100B8C 4BF0D415 80100A60 4BF0D541 80100C50 4BF0D351 bl -0x000F2BEC /* 8000DFA0 */
80156D00 4BEB72AD 801570B4 4BEB6EF9 80157218 4BEB6D95 80157178 4BEB6E35 801570BC 4BEB6EF1 801570BC 4BEB6EF1 801571DC 4BEB6DD1 801576A0 4BEB690D bl -0x00149110 /* 8000DFAC */
8015671C 4BEB7891 80156AD0 4BEB74DD 80156C34 4BEB7379 80156B94 4BEB7419 80156AD8 4BEB74D5 80156AD8 4BEB74D5 80156BF8 4BEB73B5 801570BC 4BEB6EF1 bl -0x00148C4C /* 8000DFAC */
801A1C64 4BE6C359 801A203C 4BE6BF81 801A21A0 4BE6BE1D 801A2100 4BE6BEBD 801A2040 4BE6BF7D 801A2040 4BE6BF7D 801A2164 4BE6BE59 801A2628 4BE6B995 bl -0x00194084 /* 8000DFBC */
801A1E64 4BE6C13D 801A223C 4BE6BD65 801A23A0 4BE6BC01 801A2300 4BE6BCA1 801A2240 4BE6BD61 801A2240 4BE6BD61 801A2364 4BE6BC3D 801A2828 4BE6B779 bl -0x001942A0 /* 8000DFA0 */
80205044 4BE08F85 802058B8 4BE08711 80206640 4BE07989 802063F4 4BE07BD5 80205840 4BE08789 80205840 4BE08789 80206728 4BE078A1 80206124 4BE07EA5 bl -0x001F7878 /* 8000DFC8 */
@@ -754,7 +754,7 @@ Show Enemy HP Bars
EnemyHPBars
*** name=Enemy HP bars
*** desc=Show HP bars in\nenemy info windows
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US12)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US12)
802612C4 4BFE1541 80261E9C 4BFE1349 80262EE4 4BFE0665 80262C98 4BFE1241 80261B9C 4BFE1545 80261B9C 4BFE1545 80262F5C 4BFE12B1 802627A4 4BFE12B1 bl -0x0001EABC /* 802430E0 */
804CAF00 42780000 804CE650 42780000 804D0BA0 42780000 804D0940 42780000 804CB6D0 42780000 804CBBB0 42780000 804D0218 42780000 804D0608 42780000
804CAF1C FF00FF15 804CE66C FF00FF15 804D0BBC FF00FF15 804D095C FF00FF15 804CB6EC FF00FF15 804CBBCC FF00FF15 804D0234 FF00FF15 804D0624 FF00FF15
@@ -798,7 +798,7 @@ PSO DC Reticle Colours
DCReticleColors
*** name=DC targets
*** desc=Change the target\nreticle colors to\nthose used on the\nDreamcast
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802AB3FC 3C8000FF 802AC2A4 3C8000FF 802AD3D0 3C8000FF 802AD184 3C8000FF 802ABDB8 3C8000FF 802ABDFC 3C8000FF 802AD338 3C8000FF 802ACACC 3C8000FF lis r4, 0x00FF
802AB410 388000FF 802AC2B8 388000FF 802AD3E4 388000FF 802AD198 388000FF 802ABDCC 388000FF 802ABE10 388000FF 802AD34C 388000FF 802ACAE0 388000FF li r4, 0x00FF
802AB424 3884FF00 802AC2CC 3884FF00 802AD3F8 3884FF00 802AD1AC 3884FF00 802ABDE0 3884FF00 802ABE24 3884FF00 802AD360 3884FF00 802ACAF4 3884FF00 subi r4, r4, 0x0100
@@ -819,7 +819,7 @@ PSOX / BB Reticle Colours
PSOXReticleColors
*** name=Xbox/BB targets
*** desc=Change the target\nreticle colors to\nthose used on the\nXbox and Blue Burst
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
802AB424 388000FF 802AC2CC 388000FF 802AD3F8 388000FF 802AD1AC 388000FF 802ABDE0 388000FF 802ABE24 388000FF 802AD360 388000FF 802ACAF4 388000FF li r4, 0x00FF
804A1F38 00000000 804A5658 00000000 804A7AF8 00000000 804A78B8 00000000 804A26E8 00000000 804A2BC8 00000000 804A7188 00000000 804A7608 00000000 .invalid
804A1F3C 00000000 804A565C 00000000 804A7AFC 00000000 804A78BC 00000000 804A26EC 00000000 804A2BCC 00000000 804A718C 00000000 804A760C 00000000 .invalid
@@ -829,7 +829,7 @@ Show Rare Items on Area & Radar Map
RareDropNotifications
*** name=Rare alerts
*** desc=Show rare items on\nthe map and play a\nsound when a rare\nitem drops
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000C660 881F00EF 8000C660 881F00EF 8000C660 881F00EF 8000C660 881F00EF 8000C660 881F00EF 8000C660 881F00EF 8000C660 881F00EF 8000C660 881F00EF lbz r0, [r31 + 0x00EF]
8000C664 28000004 8000C664 28000004 8000C664 28000004 8000C664 28000004 8000C664 28000004 8000C664 28000004 8000C664 28000004 8000C664 28000004 cmplwi r0, 4
8000C668 40820018 8000C668 40820018 8000C668 40820018 8000C668 40820018 8000C668 40820018 8000C668 40820018 8000C668 40820018 8000C668 40820018 bne +0x00000018 /* 8000C680 */
@@ -844,7 +844,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Rare Item Drops: Play SFX
RareDropNotifications
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000C690 28030000 8000C690 28030000 8000C690 28030000 8000C690 28030000 8000C690 28030000 8000C690 28030000 8000C690 28030000 8000C690 28030000 cmplwi r3, 0
8000C694 41820020 8000C694 41820020 8000C694 41820020 8000C694 41820020 8000C694 41820020 8000C694 41820020 8000C694 41820020 8000C694 41820020 beq +0x00000020 /* 8000C6B4 */
8000C698 880300EF 8000C698 880300EF 8000C698 880300EF 8000C698 880300EF 8000C698 880300EF 8000C698 880300EF 8000C698 880300EF 8000C698 880300EF lbz r0, [r3 + 0x00EF]
@@ -862,7 +862,7 @@ Play SFX for Hungry Mag
HungryMagSound
*** name=MAG alert
*** desc=Play a sound when\nyour MAG is hungry
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000BF30 9421FFF0 8000BF30 9421FFF0 8000BF30 9421FFF0 8000BF30 9421FFF0 8000BF30 9421FFF0 8000BF30 9421FFF0 8000BF30 9421FFF0 8000BF30 9421FFF0 stwu [r1 - 0x0010], r1
8000BF34 7C0802A6 8000BF34 7C0802A6 8000BF34 7C0802A6 8000BF34 7C0802A6 8000BF34 7C0802A6 8000BF34 7C0802A6 8000BF34 7C0802A6 8000BF34 7C0802A6 mflr r0
8000BF38 90010014 8000BF38 90010014 8000BF38 90010014 8000BF38 90010014 8000BF38 90010014 8000BF38 90010014 8000BF38 90010014 8000BF38 90010014 stw [r1 + 0x0014], r0
@@ -880,12 +880,12 @@ Invisible Mag
InvisibleMag
*** name=Invisible MAG
*** desc=Make MAGs invisible
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80114F04 480000D4 80115118 480000D4 8011521C 480000D4 801150B0 480000D4 801151A8 480000D4 801151A8 480000D4 801150C0 480000D4 80115298 480000D4 b +0x000000D4 /* 8011527C */
16:9 Aspect Ratio
169AspectRatioV1
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
80000088 C04210F0 80000088 C0421120 80000088 C0421130 80000088 C0421130 80000088 C0421108 80000088 C0421108 80000088 C0421138 80000088 C0421128 lfs f2, [r2 + 0x1108]
8000008C EFBD00B2 8000008C EFBD00B2 8000008C EFBD00B2 8000008C EFBD00B2 8000008C EFBD00B2 8000008C EFBD00B2 8000008C EFBD00B2 8000008C EFBD00B2 fmuls f29, f29, f2
80000090 FC40E890 80000090 FC40E890 80000090 FC40E890 80000090 FC40E890 80000090 FC40E890 80000090 FC40E890 80000090 FC40E890 80000090 FC40E890 fmr f2, f29
@@ -894,7 +894,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
16:9 Aspect Ratio V2
169AspectRatioV2
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000BE4C C01C0040 8000BE4C C01C0040 8000BE4C C01C0040 8000BE4C C01C0040 8000BE4C C01C0040 8000BE4C C01C0040 8000BE4C C01C0040 8000BE4C C01C0040 lfs f0, [r28 + 0x0040]
8000BE50 C062F7C0 8000BE50 C062F7C8 8000BE50 C062F7C8 8000BE50 C062F7C8 8000BE50 C062F7D0 8000BE50 C062F7D0 8000BE50 C062F7D0 8000BE50 C062F7D0 lfs f3, [r2 - 0x0830]
8000BE54 EC4100FA 8000BE54 EC4100FA 8000BE54 EC4100FA 8000BE54 EC4100FA 8000BE54 EC4100FA 8000BE54 EC4100FA 8000BE54 EC4100FA 8000BE54 EC4100FA fmadds f2, f1, f0, f3
@@ -955,7 +955,7 @@ JP12------------- JP13------------- JP14------------- JP15------------- US10----
Water & Light Effects Aspect Ratio Fix (for use with a 16:9 code)
169AmbientEffectsFix
JP12------------- JP13------------- JP14------------- JP15------------- US10------------- US11------------- US12------------- EU--------------- DISASSEMBLY (US10)
3OJ2------------- 3OJ3------------- 3OJ4------------- 3OJ5------------- 3OE0------------- 3OE1------------- 3OE2------------- 3OP0------------- DISASSEMBLY (US10)
8000BDF0 C36210F0 8000BDF0 C3621120 8000BDF0 C3621130 8000BDF0 C3621130 8000BDF0 C3621108 8000BDF0 C3621108 8000BDF0 C3621138 8000BDF0 C3621128 lfs f27, [r2 + 0x1108]
8000BDF4 EC4206F2 8000BDF4 EC4206F2 8000BDF4 EC4206F2 8000BDF4 EC4206F2 8000BDF4 EC4206F2 8000BDF4 EC4206F2 8000BDF4 EC4206F2 8000BDF4 EC4206F2 fmuls f2, f2, f27
8000BDF8 FF601090 8000BDF8 FF601090 8000BDF8 FF601090 8000BDF8 FF601090 8000BDF8 FF601090 8000BDF8 FF601090 8000BDF8 FF601090 8000BDF8 FF601090 fmr f27, f2
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -2
View File
@@ -17,7 +17,7 @@
0019 = P2 Scientist after defeating dragon
001E = Entered Caves 1 (Gov 2-1)
001F = Entered De Rol Le in 2-4
0020 = De Ro lee defeated
0020 = De Rol Le defeated
0021 = Mines unlocked (P2 Tyrell after defeating De Rol Le)
0028 = Entered Mines 1
0029 = Entered Vol Opt Area
@@ -105,7 +105,6 @@
00F5 = Weapon badge approval for gran squall //is cleared if quest is left
00F6 = Secret delivery. Got AKIKO's FRYING PAN!
00FB = Got Orochi-agito
00FB = Received OROCHI-AGITO!
00FD = Unknown addicting food
0105 = Central dome fire swirl. Got Glory of the past!
0106 = Central dome fire swirl. Got Mark3.
+4
View File
@@ -23,6 +23,10 @@ public:
return this->entries;
}
inline size_t num_entries() const {
return this->entries.size();
}
std::pair<const void*, size_t> get(size_t index) const;
std::string get_copy(size_t index) const;
phosg::StringReader get_reader(size_t index) const;
+101 -56
View File
@@ -2,6 +2,7 @@
#include <stdio.h>
#include <string.h>
#include <filesystem>
#include <phosg/Filesystem.hh>
#include <phosg/Hash.hh>
#include <phosg/Random.hh>
@@ -185,7 +186,7 @@ Account::Account(const phosg::JSON& json)
lic->gamertag = xb_gamertag;
lic->user_id = xb_user_id;
lic->account_id = xb_account_id;
this->xb_licenses.emplace(lic->gamertag, lic);
this->xb_licenses.emplace(lic->user_id, lic);
}
if (!bb_username.empty() && !bb_password.empty()) {
auto lic = make_shared<BBLicense>();
@@ -214,7 +215,7 @@ Account::Account(const phosg::JSON& json)
}
for (const auto& it : json.get_list("XBLicenses")) {
auto lic = XBLicense::from_json(*it);
this->xb_licenses.emplace(lic->gamertag, lic);
this->xb_licenses.emplace(lic->user_id, lic);
}
for (const auto& it : json.get_list("BBLicenses")) {
auto lic = BBLicense::from_json(*it);
@@ -291,8 +292,8 @@ phosg::JSON Account::json() const {
});
}
void Account::print(FILE* stream) const {
fprintf(stream, "Account: %010" PRIu32 "/%08" PRIX32 "\n", this->account_id, this->account_id);
string Account::str() const {
std::string ret = std::format("Account: {:010}/{:08X}\n", this->account_id, this->account_id);
if (this->flags) {
string flags_str = "";
@@ -336,10 +337,10 @@ void Account::print(FILE* stream) const {
}
if (flags_str.empty()) {
flags_str = "none";
} else if (phosg::ends_with(flags_str, ",")) {
} else if (flags_str.ends_with(",")) {
flags_str.pop_back();
}
fprintf(stream, " Flags: %08" PRIX32 " (%s)\n", this->flags, flags_str.c_str());
ret += std::format(" Flags: {:08X} ({})\n", this->flags, flags_str);
}
if (this->user_flags) {
@@ -349,72 +350,119 @@ void Account::print(FILE* stream) const {
}
if (user_flags_str.empty()) {
user_flags_str = "none";
} else if (phosg::ends_with(user_flags_str, ",")) {
} else if (user_flags_str.ends_with(",")) {
user_flags_str.pop_back();
}
fprintf(stream, " User flags: %08" PRIX32 " (%s)\n", this->user_flags, user_flags_str.c_str());
ret += std::format(" User flags: {:08X} ({})\n", this->user_flags, user_flags_str);
}
if (this->ban_end_time) {
string time_str = phosg::format_time(this->ban_end_time);
fprintf(stream, " Banned until: %" PRIu64 " (%s)\n", this->ban_end_time, time_str.c_str());
ret += std::format(" Banned until: {} ({})\n", this->ban_end_time, time_str);
}
if (this->ep3_current_meseta || this->ep3_total_meseta_earned) {
fprintf(stream, " Episode 3 meseta: %" PRIu32 " (total earned: %" PRIu32 ")\n", this->ep3_current_meseta, this->ep3_total_meseta_earned);
ret += std::format(" Episode 3 meseta: {} (total earned: {})\n",
this->ep3_current_meseta, this->ep3_total_meseta_earned);
}
if (!this->last_player_name.empty()) {
fprintf(stream, " Last player name: \"%s\"\n", this->last_player_name.c_str());
ret += std::format(" Last player name: \"{}\"\n", this->last_player_name);
}
if (!this->auto_reply_message.empty()) {
fprintf(stream, " Auto reply message: \"%s\"\n", this->auto_reply_message.c_str());
ret += std::format(" Auto reply message: \"{}\"\n", this->auto_reply_message);
}
if (this->bb_team_id) {
fprintf(stream, " BB team ID: %08" PRIX32 "\n", this->bb_team_id);
ret += std::format(" BB team ID: {:08X}\n", this->bb_team_id);
}
if (this->is_temporary) {
fprintf(stream, " Is temporary license: true\n");
ret += std::format(" Is temporary license: true\n");
}
for (const auto& it : this->dc_nte_licenses) {
fprintf(stream, " DC NTE license: serial_number=%s access_key=%s\n",
it.second->serial_number.c_str(), it.second->access_key.c_str());
ret += std::format(" DC NTE license: serial_number={} access_key={}\n",
it.second->serial_number, it.second->access_key);
}
for (const auto& it : this->dc_licenses) {
fprintf(stream, " DC license: serial_number=%" PRIX32 " access_key=%s\n",
it.second->serial_number, it.second->access_key.c_str());
ret += std::format(" DC license: serial_number={:X} access_key={}\n",
it.second->serial_number, it.second->access_key);
}
for (const auto& it : this->pc_licenses) {
fprintf(stream, " PC license: serial_number=%" PRIX32 " access_key=%s\n",
it.second->serial_number, it.second->access_key.c_str());
ret += std::format(" PC license: serial_number={:X} access_key={}\n",
it.second->serial_number, it.second->access_key);
}
for (const auto& it : this->gc_licenses) {
fprintf(stream, " GC license: serial_number=%010" PRIu32 " access_key=%s password=%s\n",
it.second->serial_number, it.second->access_key.c_str(), it.second->password.c_str());
ret += std::format(" GC license: serial_number={:010} access_key={} password={}\n",
it.second->serial_number, it.second->access_key, it.second->password);
}
for (const auto& it : this->xb_licenses) {
fprintf(stream, " XB license: gamertag=%s user_id=%016" PRIX64 " account_id=%016" PRIX64 "\n",
it.second->gamertag.c_str(), it.second->user_id, it.second->account_id);
ret += std::format(" XB license: gamertag={} user_id={:016X} account_id={:016X}\n",
it.second->gamertag, it.second->user_id, it.second->account_id);
}
for (const auto& it : this->bb_licenses) {
fprintf(stream, " BB license: username=%s password=%s\n",
it.second->username.c_str(), it.second->password.c_str());
ret += std::format(" BB license: username={} password={}\n",
it.second->username, it.second->password);
}
phosg::strip_trailing_whitespace(ret);
return ret;
}
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 filename = phosg::string_printf("system/licenses/%010" PRIu32 ".json", this->account_id);
string filename = std::format("system/licenses/{:010}.json", this->account_id);
phosg::save_file(filename, json_data);
}
}
void Account::delete_file() const {
string filename = phosg::string_printf("system/licenses/%010" PRIu32 ".json", this->account_id);
string filename = std::format("system/licenses/{:010}.json", this->account_id);
remove(filename.c_str());
}
uint64_t Login::proxy_session_id() const {
uint64_t low_part = 0;
if (this->dc_nte_license) {
low_part = this->dc_nte_license->proxy_session_id_part();
} else if (this->dc_license) {
low_part = this->dc_license->proxy_session_id_part();
} else if (this->pc_license) {
low_part = this->pc_license->proxy_session_id_part();
} else if (this->gc_license) {
low_part = this->gc_license->proxy_session_id_part();
} else if (this->xb_license) {
low_part = this->xb_license->proxy_session_id_part();
} else if (this->bb_license) {
low_part = this->bb_license->proxy_session_id_part();
} else {
throw logic_error("none of the licenses in a Login were present");
}
return (static_cast<uint64_t>(this->account->account_id) << 32) | low_part;
}
string Login::str() const {
string ret = std::format("Account:{:08X}", this->account->account_id);
if (this->account_was_created) {
ret += " (new)";
}
if (this->dc_nte_license) {
ret += std::format(" via DC NTE serial number {}", this->dc_nte_license->serial_number);
} else if (this->dc_license) {
ret += std::format(" via DC serial number {:08X}", this->dc_license->serial_number);
} else if (this->pc_license) {
ret += std::format(" via PC serial number {:08X}", this->pc_license->serial_number);
} else if (this->gc_license) {
ret += std::format(" via GC serial number {:010}", this->gc_license->serial_number);
} else if (this->xb_license) {
ret += std::format(" via XB user ID {:016X}", this->xb_license->user_id);
} else if (this->bb_license) {
ret += std::format(" via BB username {}", this->bb_license->username);
} else {
ret += std::format(" artificially");
}
return ret;
}
size_t AccountIndex::count() const {
shared_lock g(this->lock);
return this->by_account_id.size();
@@ -660,14 +708,10 @@ shared_ptr<Login> AccountIndex::from_gc_credentials(
}
}
shared_ptr<Login> AccountIndex::from_xb_credentials_locked(const string& gamertag, uint64_t user_id, uint64_t account_id) {
shared_ptr<Login> AccountIndex::from_xb_credentials_locked(uint64_t user_id) {
auto login = make_shared<Login>();
login->account = this->by_xb_gamertag.at(gamertag);
login->xb_license = login->account->xb_licenses.at(gamertag);
if ((login->xb_license->user_id && (login->xb_license->user_id != user_id)) ||
(login->xb_license->account_id && (login->xb_license->account_id != account_id))) {
throw incorrect_access_key();
}
login->account = this->by_xb_user_id.at(user_id);
login->xb_license = login->account->xb_licenses.at(user_id);
if (login->account->ban_end_time && (login->account->ban_end_time >= phosg::now())) {
throw account_banned();
}
@@ -682,13 +726,13 @@ shared_ptr<Login> AccountIndex::from_xb_credentials(
try {
shared_lock g(this->lock);
return this->from_xb_credentials_locked(gamertag, user_id, account_id);
return this->from_xb_credentials_locked(user_id);
} catch (const out_of_range&) {
}
unique_lock g(this->lock);
try {
return this->from_xb_credentials_locked(gamertag, user_id, account_id);
return this->from_xb_credentials_locked(user_id);
} catch (const out_of_range&) {
}
@@ -701,7 +745,7 @@ shared_ptr<Login> AccountIndex::from_xb_credentials(
lic->gamertag = gamertag;
lic->user_id = user_id;
lic->account_id = account_id;
login->account->xb_licenses.emplace(lic->gamertag, lic);
login->account->xb_licenses.emplace(lic->user_id, lic);
login->xb_license = lic;
this->add_locked(login->account);
return login;
@@ -798,8 +842,8 @@ void AccountIndex::add_locked(shared_ptr<Account> a) {
}
}
for (const auto& it : a->xb_licenses) {
if (this->by_xb_gamertag.count(it.second->gamertag)) {
throw runtime_error("account already exists with this XB gamertag");
if (this->by_xb_user_id.count(it.second->user_id)) {
throw runtime_error("account already exists with this XB user ID");
}
}
for (const auto& it : a->bb_licenses) {
@@ -826,7 +870,7 @@ void AccountIndex::add_locked(shared_ptr<Account> a) {
this->by_gc_serial_number[it.second->serial_number] = a;
}
for (const auto& it : a->xb_licenses) {
this->by_xb_gamertag[it.second->gamertag] = a;
this->by_xb_user_id[it.second->user_id] = a;
}
for (const auto& it : a->bb_licenses) {
this->by_bb_username[it.second->username] = a;
@@ -855,7 +899,7 @@ void AccountIndex::remove(uint32_t account_id) {
this->by_gc_serial_number.erase(it.second->serial_number);
}
for (const auto& it : a->xb_licenses) {
this->by_xb_gamertag.erase(it.second->gamertag);
this->by_xb_user_id.erase(it.second->user_id);
}
for (const auto& it : a->bb_licenses) {
this->by_bb_username.erase(it.second->username);
@@ -903,12 +947,12 @@ void AccountIndex::add_gc_license(shared_ptr<Account> account, shared_ptr<GCLice
}
void AccountIndex::add_xb_license(shared_ptr<Account> account, shared_ptr<XBLicense> license) {
if (!this->by_xb_gamertag.emplace(license->gamertag, account).second) {
throw runtime_error("gamertag already registered");
if (!this->by_xb_user_id.emplace(license->user_id, account).second) {
throw runtime_error("user ID already registered");
}
if (!account->xb_licenses.emplace(license->gamertag, license).second) {
this->by_xb_gamertag.erase(license->gamertag);
throw logic_error("gamertag registered in account but not in account index");
if (!account->xb_licenses.emplace(license->user_id, license).second) {
this->by_xb_user_id.erase(license->user_id);
throw logic_error("user ID registered in account but not in account index");
}
}
@@ -966,12 +1010,12 @@ void AccountIndex::remove_gc_license(shared_ptr<Account> account, uint32_t seria
account->gc_licenses.erase(it);
}
void AccountIndex::remove_xb_license(shared_ptr<Account> account, const string& gamertag) {
auto it = account->xb_licenses.find(gamertag);
void AccountIndex::remove_xb_license(shared_ptr<Account> account, uint64_t user_id) {
auto it = account->xb_licenses.find(user_id);
if (it == account->xb_licenses.end()) {
throw runtime_error("license not registered to account");
}
if (!this->by_xb_gamertag.erase(it->second->gamertag)) {
if (!this->by_xb_user_id.erase(it->second->user_id)) {
throw runtime_error("license registered in account but not in account index");
}
account->xb_licenses.erase(it);
@@ -1000,16 +1044,17 @@ shared_ptr<Account> AccountIndex::create_temporary_account_for_shared_account(
AccountIndex::AccountIndex(bool force_all_temporary)
: force_all_temporary(force_all_temporary) {
if (!this->force_all_temporary) {
if (!phosg::isdir("system/licenses")) {
mkdir("system/licenses", 0755);
if (!std::filesystem::is_directory("system/licenses")) {
std::filesystem::create_directories("system/licenses");
} else {
for (const auto& item : phosg::list_directory("system/licenses")) {
if (phosg::ends_with(item, ".json")) {
for (const auto& item : std::filesystem::directory_iterator("system/licenses")) {
string filename = item.path().filename().string();
if (filename.ends_with(".json")) {
try {
phosg::JSON json = phosg::JSON::parse(phosg::load_file("system/licenses/" + item));
phosg::JSON json = phosg::JSON::parse(phosg::load_file("system/licenses/" + filename));
this->add(make_shared<Account>(json));
} catch (const exception& e) {
phosg::log_error("Failed to index account %s", item.c_str());
phosg::log_error_f("Failed to index account {}", filename);
throw;
}
}
+30 -8
View File
@@ -2,6 +2,7 @@
#include <memory>
#include <mutex>
#include <phosg/Hash.hh>
#include <phosg/JSON.hh>
#include <shared_mutex>
#include <string>
@@ -16,6 +17,10 @@ struct DCNTELicense {
std::string serial_number;
std::string access_key;
inline uint64_t proxy_session_id_part() const {
return phosg::fnv1a32(this->serial_number);
}
static std::shared_ptr<DCNTELicense> from_json(const phosg::JSON& json);
phosg::JSON json() const;
};
@@ -24,6 +29,10 @@ struct V1V2License {
uint32_t serial_number = 0;
std::string access_key;
inline uint64_t proxy_session_id_part() const {
return this->serial_number;
}
static std::shared_ptr<V1V2License> from_json(const phosg::JSON& json);
phosg::JSON json() const;
};
@@ -33,6 +42,10 @@ struct GCLicense {
std::string access_key;
std::string password;
inline uint64_t proxy_session_id_part() const {
return this->serial_number;
}
static std::shared_ptr<GCLicense> from_json(const phosg::JSON& json);
phosg::JSON json() const;
};
@@ -42,6 +55,10 @@ struct XBLicense {
uint64_t user_id = 0;
uint64_t account_id = 0;
inline uint64_t proxy_session_id_part() const {
return phosg::fnv1a32(this->gamertag);
}
static std::shared_ptr<XBLicense> from_json(const phosg::JSON& json);
phosg::JSON json() const;
};
@@ -50,6 +67,10 @@ struct BBLicense {
std::string username;
std::string password;
inline uint64_t proxy_session_id_part() const {
return phosg::fnv1a32(this->username);
}
static std::shared_ptr<BBLicense> from_json(const phosg::JSON& json);
phosg::JSON json() const;
};
@@ -101,7 +122,7 @@ struct Account {
std::unordered_map<uint32_t, std::shared_ptr<V1V2License>> dc_licenses;
std::unordered_map<uint32_t, std::shared_ptr<V1V2License>> pc_licenses;
std::unordered_map<uint32_t, std::shared_ptr<GCLicense>> gc_licenses;
std::unordered_map<std::string, std::shared_ptr<XBLicense>> xb_licenses;
std::unordered_map<uint64_t, std::shared_ptr<XBLicense>> xb_licenses;
std::unordered_map<std::string, std::shared_ptr<BBLicense>> bb_licenses;
Account() = default;
@@ -141,7 +162,7 @@ struct Account {
this->user_flags ^= static_cast<uint32_t>(flag);
}
void print(FILE* stream) const;
std::string str() const;
};
struct Login {
@@ -156,6 +177,10 @@ struct Login {
std::shared_ptr<GCLicense> gc_license;
std::shared_ptr<XBLicense> xb_license;
std::shared_ptr<BBLicense> bb_license;
uint64_t proxy_session_id() const;
std::string str() const;
};
class AccountIndex {
@@ -202,7 +227,7 @@ public:
void remove_dc_license(std::shared_ptr<Account> account, uint32_t serial_number);
void remove_pc_license(std::shared_ptr<Account> account, uint32_t serial_number);
void remove_gc_license(std::shared_ptr<Account> account, uint32_t serial_number);
void remove_xb_license(std::shared_ptr<Account> account, const std::string& gamertag);
void remove_xb_license(std::shared_ptr<Account> account, uint64_t user_id);
void remove_bb_license(std::shared_ptr<Account> account, const std::string& username);
std::shared_ptr<Account> from_account_id(uint32_t account_id) const;
@@ -253,7 +278,7 @@ protected:
std::unordered_map<uint32_t, std::shared_ptr<Account>> by_dc_serial_number;
std::unordered_map<uint32_t, std::shared_ptr<Account>> by_pc_serial_number;
std::unordered_map<uint32_t, std::shared_ptr<Account>> by_gc_serial_number;
std::unordered_map<std::string, std::shared_ptr<Account>> by_xb_gamertag;
std::unordered_map<uint64_t, std::shared_ptr<Account>> by_xb_user_id;
std::unordered_map<std::string, std::shared_ptr<Account>> by_bb_username;
void add_locked(std::shared_ptr<Account> a);
@@ -274,10 +299,7 @@ protected:
const std::string& access_key,
const std::string* password,
const std::string& character_name);
std::shared_ptr<Login> from_xb_credentials_locked(
const std::string& gamertag,
uint64_t user_id,
uint64_t account_id);
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);
-14
View File
@@ -1,14 +0,0 @@
#pragma once
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
inline void run_address_translator(const std::string&, const std::string&, const std::string&) {
throw std::runtime_error("resource_file is not available; install it and rebuild newserv");
}
inline std::vector<std::pair<uint32_t, std::string>> diff_dol_files(const std::string&, const std::string&) {
throw std::runtime_error("resource_file is not available; install it and rebuild newserv");
}
+536 -46
View File
@@ -1,12 +1,19 @@
#include "AddressTranslator.hh"
#include <array>
#include <filesystem>
#include <future>
#include <phosg/Filesystem.hh>
#include <phosg/Strings.hh>
#include <resource_file/Emulators/X86Emulator.hh>
#include <resource_file/ExecutableFormats/DOLFile.hh>
#include <resource_file/ExecutableFormats/PEFile.hh>
#include <resource_file/ExecutableFormats/XBEFile.hh>
#include "Map.hh"
#include "Text.hh"
#include "Types.hh"
using namespace std;
class AddressTranslator {
@@ -106,38 +113,44 @@ public:
AddressTranslator(const string& directory)
: log("[addr-trans] "),
directory(directory),
enable_ppc(false) {
while (phosg::ends_with(this->directory, "/")) {
directory(directory) {
while (this->directory.ends_with("/")) {
this->directory.pop_back();
}
for (const auto& filename : phosg::list_directory(this->directory)) {
if (phosg::ends_with(filename, ".dol")) {
string name = filename.substr(0, filename.size() - 4);
string path = directory + "/" + filename;
for (const auto& item : std::filesystem::directory_iterator(this->directory)) {
string filename = item.path().filename().string();
if (filename.size() < 4) {
continue;
}
string name = filename.substr(0, filename.size() - 4);
string path = directory + "/" + filename;
if (filename.ends_with(".dol")) {
ResourceDASM::DOLFile dol(path.c_str());
auto mem = make_shared<ResourceDASM::MemoryContext>();
dol.load_into(mem);
this->mems.emplace(name, mem);
this->enable_ppc = true;
this->log.info("Loaded %s", name.c_str());
} else if (phosg::ends_with(filename, ".xbe")) {
string name = filename.substr(0, filename.size() - 4);
string path = directory + "/" + filename;
this->ppc_mems.emplace(mem);
this->log.info_f("Loaded {}", name);
} else if (filename.ends_with(".xbe")) {
ResourceDASM::XBEFile xbe(path.c_str());
auto mem = make_shared<ResourceDASM::MemoryContext>();
xbe.load_into(mem);
this->mems.emplace(name, mem);
this->log.info("Loaded %s", name.c_str());
} else if (phosg::ends_with(filename, ".bin")) {
string name = filename.substr(0, filename.size() - 4);
string path = directory + "/" + filename;
this->log.info_f("Loaded {}", name);
} else if (filename.ends_with(".exe")) {
ResourceDASM::PEFile pe(path.c_str());
auto mem = make_shared<ResourceDASM::MemoryContext>();
pe.load_into(mem);
this->mems.emplace(name, mem);
this->log.info_f("Loaded {}", name);
} else if (filename.ends_with(".bin")) {
string data = phosg::load_file(path);
auto mem = make_shared<ResourceDASM::MemoryContext>();
mem->allocate_at(0x8C010000, data.size());
mem->memcpy(0x8C010000, data.data(), data.size());
this->mems.emplace(name, mem);
this->log.info("Loaded %s", name.c_str());
this->log.info_f("Loaded {}", name);
}
}
}
@@ -191,18 +204,273 @@ public:
}
}
if (r2_low_found && r2_high_found) {
fprintf(stderr, "(%s) r2 = %08" PRIX32 "\n", it.first.c_str(), r2);
phosg::fwrite_fmt(stderr, "({}) r2 = {:08X}\n", it.first, r2);
} else {
fprintf(stderr, "(%s) r2 = __MISSING__\n", it.first.c_str());
phosg::fwrite_fmt(stderr, "({}) r2 = __MISSING__\n", it.first);
}
if (r13_low_found && r13_high_found) {
fprintf(stderr, "(%s) r13 = %08" PRIX32 "\n", it.first.c_str(), r13);
phosg::fwrite_fmt(stderr, "({}) r13 = {:08X}\n", it.first, r13);
} else {
fprintf(stderr, "(%s) r13 = __MISSING__\n", it.first.c_str());
phosg::fwrite_fmt(stderr, "({}) r13 = __MISSING__\n", it.first);
}
}
}
struct ParseDATConstructorTableSpec {
string src_name;
uint32_t index_addr;
size_t num_areas;
bool has_names;
vector<uint32_t> x86_constructor_calls;
ParseDATConstructorTableSpec(const phosg::JSON& json) {
this->src_name = json.at("SourceName").as_string();
this->index_addr = json.at("IndexAddress").as_int();
this->num_areas = json.at("AreaCount").as_int();
this->has_names = json.at("HasNames").as_bool();
for (const auto& z : json.at("X86ConstructorCalls").as_list()) {
this->x86_constructor_calls.emplace_back(z->as_int());
}
}
static vector<ParseDATConstructorTableSpec> from_json_list(const phosg::JSON& json) {
vector<ParseDATConstructorTableSpec> ret;
for (const auto& z : json.as_list()) {
ret.emplace_back(*z);
}
return ret;
}
};
template <bool BE>
struct DATConstructorTableEntry {
static constexpr bool IsBE = BE;
U16T<BE> type;
U16T<BE> unknown_a1;
U32T<BE> constructor_addr;
F32T<BE> unknown_a2;
U32T<BE> default_num_children;
} __attribute__((packed));
template <bool BE>
struct DATConstructorTableEntryWithName {
static constexpr bool IsBE = BE;
pstring<TextEncoding::ASCII, 0x10> debug_name;
U16T<BE> type;
U16T<BE> unknown_a1;
U32T<BE> constructor_addr;
F32T<BE> unknown_a2;
U32T<BE> default_num_children;
} __attribute__((packed));
// 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) {
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.
shared_ptr<const ResourceDASM::MemoryContext> effective_mem = mem;
if (!spec.x86_constructor_calls.empty()) {
auto constructed_mem = make_shared<ResourceDASM::MemoryContext>(mem->duplicate());
uint32_t esp = constructed_mem->allocate(0x1000) + 0x1000;
for (uint32_t constructor_addr : spec.x86_constructor_calls) {
ResourceDASM::X86Emulator emu(constructed_mem);
// Uncomment for debugging
// auto debugger = make_shared<ResourceDASM::EmulatorDebugger<ResourceDASM::X86Emulator>>();
// debugger->bind(emu);
// debugger->state.mode = ResourceDASM::DebuggerMode::TRACE;
auto& regs = emu.registers();
regs.eip = constructor_addr;
regs.esp().u = esp - 4;
constructed_mem->write_u32l(esp - 4, 0xFFFFFFFF); // Return addr
try {
emu.execute();
} catch (const out_of_range&) {
if (regs.eip != 0xFFFFFFFF) {
throw;
}
}
}
effective_mem = constructed_mem;
}
map<uint32_t, map<uint32_t, vector<pair<size_t, size_t>>>> table;
auto index_r = effective_mem->reader(spec.index_addr, spec.num_areas * sizeof(uint32_t));
for (size_t area = 0; area < spec.num_areas; area++) {
uint32_t entries_addr = EntryT::IsBE ? index_r.get_u32b() : index_r.get_u32l();
if (!entries_addr) {
continue;
}
auto entries_r = effective_mem->reader(entries_addr, 0x4000); // 0x4000 is probably enough
while (!entries_r.eof()) {
const auto& entry = entries_r.get<EntryT>();
if (entry.type == 0xFFFF) {
break;
}
auto& group = table[entry.type][entry.constructor_addr];
if (!group.empty() && (group.back().second == (area - 1))) {
group.back().second = area;
} else {
group.emplace_back(make_pair(area, area));
}
}
if (entries_r.eof()) {
throw runtime_error("did not find end-of-entries marker");
}
}
return table;
}
static uint64_t area_mask_for_ranges(const vector<pair<size_t, size_t>>& ranges) {
uint64_t ret = 0;
for (const auto& [start, end] : ranges) {
for (size_t z = start; z <= end; z++) {
ret |= static_cast<uint64_t>(1ULL << z);
}
}
return ret;
}
void parse_dat_constructor_table(const ParseDATConstructorTableSpec& spec) {
map<uint32_t, map<uint32_t, vector<pair<size_t, size_t>>>> table;
auto spec_mem = this->mems.at(spec.src_name);
if (this->ppc_mems.count(spec_mem)) {
table = this->parse_dat_constructor_table_t<DATConstructorTableEntry<true>>(spec_mem, spec);
} else if (!spec.has_names) {
table = this->parse_dat_constructor_table_t<DATConstructorTableEntry<false>>(spec_mem, spec);
} else {
table = this->parse_dat_constructor_table_t<DATConstructorTableEntryWithName<false>>(spec_mem, spec);
}
for (const auto& [type, constructor_to_area_ranges] : table) {
phosg::fwrite_fmt(stdout, "{:04X} =>", type);
for (const auto& [constructor, area_ranges] : constructor_to_area_ranges) {
phosg::fwrite_fmt(stdout, " {:08X}", constructor);
bool is_first = true;
for (const auto& [start, end] : area_ranges) {
fputc(is_first ? ':' : ',', stdout);
if (start == end) {
phosg::fwrite_fmt(stdout, "{:02X}", start);
} else {
phosg::fwrite_fmt(stdout, "{:02X}-{:02X}", start, end);
}
is_first = false;
}
}
fputc('\n', stdout);
}
}
void parse_dat_constructor_table_multi(
const vector<ParseDATConstructorTableSpec>& specs, bool is_enemies, bool print_area_masks) {
map<string, map<uint32_t, map<uint32_t, vector<pair<size_t, size_t>>>>> all_tables;
for (const auto& spec : specs) {
map<uint32_t, map<uint32_t, vector<pair<size_t, size_t>>>> table;
auto spec_mem = this->mems.at(spec.src_name);
if (this->ppc_mems.count(spec_mem)) {
table = this->parse_dat_constructor_table_t<DATConstructorTableEntry<true>>(spec_mem, spec);
} else if (!spec.has_names) {
table = this->parse_dat_constructor_table_t<DATConstructorTableEntry<false>>(spec_mem, spec);
} else {
table = this->parse_dat_constructor_table_t<DATConstructorTableEntryWithName<false>>(spec_mem, spec);
}
all_tables.emplace(spec.src_name, std::move(table));
}
map<string, size_t> version_widths;
map<uint32_t, map<string, string>> formatted_cells_for_type;
for (const auto& spec : specs) {
const auto& table = all_tables.at(spec.src_name);
size_t max_width = 0;
for (const auto& [type, constructor_to_area_ranges] : table) {
string cell_data;
for (const auto& [constructor, area_ranges] : constructor_to_area_ranges) {
if (!cell_data.empty()) {
cell_data.push_back(' ');
}
cell_data += std::format("{:08X}", constructor);
if (print_area_masks) {
cell_data += std::format(":{:016X}", this->area_mask_for_ranges(area_ranges));
} else {
bool is_first = true;
for (const auto& [start, end] : area_ranges) {
cell_data.push_back(is_first ? ':' : ',');
if (start == end) {
cell_data += std::format("{:02X}", start);
} else {
cell_data += std::format("{:02X}-{:02X}", start, end);
}
is_first = false;
}
}
}
max_width = max<size_t>(max_width, cell_data.size());
formatted_cells_for_type[type][spec.src_name] = std::move(cell_data);
}
version_widths[spec.src_name] = max_width;
}
vector<string> formatted_lines;
string header_line = "TYPE =>";
for (const auto& spec : specs) {
size_t width = version_widths.at(spec.src_name);
header_line.push_back(' ');
header_line += spec.src_name;
if (width > spec.src_name.size()) {
header_line.resize(header_line.size() + (width - spec.src_name.size()), '-');
}
}
header_line += " NAME";
for (const auto& [type, formatted_cells] : formatted_cells_for_type) {
string line = std::format("{:04X} =>", type);
for (const auto& spec : specs) {
size_t width = version_widths.at(spec.src_name);
try {
const auto& cell_data = formatted_cells.at(spec.src_name);
line.push_back(' ');
line += cell_data;
if (width > cell_data.size()) {
line.resize(line.size() + (width - cell_data.size()), ' ');
}
} catch (const out_of_range&) {
line.resize(line.size() + (width + 1), ' ');
}
}
line.push_back(' ');
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);
}
formatted_lines.emplace_back(std::move(line));
}
for (auto& line : formatted_lines) {
phosg::strip_trailing_whitespace(line);
phosg::fwrite_fmt(stdout, "{}\n", line);
}
}
uint32_t find_match(
shared_ptr<const ResourceDASM::MemoryContext> dest_mem,
uint32_t src_addr,
@@ -234,7 +502,7 @@ public:
size_t src_offset = src_addr - src_section.first;
size_t src_bytes_available_before = src_offset;
size_t src_bytes_available_after = src_section.second - src_offset - 4;
this->log.info("(find_match/%s) Source offset = %08zX with %zX/%zX bytes available before/after",
this->log.info_f("(find_match/{}) Source offset = {:08X} with {:X}/{:X} bytes available before/after",
method_token, src_offset, src_bytes_available_before, src_bytes_available_after);
size_t match_bytes_before = 0;
@@ -246,8 +514,8 @@ public:
phosg::StringReader src_r = this->src_mem->reader(src_section.first + src_offset - match_bytes_before, match_length);
for (const auto& dest_section : dest_mem->allocated_blocks()) {
for (size_t dest_match_offset = 0;
dest_match_offset + match_length < dest_section.second;
dest_match_offset += (is_ppc ? 4 : 1)) {
dest_match_offset + match_length < dest_section.second;
dest_match_offset += (is_ppc ? 4 : 1)) {
src_r.go(0);
phosg::StringReader dest_r = dest_mem->reader(dest_section.first + dest_match_offset, match_length);
size_t z;
@@ -304,7 +572,7 @@ public:
}
}
}
this->log.info("(find_match/%s) For match length %zX, %zu matches found", method_token, match_length, num_matches);
this->log.info_f("(find_match/{}) For match length {:X}, {} matches found", method_token, match_length, num_matches);
if (num_matches == 1) {
return last_match_address;
} else if (num_matches == 0) {
@@ -367,7 +635,13 @@ public:
throw runtime_error("scan field too long; too many matches");
}
void find_all_matches(uint32_t src_addr, uint32_t src_size) const {
enum class MatchType {
ANY = 0,
TEXT,
DATA,
};
void find_all_matches(uint32_t src_addr, uint32_t src_size, MatchType type) const {
if (!this->src_mem) {
throw runtime_error("no source file selected");
}
@@ -375,7 +649,7 @@ public:
map<string, uint32_t> results;
for (const auto& it : this->mems) {
if (it.second == this->src_mem) {
log.info("(%s) %08" PRIX32 " (from source)", it.first.c_str(), src_addr);
log.info_f("({}) {:08X} (from source)", it.first, src_addr);
results.emplace(it.first, src_addr);
} else {
@@ -392,39 +666,189 @@ public:
ExpandMethod::PPC_DATA_BACKWARD,
ExpandMethod::PPC_DATA_BOTH,
};
static const vector<ExpandMethod> ppc_text_methods = {
ExpandMethod::PPC_TEXT_FORWARD,
ExpandMethod::PPC_TEXT_FORWARD_WITH_BARRIER,
ExpandMethod::PPC_TEXT_BACKWARD,
ExpandMethod::PPC_TEXT_BACKWARD_WITH_BARRIER,
ExpandMethod::PPC_TEXT_BOTH,
ExpandMethod::PPC_TEXT_BOTH_WITH_BARRIER,
ExpandMethod::PPC_TEXT_BOTH_IGNORE_ORIGIN,
};
static const vector<ExpandMethod> ppc_data_methods = {
ExpandMethod::PPC_DATA_FORWARD,
ExpandMethod::PPC_DATA_BACKWARD,
ExpandMethod::PPC_DATA_BOTH,
};
static const vector<ExpandMethod> raw_methods = {
ExpandMethod::RAW_FORWARD,
ExpandMethod::RAW_BACKWARD,
ExpandMethod::RAW_BOTH,
};
const auto& methods = this->enable_ppc ? ppc_methods : raw_methods;
for (size_t z = 0; z < methods.size(); z++) {
futures.emplace_back(async(&AddressTranslator::find_match, this, it.second, src_addr, src_size, methods[z]));
const vector<ExpandMethod>* methods;
if (this->ppc_mems.count(it.second)) {
if (type == MatchType::ANY) {
methods = &ppc_methods;
} else if (type == MatchType::TEXT) {
methods = &ppc_text_methods;
} else if (type == MatchType::DATA) {
methods = &ppc_data_methods;
} else {
throw logic_error("invalid match type");
}
} else {
methods = &raw_methods;
}
for (size_t z = 0; z < methods->size(); z++) {
futures.emplace_back(async(&AddressTranslator::find_match, this, it.second, src_addr, src_size, methods->at(z)));
}
unordered_set<uint32_t> match_addrs;
for (size_t z = 0; z < futures.size(); z++) {
const char* method_name = this->name_for_expand_method(methods[z]);
const char* method_name = this->name_for_expand_method(methods->at(z));
try {
uint32_t ret = futures[z].get();
log.info("(%s) (%s) %08" PRIX32, it.first.c_str(), method_name, ret);
log.info_f("({}) ({}) {:08X}", it.first, method_name, ret);
match_addrs.emplace(ret);
} catch (const exception& e) {
log.error("(%s) (%s) failed: %s", it.first.c_str(), method_name, e.what());
log.error_f("({}) ({}) failed: {}", it.first, method_name, e.what());
}
}
if (match_addrs.empty()) {
log.error("(%s) no match found", it.first.c_str());
log.error_f("({}) no match found", it.first);
} else if (match_addrs.size() > 1) {
log.error("(%s) different matches found by different methods", it.first.c_str());
log.error_f("({}) different matches found by different methods", it.first);
} else {
results.emplace(it.first, *match_addrs.begin());
}
}
}
for (const auto& it : results) {
fprintf(stdout, "%s => %08" PRIX32 "\n", it.first.c_str(), it.second);
phosg::fwrite_fmt(stdout, "{} => {:08X}\n", it.first, it.second);
}
}
uint32_t find_be_to_le_data_match(
shared_ptr<const ResourceDASM::MemoryContext> dest_mem,
uint32_t src_addr,
uint32_t src_size) const {
if (src_size == 0) {
src_size = 4;
}
pair<uint32_t, uint32_t> src_section = make_pair(0, 0);
for (const auto& sec : this->src_mem->allocated_blocks()) {
if (src_addr >= sec.first && src_addr + src_size <= sec.first + sec.second) {
src_section = sec;
break;
}
}
if (!src_section.second) {
throw runtime_error("source address not within any section");
}
size_t src_offset = src_addr - src_section.first;
size_t src_bytes_available_before = src_offset;
size_t src_bytes_available_after = src_section.second - src_offset - 4;
size_t match_bytes_before = 0;
size_t match_bytes_after = 0;
while (match_bytes_before + match_bytes_after + 4 < 0x100) {
size_t num_matches = 0;
size_t last_match_address = 0;
size_t match_length = match_bytes_before + match_bytes_after + 4;
uint32_t src_addr = src_section.first + src_offset - match_bytes_before;
phosg::StringReader src_r = this->src_mem->reader(src_addr, match_length);
for (const auto& dest_section : dest_mem->allocated_blocks()) {
for (size_t dest_match_offset = 0;
dest_match_offset + match_length < dest_section.second;
dest_match_offset += 4) {
src_r.go(0);
phosg::StringReader dest_r = dest_mem->reader(dest_section.first + dest_match_offset, match_length);
size_t z;
for (z = 0; z < match_length; z += 4) {
uint32_t src_v = src_r.get_u32b();
uint32_t dest_v = dest_r.get_u32l();
bool src_is_addr = ((src_v & 0xFE000003) == 0x80000000);
bool dest_is_addr = ((dest_v >= 0x00010000) && (dest_v <= 0x00800000));
if (src_is_addr != dest_is_addr) {
break;
} else if (src_v != dest_v) {
break;
}
}
if (z == match_length) {
num_matches++;
last_match_address = dest_section.first + dest_match_offset + match_bytes_before;
}
}
}
this->log.info_f("... For match length {:X}, {} matches found", match_length, num_matches);
if (num_matches == 1) {
return last_match_address;
} else if (num_matches == 0) {
throw runtime_error("did not find exactly one match");
}
bool can_expand_backward = (src_bytes_available_before >= match_bytes_before + 4);
bool can_expand_forward = (src_bytes_available_after >= match_bytes_after + 4);
if (!can_expand_backward && !can_expand_forward) {
throw runtime_error("no further expansion is allowed");
}
if (can_expand_backward) {
match_bytes_before += 4;
}
if (can_expand_forward) {
match_bytes_after += 4;
}
}
throw runtime_error("scan field too long; too many matches");
}
void find_all_be_to_le_data_matches(uint32_t src_addr, uint32_t src_size) const {
if (!this->src_mem) {
throw runtime_error("no source file selected");
}
map<string, uint32_t> results;
for (const auto& it : this->mems) {
if (it.second == this->src_mem) {
log.info_f("({}) {:08X} (from source)", it.first, src_addr);
results.emplace(it.first, src_addr);
} else {
uint32_t ret = 0;
try {
ret = this->find_be_to_le_data_match(it.second, src_addr, src_size);
log.info_f("({}) {:08X}", it.first, ret);
} catch (const exception& e) {
log.error_f("({}) failed: {}", it.first, e.what());
}
if (ret == 0) {
log.error_f("({}) no match found", it.first);
} else {
results.emplace(it.first, ret);
}
}
}
for (const auto& it : results) {
phosg::fwrite_fmt(stdout, "{} => {:08X}\n", it.first, it.second);
}
}
void find_data(const string& data) const {
for (const auto& [name, mem] : this->mems) {
for (const auto& [sec_addr, sec_size] : mem->allocated_blocks()) {
uint32_t last_addr = sec_addr + sec_size - data.size();
for (uint32_t addr = sec_addr; addr < last_addr; addr++) {
if (!mem->memcmp(addr, data.data(), data.size())) {
phosg::fwrite_fmt(stderr, "{} => {:08X}\n", name, addr);
}
}
}
}
}
@@ -437,12 +861,34 @@ public:
if (tokens[0] == "use") {
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] == "match") {
this->find_all_matches(
stoul(tokens.at(1), nullptr, 16),
tokens.size() >= 3 ? stoul(tokens[2], nullptr, 16) : 0,
MatchType::ANY);
} else if (tokens[0] == "match-text") {
this->find_all_matches(
stoul(tokens.at(1), nullptr, 16),
tokens.size() >= 3 ? stoul(tokens[2], nullptr, 16) : 0,
MatchType::TEXT);
} else if (tokens[0] == "match-data") {
this->find_all_matches(
stoul(tokens.at(1), nullptr, 16),
tokens.size() >= 3 ? stoul(tokens[2], nullptr, 16) : 0,
MatchType::DATA);
} else if (tokens[0] == "match-be-le") {
this->find_all_be_to_le_data_matches(
stoul(tokens.at(1), nullptr, 16),
tokens.size() >= 3 ? stoul(tokens[2], nullptr, 16) : 0);
} else if (tokens[0] == "find-ppc-globals") {
this->find_ppc_rtoc_global_regs();
} else if ((tokens[0] == "parse-dat-object-constructor-tables") ||
(tokens[0] == "parse-dat-enemy-constructor-tables")) {
bool is_enemies = (tokens[0] == "parse-dat-enemy-constructor-tables");
auto specs = ParseDATConstructorTableSpec::from_json_list(phosg::JSON::parse(phosg::load_file(tokens.at(1))));
this->parse_dat_constructor_table_multi(specs, is_enemies, true);
} else if (!tokens[0].empty()) {
throw runtime_error("unknown command");
}
@@ -451,9 +897,9 @@ public:
void run_shell() {
while (!feof(stdin)) {
if (!this->src_filename.empty()) {
fprintf(stdout, "addr-trans:%s/%s> ", this->directory.c_str(), this->src_filename.c_str());
phosg::fwrite_fmt(stdout, "addr-trans:{}/{}> ", this->directory, this->src_filename);
} else {
fprintf(stdout, "addr-trans:%s> ", this->directory.c_str());
phosg::fwrite_fmt(stdout, "addr-trans:{}> ", this->directory);
}
fflush(stdout);
@@ -461,7 +907,7 @@ public:
try {
this->handle_command(command);
} catch (const exception& e) {
this->log.error("Failed: %s", e.what());
this->log.error_f("Failed: {}", e.what());
}
}
fputc('\n', stdout);
@@ -471,12 +917,12 @@ private:
phosg::PrefixedLogger log;
string directory;
unordered_map<string, shared_ptr<const ResourceDASM::MemoryContext>> mems;
unordered_set<shared_ptr<const ResourceDASM::MemoryContext>> ppc_mems;
string src_filename;
shared_ptr<const ResourceDASM::MemoryContext> src_mem;
bool enable_ppc;
};
void run_address_translator(const std::string& directory, const std::string& use_filename, const std::string& command) {
void run_address_translator(const string& directory, const string& use_filename, const string& command) {
AddressTranslator trans(directory);
if (!use_filename.empty()) {
trans.set_source_file(use_filename);
@@ -489,7 +935,7 @@ void run_address_translator(const std::string& directory, const std::string& use
}
}
vector<pair<uint32_t, string>> diff_dol_files(const string& a_filename, const string& b_filename) {
vector<DiffEntry> diff_dol_files(const string& a_filename, const string& b_filename) {
ResourceDASM::DOLFile a(a_filename.c_str());
ResourceDASM::DOLFile b(b_filename.c_str());
auto a_mem = make_shared<ResourceDASM::MemoryContext>();
@@ -508,7 +954,7 @@ vector<pair<uint32_t, string>> diff_dol_files(const string& a_filename, const st
max_addr = max<uint32_t>(max_addr, sec.address + sec.data.size());
}
vector<pair<uint32_t, string>> ret;
vector<DiffEntry> ret;
for (uint32_t addr = min_addr; addr < max_addr; addr += 4) {
bool a_exists = a_mem->exists(addr, 4);
bool b_exists = b_mem->exists(addr, 4);
@@ -516,10 +962,54 @@ vector<pair<uint32_t, string>> diff_dol_files(const string& a_filename, const st
string a_value = a_mem->read(addr, 4);
string b_value = b_mem->read(addr, 4);
if (a_value != b_value) {
if (!ret.empty() && (ret.back().first + ret.back().second.size() == addr)) {
ret.back().second += b_value;
if (!ret.empty() && (ret.back().address + ret.back().b_data.size() == addr)) {
ret.back().a_data += a_value;
ret.back().b_data += b_value;
} else {
ret.emplace_back(make_pair(addr, b_value));
ret.emplace_back(DiffEntry{.address = addr, .a_data = a_value, .b_data = b_value});
}
}
}
}
return ret;
}
vector<DiffEntry> diff_xbe_files(const string& a_filename, const string& b_filename) {
ResourceDASM::XBEFile a(a_filename.c_str());
ResourceDASM::XBEFile b(b_filename.c_str());
auto a_mem = make_shared<ResourceDASM::MemoryContext>();
auto b_mem = make_shared<ResourceDASM::MemoryContext>();
a.load_into(a_mem);
b.load_into(b_mem);
uint32_t min_addr = 0xFFFFFFFF;
uint32_t max_addr = 0x00000000;
for (const auto& sec : a.sections) {
min_addr = min<uint32_t>(min_addr, sec.addr);
max_addr = max<uint32_t>(max_addr, sec.addr + sec.size);
}
for (const auto& sec : b.sections) {
min_addr = min<uint32_t>(min_addr, sec.addr);
max_addr = max<uint32_t>(max_addr, sec.addr + sec.size);
}
vector<DiffEntry> ret;
for (uint32_t addr = min_addr; addr < max_addr; addr++) {
bool a_exists = a_mem->exists(addr, 1);
bool b_exists = b_mem->exists(addr, 1);
if (a_exists && b_exists) {
uint8_t a_value = a_mem->read_u8(addr);
uint8_t b_value = b_mem->read_u8(addr);
if (a_value != b_value) {
if (!ret.empty() && (ret.back().address + ret.back().b_data.size() == addr)) {
auto& entry = ret.back();
entry.a_data.push_back(a_value);
entry.b_data.push_back(b_value);
} else {
auto& entry = ret.emplace_back();
entry.address = addr;
entry.a_data.push_back(a_value);
entry.b_data.push_back(b_value);
}
}
}
+8 -1
View File
@@ -6,5 +6,12 @@
#include <utility>
#include <vector>
struct DiffEntry {
uint32_t address;
std::string a_data;
std::string b_data;
};
void run_address_translator(const std::string& directory, const std::string& use_filename, const std::string& command);
std::vector<std::pair<uint32_t, std::string>> diff_dol_files(const std::string& a_filename, const std::string& b_filename);
std::vector<DiffEntry> diff_dol_files(const std::string& a_filename, const std::string& b_filename);
std::vector<DiffEntry> diff_xbe_files(const std::string& a_filename, const std::string& b_filename);
+409
View File
@@ -0,0 +1,409 @@
#include "AsyncHTTPServer.hh"
#include <inttypes.h>
#include <stdlib.h>
#include <phosg/Encoding.hh>
#include <phosg/Network.hh>
#include <phosg/Time.hh>
#include <string>
#include <vector>
#include "AsyncUtils.hh"
#include "Loggers.hh"
#include "Revision.hh"
#include "Server.hh"
using namespace std;
static const unordered_map<int, const char*> explanation_for_response_code{
{100, "Continue"},
{101, "Switching Protocols"},
{102, "Processing"},
{200, "OK"},
{201, "Created"},
{202, "Accepted"},
{203, "Non-Authoritative Information"},
{204, "No Content"},
{205, "Reset Content"},
{206, "Partial Content"},
{207, "Multi-Status"},
{208, "Already Reported"},
{226, "IM Used"},
{300, "Multiple Choices"},
{301, "Moved Permanently"},
{302, "Found"},
{303, "See Other"},
{304, "Not Modified"},
{305, "Use Proxy"},
{307, "Temporary Redirect"},
{308, "Permanent Redirect"},
{400, "Bad Request"},
{401, "Unathorized"},
{402, "Payment Required"},
{403, "Forbidden"},
{404, "Not Found"},
{405, "Method Not Allowed"},
{406, "Not Acceptable"},
{407, "Proxy Authentication Required"},
{408, "Request Timeout"},
{409, "Conflict"},
{410, "Gone"},
{411, "Length Required"},
{412, "Precondition Failed"},
{413, "Request Entity Too Large"},
{414, "Request-URI Too Long"},
{415, "Unsupported Media Type"},
{416, "Requested Range Not Satisfiable"},
{417, "Expectation Failed"},
{418, "I\'m a Teapot"},
{420, "Enhance Your Calm"},
{422, "Unprocessable Entity"},
{423, "Locked"},
{424, "Failed Dependency"},
{426, "Upgrade Required"},
{428, "Precondition Required"},
{429, "Too Many Requests"},
{431, "Request Header Fields Too Large"},
{444, "No Response"},
{449, "Retry With"},
{451, "Unavailable For Legal Reasons"},
{500, "Internal Server Error"},
{501, "Not Implemented"},
{502, "Bad Gateway"},
{503, "Service Unavailable"},
{504, "Gateway Timeout"},
{505, "HTTP Version Not Supported"},
{506, "Variant Also Negotiates"},
{507, "Insufficient Storage"},
{508, "Loop Detected"},
{509, "Bandwidth Limit Exceeded"},
{510, "Not Extended"},
{511, "Network Authentication Required"},
{598, "Network Read Timeout Error"},
{599, "Network Connect Timeout Error"},
};
HTTPError::HTTPError(int code, const std::string& what)
: std::runtime_error(what), code(code) {}
const std::string* HTTPRequest::get_header(const std::string& name) const {
auto its = this->headers.equal_range(name);
if (its.first == its.second) {
return nullptr;
}
const string* ret = &its.first->second;
its.first++;
if (its.first != its.second) {
throw std::out_of_range("Header appears multiple times: " + name);
}
return ret;
}
const std::string* HTTPRequest::get_query_param(const std::string& name) const {
auto its = this->query_params.equal_range(name);
if (its.first == its.second) {
return nullptr;
}
const string* ret = &its.first->second;
its.first++;
if (its.first != its.second) {
throw std::out_of_range("Query parameter appears multiple times: " + name);
}
return ret;
}
static void url_decode_inplace(string& s) {
size_t write_offset = 0, read_offset = 0;
for (; read_offset < s.size(); write_offset++) {
if ((s[read_offset] == '%') && (read_offset < s.size() - 2)) {
s[write_offset] =
static_cast<char>(phosg::value_for_hex_char(s[read_offset + 1]) << 4) |
static_cast<char>(phosg::value_for_hex_char(s[read_offset + 2]));
read_offset += 3;
} else if (s[write_offset] == '+') {
s[write_offset] = ' ';
read_offset++;
} else {
s[write_offset] = s[read_offset];
read_offset++;
}
}
s.resize(write_offset);
}
HTTPClient::HTTPClient(asio::ip::tcp::socket&& sock) : r(std::move(sock)) {}
asio::awaitable<HTTPRequest> HTTPClient::recv_http_request(size_t max_line_size, size_t max_body_size) {
HTTPRequest req;
std::string request_line = co_await this->r.read_line("\r\n", max_line_size);
auto line_tokens = phosg::split(request_line, ' ');
if (line_tokens.size() != 3) {
throw runtime_error("invalid HTTP request line");
}
const auto& method_token = line_tokens[0];
if (method_token == "GET") {
req.method = HTTPRequest::Method::GET;
} else if (method_token == "POST") {
req.method = HTTPRequest::Method::POST;
} else if (method_token == "DELETE") {
req.method = HTTPRequest::Method::DELETE;
} else if (method_token == "HEAD") {
req.method = HTTPRequest::Method::HEAD;
} else if (method_token == "PATCH") {
req.method = HTTPRequest::Method::PATCH;
} else if (method_token == "PUT") {
req.method = HTTPRequest::Method::PUT;
} else if (method_token == "UPDATE") {
req.method = HTTPRequest::Method::UPDATE;
} else if (method_token == "OPTIONS") {
req.method = HTTPRequest::Method::OPTIONS;
} else if (method_token == "CONNECT") {
req.method = HTTPRequest::Method::CONNECT;
} else if (method_token == "TRACE") {
req.method = HTTPRequest::Method::TRACE;
} else {
throw HTTPError(400, "unknown request method");
}
req.http_version = std::move(line_tokens[2]);
size_t fragment_start_offset = line_tokens[1].find('#');
if (fragment_start_offset != string::npos) {
req.fragment = line_tokens[1].substr(fragment_start_offset + 1);
line_tokens[1].resize(fragment_start_offset);
}
size_t query_start_offset = line_tokens[1].find('?');
string query;
if (query_start_offset != string::npos) {
query = line_tokens[1].substr(query_start_offset + 1);
line_tokens[1].resize(query_start_offset);
}
req.path = std::move(line_tokens[1]);
if (req.path.empty()) {
throw std::runtime_error("request path is missing");
}
auto query_tokens = phosg::split(query, '&');
for (auto& token : query_tokens) {
size_t equals_pos = token.find('=');
if (equals_pos == string::npos) {
url_decode_inplace(token);
req.query_params.emplace(std::move(token), "");
} else {
string key = token.substr(0, equals_pos);
string value = token.substr(equals_pos + 1);
url_decode_inplace(key);
url_decode_inplace(value);
req.query_params.emplace(std::move(key), std::move(value));
}
}
auto prev_header_it = req.headers.end();
for (;;) {
std::string line = co_await this->r.read_line("\r\n", max_line_size);
if (line.empty()) {
break;
}
if (line[0] == ' ' || line[0] == '\t') {
if (prev_header_it == req.headers.end()) {
throw std::runtime_error("received header continuation line before any header");
} else {
phosg::strip_whitespace(line);
prev_header_it->second.append(1, ' ');
prev_header_it->second += line;
}
} else {
size_t colon_pos = line.find(':');
if (colon_pos == string::npos) {
throw runtime_error("malformed header line");
}
string key = line.substr(0, colon_pos);
string value = line.substr(colon_pos + 1);
phosg::strip_whitespace(key);
phosg::strip_whitespace(value);
prev_header_it = req.headers.emplace(phosg::tolower(key), std::move(value));
}
}
auto transfer_encoding_header = req.get_header("transfer-encoding");
if (transfer_encoding_header && phosg::tolower(*transfer_encoding_header) == "chunked") {
deque<string> chunks;
size_t total_data_bytes = 0;
for (;;) {
auto line = co_await this->r.read_line("\r\n", 0x20);
size_t parse_offset = 0;
size_t chunk_size = stoull(line, &parse_offset, 16);
if (parse_offset != line.size()) {
throw HTTPError(400, "invalid chunk header during chunked encoding");
}
if (chunk_size == 0) {
break;
}
total_data_bytes += chunk_size;
if (total_data_bytes > max_body_size) {
throw HTTPError(400, "request data size too large");
}
chunks.emplace_back(co_await this->r.read_data(chunk_size));
auto after_chunk_data = co_await this->r.read_line("\r\n", 0x20);
if (!after_chunk_data.empty()) {
throw HTTPError(400, "incorrect trailing sequence after chunk data");
}
}
} else {
auto content_length_header = req.get_header("content-length");
size_t content_length = content_length_header ? stoull(*content_length_header) : 0;
if (content_length > max_body_size) {
throw HTTPError(400, "request data size too large");
} else if (content_length > 0) {
req.data = co_await this->r.read_data(content_length);
}
}
co_return req;
}
asio::awaitable<void> HTTPClient::send_http_response(const HTTPResponse& resp) {
AsyncWriteCollector w;
w.add(std::format("{} {} {}\r\n",
resp.http_version, resp.response_code, explanation_for_response_code.at(resp.response_code)));
for (const auto& it : resp.headers) {
w.add(it.first + ": " + it.second + "\r\n");
}
if (!resp.data.empty()) {
w.add(std::format("Content-Length: {}\r\n", resp.data.size()));
}
w.add("\r\n");
if (!resp.data.empty()) {
w.add_reference(resp.data.data(), resp.data.size());
}
co_await w.write(this->r.get_socket());
}
asio::awaitable<WebSocketMessage> HTTPClient::recv_websocket_message(size_t max_data_size) {
WebSocketMessage prev_msg;
bool prev_msg_present = false;
while (this->r.get_socket().is_open()) {
WebSocketMessage msg;
// We need at most 10 bytes to determine if there's a valid frame, or as
// little as 2
co_await this->r.read_data_into(msg.header, 2);
// Get the payload size
bool has_mask = msg.header[1] & 0x80;
size_t payload_size = msg.header[1] & 0x7F;
if (payload_size == 0x7F) {
phosg::be_uint64_t wire_size;
co_await this->r.read_data_into(&wire_size, sizeof(wire_size));
payload_size = wire_size;
} else if (payload_size == 0x7E) {
phosg::be_uint16_t wire_size;
co_await this->r.read_data_into(&wire_size, sizeof(wire_size));
payload_size = wire_size;
}
if (payload_size > max_data_size) {
throw runtime_error("Incoming WebSocket message exceeds size limit");
}
// Read the masking key if present
if (has_mask) {
co_await this->r.read_data_into(msg.mask_key, sizeof(msg.mask_key));
}
// Read and unmask message data
msg.data = co_await this->r.read_data(payload_size);
if (has_mask) {
for (size_t x = 0; x < msg.data.size(); x++) {
msg.data[x] ^= msg.mask_key[x & 3];
}
}
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)
uint8_t opcode = msg.header[0] & 0x0F;
if (opcode & 0x08) {
if (opcode == 0x0A) {
// Ping response; ignore it
} else if (opcode == 0x08) {
// Close message
co_await this->send_websocket_message(msg.data, msg.opcode);
this->r.get_socket().close();
} else if (opcode == 0x09) {
// Ping message
co_await this->send_websocket_message(msg.data, 0x0A);
} else {
// Unknown control message type
this->r.get_socket().close();
}
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 (prev_msg_present == (opcode != 0)) {
this->r.get_socket().close();
continue;
}
// Save the message opcode, if present, and append the frame data
if (!prev_msg_present) {
prev_msg = std::move(msg);
} else {
prev_msg.header[0] = msg.header[0];
prev_msg.header[1] = msg.header[1];
if (opcode) {
prev_msg.opcode = msg.opcode;
}
if (has_mask) {
prev_msg.mask_key[0] = msg.mask_key[0];
prev_msg.mask_key[1] = msg.mask_key[1];
prev_msg.mask_key[2] = msg.mask_key[2];
prev_msg.mask_key[3] = msg.mask_key[3];
}
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 (prev_msg.header[0] & 0x80) {
co_return prev_msg;
}
}
throw logic_error("failed to receive websocket message");
}
asio::awaitable<void> HTTPClient::send_websocket_message(const void* data, size_t size, uint8_t opcode) {
phosg::StringWriter w;
w.put_u8(0x80 | (opcode & 0x0F));
if (size > 0xFFFF) {
w.put_u8(0x7F);
w.put_u64b(size);
} else if (size > 0x7D) {
w.put_u8(0x7E);
w.put_u16b(size);
} else {
w.put_u8(size);
}
array<asio::const_buffer, 2> bufs = {asio::const_buffer(w.data(), w.size()), asio::const_buffer(data, size)};
co_await asio::async_write(this->r.get_socket(), bufs, asio::use_awaitable);
}
asio::awaitable<void> HTTPClient::send_websocket_message(const std::string& data, uint8_t opcode) {
return this->send_websocket_message(data.data(), data.size(), opcode);
}
const HTTPServerLimits DEFAULT_HTTP_LIMITS;
+230
View File
@@ -0,0 +1,230 @@
#pragma once
#include "WindowsPlatform.hh"
#include <stdlib.h>
#include <asio.hpp>
#include <exception>
#include <functional>
#include <memory>
#include <optional>
#include <phosg/Hash.hh>
#include <phosg/Time.hh>
#include <string>
#include "AsyncUtils.hh"
#include "Server.hh"
struct HTTPRequest {
enum class Method {
GET = 0,
POST,
DELETE,
HEAD,
PATCH,
PUT,
UPDATE,
OPTIONS,
CONNECT,
TRACE,
};
std::string http_version;
Method method;
std::string path;
std::string fragment;
std::unordered_multimap<std::string, std::string> headers; // Header names converted to all lowercase
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.
const std::string* get_header(const std::string& name) const;
const std::string* get_query_param(const std::string& name) const;
};
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.
std::unordered_multimap<std::string, std::string> headers;
std::string data;
};
struct WebSocketMessage {
uint8_t header[2] = {0, 0};
uint8_t opcode = 0x01;
uint8_t mask_key[4] = {0, 0, 0, 0};
std::string data;
};
class HTTPError : public std::runtime_error {
public:
HTTPError(int code, const std::string& what);
int code;
};
struct HTTPClient {
AsyncSocketReader r;
uint64_t last_communication_time = 0;
bool is_websocket = false;
HTTPClient(asio::ip::tcp::socket&& sock);
asio::awaitable<HTTPRequest> recv_http_request(size_t max_line_size, size_t max_body_size);
asio::awaitable<void> send_http_response(const HTTPResponse& resp);
asio::awaitable<WebSocketMessage> recv_websocket_message(size_t max_data_size);
asio::awaitable<void> send_websocket_message(const void* data, size_t size, uint8_t opcode = 0x01);
asio::awaitable<void> send_websocket_message(const std::string& data, uint8_t opcode = 0x01);
};
struct HTTPServerLimits {
size_t max_http_request_line_size = 0x1000; // 4KB
size_t max_http_data_size = 0x200000; // 2MB
size_t max_http_keepalive_idle_usecs = 300 * 1000 * 1000; // 5 minutes (0 = no limit)
size_t max_websocket_message_size = 0x200000; // 2MB
size_t max_websocket_idle_usecs = 0; // No limit by default
};
extern const HTTPServerLimits DEFAULT_HTTP_LIMITS;
template <typename ClientT = HTTPClient>
class AsyncHTTPServer : public Server<ClientT, ServerSocket> {
public:
explicit AsyncHTTPServer(
std::shared_ptr<asio::io_context> io_context,
const std::string& log_prefix = "[AsyncHTTPServer] ",
const HTTPServerLimits& limits = DEFAULT_HTTP_LIMITS)
: Server<ClientT, ServerSocket>(io_context, log_prefix), limits(limits) {}
AsyncHTTPServer(const AsyncHTTPServer&) = delete;
AsyncHTTPServer(AsyncHTTPServer&&) = delete;
AsyncHTTPServer& operator=(const AsyncHTTPServer&) = delete;
AsyncHTTPServer& operator=(AsyncHTTPServer&&) = delete;
virtual ~AsyncHTTPServer() = default;
void listen(const std::string& addr, int port) {
if (port == 0) {
throw std::runtime_error("Listening port cannot be zero");
}
asio::ip::address asio_addr = addr.empty() ? asio::ip::address_v4::any() : asio::ip::make_address(addr);
auto sock = std::make_shared<ServerSocket>();
sock->name = std::format("http:{}:{}", addr, port);
sock->endpoint = asio::ip::tcp::endpoint(asio_addr, port);
this->add_socket(std::move(sock));
}
protected:
HTTPServerLimits limits;
// 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;
}
auto connection_header = req.get_header("connection");
if (!connection_header || phosg::tolower(*connection_header) != "upgrade") {
co_return false;
}
auto upgrade_header = req.get_header("upgrade");
if (!upgrade_header || phosg::tolower(*upgrade_header) != "websocket") {
co_return false;
}
auto sec_websocket_key_header = req.get_header("sec-websocket-key");
if (!sec_websocket_key_header) {
co_return false;
}
std::string sec_websocket_accept_data = *sec_websocket_key_header + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string sec_websocket_accept = phosg::base64_encode(phosg::SHA1(sec_websocket_accept_data).bin());
HTTPResponse resp;
resp.http_version = req.http_version;
resp.response_code = 101;
resp.headers.emplace("Upgrade", "websocket");
resp.headers.emplace("Connection", "upgrade");
resp.headers.emplace("Sec-WebSocket-Accept", std::move(sec_websocket_accept));
co_await c->send_http_response(resp);
c->is_websocket = true;
co_return true;
}
[[nodiscard]] virtual std::shared_ptr<ClientT> create_client(
std::shared_ptr<ServerSocket>, asio::ip::tcp::socket&& client_sock) {
return std::make_shared<HTTPClient>(std::move(client_sock));
}
// 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.
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;
}
virtual asio::awaitable<void> handle_client(std::shared_ptr<ClientT> c) {
asio::steady_timer idle_timer(*this->io_context);
while (c->r.get_socket().is_open()) {
if (c->is_websocket) {
WebSocketMessage msg = co_await c->recv_websocket_message(this->limits.max_websocket_message_size);
idle_timer.cancel();
try {
co_await this->handle_websocket_message(c, std::move(msg));
} catch (const std::exception& e) {
c->r.close();
}
} else {
HTTPRequest req = co_await c->recv_http_request(
this->limits.max_http_request_line_size, this->limits.max_http_data_size);
idle_timer.cancel();
std::unique_ptr<HTTPResponse> resp;
try {
resp = co_await this->handle_request(c, std::move(req));
} catch (const std::exception& e) {
resp = std::make_unique<HTTPResponse>();
resp->http_version = req.http_version;
resp->response_code = 500;
resp->headers.emplace("Content-Type", "text/plain");
resp->data = "Internal server error:\n";
resp->data += e.what();
}
if (resp) {
co_await c->send_http_response(*resp);
}
if (!c->is_websocket) {
auto* conn_header = req.get_header("connection");
if (!conn_header || (*conn_header != "keep-alive")) {
c->r.close();
}
}
}
size_t idle_usecs_limit = c->is_websocket
? this->limits.max_websocket_idle_usecs
: this->limits.max_http_keepalive_idle_usecs;
if (idle_usecs_limit && c->r.get_socket().is_open()) {
idle_timer.expires_after(std::chrono::microseconds(idle_usecs_limit));
idle_timer.async_wait([c](std::error_code ec) {
if (!ec) {
c->r.close();
}
});
}
}
idle_timer.cancel();
}
};
+160
View File
@@ -0,0 +1,160 @@
#include "AsyncUtils.hh"
#include <asio.hpp>
#include <exception>
#include <functional>
#include <optional>
#include <phosg/Strings.hh>
#include <string>
using namespace std;
AsyncEvent::AsyncEvent(asio::any_io_executor ex)
: executor(ex), is_set(false) {}
void AsyncEvent::set() {
lock_guard g(this->lock);
this->is_set = true;
for (auto& waiter : this->waiters) {
asio::post(this->executor,
[handler = std::move(waiter)]() mutable {
(*handler)();
});
}
this->waiters.clear();
}
void AsyncEvent::clear() {
lock_guard g(this->lock);
this->is_set = false;
}
asio::awaitable<void> AsyncEvent::wait() {
auto token = asio::use_awaitable_t<>{};
co_await asio::async_initiate<asio::use_awaitable_t<>, void()>(
[this](auto&& handler) -> void {
lock_guard g(this->lock);
if (this->is_set) {
handler();
} else {
this->waiters.emplace_back(make_unique<asio::detail::awaitable_handler<asio::any_io_executor>>(std::move(handler)));
}
},
token);
}
AsyncSocketReader::AsyncSocketReader(asio::ip::tcp::socket&& sock)
: sock(std::move(sock)) {}
asio::awaitable<string> AsyncSocketReader::read_line(const char* delimiter, size_t max_length) {
size_t delimiter_size = strlen(delimiter);
if (delimiter_size == 0) {
throw logic_error("delimiter is empty");
}
size_t delimiter_backup_bytes = delimiter_size - 1;
size_t delimiter_pos = this->pending_data.find(delimiter);
while ((delimiter_pos == string::npos) && (!max_length || (this->pending_data.size() < max_length))) {
size_t pre_size = this->pending_data.size();
this->pending_data.resize(min(max_length, this->pending_data.size() + 0x400));
auto buf = asio::buffer(this->pending_data.data() + pre_size, this->pending_data.size() - pre_size);
size_t bytes_read = co_await this->sock.async_read_some(buf, asio::use_awaitable);
this->pending_data.resize(pre_size + bytes_read);
delimiter_pos = this->pending_data.find(
delimiter,
(delimiter_backup_bytes > pre_size) ? 0 : (pre_size - delimiter_backup_bytes));
}
if (delimiter_pos == string::npos) {
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.
string ret = this->pending_data.substr(0, delimiter_pos);
this->pending_data = this->pending_data.substr(delimiter_pos + delimiter_size);
co_return ret;
}
asio::awaitable<string> AsyncSocketReader::read_data(size_t size) {
string ret;
if (this->pending_data.size() == size) {
this->pending_data.swap(ret);
} else if (this->pending_data.size() > size) {
ret = this->pending_data.substr(0, size);
this->pending_data = this->pending_data.substr(size);
} else {
size_t bytes_to_read = size - this->pending_data.size();
this->pending_data.swap(ret);
ret.resize(size);
co_await asio::async_read(this->sock, asio::buffer(ret.data() + size - bytes_to_read, bytes_to_read), asio::use_awaitable);
}
co_return ret;
}
asio::awaitable<void> AsyncSocketReader::read_data_into(void* data, size_t size) {
if (this->pending_data.size() == size) {
memcpy(data, this->pending_data.data(), size);
this->pending_data.clear();
} else if (this->pending_data.size() > size) {
memcpy(data, this->pending_data.data(), size);
this->pending_data = this->pending_data.substr(size);
} else {
memcpy(data, this->pending_data.data(), this->pending_data.size());
size_t bytes_to_read = size - this->pending_data.size();
this->pending_data.clear();
void* read_buf = reinterpret_cast<uint8_t*>(data) + size - bytes_to_read;
co_await asio::async_read(this->sock, asio::buffer(read_buf, bytes_to_read), asio::use_awaitable);
}
}
void AsyncWriteCollector::add(string&& data) {
const auto& item = this->owned_data.emplace_back(std::move(data));
bufs.emplace_back(asio::buffer(item.data(), item.size()));
}
void AsyncWriteCollector::add_reference(const void* data, size_t size) {
bufs.emplace_back(asio::buffer(data, size));
}
asio::awaitable<void> AsyncWriteCollector::write(asio::ip::tcp::socket& sock) {
deque<string> local_owned_data;
local_owned_data.swap(this->owned_data);
vector<asio::const_buffer> local_bufs;
local_bufs.swap(this->bufs);
co_await asio::async_write(sock, local_bufs, asio::use_awaitable);
}
asio::awaitable<void> async_sleep(chrono::steady_clock::duration duration) {
asio::steady_timer timer(co_await asio::this_coro::executor, duration);
co_await timer.async_wait(asio::use_awaitable);
}
asio::awaitable<asio::ip::tcp::socket> async_connect_tcp(uint32_t ipv4_addr, uint16_t port) {
uint8_t octets[4] = {
static_cast<uint8_t>(ipv4_addr >> 24),
static_cast<uint8_t>(ipv4_addr >> 16),
static_cast<uint8_t>(ipv4_addr >> 8),
static_cast<uint8_t>(ipv4_addr)};
return async_connect_tcp(std::format("{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]), port);
}
asio::awaitable<asio::ip::tcp::socket> async_connect_tcp(const std::string& host, uint16_t port) {
auto executor = co_await asio::this_coro::executor;
asio::ip::tcp::resolver resolver(executor);
auto endpoints = co_await resolver.async_resolve(host, std::format("{}", port), asio::use_awaitable);
asio::ip::tcp::socket sock(executor);
co_await asio::async_connect(sock, endpoints, asio::use_awaitable);
co_return sock;
}
asio::awaitable<asio::ip::tcp::socket> async_connect_tcp(const asio::ip::tcp::endpoint& ep) {
auto executor = co_await asio::this_coro::executor;
asio::ip::tcp::socket sock(executor);
co_await sock.async_connect(ep, asio::use_awaitable);
co_return sock;
}
+265
View File
@@ -0,0 +1,265 @@
#pragma once
#include <asio.hpp>
#include <asio/experimental/parallel_group.hpp>
#include <asio/experimental/promise.hpp>
#include <deque>
#include <exception>
#include <functional>
#include <optional>
#include <phosg/Strings.hh>
template <typename T>
class AsyncPromise {
public:
AsyncPromise() = default;
asio::awaitable<T> get() {
if (!this->exc && !this->val.has_value()) {
auto executor = co_await asio::this_coro::executor;
co_await asio::async_initiate<decltype(asio::use_awaitable), void(std::error_code)>(
[this, &executor](auto&& new_handler) {
this->resolver_ref.emplace(ResolverRef{.resolve = std::move(new_handler), .executor = &executor});
},
asio::use_awaitable);
}
if (this->exc) {
std::rethrow_exception(this->exc);
} else if (this->val.has_value()) {
co_return *this->val;
} else {
throw std::logic_error("AsyncPromise await resolved but did not have a value or exception");
}
}
void set_value(T&& result) {
if (this->done()) {
throw std::logic_error("attempted to set value on completed promise");
}
this->val = result;
this->resolve();
}
void set_exception(std::exception_ptr ex) {
if (this->done()) {
throw std::logic_error("attempted to set value on completed promise");
}
this->exc = ex;
this->resolve();
}
void cancel() {
this->set_exception(std::make_exception_ptr(std::runtime_error("AsyncPromise cancelled")));
}
bool done() const {
return this->exc || this->val.has_value();
}
private:
struct ResolverRef {
asio::detail::awaitable_handler<asio::any_io_executor, std::error_code> resolve;
asio::any_io_executor* executor;
};
std::optional<T> val;
std::exception_ptr exc;
std::optional<ResolverRef> resolver_ref;
void resolve() {
if (this->resolver_ref) {
auto* executor = this->resolver_ref->executor;
ResolverRef ref = std::move(*this->resolver_ref);
this->resolver_ref.reset();
asio::post(*executor, [ref = std::move(ref)]() mutable -> void {
ref.resolve(std::error_code{});
});
}
}
};
template <>
class AsyncPromise<void> {
public:
AsyncPromise() = default;
asio::awaitable<void> get() {
if (!this->exc && !this->returned) {
auto executor = co_await asio::this_coro::executor;
co_await asio::async_initiate<decltype(asio::use_awaitable), void(std::error_code)>(
[this, &executor](auto&& new_handler) {
this->resolver_ref.emplace(ResolverRef{.resolve = std::move(new_handler), .executor = &executor});
},
asio::use_awaitable);
}
if (this->exc) {
std::rethrow_exception(this->exc);
} else if (this->returned) {
co_return;
} else {
throw std::logic_error("AsyncPromise await resolved but did not have a value or exception");
}
}
void set_value() {
if (this->done()) {
throw std::logic_error("attempted to set value on completed promise");
}
this->returned = true;
this->resolve();
}
void set_exception(std::exception_ptr ex) {
if (this->done()) {
throw std::logic_error("attempted to set value on completed promise");
}
this->exc = ex;
this->resolve();
}
void cancel() {
this->set_exception(std::make_exception_ptr(std::runtime_error("AsyncPromise cancelled")));
}
bool done() const {
return this->exc || this->returned;
}
private:
struct ResolverRef {
asio::detail::awaitable_handler<asio::any_io_executor, std::error_code> resolve;
asio::any_io_executor* executor;
};
bool returned = false;
std::exception_ptr exc;
std::optional<ResolverRef> resolver_ref;
void resolve() {
if (this->resolver_ref) {
auto* executor = this->resolver_ref->executor;
ResolverRef ref = std::move(*this->resolver_ref);
this->resolver_ref.reset();
asio::post(*executor, [ref = std::move(ref)]() mutable -> void {
ref.resolve(std::error_code{});
});
}
}
};
class AsyncEvent {
public:
AsyncEvent(asio::any_io_executor ex);
AsyncEvent(const AsyncEvent&) = delete;
AsyncEvent(AsyncEvent&&) = delete;
AsyncEvent& operator=(const AsyncEvent&) = delete;
AsyncEvent& operator=(AsyncEvent&&) = delete;
void set();
void clear();
asio::awaitable<void> wait();
private:
asio::any_io_executor executor;
bool is_set;
std::mutex lock;
std::vector<std::unique_ptr<asio::detail::awaitable_handler<asio::any_io_executor>>> waiters;
};
class AsyncSocketReader {
public:
explicit AsyncSocketReader(asio::ip::tcp::socket&& sock);
AsyncSocketReader(const AsyncSocketReader&) = delete;
AsyncSocketReader(AsyncSocketReader&&) = delete;
AsyncSocketReader& operator=(const AsyncSocketReader&) = delete;
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.
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
inline asio::ip::tcp::socket& get_socket() {
return this->sock;
}
inline void close() {
this->sock.close();
}
private:
std::string pending_data; // Data read but not yet returned to the caller
asio::ip::tcp::socket sock;
};
class AsyncWriteCollector {
public:
AsyncWriteCollector() = default;
AsyncWriteCollector(const AsyncWriteCollector&) = delete;
AsyncWriteCollector(AsyncWriteCollector&&) = delete;
AsyncWriteCollector& operator=(const AsyncWriteCollector&) = delete;
AsyncWriteCollector& operator=(AsyncWriteCollector&&) = delete;
~AsyncWriteCollector() = default;
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.
void add_reference(const void* data, size_t size);
asio::awaitable<void> write(asio::ip::tcp::socket& sock);
private:
std::deque<std::string> owned_data;
std::vector<asio::const_buffer> bufs;
};
asio::awaitable<void> async_sleep(std::chrono::steady_clock::duration duration);
inline asio::ip::tcp::endpoint make_endpoint_ipv4(uint32_t addr, uint16_t port) {
return asio::ip::tcp::endpoint(asio::ip::address_v4(addr), port);
}
inline asio::ip::tcp::endpoint make_endpoint_ipv6(const void* addr, uint16_t port) {
std::array<uint8_t, 0x10> bytes;
for (size_t z = 0; z < 0x10; z++) {
bytes[z] = reinterpret_cast<const uint8_t*>(addr)[z];
}
return asio::ip::tcp::endpoint(asio::ip::address_v6(bytes), port);
}
inline std::string str_for_endpoint(const asio::ip::tcp::endpoint& ep) {
return ep.address().to_string() + std::format(":{}", ep.port());
}
inline uint32_t ipv4_addr_for_asio_addr(const asio::ip::address& addr) {
if (!addr.is_v4()) {
throw std::runtime_error("Address is not IPv4");
}
return addr.to_v4().to_uint();
}
asio::awaitable<asio::ip::tcp::socket> async_connect_tcp(uint32_t ipv4_addr, uint16_t port);
asio::awaitable<asio::ip::tcp::socket> async_connect_tcp(const std::string& host, uint16_t port);
asio::awaitable<asio::ip::tcp::socket> async_connect_tcp(const asio::ip::tcp::endpoint& ep);
template <typename FnT, typename... ArgTs>
asio::awaitable<std::invoke_result_t<FnT, ArgTs...>> call_on_thread_pool(asio::thread_pool& pool, FnT&& f, ArgTs&&... args) {
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)
auto promise = std::make_shared<AsyncPromise<ReturnT>>();
asio::post(pool, [bound = std::move(bound), promise]() mutable {
promise->set_value(bound());
});
co_return co_await promise->get();
}
+2 -2
View File
@@ -14,7 +14,7 @@ struct BMLHeaderT {
parray<uint8_t, 0x04> unknown_a1;
U32T<BE> num_entries;
parray<uint8_t, 0x38> unknown_a2;
} __packed__;
} __attribute__((packed));
using BMLHeader = BMLHeaderT<false>;
using BMLHeaderBE = BMLHeaderT<true>;
@@ -30,7 +30,7 @@ struct BMLHeaderEntryT {
U32T<BE> compressed_gvm_size;
U32T<BE> decompressed_gvm_size;
parray<uint8_t, 0x0C> unknown_a2;
} __packed__;
} __attribute__((packed));
using BMLHeaderEntry = BMLHeaderEntryT<false>;
using BMLHeaderEntryBE = BMLHeaderEntryT<true>;
+27 -19
View File
@@ -9,28 +9,36 @@
using namespace std;
void BattleParamsIndex::Table::print(FILE* stream) const {
auto print_entry = +[](FILE* stream, const PlayerStats& e) {
fprintf(stream,
"%5hu %5hu %5hu %5hu %5hu %5hu %5hu %5hu %5" PRIu32 " %5" PRIu32,
e.char_stats.atp.load(),
e.char_stats.mst.load(),
e.char_stats.evp.load(),
e.char_stats.hp.load(),
e.char_stats.dfp.load(),
e.char_stats.ata.load(),
e.char_stats.lck.load(),
e.esp.load(),
e.experience.load(),
e.meseta.load());
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);
};
for (size_t diff = 0; diff < 4; diff++) {
fprintf(stream, "%c ZZ ATP PSV EVP HP DFP ATA LCK ESP EXP DIFF\n",
phosg::fwrite_fmt(stream, "{} ZZ ATP PSV EVP HP DFP ATA LCK ESP EXP DIFF NAMES\n",
abbreviation_for_difficulty(diff));
for (size_t z = 0; z < 0x60; z++) {
fprintf(stream, " %02zX ", z);
print_entry(stream, this->stats[diff][z]);
phosg::fwrite_fmt(stream, " {:02X} ", z);
print_entry(this->stats[diff][z], z);
fputc('\n', stream);
}
}
@@ -54,8 +62,8 @@ BattleParamsIndex::BattleParamsIndex(
for (uint8_t episode = 0; episode < 3; episode++) {
auto& file = this->files[is_solo][episode];
if (file.data->size() < sizeof(Table)) {
throw runtime_error(phosg::string_printf(
"battle params table size is incorrect (expected %zX bytes, have %zX bytes; is_solo=%hhu, episode=%hhu)",
throw runtime_error(std::format(
"battle params table size is incorrect (expected {:X} bytes, have {:X} bytes; is_solo={}, episode={})",
sizeof(Table), file.data->size(), is_solo, episode));
}
file.table = reinterpret_cast<const Table*>(file.data->data());
+2 -2
View File
@@ -76,7 +76,7 @@ public:
/* AE00 */ parray<parray<MovementData, 0x60>, 4> movement_data;
/* F600 */
void print(FILE* stream) const;
void print(FILE* stream, Episode episode) const;
} __packed_ws__(Table, 0xF600);
BattleParamsIndex(
@@ -92,7 +92,7 @@ public:
private:
struct File {
std::shared_ptr<const std::string> data;
const Table* table;
const Table* table = nullptr;
};
// Indexed as [online/offline][episode]
-187
View File
@@ -1,187 +0,0 @@
#include "CatSession.hh"
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <algorithm>
#include <iostream>
#include <phosg/Encoding.hh>
#include <phosg/Filesystem.hh>
#include <phosg/Network.hh>
#include <phosg/Random.hh>
#include <phosg/Strings.hh>
#include <phosg/Time.hh>
#include "Loggers.hh"
#include "PSOProtocol.hh"
#include "ProxyCommands.hh"
#include "ReceiveCommands.hh"
#include "ReceiveSubcommands.hh"
#include "SendCommands.hh"
using namespace std;
CatSession::exit_shell::exit_shell() : runtime_error("shell exited") {}
CatSession::CatSession(
shared_ptr<struct event_base> base,
const struct sockaddr_storage& remote,
Version version,
shared_ptr<const PSOBBEncryption::KeyFile> bb_key_file)
: log(phosg::string_printf("[CatSession:%s] ", phosg::name_for_enum(version)), proxy_server_log.min_level),
base(base),
read_event(event_new(this->base.get(), 0, EV_READ | EV_PERSIST, CatSession::dispatch_read_stdin, this), event_free),
channel(version, 1, CatSession::dispatch_on_channel_input, CatSession::dispatch_on_channel_error, this, "CatSession"),
bb_key_file(bb_key_file) {
if (remote.ss_family != AF_INET) {
throw runtime_error("remote is not AF_INET");
}
string netloc_str = phosg::render_sockaddr_storage(remote);
this->log.info("Connecting to %s", netloc_str.c_str());
struct bufferevent* bev = bufferevent_socket_new(
this->base.get(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
if (!bev) {
throw runtime_error(phosg::string_printf("failed to open socket (%d)", EVUTIL_SOCKET_ERROR()));
}
this->channel.set_bufferevent(bev, 0);
if (bufferevent_socket_connect(this->channel.bev.get(),
reinterpret_cast<const sockaddr*>(&remote), sizeof(struct sockaddr_in)) != 0) {
throw runtime_error(phosg::string_printf("failed to connect (%d)", EVUTIL_SOCKET_ERROR()));
}
event_add(this->read_event.get(), nullptr);
this->poll.add(0, POLLIN);
}
void CatSession::execute_command(const std::string& command) {
string full_cmd = phosg::parse_data_string(command, nullptr, phosg::ParseDataFlags::ALLOW_FILES);
send_command_with_header(this->channel, full_cmd.data(), full_cmd.size());
}
void CatSession::dispatch_on_channel_input(
Channel& ch, uint16_t command, uint32_t flag, std::string& data) {
auto* session = reinterpret_cast<CatSession*>(ch.context_obj);
session->on_channel_input(command, flag, data);
}
void CatSession::on_channel_input(
uint16_t command, uint32_t flag, std::string& data) {
if (!uses_v4_encryption(this->channel.version)) {
if (command == 0x02 || command == 0x17 || command == 0x91 || command == 0x9B) {
const auto& cmd = check_size_t<S_ServerInitDefault_DC_PC_V3_02_17_91_9B>(data, 0xFFFF);
if (uses_v3_encryption(this->channel.version)) {
this->channel.crypt_in = make_shared<PSOV3Encryption>(cmd.server_key);
this->channel.crypt_out = make_shared<PSOV3Encryption>(cmd.client_key);
this->log.info("Enabled V3 encryption (server key %08" PRIX32 ", client key %08" PRIX32 ")",
cmd.server_key.load(), cmd.client_key.load());
} else { // PC, DC, or patch server
this->channel.crypt_in = make_shared<PSOV2Encryption>(cmd.server_key);
this->channel.crypt_out = make_shared<PSOV2Encryption>(cmd.client_key);
this->log.info("Enabled V2 encryption (server key %08" PRIX32 ", client key %08" PRIX32 ")",
cmd.server_key.load(), cmd.client_key.load());
}
}
} else { // BB
if (command == 0x03 || command == 0x9B) {
if (!this->bb_key_file) {
throw runtime_error("BB encryption requires a key file");
}
const auto& cmd = check_size_t<S_ServerInitDefault_BB_03_9B>(data, 0xFFFF);
this->channel.crypt_in = make_shared<PSOBBEncryption>(*this->bb_key_file, &cmd.server_key[0], sizeof(cmd.server_key));
this->channel.crypt_out = make_shared<PSOBBEncryption>(*this->bb_key_file, &cmd.client_key[0], sizeof(cmd.client_key));
this->log.info("Enabled BB encryption");
}
}
// TODO: Use the iovec form of print_data here instead of
// prepend_command_header (which copies the string)
string full_cmd = prepend_command_header(this->channel.version, this->channel.crypt_in.get(), command, flag, data);
phosg::print_data(stdout, full_cmd, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::OFFSET_16_BITS);
}
void CatSession::dispatch_on_channel_error(Channel& ch, short events) {
auto* session = reinterpret_cast<CatSession*>(ch.context_obj);
session->on_channel_error(events);
}
void CatSession::on_channel_error(short events) {
if (events & BEV_EVENT_CONNECTED) {
this->log.info("Channel connected");
}
if (events & BEV_EVENT_ERROR) {
int err = EVUTIL_SOCKET_ERROR();
this->log.warning("Error %d (%s) in unlinked client stream", err,
evutil_socket_error_to_string(err));
}
if (events & (BEV_EVENT_ERROR | BEV_EVENT_EOF)) {
this->log.info("Session endpoint has disconnected");
this->channel.disconnect();
event_base_loopexit(this->base.get(), nullptr);
}
}
void CatSession::dispatch_read_stdin(evutil_socket_t, short, void* ctx) {
reinterpret_cast<CatSession*>(ctx)->read_stdin();
}
void CatSession::read_stdin() {
bool any_command_read = false;
for (;;) {
auto poll_result = this->poll.poll();
short fd_events = 0;
try {
fd_events = poll_result.at(0);
} catch (const out_of_range&) {
}
if (!(fd_events & POLLIN)) {
break;
}
string command(2048, '\0');
if (!fgets(command.data(), command.size(), stdin)) {
if (!any_command_read) {
// ctrl+d probably; we should exit
fputc('\n', stderr);
event_base_loopexit(this->base.get(), nullptr);
return;
} else {
break; // probably not EOF; just no more commands for now
}
}
// trim the extra data off the string
size_t len = strlen(command.c_str());
if (len == 0) {
break;
}
if (command[len - 1] == '\n') {
len--;
}
command.resize(len);
any_command_read = true;
try {
execute_command(command);
} catch (const exit_shell&) {
event_base_loopexit(this->base.get(), nullptr);
return;
} catch (const exception& e) {
fprintf(stderr, "FAILED: %s\n", e.what());
}
}
}
-54
View File
@@ -1,54 +0,0 @@
#pragma once
#include <event2/event.h>
#include <functional>
#include <map>
#include <memory>
#include <phosg/Filesystem.hh>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "PSOEncryption.hh"
#include "PSOProtocol.hh"
#include "ServerState.hh"
class CatSession {
public:
CatSession(
std::shared_ptr<struct event_base> base,
const struct sockaddr_storage& remote,
Version version,
std::shared_ptr<const PSOBBEncryption::KeyFile> bb_key_file);
CatSession(const CatSession&) = delete;
CatSession(CatSession&&) = delete;
CatSession& operator=(const CatSession&) = delete;
CatSession& operator=(CatSession&&) = delete;
virtual ~CatSession() = default;
protected:
phosg::PrefixedLogger log;
std::shared_ptr<struct event_base> base;
std::unique_ptr<struct event, void (*)(struct event*)> read_event;
phosg::Poll poll;
Channel channel;
std::shared_ptr<const PSOBBEncryption::KeyFile> bb_key_file;
class exit_shell : public std::runtime_error {
public:
exit_shell();
~exit_shell() = default;
};
virtual void execute_command(const std::string& command);
static void dispatch_read_stdin(evutil_socket_t fd, short events, void* ctx);
static void dispatch_on_channel_input(Channel& ch, uint16_t command, uint32_t flag, std::string& msg);
static void dispatch_on_channel_error(Channel& ch, short events);
void on_channel_input(uint16_t command, uint32_t flag, std::string& msg);
void on_channel_error(short events);
void read_stdin();
};
+228 -251
View File
@@ -1,9 +1,6 @@
#include "Channel.hh"
#include <errno.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <string.h>
#include <unistd.h>
@@ -17,230 +14,17 @@ using namespace std;
extern bool use_terminal_colors;
static void flush_and_free_bufferevent(struct bufferevent* bev) {
bufferevent_flush(bev, EV_READ | EV_WRITE, BEV_FINISHED);
bufferevent_free(bev);
}
Channel::Channel(
Version version,
uint8_t language,
on_command_received_t on_command_received,
on_error_t on_error,
void* context_obj,
const string& name,
phosg::TerminalFormat terminal_send_color,
phosg::TerminalFormat terminal_recv_color)
: bev(nullptr, flush_and_free_bufferevent),
virtual_network_id(0),
version(version),
: version(version),
language(language),
name(name),
terminal_send_color(terminal_send_color),
terminal_recv_color(terminal_recv_color),
on_command_received(on_command_received),
on_error(on_error),
context_obj(context_obj) {
}
Channel::Channel(
struct bufferevent* bev,
uint64_t virtual_network_id,
Version version,
uint8_t language,
on_command_received_t on_command_received,
on_error_t on_error,
void* context_obj,
const string& name,
phosg::TerminalFormat terminal_send_color,
phosg::TerminalFormat terminal_recv_color)
: bev(nullptr, flush_and_free_bufferevent),
version(version),
language(language),
name(name),
terminal_send_color(terminal_send_color),
terminal_recv_color(terminal_recv_color),
on_command_received(on_command_received),
on_error(on_error),
context_obj(context_obj) {
this->set_bufferevent(bev, virtual_network_id);
}
void Channel::replace_with(
Channel&& other,
on_command_received_t on_command_received,
on_error_t on_error,
void* context_obj,
const std::string& name) {
this->set_bufferevent(other.bev.release(), other.virtual_network_id);
this->local_addr = other.local_addr;
this->remote_addr = other.remote_addr;
this->version = other.version;
this->language = other.language;
this->crypt_in = other.crypt_in;
this->crypt_out = other.crypt_out;
this->name = name;
this->terminal_send_color = other.terminal_send_color;
this->terminal_recv_color = other.terminal_recv_color;
this->on_command_received = on_command_received;
this->on_error = on_error;
this->context_obj = context_obj;
other.disconnect(); // Clears crypts, addrs, etc.
}
void Channel::set_bufferevent(struct bufferevent* bev, uint64_t virtual_network_id) {
this->bev.reset(bev);
this->virtual_network_id = virtual_network_id;
if (this->bev.get()) {
int fd = bufferevent_getfd(this->bev.get());
if (fd < 0) {
memset(&this->local_addr, 0, sizeof(this->local_addr));
memset(&this->remote_addr, 0, sizeof(this->remote_addr));
} else {
phosg::get_socket_addresses(fd, &this->local_addr, &this->remote_addr);
}
bufferevent_setcb(this->bev.get(), &Channel::dispatch_on_input, nullptr, &Channel::dispatch_on_error, this);
bufferevent_enable(this->bev.get(), EV_READ | EV_WRITE);
} else {
memset(&this->local_addr, 0, sizeof(this->local_addr));
memset(&this->remote_addr, 0, sizeof(this->remote_addr));
}
}
void Channel::disconnect() {
if (this->bev.get()) {
// If the output buffer is not empty, move the bufferevent into the draining
// pool instead of disconnecting it, to make sure all the data gets sent.
struct evbuffer* out_buffer = bufferevent_get_output(this->bev.get());
if (evbuffer_get_length(out_buffer) == 0) {
this->bev.reset(); // Destructor flushes and frees the bufferevent
} else {
// The callbacks will free it when all the data is sent or the client
// disconnects
auto on_output = +[](struct bufferevent* bev, void*) -> void {
flush_and_free_bufferevent(bev);
};
auto on_error = +[](struct bufferevent* bev, short events, void*) -> void {
if (events & BEV_EVENT_ERROR) {
int err = EVUTIL_SOCKET_ERROR();
channel_exceptions_log.warning(
"Disconnecting channel caused error %d (%s)", err,
evutil_socket_error_to_string(err));
}
if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
bufferevent_flush(bev, EV_WRITE, BEV_FINISHED);
bufferevent_free(bev);
}
};
struct bufferevent* bev = this->bev.release();
bufferevent_setcb(bev, nullptr, on_output, on_error, bev);
bufferevent_disable(bev, EV_READ);
}
}
memset(&this->local_addr, 0, sizeof(this->local_addr));
memset(&this->remote_addr, 0, sizeof(this->remote_addr));
this->virtual_network_id = false;
this->crypt_in.reset();
this->crypt_out.reset();
}
Channel::Message Channel::recv() {
struct evbuffer* buf = bufferevent_get_input(this->bev.get());
size_t header_size = (this->version == Version::BB_V4) ? 8 : 4;
PSOCommandHeader header;
if (evbuffer_copyout(buf, &header, header_size) < static_cast<ssize_t>(header_size)) {
throw out_of_range("no command available");
}
if (this->crypt_in.get()) {
this->crypt_in->decrypt(&header, header_size, false);
}
size_t command_logical_size = header.size(version);
// 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;
if (evbuffer_get_length(buf) < command_physical_size) {
throw out_of_range("no command available");
}
// If we get here, then there is a full command in the buffer. Some encryption
// algorithms' advancement depends on the decrypted data, so we have to
// actually decrypt the header again (with advance=true) to keep them in a
// consistent state.
string header_data(header_size, '\0');
if (evbuffer_remove(buf, header_data.data(), header_data.size()) < static_cast<ssize_t>(header_data.size())) {
throw logic_error("enough bytes available, but could not remove them");
}
if (this->crypt_in.get()) {
this->crypt_in->decrypt(header_data.data(), header_data.size());
}
string command_data(command_physical_size - header_size, '\0');
if (evbuffer_remove(buf, command_data.data(), command_data.size()) < static_cast<ssize_t>(command_data.size())) {
throw logic_error("enough bytes available, but could not remove them");
}
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.
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());
command_data.resize(orig_size);
}
command_data.resize(command_logical_size - header_size);
if (command_data_log.should_log(phosg::LogLevel::INFO) && (this->terminal_recv_color != phosg::TerminalFormat::END)) {
if (use_terminal_colors && this->terminal_recv_color != phosg::TerminalFormat::NORMAL) {
print_color_escape(stderr, this->terminal_recv_color, phosg::TerminalFormat::BOLD, phosg::TerminalFormat::END);
}
if (version == Version::BB_V4) {
command_data_log.info(
"Received from %s (version=BB command=%04hX flag=%08" PRIX32 ")",
this->name.c_str(),
header.command(this->version),
header.flag(this->version));
} else {
command_data_log.info(
"Received from %s (version=%s command=%02hX flag=%02" PRIX32 ")",
this->name.c_str(),
phosg::name_for_enum(this->version),
header.command(this->version),
header.flag(this->version));
}
vector<struct iovec> iovs;
iovs.emplace_back(iovec{.iov_base = header_data.data(), .iov_len = header_data.size()});
iovs.emplace_back(iovec{.iov_base = command_data.data(), .iov_len = command_data.size()});
phosg::print_data(stderr, iovs, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
if (use_terminal_colors && this->terminal_recv_color != phosg::TerminalFormat::NORMAL) {
phosg::print_color_escape(stderr, phosg::TerminalFormat::NORMAL, phosg::TerminalFormat::END);
}
}
return {
.command = header.command(this->version),
.flag = header.flag(this->version),
.data = std::move(command_data),
};
terminal_recv_color(terminal_recv_color) {
}
void Channel::send(uint16_t cmd, uint32_t flag, bool silent) {
@@ -249,7 +33,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, 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("Attempted to send command on closed channel; dropping data");
channel_exceptions_log.warning_f("Attempted to send command on closed channel; dropping data");
return;
}
@@ -263,7 +47,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
size_t send_data_size = 0;
switch (this->version) {
case Version::DC_NTE:
case Version::DC_V1_11_2000_PROTOTYPE:
case Version::DC_11_2000:
case Version::DC_V1:
case Version::DC_V2:
case Version::GC_NTE:
@@ -274,7 +58,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
PSOCommandHeaderDCV3 header;
if (this->crypt_out.get() &&
(this->version != Version::DC_NTE) &&
(this->version != Version::DC_V1_11_2000_PROTOTYPE) &&
(this->version != Version::DC_11_2000) &&
(this->version != Version::DC_V1)) {
send_data_size = (sizeof(header) + size + 3) & ~3;
} else {
@@ -342,16 +126,16 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
}
send_data.resize(send_data_size, '\0');
if (!silent && (command_data_log.should_log(phosg::LogLevel::INFO)) && (this->terminal_send_color != phosg::TerminalFormat::END)) {
if (!silent && (command_data_log.should_log(phosg::LogLevel::L_INFO)) && (this->terminal_send_color != phosg::TerminalFormat::END)) {
if (use_terminal_colors && this->terminal_send_color != phosg::TerminalFormat::NORMAL) {
print_color_escape(stderr, phosg::TerminalFormat::FG_YELLOW, phosg::TerminalFormat::BOLD, phosg::TerminalFormat::END);
}
if (version == Version::BB_V4) {
command_data_log.info("Sending to %s (version=BB command=%04hX flag=%08" PRIX32 ")",
this->name.c_str(), cmd, flag);
command_data_log.info_f("Sending to {} (version=BB command={:04X} flag={:08X})",
this->name, cmd, flag);
} else {
command_data_log.info("Sending to %s (version=%s command=%02hX flag=%02" PRIX32 ")",
this->name.c_str(), phosg::name_for_enum(version), cmd, flag);
command_data_log.info_f("Sending to {} (version={} command={:02X} flag={:02X})",
this->name, phosg::name_for_enum(version), cmd, flag);
}
phosg::print_data(stderr, send_data.data(), logical_size, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
if (use_terminal_colors && this->terminal_send_color != phosg::TerminalFormat::NORMAL) {
@@ -363,8 +147,7 @@ void Channel::send(uint16_t cmd, uint32_t flag, const std::vector<std::pair<cons
this->crypt_out->encrypt(send_data.data(), send_data.size());
}
struct evbuffer* buf = bufferevent_get_output(this->bev.get());
evbuffer_add(buf, send_data.data(), send_data.size());
this->send_raw(std::move(send_data));
}
void Channel::send(uint16_t cmd, uint32_t flag, const void* data, size_t size, bool silent) {
@@ -387,35 +170,229 @@ void Channel::send(const void* data, size_t size, bool silent) {
}
void Channel::send(const string& data, bool silent) {
return this->send(data.data(), data.size(), silent);
this->send(data.data(), data.size(), silent);
}
void Channel::dispatch_on_input(struct bufferevent*, void* ctx) {
Channel* ch = reinterpret_cast<Channel*>(ctx);
// The client can be disconnected during on_command_received, so we have to
// make sure ch->bev is valid every time before calling recv()
while (ch->bev.get()) {
Message msg;
try {
msg = ch->recv();
} catch (const out_of_range&) {
break;
} catch (const exception& e) {
channel_exceptions_log.warning("Error receiving on channel: %s", e.what());
ch->on_error(*ch, BEV_EVENT_ERROR);
break;
asio::awaitable<Channel::Message> Channel::recv() {
size_t header_size = (this->version == Version::BB_V4) ? 8 : 4;
PSOCommandHeader header;
co_await this->recv_raw(&header, header_size);
if (this->crypt_in.get()) {
this->crypt_in->decrypt(&header, header_size);
}
size_t command_logical_size = header.size(version);
if (command_logical_size < header_size) {
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.
size_t command_physical_size = (this->crypt_in.get() && (version == Version::BB_V4))
? ((command_logical_size + 7) & ~7)
: command_logical_size;
string command_data(command_physical_size - header_size, '\0');
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.
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());
command_data.resize(orig_size);
}
command_data.resize(command_logical_size - header_size);
if (command_data_log.should_log(phosg::LogLevel::L_INFO) && (this->terminal_recv_color != phosg::TerminalFormat::END)) {
if (use_terminal_colors && this->terminal_recv_color != phosg::TerminalFormat::NORMAL) {
print_color_escape(stderr, this->terminal_recv_color, phosg::TerminalFormat::BOLD, phosg::TerminalFormat::END);
}
if (ch->on_command_received) {
ch->on_command_received(*ch, msg.command, msg.flag, msg.data);
if (version == Version::BB_V4) {
command_data_log.info_f(
"Received from {} (version=BB command={:04X} flag={:08X})",
this->name,
header.command(this->version),
header.flag(this->version));
} else {
command_data_log.info_f(
"Received from {} (version={} command={:02X} flag={:02X})",
this->name,
phosg::name_for_enum(this->version),
header.command(this->version),
header.flag(this->version));
}
vector<struct iovec> iovs;
iovs.emplace_back(iovec{.iov_base = &header, .iov_len = header_size});
iovs.emplace_back(iovec{.iov_base = command_data.data(), .iov_len = command_data.size()});
phosg::print_data(stderr, iovs, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
if (use_terminal_colors && this->terminal_recv_color != phosg::TerminalFormat::NORMAL) {
phosg::print_color_escape(stderr, phosg::TerminalFormat::NORMAL, phosg::TerminalFormat::END);
}
}
co_return Message{
.command = header.command(this->version),
.flag = header.flag(this->version),
.data = std::move(command_data),
};
}
shared_ptr<SocketChannel> SocketChannel::create(
std::shared_ptr<asio::io_context> io_context,
std::unique_ptr<asio::ip::tcp::socket>&& sock,
Version version,
uint8_t language,
const string& name,
phosg::TerminalFormat terminal_send_color,
phosg::TerminalFormat terminal_recv_color) {
shared_ptr<SocketChannel> ret(new SocketChannel(
io_context, std::move(sock), version, language, name, terminal_send_color, terminal_recv_color));
asio::co_spawn(*io_context, ret->send_task(), asio::detached);
return ret;
}
SocketChannel::SocketChannel(
std::shared_ptr<asio::io_context> io_context,
std::unique_ptr<asio::ip::tcp::socket>&& sock,
Version version,
uint8_t language,
const string& name,
phosg::TerminalFormat terminal_send_color,
phosg::TerminalFormat terminal_recv_color)
: Channel(version, language, name, terminal_send_color, terminal_recv_color),
sock(std::move(sock)),
local_addr(this->sock->local_endpoint()),
remote_addr(this->sock->remote_endpoint()),
send_buffer_nonempty_signal(io_context->get_executor()) {}
std::string SocketChannel::default_name() const {
return "ip:" + str_for_endpoint(this->remote_addr);
}
bool SocketChannel::connected() const {
return !this->should_disconnect && this->sock && this->sock->is_open();
}
void SocketChannel::disconnect() {
this->should_disconnect = true;
this->send_buffer_nonempty_signal.set();
}
void SocketChannel::send_raw(string&& data) {
if (this->sock && !this->should_disconnect) {
this->outbound_data.emplace_back(std::move(data));
this->send_buffer_nonempty_signal.set();
}
}
asio::awaitable<void> SocketChannel::recv_raw(void* data, size_t size) {
if (!this->sock || this->should_disconnect) {
throw runtime_error("Cannot receive on closed channel");
}
co_await asio::async_read(*this->sock, asio::buffer(data, size), asio::use_awaitable);
}
asio::awaitable<void> SocketChannel::send_task() {
// Ensure *this doesn't get deleted while the socket is open
auto this_sh = this->shared_from_this();
while (this->sock->is_open()) {
deque<string> to_send;
to_send.swap(this->outbound_data);
if (!to_send.empty()) {
vector<asio::const_buffer> bufs;
bufs.reserve(to_send.size());
for (const auto& it : to_send) {
bufs.emplace_back(asio::buffer(it.data(), it.size()));
}
co_await asio::async_write(*this->sock, bufs, asio::use_awaitable);
}
if (this->outbound_data.empty()) {
if (this->should_disconnect) {
this->sock->close();
} else {
this->send_buffer_nonempty_signal.clear();
co_await this->send_buffer_nonempty_signal.wait();
}
}
}
}
void Channel::dispatch_on_error(struct bufferevent*, short events, void* ctx) {
Channel* ch = reinterpret_cast<Channel*>(ctx);
if (ch->on_error) {
ch->on_error(*ch, events);
} else {
ch->disconnect();
PeerChannel::PeerChannel(
std::shared_ptr<asio::io_context> io_context,
Version version,
uint8_t language,
const std::string& name,
phosg::TerminalFormat terminal_send_color,
phosg::TerminalFormat terminal_recv_color)
: Channel(version, language, name, terminal_send_color, terminal_recv_color),
send_buffer_nonempty_signal(io_context->get_executor()) {}
void PeerChannel::link_peers(std::shared_ptr<PeerChannel> peer1, std::shared_ptr<PeerChannel> peer2) {
if (peer1->connected() || peer2->connected()) {
throw logic_error("Cannot link already-connected peer channels");
}
peer1->peer = peer2;
peer2->peer = peer1;
}
std::string PeerChannel::default_name() const {
return std::format("peer:{}->{}", reinterpret_cast<const void*>(this), reinterpret_cast<const void*>(this->peer.lock().get()));
}
bool PeerChannel::connected() const {
return (!this->inbound_data.empty()) || (this->peer.lock() != nullptr);
}
void PeerChannel::disconnect() {
auto peer = this->peer.lock();
if (peer) {
peer->peer.reset();
peer->send_buffer_nonempty_signal.set();
}
this->peer.reset();
this->send_buffer_nonempty_signal.set();
}
void PeerChannel::send_raw(string&& data) {
auto peer = this->peer.lock();
if (peer) {
peer->inbound_data.emplace_back(std::move(data));
peer->send_buffer_nonempty_signal.set();
}
}
asio::awaitable<void> PeerChannel::recv_raw(void* data, size_t size) {
while (size > 0) {
while (this->inbound_data.empty() && this->peer.lock()) {
this->send_buffer_nonempty_signal.clear();
co_await this->send_buffer_nonempty_signal.wait();
}
if (!this->inbound_data.empty()) {
auto& front_block = this->inbound_data.front();
if (size < front_block.size()) {
memcpy(data, front_block.data(), size);
front_block = front_block.substr(size);
size = 0;
} else {
memcpy(data, front_block.data(), front_block.size());
size -= front_block.size();
data = reinterpret_cast<uint8_t*>(data) + front_block.size();
this->inbound_data.pop_front();
}
} else if (!this->peer.lock()) {
throw runtime_error("Channel peer has disconnected");
}
}
}
+134 -58
View File
@@ -1,20 +1,16 @@
#pragma once
#include <netinet/in.h>
#include <asio.hpp>
#include <memory>
#include <string>
#include "AsyncUtils.hh"
#include "PSOEncryption.hh"
#include "PSOProtocol.hh"
#include "Version.hh"
struct Channel {
std::unique_ptr<struct bufferevent, void (*)(struct bufferevent*)> bev;
struct sockaddr_storage local_addr;
struct sockaddr_storage remote_addr;
uint64_t virtual_network_id; // 0 = normal TCP connection
class Channel {
public:
Version version;
uint8_t language;
std::shared_ptr<PSOEncryption> crypt_in;
@@ -28,58 +24,46 @@ struct Channel {
uint16_t command;
uint32_t flag;
std::string data;
template <typename T>
const T& check_size_t(size_t min_size, size_t max_size) const {
return ::check_size_t<const T>(this->data.data(), this->data.size(), min_size, max_size);
}
template <typename T>
T& check_size_t(size_t min_size, size_t max_size) {
return ::check_size_t<T>(this->data.data(), this->data.size(), min_size, max_size);
}
template <typename T>
const T& check_size_t(size_t max_size) const {
return ::check_size_t<const T>(this->data.data(), this->data.size(), sizeof(T), max_size);
}
template <typename T>
T& check_size_t(size_t max_size) {
return ::check_size_t<T>(this->data.data(), this->data.size(), sizeof(T), max_size);
}
template <typename T>
const T& check_size_t() const {
return ::check_size_t<const T>(this->data.data(), this->data.size(), sizeof(T), sizeof(T));
}
template <typename T>
T& check_size_t() {
return ::check_size_t<T>(this->data.data(), this->data.size(), sizeof(T), sizeof(T));
}
};
typedef void (*on_command_received_t)(Channel&, uint16_t, uint32_t, std::string&);
typedef void (*on_error_t)(Channel&, short);
virtual ~Channel() = default;
on_command_received_t on_command_received;
on_error_t on_error;
void* context_obj;
virtual std::string default_name() const = 0;
// Creates an unconnected channel
Channel(
Version version,
uint8_t language,
on_command_received_t on_command_received,
on_error_t on_error,
void* context_obj,
const std::string& name,
phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END,
phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END);
// Creates a connected channel
Channel(
struct bufferevent* bev,
uint64_t virtual_network_id,
Version version,
uint8_t language,
on_command_received_t on_command_received,
on_error_t on_error,
void* context_obj,
const std::string& name = "",
phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END,
phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END);
Channel(const Channel& other) = delete;
Channel(Channel&& other) = delete;
Channel& operator=(const Channel& other) = delete;
Channel& operator=(Channel&& other) = delete;
// Returns whether the channel is connected or not.
virtual bool connected() const = 0;
void replace_with(
Channel&& other,
on_command_received_t on_command_received,
on_error_t on_error,
void* context_obj,
const std::string& name = "");
void set_bufferevent(struct bufferevent* bev, uint64_t virtual_network_id);
inline bool connected() const {
return this->bev.get() != nullptr;
}
void disconnect();
// Receives a message. Throws std::out_of_range if no messages are available.
Message recv();
// 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.
void send(uint16_t cmd, uint32_t flag = 0, bool silent = false);
@@ -97,7 +81,99 @@ struct Channel {
void send(const void* data, size_t size, bool silent = false);
void send(const std::string& data, bool silent = false);
private:
static void dispatch_on_input(struct bufferevent*, void* ctx);
static void dispatch_on_error(struct bufferevent*, short events, void* ctx);
// Receives a message. Throws std::out_of_range if no messages are available.
asio::awaitable<Message> recv();
protected:
Channel(
Version version,
uint8_t language,
const std::string& name,
phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END,
phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END);
Channel(const Channel& other) = delete;
Channel(Channel&& other) = delete;
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.
virtual void send_raw(std::string&& data) = 0;
// 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.
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
static std::shared_ptr<SocketChannel> create(std::shared_ptr<asio::io_context> io_context,
std::unique_ptr<asio::ip::tcp::socket>&& sock,
Version version,
uint8_t language,
const std::string& name = "",
phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END,
phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END);
virtual std::string default_name() const;
virtual bool connected() const;
virtual void disconnect();
virtual void send_raw(std::string&& data);
virtual asio::awaitable<void> recv_raw(void* data, size_t size);
private:
SocketChannel(
std::shared_ptr<asio::io_context> io_context,
std::unique_ptr<asio::ip::tcp::socket>&& sock,
Version version,
uint8_t language,
const std::string& name,
phosg::TerminalFormat terminal_send_color,
phosg::TerminalFormat terminal_recv_color);
std::deque<std::string> outbound_data;
bool should_disconnect = false;
AsyncEvent send_buffer_nonempty_signal;
asio::awaitable<void> send_task();
};
// In-process peer channel, used for replay testing.
class PeerChannel : public Channel {
public:
std::weak_ptr<PeerChannel> peer;
PeerChannel(
std::shared_ptr<asio::io_context> io_context,
Version version,
uint8_t language,
const std::string& name = "",
phosg::TerminalFormat terminal_send_color = phosg::TerminalFormat::END,
phosg::TerminalFormat terminal_recv_color = phosg::TerminalFormat::END);
static void link_peers(std::shared_ptr<PeerChannel> peer1, std::shared_ptr<PeerChannel> peer2);
virtual std::string default_name() const;
virtual bool connected() const;
virtual void disconnect();
virtual void send_raw(std::string&& data);
virtual asio::awaitable<void> recv_raw(void* data, size_t size);
private:
AsyncEvent send_buffer_nonempty_signal;
std::deque<std::string> inbound_data;
};
+2857 -2548
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -2,13 +2,13 @@
#include <stdint.h>
#include <asio.hpp>
#include <memory>
#include <string>
#include "Client.hh"
#include "Lobby.hh"
#include "ProxyServer.hh"
#include "ProxySession.hh"
#include "ServerState.hh"
void on_chat_command(std::shared_ptr<Client> c, const std::string& text);
void on_chat_command(std::shared_ptr<ProxyServer::LinkedSession> ses, const std::string& text);
asio::awaitable<void> on_chat_command(std::shared_ptr<Client> c, const std::string& text, bool check_permissions);
+8 -8
View File
@@ -28,10 +28,10 @@ const vector<ChoiceSearchCategory> CHOICE_SEARCH_CATEGORIES({
if (choice_id == 0x0000) {
return true;
}
uint32_t target_level = target_c->character()->disp.stats.level + 1;
uint32_t target_level = target_c->character_file()->disp.stats.level + 1;
switch (choice_id) {
case 0x0001:
return (labs(static_cast<int32_t>(target_level - searcher_c->character()->disp.stats.level)) <= 5);
return (labs(static_cast<int32_t>(target_level - searcher_c->character_file()->disp.stats.level)) <= 5);
case 0x0002:
return (target_level <= 10);
case 0x0003:
@@ -80,13 +80,13 @@ const vector<ChoiceSearchCategory> CHOICE_SEARCH_CATEGORIES({
case 0x0000:
return true;
case 0x0010:
return target_c->character()->disp.visual.class_flags & 0x20;
return target_c->character_file()->disp.visual.class_flags & 0x20;
case 0x0011:
return target_c->character()->disp.visual.class_flags & 0x40;
return target_c->character_file()->disp.visual.class_flags & 0x40;
case 0x0012:
return target_c->character()->disp.visual.class_flags & 0x80;
return target_c->character_file()->disp.visual.class_flags & 0x80;
default:
return ((choice_id - 1) == target_c->character()->disp.visual.char_class);
return ((choice_id - 1) == target_c->character_file()->disp.visual.char_class);
}
},
},
@@ -108,7 +108,7 @@ const vector<ChoiceSearchCategory> CHOICE_SEARCH_CATEGORIES({
}
switch (target_c->version()) {
case Version::DC_NTE:
case Version::DC_V1_11_2000_PROTOTYPE:
case Version::DC_11_2000:
return (choice_id == 0x0001);
case Version::DC_V1:
return (choice_id == 0x0002);
@@ -143,7 +143,7 @@ const vector<ChoiceSearchCategory> CHOICE_SEARCH_CATEGORIES({
{0x0006, "Challenge"},
},
.client_matches = +[](shared_ptr<Client>, shared_ptr<Client> target_c, uint16_t choice_id) -> bool {
uint16_t target_choice_id = target_c->character()->choice_search_config.get_setting(0x0204);
uint16_t target_choice_id = target_c->character_file()->choice_search_config.get_setting(0x0204);
return (choice_id == 0) || (target_choice_id == 0) || (choice_id == target_choice_id);
},
},
+4 -4
View File
@@ -31,16 +31,16 @@ struct ChoiceSearchConfigT {
operator ChoiceSearchConfigT<!BE>() const {
ChoiceSearchConfigT<!BE> ret;
ret.disabled = this->disabled.load();
ret.disabled = this->disabled;
for (size_t z = 0; z < this->entries.size(); z++) {
auto& ret_e = ret.entries[z];
const auto& this_e = this->entries[z];
ret_e.parent_choice_id = this_e.parent_choice_id.load();
ret_e.choice_id = this_e.choice_id.load();
ret_e.parent_choice_id = this_e.parent_choice_id;
ret_e.choice_id = this_e.choice_id;
}
return ret;
}
} __packed__;
} __attribute__((packed));
using ChoiceSearchConfig = ChoiceSearchConfigT<false>;
using ChoiceSearchConfigBE = ChoiceSearchConfigT<true>;
+501 -487
View File
File diff suppressed because it is too large Load Diff
+162 -216
View File
@@ -1,11 +1,10 @@
#pragma once
#include <netinet/in.h>
#include <memory>
#include <stdexcept>
#include "Account.hh"
#include "AsyncUtils.hh"
#include "Channel.hh"
#include "CommandFormats.hh"
#include "Episode3/BattleRecord.hh"
@@ -15,6 +14,7 @@
#include "PSOEncryption.hh"
#include "PSOProtocol.hh"
#include "PatchFileIndex.hh"
#include "ProxySession.hh"
#include "Quest.hh"
#include "QuestScript.hh"
#include "TeamIndex.hh"
@@ -22,21 +22,22 @@
extern const uint64_t CLIENT_CONFIG_MAGIC;
class Server;
class GameServer;
struct Lobby;
class Parsed6x70Data;
struct GetPlayerInfoResult {
// Exactly one of the following two shared_ptrs is not null
std::shared_ptr<PSOBBCharacterFile> character;
std::shared_ptr<PSOGCEp3CharacterFile::Character> ep3_character;
bool is_full_info; // True if the client sent 30; false if it was 61 or 98
};
class Client : public std::enable_shared_from_this<Client> {
public:
enum class Flag : uint64_t {
// clang-format off
// This mask specifies which flags are sent to the client
// TODO: It'd be nice to use a pattern here (e.g. all server-side flags are
// in the high bits) but that would require re-recording or manually
// rewriting all the tests
CLIENT_SIDE_MASK = 0xE73CFFFF7C0BFFFB,
// Version-related flags
CHECKED_FOR_DC_V1_PROTOTYPE = 0x0000000000000002,
NO_D6_AFTER_LOBBY = 0x0000000000000100,
@@ -46,34 +47,32 @@ public:
// Flags describing the behavior for send_function_call
HAS_SEND_FUNCTION_CALL = 0x0000000000001000,
ENCRYPTED_SEND_FUNCTION_CALL = 0x0000000000002000,
SEND_FUNCTION_CALL_CHECKSUM_ONLY = 0x0000000000004000,
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, // Server-side only
AWAITING_ENABLE_B2_QUEST = 0x0000000000040000,
// State flags
LOADING = 0x0000000000100000, // Server-side only
LOADING_QUEST = 0x0000000000200000, // Server-side only
LOADING_RUNNING_JOINABLE_QUEST = 0x0000000000400000, // Server-side only
LOADING_TOURNAMENT = 0x0000000000800000, // Server-side only
IN_INFORMATION_MENU = 0x0000000001000000, // Server-side only
AT_WELCOME_MESSAGE = 0x0000000002000000, // Server-side only
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,
USE_OVERRIDE_RANDOM_SEED = 0x0000000020000000,
HAS_GUILD_CARD_NUMBER = 0x0000000040000000,
HAS_AUTO_PATCHES = 0x0000004000000000,
AT_BANK_COUNTER = 0x0000000080000000, // Server-side only
SHOULD_SEND_ARTIFICIAL_ITEM_STATE = 0x0001000000000000, // Server-side only
SHOULD_SEND_ARTIFICIAL_ENEMY_AND_SET_STATE = 0x0040000000000000, // Server-side only
SHOULD_SEND_ARTIFICIAL_OBJECT_STATE = 0x0080000000000000, // Server-side only
SHOULD_SEND_ARTIFICIAL_FLAG_STATE = 0x0002000000000000, // Server-side only
SHOULD_SEND_ARTIFICIAL_PLAYER_STATES = 0x0200000000000000, // Server-side only
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, // Server-side only
EP3_ALLOW_6xBC = 0x1000000000000000,
// Cheat mode and option flags
INFINITE_HP_ENABLED = 0x0000000200000000,
@@ -81,22 +80,16 @@ public:
DEBUG_ENABLED = 0x0000000800000000,
ITEM_DROP_NOTIFICATIONS_1 = 0x0010000000000000,
ITEM_DROP_NOTIFICATIONS_2 = 0x0020000000000000,
FORCE_BATTLE_MODE_GAME = 0x0800000000000000, // Server-side only
HAS_ENEMY_DAMAGE_SYNC_PATCH = 0x2000000000000000, // Must be same as in EnemyDamageSync*.s
// Proxy option flags
PROXY_SAVE_FILES = 0x0000001000000000,
PROXY_CHAT_COMMANDS_ENABLED = 0x0000002000000000,
PROXY_PLAYER_NOTIFICATIONS_ENABLED = 0x0000008000000000,
PROXY_SUPPRESS_CLIENT_PINGS = 0x0000010000000000,
PROXY_SUPPRESS_REMOTE_LOGIN = 0x0000020000000000,
PROXY_ZERO_REMOTE_GUILD_CARD = 0x0000040000000000,
PROXY_EP3_INFINITE_MESETA_ENABLED = 0x0000080000000000,
PROXY_EP3_INFINITE_TIME_ENABLED = 0x0000100000000000,
PROXY_RED_NAME_ENABLED = 0x0000200000000000,
PROXY_BLANK_NAME_ENABLED = 0x0000400000000000,
PROXY_BLOCK_FUNCTION_CALLS = 0x0000800000000000,
PROXY_EP3_UNMASK_WHISPERS = 0x0008000000000000,
PROXY_VIRTUAL_CLIENT = 0x0400000000000000,
// clang-format on
};
enum class ItemDropNotificationMode {
@@ -108,124 +101,71 @@ public:
static constexpr uint64_t DEFAULT_FLAGS = static_cast<uint64_t>(Flag::PROXY_CHAT_COMMANDS_ENABLED);
struct Config {
uint64_t enabled_flags = DEFAULT_FLAGS; // Client::Flag enum
uint32_t specific_version = 0;
int32_t override_random_seed = 0;
uint8_t override_section_id = 0xFF; // FF = no override
uint8_t override_lobby_event = 0xFF; // FF = no override
uint8_t override_lobby_number = 0x80; // 80 = no override
uint32_t proxy_destination_address = 0;
uint16_t proxy_destination_port = 0;
Config() = default;
bool operator==(const Config& other) const = default;
bool operator!=(const Config& other) const = default;
bool should_update_vs(const Config& other) const;
[[nodiscard]] static inline bool check_flag(uint64_t enabled_flags, Flag flag) {
return !!(enabled_flags & static_cast<uint64_t>(flag));
}
[[nodiscard]] inline bool check_flag(Flag flag) const {
return this->check_flag(this->enabled_flags, flag);
}
inline void set_flag(Flag flag) {
this->enabled_flags |= static_cast<uint64_t>(flag);
}
inline void clear_flag(Flag flag) {
this->enabled_flags &= (~static_cast<uint64_t>(flag));
}
inline void toggle_flag(Flag flag) {
this->enabled_flags ^= static_cast<uint64_t>(flag);
}
void set_flags_for_version(Version version, int64_t sub_version);
ItemDropNotificationMode get_drop_notification_mode() const;
void set_drop_notification_mode(ItemDropNotificationMode new_mode);
template <size_t Bytes>
void parse_from(const parray<uint8_t, Bytes>& data) {
phosg::StringReader r(data.data(), data.size());
if (r.get_u32l() != CLIENT_CONFIG_MAGIC) {
throw std::invalid_argument("config signature is incorrect");
}
this->specific_version = r.get_u32l();
this->enabled_flags = r.get_u64l();
this->override_random_seed = r.get_u32l();
this->proxy_destination_address = r.get_u32b();
this->proxy_destination_port = r.get_u16l();
this->override_section_id = r.get_u8();
this->override_lobby_event = r.get_u8();
this->override_lobby_number = r.get_u8();
}
template <size_t Bytes>
void serialize_into(parray<uint8_t, Bytes>& data) const {
phosg::StringWriter w;
w.put_u32l(CLIENT_CONFIG_MAGIC);
w.put_u32l(this->specific_version);
w.put_u64l(this->enabled_flags & static_cast<uint64_t>(Flag::CLIENT_SIDE_MASK));
w.put_u32l(this->override_random_seed);
w.put_u32b(this->proxy_destination_address);
w.put_u16l(this->proxy_destination_port);
w.put_u8(this->override_section_id);
w.put_u8(this->override_lobby_event);
w.put_u8(this->override_lobby_number);
const auto& s = w.str();
for (size_t z = 0; z < s.size(); z++) {
data[z] = s[z];
}
data.clear_after(s.size(), 0xFF);
}
};
std::weak_ptr<Server> server;
std::weak_ptr<GameServer> server;
uint64_t id;
phosg::PrefixedLogger log;
// Account information (not all of these are used; depends on game version)
std::string username;
std::string password;
std::string email_address;
uint64_t hardware_id = 0;
int32_t sub_version = 0;
uint8_t bb_client_code = 0;
uint8_t bb_connection_phase = 0xFF;
ssize_t bb_character_index = -1; // -1 = not set
ssize_t bb_bank_character_index = -1; // -1 = shared bank
uint32_t bb_security_token = 0;
parray<uint8_t, 0x28> bb_client_config;
std::string login_character_name;
std::string serial_number;
std::string access_key;
std::string serial_number2;
std::string access_key2;
std::string v1_serial_number;
std::string v1_access_key;
XBNetworkLocation xb_netloc;
parray<le_uint32_t, 3> xb_unknown_a1a;
uint64_t xb_user_id = 0;
uint32_t xb_unknown_a1b = 0;
std::shared_ptr<Login> login;
std::shared_ptr<ProxySession> proxy_session;
// Patch server state (only used for PC_PATCH and BB_PATCH versions)
std::vector<PatchFileChecksumRequest> patch_file_checksum_requests;
// Network
Channel channel;
struct sockaddr_storage next_connection_addr;
std::shared_ptr<Channel> channel;
std::shared_ptr<PSOBBMultiKeyDetectorEncryption> bb_detector_crypt;
ServerBehavior server_behavior;
bool should_disconnect;
bool should_send_to_lobby_server;
bool should_send_to_proxy_server;
std::unordered_map<std::string, std::function<void()>> disconnect_hooks;
std::shared_ptr<XBNetworkLocation> xb_netloc;
parray<le_uint32_t, 3> xb_9E_unknown_a1a;
uint8_t bb_connection_phase;
uint64_t ping_start_time;
uint64_t ping_start_time = 0;
// Lobby/positioning
Config config;
Config synced_config;
std::unique_ptr<parray<le_uint32_t, 0x20>> override_variations;
int32_t sub_version;
float x;
float z;
uint32_t floor;
// Basic state
uint64_t enabled_flags = DEFAULT_FLAGS; // Client::Flag enum
uint32_t specific_version = 0;
uint8_t override_section_id = 0xFF; // FF = no override
uint8_t override_lobby_event = 0xFF; // FF = no override
uint8_t override_lobby_number = 0x80; // 80 = no override
int64_t override_random_seed = -1;
std::unique_ptr<Variations> override_variations;
VectorXZF pos;
uint32_t floor = 0x0F;
std::weak_ptr<Lobby> lobby;
uint8_t lobby_client_id;
uint8_t lobby_arrow_color;
int64_t preferred_lobby_id; // <0 = no preference
uint8_t lobby_client_id = 0;
uint8_t lobby_arrow_color = 0;
int64_t preferred_lobby_id = -1; // <0 = no preference
std::unique_ptr<struct event, void (*)(struct event*)> save_game_data_event;
std::unique_ptr<struct event, void (*)(struct event*)> send_ping_event;
std::unique_ptr<struct event, void (*)(struct event*)> idle_timeout_event;
int16_t card_battle_table_number;
uint16_t card_battle_table_seat_number;
uint16_t card_battle_table_seat_state;
asio::steady_timer save_game_data_timer;
asio::steady_timer send_ping_timer;
asio::steady_timer idle_timeout_timer;
int16_t card_battle_table_number = -1;
uint16_t card_battle_table_seat_number = 0;
uint16_t card_battle_table_seat_state = 0;
std::weak_ptr<Episode3::Tournament::Team> ep3_tournament_team;
std::shared_ptr<const Episode3::BattleRecord> ep3_prev_battle_record;
std::shared_ptr<const Menu> last_menu_sent;
uint32_t last_game_info_requested;
uint32_t last_game_info_requested = 0;
struct JoinCommand {
uint16_t command;
uint32_t flag;
@@ -248,52 +188,72 @@ 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;
G_SetTelepipeState_6x68 telepipe_state;
uint32_t telepipe_lobby_id = 0;
TelepipeState telepipe_state;
std::shared_ptr<Episode3::PlayerConfig> ep3_config; // Null for non-Ep3
int8_t bb_character_index;
ItemData bb_identify_result;
std::array<std::vector<ItemData>, 3> bb_shop_contents;
// Miscellaneous (used by chat commands)
uint32_t next_exp_value; // next EXP value to give
bool can_chat;
struct PendingCharacterExport {
std::shared_ptr<const Account> dest_account;
ssize_t character_index = -1;
std::shared_ptr<const BBLicense> dest_bb_license; // Only used for $bbchar; null for $savechar
};
std::unique_ptr<PendingCharacterExport> pending_character_export;
std::deque<std::function<void(uint32_t, uint32_t)>> function_call_response_queue;
uint32_t next_exp_value = 0; // next EXP value to give
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.
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;
// File loading state
uint32_t dol_base_addr;
std::shared_ptr<DOLFileIndex::File> loading_dol_file;
std::unordered_map<std::string, std::shared_ptr<const std::string>> sending_files;
Client(
std::shared_ptr<Server> server,
struct bufferevent* bev,
uint64_t virtual_network_id,
Version version,
std::shared_ptr<GameServer> server,
std::shared_ptr<Channel> channel,
ServerBehavior server_behavior);
~Client();
void update_channel_name();
void reschedule_save_game_data_event();
void reschedule_ping_and_timeout_events();
void reschedule_save_game_data_timer();
void reschedule_ping_and_timeout_timers();
inline Version version() const {
return this->channel.version;
return this->channel->version;
}
inline uint8_t language() const {
return this->channel.language;
return this->channel->language;
}
[[nodiscard]] static inline bool check_flag(uint64_t enabled_flags, Flag flag) {
return !!(enabled_flags & static_cast<uint64_t>(flag));
}
[[nodiscard]] inline bool check_flag(Flag flag) const {
return this->check_flag(this->enabled_flags, flag);
}
inline void set_flag(Flag flag) {
this->enabled_flags |= static_cast<uint64_t>(flag);
}
inline void clear_flag(Flag flag) {
this->enabled_flags &= (~static_cast<uint64_t>(flag));
}
inline void toggle_flag(Flag flag) {
this->enabled_flags ^= static_cast<uint64_t>(flag);
}
void set_flags_for_version(Version version, int64_t sub_version);
ItemDropNotificationMode get_drop_notification_mode() const;
void set_drop_notification_mode(ItemDropNotificationMode new_mode);
void convert_account_to_temporary_if_nte();
void sync_config();
@@ -327,18 +287,38 @@ public:
bool can_use_chat_commands() const;
static void dispatch_save_game_data(evutil_socket_t, short, void* ctx);
void save_game_data();
static void dispatch_send_ping(evutil_socket_t, short, void* ctx);
void send_ping();
static void dispatch_idle_timeout(evutil_socket_t, short, void* ctx);
void idle_timeout();
void set_login(std::shared_ptr<Login> login);
void suspend_timeouts();
void import_blocked_senders(const parray<le_uint32_t, 30>& blocked_senders);
const std::string& get_bb_username() const;
void set_bb_username(const std::string& bb_username);
static std::string system_filename(const std::string& bb_username);
std::string system_filename() const;
std::shared_ptr<PSOBBBaseSystemFile> system_file(bool allow_load = true);
std::shared_ptr<const PSOBBBaseSystemFile> system_file(bool throw_if_missing = true) const;
void save_system_file() const;
static std::string guild_card_filename(const std::string& bb_username);
std::string guild_card_filename() const;
std::shared_ptr<PSOBBGuildCardFile> guild_card_file(bool allow_load = true);
std::shared_ptr<const PSOBBGuildCardFile> guild_card_file(bool allow_load = true) const;
void save_guild_card_file() const;
static std::string character_filename(const std::string& bb_username, ssize_t index);
static std::string backup_character_filename(uint32_t account_id, size_t index, bool is_ep3);
std::string character_filename() const;
std::shared_ptr<PSOBBCharacterFile> character_file(bool allow_load = true, bool allow_overlay = true);
std::shared_ptr<const PSOBBCharacterFile> character_file(bool throw_if_missing = true, bool allow_overlay = true) const;
static void save_character_file(
const std::string& filename,
std::shared_ptr<const PSOBBBaseSystemFile> sys,
std::shared_ptr<const PSOBBCharacterFile> character);
static void save_ep3_character_file(const std::string& filename, const PSOGCEp3CharacterFile::Character& character);
void save_character_file();
void create_character_file(
uint32_t guild_card_number,
uint8_t language,
const PlayerDispDataBBPreview& preview,
std::shared_ptr<const LevelTable> level_table);
void create_battle_overlay(std::shared_ptr<const BattleRules> rules, std::shared_ptr<const LevelTable> level_table);
void create_challenge_overlay(Version version, size_t template_index, std::shared_ptr<const LevelTable> level_table);
inline void delete_overlay() {
@@ -348,57 +328,27 @@ public:
return this->overlay_character_data.get() != nullptr;
}
void import_blocked_senders(const parray<le_uint32_t, 30>& blocked_senders);
static std::string bank_filename(const std::string& bb_username, ssize_t index);
std::string bank_filename() const;
std::shared_ptr<PlayerBank> bank_file(bool allow_load = true);
std::shared_ptr<const PlayerBank> bank_file(bool throw_if_missing = true) const;
static void save_bank_file(const std::string& filename, const PlayerBank& bank);
void save_bank_file() const;
void change_bank(ssize_t bb_character_index); // -1 = use shared bank
std::shared_ptr<PSOBBBaseSystemFile> system_file(bool allow_load = true);
std::shared_ptr<PSOBBCharacterFile> character(bool allow_load = true, bool allow_overlay = true);
std::shared_ptr<PSOBBGuildCardFile> guild_card_file(bool allow_load = true);
std::shared_ptr<const PSOBBBaseSystemFile> system_file(bool allow_load = true) const;
std::shared_ptr<const PSOBBCharacterFile> character(bool allow_load = true, bool allow_overlay = true) const;
std::shared_ptr<const PSOBBGuildCardFile> guild_card_file(bool allow_load = true) const;
void create_character_file(
uint32_t guild_card_number,
uint8_t language,
const PlayerDispDataBBPreview& preview,
std::shared_ptr<const LevelTable> level_table);
std::string system_filename() const;
static std::string character_filename(const std::string& bb_username, int8_t index);
static std::string backup_character_filename(uint32_t account_id, size_t index, bool is_ep3);
std::string character_filename(int8_t index = -1) const;
std::string guild_card_filename() const;
std::string shared_bank_filename() const;
std::string legacy_player_filename() const;
std::string legacy_account_filename() const;
std::string legacy_player_filename() const;
void save_all();
void save_system_file() const;
static void save_character_file(
const std::string& filename,
std::shared_ptr<const PSOBBBaseSystemFile> sys,
std::shared_ptr<const PSOBBCharacterFile> character);
static void save_ep3_character_file(
const std::string& filename,
const PSOGCEp3CharacterFile::Character& character);
// Note: This function is not const because it updates the player's play time.
void save_character_file();
void save_guild_card_file() const;
void load_backup_character(uint32_t account_id, size_t index);
std::shared_ptr<PSOGCEp3CharacterFile::Character> load_ep3_backup_character(uint32_t account_id, size_t index);
void save_and_unload_character();
PlayerBank200& current_bank();
const PlayerBank200& current_bank() const;
std::shared_ptr<PSOBBCharacterFile> current_bank_character();
bool use_shared_bank(); // Returns true if the bank exists; false if it was created
void use_character_bank(int8_t bb_character_index);
void use_default_bank();
void print_inventory() const;
void print_bank() const;
void print_inventory(FILE* stream) const;
void print_bank(FILE* stream) const;
void cancel_pending_promises();
private:
// The overlay character data is used in battle and challenge modes, when
@@ -408,12 +358,8 @@ private:
std::shared_ptr<PSOBBCharacterFile> overlay_character_data;
std::shared_ptr<PSOBBCharacterFile> character_data;
std::shared_ptr<PSOBBGuildCardFile> guild_card_data;
std::shared_ptr<PlayerBank200> external_bank;
std::shared_ptr<PSOBBCharacterFile> external_bank_character;
int8_t external_bank_character_index;
uint64_t last_play_time_update;
void save_and_clear_external_bank();
std::shared_ptr<PlayerBank> bank_data;
uint64_t last_play_time_update = 0;
void load_all_files();
void update_character_data_after_load(std::shared_ptr<PSOBBCharacterFile> character_data);
+984 -822
View File
File diff suppressed because it is too large Load Diff
+170
View File
@@ -0,0 +1,170 @@
#pragma once
#include <phosg/Encoding.hh>
#include <phosg/Vector.hh>
#include "Text.hh"
constexpr double radians_for_fixed_point_angle(uint16_t angle) {
return static_cast<double>(angle * 2 * M_PI) / 0x10000;
}
struct VectorXZF {
le_float x = 0.0;
le_float z = 0.0;
inline VectorXZF operator-() const {
return VectorXZF{-this->x, -this->z};
}
inline VectorXZF operator+(const VectorXZF& other) const {
return VectorXZF{this->x + other.x, this->z + other.z};
}
inline VectorXZF operator-(const VectorXZF& other) const {
return VectorXZF{this->x - other.x, this->z - other.z};
}
inline bool operator==(const VectorXZF& other) const {
return ((this->x == other.x) && (this->z == other.z));
}
inline bool operator!=(const VectorXZF& other) const {
return !this->operator==(other);
}
inline double norm() const {
return sqrt(this->norm2());
}
inline double norm2() const {
return ((this->x * this->x) + (this->z * this->z));
}
inline VectorXZF rotate_y(double angle) const {
double s = sin(angle);
double c = cos(angle);
return VectorXZF{this->x * c - this->z * s, this->x * s + this->z * c};
}
inline std::string str() const {
return std::format("[VectorXZF x={:g} z={:g}]", this->x, this->z);
}
} __packed_ws__(VectorXZF, 0x08);
struct VectorXYZF {
le_float x = 0.0;
le_float y = 0.0;
le_float z = 0.0;
inline operator VectorXZF() const {
return VectorXZF{this->x, this->z};
}
inline VectorXYZF operator-() const {
return VectorXYZF{-this->x, -this->y, -this->z};
}
inline VectorXYZF operator+(const VectorXYZF& other) const {
return VectorXYZF{this->x + other.x, this->y + other.y, this->z + other.z};
}
inline VectorXYZF operator-(const VectorXYZF& other) const {
return VectorXYZF{this->x - other.x, this->y - other.y, this->z - other.z};
}
inline bool operator==(const VectorXYZF& other) const {
return ((this->x == other.x) && (this->y == other.y) && (this->z == other.z));
}
inline bool operator!=(const VectorXYZF& other) const {
return !this->operator==(other);
}
inline double norm() const {
return sqrt(this->norm2());
}
inline double norm2() const {
return ((this->x * this->x) + (this->y * this->y) + (this->z * this->z));
}
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};
}
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};
}
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};
}
inline std::string str() const {
return std::format("[VectorXYZF x={:g} y={:g} z={:g}]", this->x, this->y, this->z);
}
} __packed_ws__(VectorXYZF, 0x0C);
struct VectorXYZTF {
le_float x = 0.0;
le_float y = 0.0;
le_float z = 0.0;
le_float t = 0.0;
} __packed_ws__(VectorXYZTF, 0x10);
struct VectorXYZI {
le_uint32_t x = 0;
le_uint32_t y = 0;
le_uint32_t z = 0;
} __packed_ws__(VectorXYZI, 0x0C);
template <bool BE>
struct ArrayRefT {
static constexpr bool IsBE = BE;
/* 00 */ U32T<BE> count;
/* 04 */ U32T<BE> offset;
/* 08 */
} __attribute__((packed));
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):
// 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).
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));
using RELFileFooter = RELFileFooterT<false>;
using RELFileFooterBE = RELFileFooterT<true>;
check_struct_size(RELFileFooter, 0x20);
check_struct_size(RELFileFooterBE, 0x20);
+279 -104
View File
@@ -48,11 +48,7 @@ void from_json_into(const phosg::JSON& json, parray<CommonItemSet::Table::Range<
template <typename IntT>
phosg::JSON to_json(const CommonItemSet::Table::Range<IntT>& v) {
if (v.min == v.max) {
return phosg::JSON(v.min);
} else {
return phosg::JSON::list({v.min, v.max});
}
return (v.min == v.max) ? phosg::JSON(v.min) : phosg::JSON::list({v.min, v.max});
}
template <typename IntT>
@@ -128,8 +124,15 @@ CommonItemSet::Table::Table(const phosg::JSON& json, Episode episode)
for (size_t z = 0; z < 0x64; z++) {
static const array<Episode, 3> episodes = {Episode::EP1, Episode::EP2, Episode::EP4};
for (Episode episode : episodes) {
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));
}
for (auto type : enemy_types_for_rare_table_index(episode, z)) {
string name = phosg::string_printf("%s:%s", abbreviation_for_episode(episode), phosg::name_for_enum(type));
names.emplace_back(std::format("{}:{}", abbreviation_for_episode(episode), phosg::name_for_enum(type)));
}
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();
@@ -163,8 +166,8 @@ void CommonItemSet::Table::print(FILE* stream) const {
const auto& meseta_ranges = this->enemy_meseta_ranges;
const auto& drop_probs = this->enemy_type_drop_probs;
const auto& item_classes = this->enemy_item_classes;
fprintf(stream, "Enemy tables:\n");
fprintf(stream, " ## $LOW $HIGH DAR%% ITEM ENEMIES\n");
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)) {
@@ -174,11 +177,11 @@ void CommonItemSet::Table::print(FILE* stream) const {
enemies_str += phosg::name_for_enum(enemy_type);
}
if (drop_probs[z]) {
fprintf(stream, " %02zX %5hu %5hu %3hhu%% %02hX:%s %s\n",
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.c_str());
name_for_common_item_class(item_classes[z]), enemies_str);
} else {
fprintf(stream, " %02zX ----- ----- 0%% -- %s\n", z, enemies_str.c_str());
phosg::fwrite_fmt(stream, " {:02X} ----- ----- 0% -- {}\n", z, enemies_str);
}
}
@@ -196,8 +199,8 @@ void CommonItemSet::Table::print(FILE* stream) const {
"ROD ",
"WAND ",
};
fprintf(stream, "Base weapon config:\n");
fprintf(stream, " TYPE PROB [SB AL] FLOORS\n");
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++) {
uint8_t floor_to_class[10];
if (this->subtype_base_table[z] < 0) {
@@ -213,17 +216,17 @@ void CommonItemSet::Table::print(FILE* stream) const {
floor_to_class[x] = this->subtype_base_table[z] + (x / this->subtype_area_length_table[z]);
}
}
fprintf(stream, " %02zX:%s %3hhu%% [%02hhX %02hhX] %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX\n",
phosg::fwrite_fmt(stream, " {:02X}:{} {: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],
floor_to_class[5], floor_to_class[6], floor_to_class[7], floor_to_class[8], floor_to_class[9]);
}
fprintf(stream, "Box configuration:\n");
fprintf(stream, " AR $LOW $HIGH WEP%% ARM%% SHD%% UNI%% TL%% MST%% NO%%\n");
phosg::fwrite_fmt(stream, "Box configuration:\n");
phosg::fwrite_fmt(stream, " AR $LOW $HIGH WEP% ARM% SHD% UNI% TL% MST% NO%\n");
for (size_t z = 0; z < 10; z++) {
fprintf(stream, " %02zX %5hu %5hu %3hhu%% %3hhu%% %3hhu%% %3hhu%% %3hhu%% %3hhu%% %3hhu%%\n",
phosg::fwrite_fmt(stream, " {:02X} {:5} {:5} {:3}% {:3}% {:3}% {:3}% {:3}% {:3}% {:3}%\n",
z, this->box_meseta_ranges[z].min, this->box_meseta_ranges[z].max,
this->box_item_class_prob_table[0][z],
this->box_item_class_prob_table[1][z],
@@ -234,43 +237,43 @@ void CommonItemSet::Table::print(FILE* stream) const {
this->box_item_class_prob_table[6][z]);
}
fprintf(stream, "Weapon drops:\n");
fprintf(stream, " Grinds:\n");
fprintf(stream, " GD AR0%% AR1%% AR2%% AR3%%\n");
phosg::fwrite_fmt(stream, "Weapon drops:\n");
phosg::fwrite_fmt(stream, " Grinds:\n");
phosg::fwrite_fmt(stream, " GD AR0% AR1% AR2% AR3%\n");
for (size_t z = 0; z < 9; z++) {
fprintf(stream, " +%zu %3hhd%% %3hhd%% %3hhd%% %3hhd%%\n", z,
phosg::fwrite_fmt(stream, " +{} {:3}% {:3}% {:3}% {:3}%\n", z,
this->grind_prob_table[z][0], this->grind_prob_table[z][1],
this->grind_prob_table[z][2], this->grind_prob_table[z][3]);
}
fprintf(stream, " Bonus value table:\n");
fprintf(stream, " ID");
phosg::fwrite_fmt(stream, " Bonus value table:\n");
phosg::fwrite_fmt(stream, " ID");
for (int8_t v = -10; v <= 100; v += 5) {
fprintf(stream, " %5hhd%%", v);
phosg::fwrite_fmt(stream, " {:5}%", v);
}
fputc('\n', stream);
for (size_t z = 0; z < (this->has_rare_bonus_value_prob_table ? 6 : 5); z++) {
fprintf(stream, " %02zX", z);
phosg::fwrite_fmt(stream, " {:02X}", z);
for (size_t x = 0; x < 0x17; x++) {
fprintf(stream, " %5hu#", this->bonus_value_prob_table[x][z]);
phosg::fwrite_fmt(stream, " {:5}#", this->bonus_value_prob_table[x][z]);
}
fputc('\n', stream);
}
fprintf(stream, " Area config tables:\n");
fprintf(stream, " AR BONUS SP NO%% NTV%% AB%% MAC%% DRK%% HIT%% SM SPC%%\n");
phosg::fwrite_fmt(stream, " Area config tables:\n");
phosg::fwrite_fmt(stream, " AR BONUS SP NO% NTV% AB% MAC% DRK% HIT% SM SPC%\n");
for (size_t z = 0; z < 10; z++) {
fprintf(stream, " %02zX %02hhX %02hhX %02hhX %3hhu%% %3hhu%% %3hhu%% %3hhu%% %3hhu%% %3hhu%% %02hhX %3hhu%%\n",
phosg::fwrite_fmt(stream, " {:02X} {:02X} {:02X} {:02X} {:3}% {:3}% {:3}% {:3}% {:3}% {:3}% {:02X} {:3}%\n",
z, this->nonrare_bonus_prob_spec[0][z], this->nonrare_bonus_prob_spec[1][z], this->nonrare_bonus_prob_spec[2][z],
this->bonus_type_prob_table[0][z], this->bonus_type_prob_table[1][z], this->bonus_type_prob_table[2][z],
this->bonus_type_prob_table[3][z], this->bonus_type_prob_table[4][z], this->bonus_type_prob_table[5][z],
this->special_mult[z], this->special_percent[z]);
}
fprintf(stream, " Tool class table:\n");
fprintf(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++) {
fprintf(stream, " %02zX", tool_class);
phosg::fwrite_fmt(stream, " {:02X}", tool_class);
for (size_t area_norm = 0; area_norm < 10; area_norm++) {
fprintf(stream, " %5hu", this->tool_class_prob_table[tool_class][area_norm]);
phosg::fwrite_fmt(stream, " {:5}", this->tool_class_prob_table[tool_class][area_norm]);
}
fputc('\n', stream);
}
@@ -297,42 +300,158 @@ void CommonItemSet::Table::print(FILE* stream) const {
"MEGID ",
};
fprintf(stream, " Technique table:\n");
fprintf(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++) {
fprintf(stream, " %02zX:%s", 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) {
const auto& level_range = this->technique_level_ranges[tech_num][area_norm];
size_t min_level = level_range.min + 1;
size_t max_level = level_range.max + 1;
fprintf(stream, " %5hu[%2zu-%2zu]", prob, min_level, max_level);
phosg::fwrite_fmt(stream, " {:5}[{:2}-{:2}]", prob, min_level, max_level);
} else {
fprintf(stream, " 0[-----]");
phosg::fwrite_fmt(stream, " 0[-----]");
}
}
fputc('\n', stream);
}
fprintf(stream, " Armor/shield type bias: %hhu\n", this->armor_or_shield_type_bias);
phosg::fwrite_fmt(stream, " Armor/shield type bias: {}\n", this->armor_or_shield_type_bias);
fprintf(stream, " Armor/shield type index table:\n");
fprintf(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++) {
fprintf(stream, " %02zX %3hhu%%\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]);
}
fprintf(stream, " Armor/shield slot count table:\n");
fprintf(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++) {
fprintf(stream, " %02zX %3hhu%%\n", z, this->armor_slot_count_prob_table[z]);
phosg::fwrite_fmt(stream, " {:02X} {:3}%\n", z, this->armor_slot_count_prob_table[z]);
}
fprintf(stream, " Unit maximum stars table:\n");
fprintf(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++) {
fprintf(stream, " %02zX %3hhu\n", z, this->unit_max_stars_table[z]);
phosg::fwrite_fmt(stream, " {:02X} {:3}\n", z, this->unit_max_stars_table[z]);
}
}
void CommonItemSet::Table::print_diff(FILE* stream, const Table& other) const {
if (this->episode != other.episode) {
phosg::fwrite_fmt(stream, "> Episode: {} -> {}\n", name_for_episode(this->episode), name_for_episode(other.episode));
}
if (this->base_weapon_type_prob_table != other.base_weapon_type_prob_table) {
phosg::fwrite_fmt(stream, "> base_weapon_type_prob_table: {} -> {}\n",
phosg::format_data_string(&this->base_weapon_type_prob_table, sizeof(this->base_weapon_type_prob_table)),
phosg::format_data_string(&other.base_weapon_type_prob_table, sizeof(other.base_weapon_type_prob_table)));
}
if (this->subtype_base_table != other.subtype_base_table) {
phosg::fwrite_fmt(stream, "> subtype_base_table: {} -> {}\n",
phosg::format_data_string(&this->subtype_base_table, sizeof(this->subtype_base_table)),
phosg::format_data_string(&other.subtype_base_table, sizeof(other.subtype_base_table)));
}
if (this->subtype_area_length_table != other.subtype_area_length_table) {
phosg::fwrite_fmt(stream, "> subtype_area_length_table: {} -> {}\n",
phosg::format_data_string(&this->subtype_area_length_table, sizeof(this->subtype_area_length_table)),
phosg::format_data_string(&other.subtype_area_length_table, sizeof(other.subtype_area_length_table)));
}
if (this->grind_prob_table != other.grind_prob_table) {
phosg::fwrite_fmt(stream, "> grind_prob_table: {} -> {}\n",
phosg::format_data_string(&this->grind_prob_table, sizeof(this->grind_prob_table)),
phosg::format_data_string(&other.grind_prob_table, sizeof(other.grind_prob_table)));
}
if (this->armor_shield_type_index_prob_table != other.armor_shield_type_index_prob_table) {
phosg::fwrite_fmt(stream, "> armor_shield_type_index_prob_table: {} -> {}\n",
phosg::format_data_string(&this->armor_shield_type_index_prob_table, sizeof(this->armor_shield_type_index_prob_table)),
phosg::format_data_string(&other.armor_shield_type_index_prob_table, sizeof(other.armor_shield_type_index_prob_table)));
}
if (this->armor_slot_count_prob_table != other.armor_slot_count_prob_table) {
phosg::fwrite_fmt(stream, "> armor_slot_count_prob_table: {} -> {}\n",
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)));
}
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)));
}
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->box_meseta_ranges != other.box_meseta_ranges) {
phosg::fwrite_fmt(stream, "> box_meseta_ranges: {} -> {}\n",
phosg::format_data_string(&this->box_meseta_ranges, sizeof(this->box_meseta_ranges)),
phosg::format_data_string(&other.box_meseta_ranges, sizeof(other.box_meseta_ranges)));
}
if (this->has_rare_bonus_value_prob_table != other.has_rare_bonus_value_prob_table) {
phosg::fwrite_fmt(stream, "> Has rare bonus value prob table: {} -> {}\n",
this->has_rare_bonus_value_prob_table ? "true" : "false",
other.has_rare_bonus_value_prob_table ? "true" : "false");
}
if (this->bonus_value_prob_table != other.bonus_value_prob_table) {
phosg::fwrite_fmt(stream, "> bonus_value_prob_table: {} -> {}\n",
phosg::format_data_string(&this->bonus_value_prob_table, sizeof(this->bonus_value_prob_table)),
phosg::format_data_string(&other.bonus_value_prob_table, sizeof(other.bonus_value_prob_table)));
}
if (this->nonrare_bonus_prob_spec != other.nonrare_bonus_prob_spec) {
phosg::fwrite_fmt(stream, "> nonrare_bonus_prob_spec: {} -> {}\n",
phosg::format_data_string(&this->nonrare_bonus_prob_spec, sizeof(this->nonrare_bonus_prob_spec)),
phosg::format_data_string(&other.nonrare_bonus_prob_spec, sizeof(other.nonrare_bonus_prob_spec)));
}
if (this->bonus_type_prob_table != other.bonus_type_prob_table) {
phosg::fwrite_fmt(stream, "> bonus_type_prob_table: {} -> {}\n",
phosg::format_data_string(&this->bonus_type_prob_table, sizeof(this->bonus_type_prob_table)),
phosg::format_data_string(&other.bonus_type_prob_table, sizeof(other.bonus_type_prob_table)));
}
if (this->special_mult != other.special_mult) {
phosg::fwrite_fmt(stream, "> special_mult: {} -> {}\n",
phosg::format_data_string(&this->special_mult, sizeof(this->special_mult)),
phosg::format_data_string(&other.special_mult, sizeof(other.special_mult)));
}
if (this->special_percent != other.special_percent) {
phosg::fwrite_fmt(stream, "> special_percent: {} -> {}\n",
phosg::format_data_string(&this->special_percent, sizeof(this->special_percent)),
phosg::format_data_string(&other.special_percent, sizeof(other.special_percent)));
}
if (this->tool_class_prob_table != other.tool_class_prob_table) {
phosg::fwrite_fmt(stream, "> tool_class_prob_table: {} -> {}\n",
phosg::format_data_string(&this->tool_class_prob_table, sizeof(this->tool_class_prob_table)),
phosg::format_data_string(&other.tool_class_prob_table, sizeof(other.tool_class_prob_table)));
}
if (this->technique_index_prob_table != other.technique_index_prob_table) {
phosg::fwrite_fmt(stream, "> technique_index_prob_table: {} -> {}\n",
phosg::format_data_string(&this->technique_index_prob_table, sizeof(this->technique_index_prob_table)),
phosg::format_data_string(&other.technique_index_prob_table, sizeof(other.technique_index_prob_table)));
}
if (this->technique_level_ranges != other.technique_level_ranges) {
phosg::fwrite_fmt(stream, "> technique_level_ranges: {} -> {}\n",
phosg::format_data_string(&this->technique_level_ranges, sizeof(this->technique_level_ranges)),
phosg::format_data_string(&other.technique_level_ranges, sizeof(other.technique_level_ranges)));
}
if (this->armor_or_shield_type_bias != other.armor_or_shield_type_bias) {
phosg::fwrite_fmt(stream, "> Armor/shield type bias: {} -> {}\n",
this->armor_or_shield_type_bias ? "true" : "false",
other.armor_or_shield_type_bias ? "true" : "false");
}
if (this->unit_max_stars_table != other.unit_max_stars_table) {
phosg::fwrite_fmt(stream, "> unit_max_stars_table: {} -> {}\n",
phosg::format_data_string(&this->unit_max_stars_table, sizeof(this->unit_max_stars_table)),
phosg::format_data_string(&other.unit_max_stars_table, sizeof(other.unit_max_stars_table)));
}
if (this->box_item_class_prob_table != other.box_item_class_prob_table) {
phosg::fwrite_fmt(stream, "> box_item_class_prob_table: {} -> {}\n",
phosg::format_data_string(&this->box_item_class_prob_table, sizeof(this->box_item_class_prob_table)),
phosg::format_data_string(&other.box_item_class_prob_table, sizeof(other.box_item_class_prob_table)));
}
}
@@ -343,8 +462,16 @@ phosg::JSON CommonItemSet::Table::json() const {
for (size_t z = 0; z < 0x64; z++) {
static const array<Episode, 3> episodes = {Episode::EP1, Episode::EP2, Episode::EP4};
for (Episode episode : episodes) {
for (auto type : enemy_types_for_rare_table_index(episode, z)) {
string name = phosg::string_printf("%s:%s", abbreviation_for_episode(episode), phosg::name_for_enum(type));
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)));
}
}
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]);
@@ -413,7 +540,7 @@ void CommonItemSet::print(FILE* stream) const {
for (uint8_t section_id = 0; section_id < 10; section_id++) {
try {
auto table = this->get_table(episode, mode, difficulty, section_id);
fprintf(stream, "============ %s %s %s %s\n",
phosg::fwrite_fmt(stream, "============ {} {} {} {}\n",
name_for_mode(mode), name_for_episode(episode), name_for_difficulty(difficulty), name_for_section_id(section_id));
table->print(stream);
} catch (const runtime_error&) {
@@ -424,6 +551,43 @@ void CommonItemSet::print(FILE* stream) const {
}
}
void CommonItemSet::print_diff(FILE* stream, const CommonItemSet& other) const {
static const array<GameMode, 4> modes = {GameMode::NORMAL, GameMode::BATTLE, GameMode::CHALLENGE, GameMode::SOLO};
for (const auto& mode : modes) {
static const array<Episode, 3> episodes = {Episode::EP1, Episode::EP2, Episode::EP4};
for (const auto& episode : episodes) {
for (uint8_t difficulty = 0; difficulty < 4; difficulty++) {
for (uint8_t section_id = 0; section_id < 10; section_id++) {
shared_ptr<const Table> this_table;
shared_ptr<const Table> other_table;
try {
this_table = this->get_table(episode, mode, difficulty, section_id);
} catch (const runtime_error&) {
}
try {
other_table = other.get_table(episode, mode, difficulty, section_id);
} catch (const runtime_error&) {
}
if (!this_table && !other_table) {
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));
} 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));
} 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));
this_table->print_diff(stream, *other_table);
}
}
}
}
}
}
CommonItemSet::Table::Table(const phosg::StringReader& r, bool is_big_endian, bool is_v3, Episode episode)
: episode(episode) {
if (is_big_endian) {
@@ -503,35 +667,55 @@ shared_ptr<const CommonItemSet::Table> CommonItemSet::get_table(
try {
return this->tables.at(this->key_for_table(episode, mode, difficulty, secid));
} catch (const out_of_range&) {
throw runtime_error(phosg::string_printf("common item table not available for episode=%s, mode=%s, difficulty=%hu, secid=%hu",
throw runtime_error(std::format("common item table not available for episode={}, mode={}, difficulty={}, secid={}",
name_for_episode(episode), name_for_mode(mode), difficulty, secid));
}
}
AFSV2CommonItemSet::AFSV2CommonItemSet(
std::shared_ptr<const std::string> pt_afs_data,
std::shared_ptr<const std::string> ct_afs_data) {
// ItemPT.afs has 40 entries; the first 10 are for Normal, then Hard, etc.
AFSArchive pt_afs(pt_afs_data);
for (size_t difficulty = 0; difficulty < 4; difficulty++) {
for (size_t section_id = 0; section_id < 10; section_id++) {
auto entry = pt_afs.get(difficulty * 10 + section_id);
phosg::StringReader r(entry.first, entry.second);
auto table = make_shared<Table>(r, false, false, Episode::EP1);
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::NORMAL, difficulty, section_id), table);
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::BATTLE, difficulty, section_id), table);
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::SOLO, difficulty, section_id), table);
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.
{
AFSArchive pt_afs(pt_afs_data);
size_t max_difficulty;
if (pt_afs.num_entries() >= 40) {
max_difficulty = 4;
} else if (pt_afs.num_entries() >= 30) {
max_difficulty = 3;
} else {
throw std::runtime_error(std::format("PT AFS file has unexpected entry count ({})", pt_afs.num_entries()));
}
for (size_t difficulty = 0; difficulty < max_difficulty; difficulty++) {
for (size_t section_id = 0; section_id < 10; section_id++) {
auto entry = pt_afs.get(difficulty * 10 + section_id);
phosg::StringReader r(entry.first, entry.second);
auto table = make_shared<Table>(r, false, false, Episode::EP1);
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::NORMAL, difficulty, section_id), table);
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::BATTLE, difficulty, section_id), table);
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::SOLO, difficulty, section_id), table);
}
}
}
// ItemCT.afs also has 40 entries, but only the 0th, 10th, 20th, and 30th are
// used (section_id is ignored)
AFSArchive ct_afs(ct_afs_data);
for (size_t difficulty = 0; difficulty < 4; difficulty++) {
auto r = ct_afs.get_reader(difficulty * 10);
auto table = make_shared<Table>(r, false, false, Episode::EP1);
for (size_t section_id = 0; section_id < 10; section_id++) {
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::CHALLENGE, difficulty, section_id), table);
// 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);
size_t max_difficulty;
if (ct_afs.num_entries() >= 40) {
max_difficulty = 4;
} else if (ct_afs.num_entries() >= 30) {
max_difficulty = 3;
} else {
throw std::runtime_error(std::format("CT AFS file has unexpected entry count ({})", ct_afs.num_entries()));
}
for (size_t difficulty = 0; difficulty < max_difficulty; difficulty++) {
auto r = ct_afs.get_reader(difficulty * 10);
auto table = make_shared<Table>(r, false, false, Episode::EP1);
for (size_t section_id = 0; section_id < 10; section_id++) {
this->tables.emplace(this->key_for_table(Episode::EP1, GameMode::CHALLENGE, difficulty, section_id), table);
}
}
}
}
@@ -554,11 +738,11 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr<const std::string> gs
default:
throw runtime_error("invalid episode");
}
return phosg::string_printf(
"ItemPT%s%s%c%1hhu.rel",
return std::format(
"ItemPT{}{}{}{}.rel",
is_challenge ? "c" : "",
episode_token,
tolower(abbreviation_for_difficulty(difficulty)),
static_cast<char>(tolower(abbreviation_for_difficulty(difficulty))),
section_id);
};
@@ -590,10 +774,14 @@ GSLV3V4CommonItemSet::GSLV3V4CommonItemSet(std::shared_ptr<const std::string> gs
if (episode != Episode::EP4) {
for (size_t difficulty = 0; difficulty < 4; difficulty++) {
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);
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
}
}
}
@@ -628,8 +816,7 @@ JSONCommonItemSet::JSONCommonItemSet(const phosg::JSON& json) {
}
RELFileSet::RELFileSet(std::shared_ptr<const std::string> data)
: data(data),
r(*this->data) {}
: data(data), r(*this->data) {}
ArmorRandomSet::ArmorRandomSet(std::shared_ptr<const std::string> data)
: RELFileSet(data) {
@@ -657,18 +844,13 @@ ArmorRandomSet::get_unit_table(size_t index) const {
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));
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));
this->tech_disk_table_spec = this->rare_recovery_table_spec + 1;
this->tech_disk_level_table_spec = &r.pget<TableSpec>(r.pget_u32b(
specs_offset + 2 * sizeof(uint32_t)));
this->tech_disk_level_table_spec = &r.pget<TableSpec>(r.pget_u32b(specs_offset + 2 * sizeof(uint32_t)));
}
pair<const uint8_t*, size_t> ToolRandomSet::get_common_recovery_table(
size_t index) const {
pair<const uint8_t*, size_t> ToolRandomSet::get_common_recovery_table(size_t index) const {
return this->get_table<uint8_t>(*this->common_recovery_table_spec, index);
}
@@ -695,25 +877,21 @@ WeaponRandomSet::WeaponRandomSet(std::shared_ptr<const std::string> data)
std::pair<const WeaponRandomSet::WeightTableEntry8*, size_t>
WeaponRandomSet::get_weapon_type_table(size_t index) const {
const auto& spec = this->r.pget<TableSpec>(
this->offsets->weapon_type_table + index * sizeof(TableSpec));
const auto* data = &this->r.pget<WeightTableEntry8>(
spec.offset, spec.entries_per_table * sizeof(WeightTableEntry8));
const auto& spec = this->r.pget<TableSpec>(this->offsets->weapon_type_table + index * sizeof(TableSpec));
const auto* data = &this->r.pget<WeightTableEntry8>(spec.offset, spec.entries_per_table * sizeof(WeightTableEntry8));
return make_pair(data, spec.entries_per_table);
}
const parray<WeaponRandomSet::WeightTableEntry32, 6>*
WeaponRandomSet::get_bonus_type_table(size_t which, size_t index) const {
uint32_t base_offset = which ? this->offsets->bonus_type_table2 : this->offsets->bonus_type_table1;
return &this->r.pget<parray<WeightTableEntry32, 6>>(
base_offset + sizeof(parray<WeightTableEntry32, 6>) * index);
return &this->r.pget<parray<WeightTableEntry32, 6>>(base_offset + sizeof(parray<WeightTableEntry32, 6>) * index);
}
const WeaponRandomSet::RangeTableEntry*
WeaponRandomSet::get_bonus_range(size_t which, size_t index) const {
uint32_t base_offset = which ? this->offsets->bonus_range_table2 : this->offsets->bonus_range_table1;
return &this->r.pget<RangeTableEntry>(
base_offset + sizeof(RangeTableEntry) * index);
return &this->r.pget<RangeTableEntry>(base_offset + sizeof(RangeTableEntry) * index);
}
const parray<WeaponRandomSet::WeightTableEntry32, 3>*
@@ -724,19 +902,16 @@ WeaponRandomSet::get_special_mode_table(size_t index) const {
const WeaponRandomSet::RangeTableEntry*
WeaponRandomSet::get_standard_grind_range(size_t index) const {
return &this->r.pget<RangeTableEntry>(
this->offsets->standard_grind_range_table + sizeof(RangeTableEntry) * index);
return &this->r.pget<RangeTableEntry>(this->offsets->standard_grind_range_table + sizeof(RangeTableEntry) * index);
}
const WeaponRandomSet::RangeTableEntry*
WeaponRandomSet::get_favored_grind_range(size_t index) const {
return &this->r.pget<RangeTableEntry>(
this->offsets->favored_grind_range_table + sizeof(RangeTableEntry) * index);
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) {
: data(data), r(*data) {
this->offsets = &this->r.pget<Offsets>(this->r.pget_u32b(this->r.size() - 0x10));
}
+18 -7
View File
@@ -18,11 +18,17 @@ public:
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;
bool operator!=(const Table& other) const = default;
template <typename IntT>
struct Range {
IntT min;
IntT max;
} __packed__;
bool operator==(const Range& other) const = default;
bool operator!=(const Range& other) const = default;
} __attribute__((packed));
Episode episode;
parray<uint8_t, 0x0C> base_weapon_type_prob_table;
@@ -50,6 +56,7 @@ public:
phosg::JSON json() const;
void print(FILE* stream) const;
void print_diff(FILE* stream, const Table& other) const;
private:
template <bool BE>
@@ -254,16 +261,20 @@ public:
/* 50 */ U32T<BE> box_item_class_prob_table_offset;
// There are several unused fields here.
} __packed__;
} __attribute__((packed));
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, uint8_t difficulty, uint8_t secid) const;
phosg::JSON json() const;
void print(FILE* stream) const;
void print_diff(FILE* stream, const CommonItemSet& other) const;
protected:
CommonItemSet() = default;
@@ -311,22 +322,22 @@ struct ProbabilityTable {
return this->items[--this->count];
}
void shuffle(std::shared_ptr<PSOLFGEncryption> opt_rand_crypt) {
void shuffle(std::shared_ptr<RandomGenerator> rand_crypt) {
for (size_t z = 1; z < this->count; z++) {
size_t other_z = random_from_optional_crypt(opt_rand_crypt) % (z + 1);
size_t other_z = rand_crypt->next() % (z + 1);
ItemT t = this->items[z];
this->items[z] = this->items[other_z];
this->items[other_z] = t;
}
}
ItemT sample(std::shared_ptr<PSOLFGEncryption> opt_rand_crypt) const {
ItemT sample(std::shared_ptr<RandomGenerator> rand_crypt) const {
if (this->count == 0) {
throw std::runtime_error("sample from empty probability table");
} else if (this->count == 1) {
return this->items[0];
} else {
return this->items[random_from_optional_crypt(opt_rand_crypt) % this->count];
return this->items[rand_crypt->next() % this->count];
}
}
};
@@ -337,7 +348,7 @@ public:
struct WeightTableEntry {
ValueT value;
WeightT weight;
} __packed__;
} __attribute__((packed));
using WeightTableEntry8 = WeightTableEntry<uint8_t>;
using WeightTableEntry32 = WeightTableEntry<be_uint32_t>;
+16 -16
View File
@@ -1018,7 +1018,7 @@ void prs_disassemble(FILE* stream, const void* data, size_t size) {
uint8_t buffered_bits = cr.buffered_bits();
if (cr.read()) {
uint8_t literal_value = r.get_u8();
fprintf(stream, "[%zX] %hhu> 1 %02hhX literal %02hhX\n",
phosg::fwrite_fmt(stream, "[{:X}] {}> 1 {:02X} literal {:02X}\n",
output_bytes, buffered_bits, literal_value, literal_value);
output_bytes++;
@@ -1030,19 +1030,19 @@ void prs_disassemble(FILE* stream, const void* data, size_t size) {
uint16_t a = (a_high << 8) | a_low;
ssize_t offset = (a >> 3) | (~0x1FFF);
if (offset == ~0x1FFF) {
fprintf(stream, "[%zX] end\n", output_bytes);
phosg::fwrite_fmt(stream, "[{:X}] end\n", output_bytes);
break;
}
if (a & 7) {
count = (a & 7) + 2;
read_offset = output_bytes + offset;
fprintf(stream, "[%zX] %hhu> 01 %02hhX %02hhX long copy from %zd (offset=%zX) size=%zX\n",
phosg::fwrite_fmt(stream, "[{:X}] {}> 01 {:02X} {:02X} long copy from {} (offset={:X}) size={:X}\n",
output_bytes, buffered_bits, a_low, a_high, offset, read_offset, count);
} else {
uint8_t count_u8 = r.get_u8();
count = count_u8 + 1;
read_offset = output_bytes + offset;
fprintf(stream, "[%zX] %hhu> 01 %02hhX %02hhX %02hhX extended copy from %zd (offset=%zX) size=%zX\n",
phosg::fwrite_fmt(stream, "[{:X}] {}> 01 {:02X} {:02X} {:02X} extended copy from {} (offset={:X}) size={:X}\n",
output_bytes, buffered_bits, a_low, a_high, count_u8, offset, read_offset, count);
}
@@ -1053,7 +1053,7 @@ void prs_disassemble(FILE* stream, const void* data, size_t size) {
count = ((first_bit ? 2 : 0) | (second_bit ? 1 : 0)) + 2;
ssize_t offset = offset_u8 | (~0xFF);
read_offset = output_bytes + offset;
fprintf(stream, "[%zX] %hhu> 00%c%c %02hhX short copy from %zd (offset=%zX) size=%zX\n",
phosg::fwrite_fmt(stream, "[{:X}] {}> 00{}{} {:02X} short copy from {} (offset={:X}) size={:X}\n",
output_bytes, buffered_bits, first_bit ? '1' : '0', second_bit ? '1' : '0', offset_u8, offset, read_offset, count);
}
@@ -1281,15 +1281,15 @@ string bc0_decompress(const void* data, size_t size) {
}
}
// 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.
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.
uint8_t a1 = r.get_u8();
if (r.eof()) {
break;
@@ -1304,9 +1304,9 @@ string bc0_decompress(const void* data, size_t size) {
memo_offset = (memo_offset + 1) & 0x0FFF;
}
} 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.
} else {
uint8_t v = r.get_u8();
w.put_u8(v);
memo[memo_offset] = v;
@@ -1346,11 +1346,11 @@ void bc0_disassemble(FILE* stream, const void* data, size_t size) {
uint8_t a2 = r.get_u8();
size_t count = (a2 & 0x0F) + 3;
// size_t backreference_offset = a1 | ((a2 << 4) & 0xF00);
fprintf(stream, "[%zX] backreference %02zX\n", output_bytes, count);
phosg::fwrite_fmt(stream, "[{:X}] backreference {:02X}\n", output_bytes, count);
output_bytes += count;
} else {
fprintf(stream, "[%zX] literal %02hhX\n", output_bytes, r.get_u8());
phosg::fwrite_fmt(stream, "[{:X}] literal {:02X}\n", output_bytes, r.get_u8());
output_bytes++;
}
}
+10 -10
View File
@@ -1304,7 +1304,7 @@ string generate_dc_serial_number(uint8_t domain, uint8_t subdomain) {
size_t index2 = phosg::random_object<uint32_t>() % num_primes2;
size_t index3 = phosg::random_object<uint32_t>() % num_primes3;
uint32_t value = primes1[index1] * primes2[index2] * primes3[index3];
string s = phosg::string_printf("%08X", value);
string s = std::format("{:08X}", value);
string ret;
for (char ch : s) {
@@ -1336,7 +1336,7 @@ unordered_map<uint32_t, string> generate_all_dc_serial_numbers(uint8_t domain, u
while ((serial_number = iter.next()) != 0) {
ret[serial_number].push_back(((iter.domain << 2) & 3) | (iter.subdomain & 3));
if (iter.index3 == 0) {
fprintf(stderr, "... (it) domain=%hhu subdomain=%hhu index2=%hu results=%zu (0x%zX)\n", iter.domain, iter.subdomain, iter.index2, ret.size(), ret.size());
phosg::fwrite_fmt(stderr, "... (it) domain={} subdomain={} index2={} results={} (0x{:X})\n", iter.domain, iter.subdomain, iter.index2, ret.size(), ret.size());
}
}
return ret;
@@ -1389,14 +1389,14 @@ size_t DCSerialNumberIterator::progress() const {
void dc_serial_number_speed_test(uint64_t seed) {
uint32_t effective_seed = (seed & 0xFFFFFFFF00000000) ? phosg::random_object<uint32_t>() : seed;
fprintf(stderr, "Product speed test with seed=%08" PRIX32 "\n", effective_seed);
phosg::fwrite_fmt(stderr, "Product speed test with seed={:08X}\n", effective_seed);
PSOV2Encryption crypt(effective_seed);
uint64_t time_slow = 0;
uint64_t time_fast = 0;
size_t num_disagreements = 0;
static constexpr size_t count = 0x1000;
for (size_t z = 0; z < count; z++) {
string s = phosg::string_printf("%08X", crypt.next());
string s = std::format("{:08X}", crypt.next());
uint64_t start = phosg::now();
bool is_valid_fast = dc_serial_number_is_valid_fast(s, 1, 0xFF);
@@ -1407,17 +1407,17 @@ void dc_serial_number_speed_test(uint64_t seed) {
time_slow += phosg::now() - start;
if (((z & 0xF) == 0) || is_valid_slow || is_valid_fast) {
fprintf(stderr, "... %02zX: %s => %s %s%s\n", z, s.c_str(), is_valid_slow ? "SLOW" : "----", is_valid_fast ? "FAST" : "----", is_valid_slow != is_valid_fast ? " !!!" : "");
phosg::fwrite_fmt(stderr, "... {:02X}: {} => {} {}{}\n", z, s, is_valid_slow ? "SLOW" : "----", is_valid_fast ? "FAST" : "----", is_valid_slow != is_valid_fast ? " !!!" : "");
}
if (is_valid_fast != is_valid_slow) {
num_disagreements++;
}
}
fprintf(stderr, "Total time (slow): %" PRId64 " usecs (%" PRIu64 " per serial number)\n", time_slow, time_slow / count);
fprintf(stderr, "Total time (fast): %" PRId64 " usecs (%" PRIu64 " per serial number)\n", time_fast, time_fast / count);
fprintf(stderr, "Fast vs. slow speedup: %zux\n", static_cast<size_t>(time_slow / time_fast));
fprintf(stderr, "Disagreements: %zu\n", num_disagreements);
phosg::fwrite_fmt(stderr, "Total time (slow): {} usecs ({} per serial number)\n", time_slow, time_slow / count);
phosg::fwrite_fmt(stderr, "Total time (fast): {} usecs ({} per serial number)\n", time_fast, time_fast / count);
phosg::fwrite_fmt(stderr, "Fast vs. slow speedup: {}x\n", static_cast<size_t>(time_slow / time_fast));
phosg::fwrite_fmt(stderr, "Disagreements: {}\n", num_disagreements);
}
string decrypt_dp_address_jpn(
@@ -1480,7 +1480,7 @@ std::string crypt_dp_address_jpn_simple(const std::string& data, int64_t mask_ke
if (mask_key < 0) {
throw runtime_error("cannot determine mask key");
}
phosg::log_info("Determined %08" PRIX64 " to be the most likely mask key", mask_key);
phosg::log_info_f("Determined {:08X} to be the most likely mask key", mask_key);
r.go(0);
}
+23 -68
View File
@@ -1,7 +1,5 @@
#include "DNSServer.hh"
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
@@ -14,48 +12,23 @@
#include "Loggers.hh"
#include "NetworkAddresses.hh"
#include "ServerState.hh"
using namespace std;
DNSServer::DNSServer(
shared_ptr<struct event_base> base,
uint32_t local_connect_address,
uint32_t external_connect_address,
shared_ptr<const IPV4RangeSet> banned_ipv4_ranges)
: base(base),
local_connect_address(local_connect_address),
external_connect_address(external_connect_address),
banned_ipv4_ranges(banned_ipv4_ranges) {}
DNSServer::~DNSServer() {
for (const auto& it : this->fd_to_receive_event) {
close(it.first);
}
}
void DNSServer::listen(const std::string& socket_path) {
this->add_socket(phosg::listen(socket_path, 0, 0));
}
DNSServer::DNSServer(shared_ptr<ServerState> state)
: state(state) {}
void DNSServer::listen(const std::string& addr, int port) {
this->add_socket(phosg::listen(addr, port, 0));
}
if (port == 0) {
throw std::runtime_error("Listening port cannot be zero");
}
asio::ip::address asio_addr = addr.empty() ? asio::ip::address_v4::any() : asio::ip::make_address(addr);
asio::ip::udp::endpoint endpoint(asio_addr, port);
auto sock = make_shared<asio::ip::udp::socket>(*this->state->io_context, endpoint);
this->sockets.emplace(sock);
void DNSServer::listen(int port) {
this->add_socket(phosg::listen("", port, 0));
}
void DNSServer::add_socket(int fd) {
unique_ptr<struct event, void (*)(struct event*)> e(
event_new(this->base.get(), fd, EV_READ | EV_PERSIST, &DNSServer::dispatch_on_receive_message, this),
event_free);
event_add(e.get(), nullptr);
this->fd_to_receive_event.emplace(fd, std::move(e));
}
void DNSServer::dispatch_on_receive_message(evutil_socket_t fd,
short events, void* ctx) {
reinterpret_cast<DNSServer*>(ctx)->on_receive_message(fd, events);
asio::co_spawn(*this->state->io_context, this->dns_server_task(sock), asio::detached);
}
string DNSServer::response_for_query(const void* vdata, size_t size, uint32_t resolved_address) {
@@ -77,45 +50,27 @@ string DNSServer::response_for_query(const void* vdata, size_t size, uint32_t re
return response;
}
string DNSServer::response_for_query(
const string& query, uint32_t resolved_address) {
string DNSServer::response_for_query(const string& query, uint32_t resolved_address) {
return DNSServer::response_for_query(query.data(), query.size(), resolved_address);
}
void DNSServer::on_receive_message(int fd, short) {
asio::awaitable<void> DNSServer::dns_server_task(std::shared_ptr<asio::ip::udp::socket> sock) {
for (;;) {
struct sockaddr_storage remote;
socklen_t remote_size = sizeof(sockaddr_in);
memset(&remote, 0, remote_size);
string input(2048, 0);
ssize_t bytes = recvfrom(fd, const_cast<char*>(input.data()), input.size(),
0, reinterpret_cast<sockaddr*>(&remote), &remote_size);
asio::ip::udp::endpoint sender_ep;
size_t bytes = co_await sock->async_receive_from(asio::buffer(input), sender_ep, asio::use_awaitable);
uint32_t sender_addr = ipv4_addr_for_asio_addr(sender_ep.address());
if (bytes < 0) {
if (errno != EAGAIN) {
dns_server_log.error("input error %d", errno);
throw runtime_error("cannot read from udp socket");
}
break;
} else if (bytes == 0) {
break;
} else if (bytes < 0x0C) {
dns_server_log.warning("input query too small");
if (bytes < 0x0C) {
dns_server_log.warning_f("input query too small");
phosg::print_data(stderr, input.data(), bytes);
} else if (!this->banned_ipv4_ranges->check(remote)) {
} else if (!this->state->banned_ipv4_ranges->check(sender_addr)) {
input.resize(bytes);
const sockaddr_in* remote_sin = reinterpret_cast<const sockaddr_in*>(&remote);
uint32_t remote_address = ntohl(remote_sin->sin_addr.s_addr);
uint32_t connect_address = is_local_address(remote_address)
? this->local_connect_address
: this->external_connect_address;
uint32_t connect_address = is_local_address(sender_addr)
? this->state->local_address
: this->state->external_address;
string response = this->response_for_query(input, connect_address);
sendto(fd, response.data(), response.size(), 0,
reinterpret_cast<const sockaddr*>(&remote), remote_size);
co_await sock->async_send_to(asio::buffer(response.data(), response.size()), sender_ep, asio::use_awaitable);
}
}
}
+10 -22
View File
@@ -1,7 +1,6 @@
#pragma once
#include <event2/event.h>
#include <asio.hpp>
#include <memory>
#include <set>
#include <string>
@@ -9,36 +8,25 @@
#include "IPV4RangeSet.hh"
struct ServerState;
class DNSServer {
public:
DNSServer(
std::shared_ptr<struct event_base> base,
uint32_t local_connect_address,
uint32_t external_connect_address,
std::shared_ptr<const IPV4RangeSet> banned_ipv4_ranges);
explicit DNSServer(std::shared_ptr<ServerState> state);
DNSServer(const DNSServer&) = delete;
DNSServer(DNSServer&&) = delete;
virtual ~DNSServer();
DNSServer& operator=(const DNSServer&) = delete;
DNSServer& operator=(DNSServer&&) = delete;
virtual ~DNSServer() = default;
inline void set_banned_ipv4_ranges(std::shared_ptr<const IPV4RangeSet> banned_ipv4_ranges) {
this->banned_ipv4_ranges = banned_ipv4_ranges;
}
void listen(const std::string& socket_path);
void listen(const std::string& addr, int port);
void listen(int port);
void add_socket(int fd);
static std::string response_for_query(const void* vdata, size_t size, uint32_t resolved_address);
static std::string response_for_query(const std::string& query, uint32_t resolved_address);
private:
std::shared_ptr<struct event_base> base;
std::unordered_map<int, std::unique_ptr<struct event, void (*)(struct event*)>> fd_to_receive_event;
uint32_t local_connect_address;
uint32_t external_connect_address;
std::shared_ptr<const IPV4RangeSet> banned_ipv4_ranges;
std::shared_ptr<ServerState> state;
std::unordered_set<std::shared_ptr<asio::ip::udp::socket>> sockets;
static void dispatch_on_receive_message(evutil_socket_t fd, short events, void* ctx);
void on_receive_message(int fd, short event);
asio::awaitable<void> dns_server_task(std::shared_ptr<asio::ip::udp::socket> sock);
};
+232 -278
View File
@@ -1,13 +1,7 @@
#include "DownloadSession.hh"
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -24,7 +18,6 @@
#include "Loggers.hh"
#include "PSOProtocol.hh"
#include "ProxyCommands.hh"
#include "ReceiveCommands.hh"
#include "ReceiveSubcommands.hh"
#include "SendCommands.hh"
@@ -42,13 +35,14 @@ static string random_name() {
}
DownloadSession::DownloadSession(
std::shared_ptr<struct event_base> base,
const struct sockaddr_storage& remote,
std::shared_ptr<asio::io_context> io_context,
const std::string& remote_host,
uint16_t remote_port,
const std::string& output_dir,
Version version,
uint8_t language,
std::shared_ptr<const PSOBBEncryption::KeyFile> bb_key_file,
uint32_t hardware_id,
uint32_t serial_number2,
uint32_t serial_number,
const std::string& access_key,
const std::string& username,
@@ -61,10 +55,15 @@ DownloadSession::DownloadSession(
const std::vector<std::string>& on_request_complete_commands,
bool interactive,
bool show_command_data)
: output_dir(output_dir),
: remote_host(remote_host),
remote_port(remote_port),
output_dir(output_dir),
version(version),
language(language),
show_command_data(show_command_data),
bb_key_file(bb_key_file),
hardware_id(hardware_id),
serial_number(serial_number),
serial_number2(serial_number2),
access_key(access_key),
username(username),
password(password),
@@ -75,35 +74,19 @@ DownloadSession::DownloadSession(
ship_menu_selections(ship_menu_selections),
on_request_complete_commands(on_request_complete_commands),
interactive(interactive),
log(phosg::string_printf("[DownloadSession:%s] ", phosg::name_for_enum(version)), proxy_server_log.min_level),
base(base),
channel(
version,
language,
DownloadSession::dispatch_on_channel_input,
DownloadSession::dispatch_on_channel_error,
this,
phosg::render_sockaddr_storage(remote),
show_command_data ? phosg::TerminalFormat::FG_GREEN : phosg::TerminalFormat::END,
show_command_data ? phosg::TerminalFormat::FG_YELLOW : phosg::TerminalFormat::END),
guild_card_number(0),
log(std::format("[DownloadSession:{}] ", phosg::name_for_enum(version)), proxy_server_log.min_level),
io_context(io_context),
hardware_id(generate_random_hardware_id(version)),
prev_cmd_data(0),
client_config(0),
sent_96(false),
should_request_category_list(true),
current_request(0),
current_game_config_index(0),
in_game(false),
bin_complete(false),
dat_complete(false) {
client_config(0) {
if (this->output_dir.empty()) {
this->output_dir = ".";
}
switch (this->channel.version) {
switch (version) {
case Version::DC_V1:
case Version::DC_V2:
if (this->hardware_id == 0 || this->serial_number == 0 || this->access_key.empty()) {
if (this->serial_number2 == 0 || this->serial_number == 0 || this->access_key.empty()) {
throw runtime_error("missing credentials");
}
break;
@@ -131,102 +114,102 @@ DownloadSession::DownloadSession(
throw runtime_error("unsupported version");
}
this->character->inventory.language = this->channel.language;
if (remote.ss_family != AF_INET) {
throw runtime_error("remote is not AF_INET");
}
string netloc_str = phosg::render_sockaddr_storage(remote);
this->log.info("Connecting to %s", netloc_str.c_str());
struct bufferevent* bev = bufferevent_socket_new(
this->base.get(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
if (!bev) {
throw runtime_error(phosg::string_printf("failed to open socket (%d)", EVUTIL_SOCKET_ERROR()));
}
this->channel.set_bufferevent(bev, 0);
if (bufferevent_socket_connect(this->channel.bev.get(),
reinterpret_cast<const sockaddr*>(&remote), sizeof(struct sockaddr_in)) != 0) {
throw runtime_error(phosg::string_printf("failed to connect (%d)", EVUTIL_SOCKET_ERROR()));
}
this->character->inventory.language = language;
}
void DownloadSession::dispatch_on_channel_input(Channel& ch, uint16_t command, uint32_t flag, std::string& data) {
auto* session = reinterpret_cast<DownloadSession*>(ch.context_obj);
session->on_channel_input(command, flag, data);
asio::awaitable<void> DownloadSession::run() {
string netloc_str = std::format("{}:{}", this->remote_host, this->remote_port);
this->log.info_f("Connecting to {}", netloc_str);
auto sock = make_unique<asio::ip::tcp::socket>(co_await async_connect_tcp(this->remote_host, this->remote_port));
this->channel = SocketChannel::create(
this->io_context,
std::move(sock),
this->version,
this->language,
netloc_str,
this->show_command_data ? phosg::TerminalFormat::FG_GREEN : phosg::TerminalFormat::END,
this->show_command_data ? phosg::TerminalFormat::FG_YELLOW : phosg::TerminalFormat::END);
this->log.info_f("Server channel connected");
while (this->channel->connected()) {
auto msg = co_await this->channel->recv();
co_await this->on_message(msg);
}
}
void DownloadSession::send_93_9D_9E(bool extended) {
if (is_v1(this->channel.version)) {
if (is_v1(this->version)) {
C_LoginExtendedV1_DC_93 ret;
ret.player_tag = this->guild_card_number ? 0xFFFF0000 : 0x00010000;
ret.guild_card_number = this->guild_card_number;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.hardware_id = this->hardware_id;
ret.sub_version = default_sub_version_for_version(this->version);
ret.is_extended = extended ? 1 : 0;
ret.language = this->channel.language;
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.language = this->language;
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
ret.hardware_id.encode(phosg::string_printf("%08" PRIX32, this->hardware_id));
ret.name.encode(this->character->disp.name.decode());
this->channel.send(0x93, 0x01, &ret, extended ? sizeof(ret) : sizeof(C_LoginV1_DC_93));
ret.serial_number2.encode(std::format("{:08X}", this->serial_number2));
ret.login_character_name.encode(this->character->disp.name.decode());
this->channel->send(0x93, 0x01, &ret, extended ? sizeof(ret) : sizeof(C_LoginV1_DC_93));
} else if (is_v2(this->channel.version)) {
} else if (is_v2(this->version)) {
C_LoginExtended_PC_9D ret;
ret.player_tag = this->guild_card_number ? 0xFFFF0000 : 0x00010000;
ret.guild_card_number = this->guild_card_number;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.hardware_id = this->hardware_id;
ret.sub_version = default_sub_version_for_version(this->version);
ret.is_extended = extended ? 1 : 0;
ret.language = this->channel.language;
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.language = this->language;
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
ret.serial_number2 = ret.serial_number;
ret.access_key2 = ret.access_key;
ret.name.encode(this->character->disp.name.decode());
ret.login_character_name.encode(this->character->disp.name.decode());
size_t data_size = extended
? ((this->channel.version == Version::PC_V2) ? sizeof(ret) : sizeof(C_LoginExtended_DC_GC_9D))
? ((this->version == Version::PC_V2) ? sizeof(ret) : sizeof(C_LoginExtended_DC_GC_9D))
: sizeof(C_Login_DC_PC_GC_9D);
this->channel.send(0x9D, 0x01, &ret, data_size);
this->channel->send(0x9D, 0x01, &ret, data_size);
} else if (this->channel.version == Version::GC_V3) {
} else if (this->version == Version::GC_V3) {
C_LoginExtended_GC_9E ret;
ret.player_tag = this->guild_card_number ? 0xFFFF0000 : 0x00010000;
ret.guild_card_number = this->guild_card_number;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.hardware_id = this->hardware_id;
ret.sub_version = default_sub_version_for_version(this->version);
ret.is_extended = extended ? 1 : 0;
ret.language = this->channel.language;
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.language = this->language;
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
ret.serial_number2 = ret.serial_number;
ret.access_key2 = ret.access_key;
ret.name.encode(this->character->disp.name.decode());
ret.login_character_name.encode(this->character->disp.name.decode());
ret.client_config = this->client_config;
this->channel.send(0x9E, 0x01, &ret, extended ? sizeof(ret) : sizeof(C_Login_GC_9E));
this->channel->send(0x9E, 0x01, &ret, extended ? sizeof(ret) : sizeof(C_Login_PC_GC_9E));
} else if (this->channel.version == Version::XB_V3) {
} else if (this->version == Version::XB_V3) {
C_LoginExtended_XB_9E ret;
ret.player_tag = this->guild_card_number ? 0xFFFF0000 : 0x00010000;
ret.guild_card_number = this->guild_card_number;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.hardware_id = this->hardware_id;
ret.sub_version = default_sub_version_for_version(this->version);
ret.is_extended = extended ? 1 : 0;
ret.language = this->channel.language;
ret.language = this->language;
ret.serial_number.encode(this->xb_gamertag);
ret.access_key.encode(phosg::string_printf("%016" PRIX64, this->xb_user_id));
ret.access_key.encode(std::format("{:016X}", this->xb_user_id));
ret.serial_number2 = ret.serial_number;
ret.access_key2 = ret.access_key;
ret.name.encode(this->character->disp.name.decode());
ret.netloc.internal_ipv4_address = phosg::random_object<uint32_t>();
ret.netloc.external_ipv4_address = phosg::random_object<uint32_t>();
ret.netloc.port = 9500;
phosg::random_data(&ret.netloc.mac_address, sizeof(ret.netloc.mac_address));
ret.netloc.sg_ip_address = phosg::random_object<uint32_t>();
ret.netloc.spi = phosg::random_object<uint32_t>();
ret.netloc.account_id = this->xb_account_id;
ret.netloc.unknown_a3.clear(0);
ret.login_character_name.encode(this->character->disp.name.decode());
ret.xb_netloc.internal_ipv4_address = phosg::random_object<uint32_t>();
ret.xb_netloc.external_ipv4_address = phosg::random_object<uint32_t>();
ret.xb_netloc.port = 9500;
phosg::random_data(&ret.xb_netloc.mac_address, sizeof(ret.xb_netloc.mac_address));
ret.xb_netloc.sg_ip_address = phosg::random_object<uint32_t>();
ret.xb_netloc.spi = phosg::random_object<uint32_t>();
ret.xb_netloc.account_id = this->xb_account_id;
ret.xb_netloc.unknown_a3.clear(0);
ret.xb_user_id_high = this->xb_user_id >> 32;
ret.xb_user_id_low = this->xb_user_id;
this->channel.send(0x9E, 0x01, &ret, extended ? sizeof(ret) : sizeof(C_Login_DC_PC_GC_9D));
this->channel->send(0x9E, 0x01, &ret, extended ? sizeof(ret) : sizeof(C_Login_DC_PC_GC_9D));
} else {
throw runtime_error("unsupported version");
@@ -236,31 +219,31 @@ void DownloadSession::send_93_9D_9E(bool extended) {
void DownloadSession::send_61_98(bool is_98) {
uint8_t command = is_98 ? 0x98 : 0x61;
if (is_v1(this->channel.version)) {
if (is_v1(this->version)) {
C_CharacterData_DCv1_61_98 ret;
ret.inventory = this->character->inventory;
ret.disp = convert_player_disp_data<PlayerDispDataDCPCV3, PlayerDispDataBB>(this->character->disp, 1, 1);
this->channel.send(command, 0x01, ret);
this->channel->send(command, 0x01, ret);
} else if (this->channel.version == Version::DC_V2) {
} else if (this->version == Version::DC_V2) {
C_CharacterData_DCv2_61_98 ret;
ret.inventory = this->character->inventory;
ret.disp = convert_player_disp_data<PlayerDispDataDCPCV3, PlayerDispDataBB>(this->character->disp, 1, 1);
ret.records.challenge = this->character->challenge_records;
ret.records.battle = this->character->battle_records;
ret.choice_search_config = this->character->choice_search_config;
this->channel.send(command, 0x02, ret);
this->channel->send(command, 0x02, ret);
} else if (this->channel.version == Version::PC_V2) {
} else if (this->version == Version::PC_V2) {
C_CharacterData_PC_61_98 ret;
ret.inventory = this->character->inventory;
ret.disp = convert_player_disp_data<PlayerDispDataDCPCV3, PlayerDispDataBB>(this->character->disp, 1, 1);
ret.records.challenge = this->character->challenge_records;
ret.records.battle = this->character->battle_records;
ret.choice_search_config = this->character->choice_search_config;
this->channel.send(command, 0x02, ret);
this->channel->send(command, 0x02, ret);
} else if (is_v3(this->channel.version)) {
} else if (is_v3(this->version)) {
C_CharacterData_V3_61_98 ret;
ret.inventory = this->character->inventory;
ret.disp = convert_player_disp_data<PlayerDispDataDCPCV3, PlayerDispDataBB>(this->character->disp, 1, 1);
@@ -268,9 +251,9 @@ void DownloadSession::send_61_98(bool is_98) {
ret.records.battle = this->character->battle_records;
ret.choice_search_config = this->character->choice_search_config;
ret.info_board.encode(this->character->info_board.decode());
this->channel.send(command, 0x03, ret);
this->channel->send(command, 0x03, ret);
} else if (this->channel.version == Version::BB_V4) {
} else if (this->version == Version::BB_V4) {
C_CharacterData_BB_61_98 ret;
ret.inventory = this->character->inventory;
ret.disp = this->character->disp;
@@ -278,34 +261,30 @@ void DownloadSession::send_61_98(bool is_98) {
ret.records.battle = this->character->battle_records;
ret.choice_search_config = this->character->choice_search_config;
ret.info_board.encode(this->character->info_board.decode());
this->channel.send(command, 0x04, ret);
this->channel->send(command, 0x04, ret);
} else {
throw runtime_error("unsupported version");
}
}
void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::string& data) {
// TODO: Use the iovec form of print_data here instead of
// prepend_command_header (which copies the string)
string full_cmd = prepend_command_header(this->channel.version, this->channel.crypt_in.get(), command, flag, data);
for (size_t z = 0; z < 0x28 && z < data.size(); z++) {
this->prev_cmd_data[z] = data[z];
asio::awaitable<void> DownloadSession::on_message(Channel::Message& msg) {
for (size_t z = 0; z < 0x28 && z < msg.data.size(); z++) {
this->prev_cmd_data[z] = msg.data[z];
}
switch (command) {
switch (msg.command) {
case 0x03: {
if (this->channel.version != Version::BB_V4) {
if (this->version != Version::BB_V4) {
throw runtime_error("BB server sent non-BB encryption command");
}
if (!this->bb_key_file) {
throw runtime_error("BB encryption requires a key file");
}
const auto& cmd = check_size_t<S_ServerInitDefault_BB_03_9B>(data, 0xFFFF);
this->channel.crypt_in = make_shared<PSOBBEncryption>(*this->bb_key_file, &cmd.server_key[0], sizeof(cmd.server_key));
this->channel.crypt_out = make_shared<PSOBBEncryption>(*this->bb_key_file, &cmd.client_key[0], sizeof(cmd.client_key));
this->log.info("Enabled BB encryption");
const auto& cmd = msg.check_size_t<S_ServerInitDefault_BB_03_9B>(0xFFFF);
this->channel->crypt_in = make_shared<PSOBBEncryption>(*this->bb_key_file, &cmd.server_key[0], sizeof(cmd.server_key));
this->channel->crypt_out = make_shared<PSOBBEncryption>(*this->bb_key_file, &cmd.client_key[0], sizeof(cmd.client_key));
this->log.info_f("Enabled BB encryption");
throw runtime_error("not yet implemented"); // Send 93
break;
}
@@ -314,54 +293,54 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
case 0x17:
case 0x91:
case 0x9B: {
const auto& cmd = check_size_t<S_ServerInitDefault_DC_PC_V3_02_17_91_9B>(data, 0xFFFF);
if (uses_v3_encryption(this->channel.version)) {
this->channel.crypt_in = make_shared<PSOV3Encryption>(cmd.server_key);
this->channel.crypt_out = make_shared<PSOV3Encryption>(cmd.client_key);
this->log.info("Enabled V3 encryption (server key %08" PRIX32 ", client key %08" PRIX32 ")",
cmd.server_key.load(), cmd.client_key.load());
} else if (!uses_v4_encryption(this->channel.version)) {
this->channel.crypt_in = make_shared<PSOV2Encryption>(cmd.server_key);
this->channel.crypt_out = make_shared<PSOV2Encryption>(cmd.client_key);
this->log.info("Enabled V2 encryption (server key %08" PRIX32 ", client key %08" PRIX32 ")",
cmd.server_key.load(), cmd.client_key.load());
const auto& cmd = msg.check_size_t<S_ServerInitDefault_DC_PC_V3_02_17_91_9B>(0xFFFF);
if (uses_v3_encryption(this->version)) {
this->channel->crypt_in = make_shared<PSOV3Encryption>(cmd.server_key);
this->channel->crypt_out = make_shared<PSOV3Encryption>(cmd.client_key);
this->log.info_f("Enabled V3 encryption (server key {:08X}, client key {:08X})",
cmd.server_key, cmd.client_key);
} else if (!uses_v4_encryption(this->version)) {
this->channel->crypt_in = make_shared<PSOV2Encryption>(cmd.server_key);
this->channel->crypt_out = make_shared<PSOV2Encryption>(cmd.client_key);
this->log.info_f("Enabled V2 encryption (server key {:08X}, client key {:08X})",
cmd.server_key, cmd.client_key);
} else {
throw runtime_error("BB server sent non-BB encryption command");
}
if (command == 0x02) {
bool is_extended = (this->channel.version == Version::XB_V3);
if (msg.command == 0x02) {
bool is_extended = (this->version == Version::XB_V3);
this->send_93_9D_9E(is_extended);
} else {
if (is_v1(this->channel.version)) {
if (is_v1(this->version)) {
C_LoginV1_DC_PC_V3_90 ret;
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
this->channel.send(0x90, 0x00, ret);
this->channel->send(0x90, 0x00, ret);
} else if (is_v2(this->channel.version)) {
} else if (is_v2(this->version)) {
C_Login_DC_PC_V3_9A ret;
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
ret.player_tag = this->guild_card_number ? 0xFFFF0000 : 0x00010000;
ret.guild_card_number = this->guild_card_number;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.sub_version = default_sub_version_for_version(this->version);
ret.serial_number2 = ret.serial_number;
ret.access_key2 = ret.access_key;
this->channel.send(0x9A, 0x00, ret);
this->channel->send(0x9A, 0x00, ret);
} else if (this->channel.version == Version::GC_V3) {
} else if (this->version == Version::GC_V3) {
C_VerifyAccount_V3_DB ret;
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.sub_version = default_sub_version_for_version(this->version);
ret.serial_number2 = ret.serial_number;
ret.access_key2 = ret.access_key;
ret.password.encode(this->password);
this->channel.send(0xDB, 0x00, ret);
this->channel->send(0xDB, 0x00, ret);
} else if (this->channel.version == Version::XB_V3) {
} else if (this->version == Version::XB_V3) {
this->send_93_9D_9E(true);
} else {
@@ -374,34 +353,36 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
case 0x90:
case 0x9A: {
if (flag == 1) {
if (is_v1(this->channel.version)) {
if (msg.flag == 1) {
if (is_v1(this->version)) {
C_RegisterV1_DC_92 ret;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.language = this->channel.language;
ret.hardware_id.encode(phosg::string_printf("%08" PRIX32, this->hardware_id));
this->channel.send(0x92, 0x00, ret);
ret.hardware_id = this->hardware_id;
ret.sub_version = default_sub_version_for_version(this->version);
ret.language = this->language;
ret.serial_number2.encode(std::format("{:08X}", this->serial_number2));
this->channel->send(0x92, 0x00, ret);
} else if (!is_v4(this->channel.version)) {
} else if (!is_v4(this->version)) {
C_Register_DC_PC_V3_9C ret;
ret.sub_version = default_sub_version_for_version(this->channel.version);
ret.language = this->channel.language;
if (this->channel.version == Version::XB_V3) {
ret.hardware_id = this->hardware_id;
ret.sub_version = default_sub_version_for_version(this->version);
ret.language = this->language;
if (this->version == Version::XB_V3) {
ret.serial_number.encode(this->xb_gamertag);
ret.access_key.encode(phosg::string_printf("%016" PRIX64, this->xb_user_id));
ret.access_key.encode(std::format("{:016X}", this->xb_user_id));
ret.password.encode("xbox-pso");
} else {
ret.serial_number.encode(phosg::string_printf("%08" PRIX32, this->serial_number));
ret.serial_number.encode(std::format("{:08X}", this->serial_number));
ret.access_key.encode(this->access_key);
ret.password.encode(this->password);
}
this->channel.send(0x9C, 0x00, ret);
this->channel->send(0x9C, 0x00, ret);
} else {
throw runtime_error("unsupported version");
}
} else if (flag == 0 || flag == 2) {
} else if (msg.flag == 0 || msg.flag == 2) {
this->send_93_9D_9E(true);
} else {
@@ -412,17 +393,17 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
case 0x92:
case 0x9C:
if (flag == 0) {
if (msg.flag == 0) {
throw runtime_error("server rejected login credentials");
}
this->send_93_9D_9E(true);
break;
case 0x9F: {
if (is_v1_or_v2(this->channel.version)) {
if (is_v1_or_v2(this->version)) {
throw runtime_error("invalid command");
}
this->channel.send(0x9F, 0x00, this->client_config);
this->channel->send(0x9F, 0x00, this->client_config);
break;
}
@@ -430,16 +411,16 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
C_ExecuteCodeResult_B3 ret;
ret.checksum = 0;
ret.return_value = 0;
this->channel.send(0xB3, 0x00, ret);
this->channel->send(0xB3, 0x00, ret);
break;
}
case 0x04: {
const auto& cmd = check_size_t<S_UpdateClientConfig_V3_04>(data, 0x08, sizeof(S_UpdateClientConfig_V3_04));
if (!is_v1_or_v2(this->channel.version)) {
const auto& cmd = msg.check_size_t<S_UpdateClientConfig_V3_04>(0x08, sizeof(S_UpdateClientConfig_V3_04));
if (!is_v1_or_v2(this->version)) {
for (size_t z = 0; z < 0x20; z++) {
size_t read_index = z + 8;
this->client_config[z] = (read_index < data.size()) ? data[read_index] : this->prev_cmd_data[read_index];
this->client_config[z] = (read_index < msg.data.size()) ? msg.data[read_index] : this->prev_cmd_data[read_index];
}
}
this->guild_card_number = cmd.guild_card_number;
@@ -447,14 +428,14 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
C_CharSaveInfo_DCv2_PC_V3_BB_96 ret;
ret.creation_timestamp = this->character->creation_timestamp;
ret.event_counter = this->character->save_count;
this->channel.send(0x96, 0x00, ret);
this->channel->send(0x96, 0x00, ret);
this->sent_96 = true;
}
break;
}
case 0x97:
this->channel.send(0xB1, 0x00);
this->channel->send(0xB1, 0x00);
break;
case 0x95:
@@ -462,13 +443,13 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
break;
case 0xB1:
this->channel.send(0x99, 0x00);
this->channel->send(0x99, 0x00);
break;
case 0x1A:
case 0xD5:
if (is_v3(this->channel.version)) {
this->channel.send(0xD6, 0x00);
if (is_v3(this->version)) {
this->channel->send(0xD6, 0x00);
}
break;
@@ -476,24 +457,24 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
case 0x1F:
case 0xA0:
case 0xA1: {
C_MenuSelection_10_Flag00 ret;
C_MenuSelectionBase_10 ret;
auto handle_command = [&]<typename CmdT>() {
const auto* items = check_size_vec_t<CmdT>(data, flag + 1);
const auto* items = check_size_vec_t<CmdT>(msg.data, msg.flag + 1);
size_t item_index;
this->log.info("Ship Select menu:");
for (item_index = 1; item_index <= flag; item_index++) {
this->log.info_f("Ship Select menu:");
for (item_index = 1; item_index <= msg.flag; item_index++) {
const auto& item = items[item_index];
auto text = strip_color(item.text.decode());
this->log.info("%zu: (%08" PRIX32 " %08" PRIX32 ") %s", item_index, item.menu_id.load(), item.item_id.load(), text.c_str());
auto text = strip_color(item.name.decode());
this->log.info_f("{}: ({:08X} {:08X}) {}", item_index, item.menu_id, item.item_id, text);
if (this->ship_menu_selections.count(text)) {
break;
}
}
if (item_index > flag) {
if (item_index > msg.flag) {
if (this->interactive) {
while (item_index == 0 || item_index > flag) {
this->log.info("Choose response index:");
while (item_index == 0 || item_index > msg.flag) {
this->log.info_f("Choose response index:");
string input = phosg::fgets(stdin);
item_index = stoul(input, nullptr, 0);
}
@@ -505,13 +486,13 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
ret.item_id = items[item_index].item_id;
};
if (uses_utf16(this->channel.version)) {
handle_command.operator()<S_MenuEntry_PC_BB_07_1F>();
if (uses_utf16(this->version)) {
handle_command.operator()<S_MenuItem_PC_BB_08>();
} else {
handle_command.operator()<S_MenuEntry_DC_V3_07_1F>();
handle_command.operator()<S_MenuItem_DC_V3_08_Ep3_E6>();
}
this->channel.send(0x10, 0x00, ret);
this->channel->send(0x10, 0x00, ret);
break;
}
@@ -531,39 +512,32 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
break;
case 0x1D:
this->channel.send(0x1D, 0x00);
this->channel->send(0x1D, 0x00);
break;
case 0x19: {
const auto& cmd = check_size_t<S_Reconnect_19>(data, sizeof(S_Reconnect_19), 0xFFFF);
sockaddr_storage ss;
auto* sin = reinterpret_cast<sockaddr_in*>(&ss);
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = htonl(cmd.address);
sin->sin_port = htons(cmd.port);
string netloc_str = phosg::render_sockaddr_storage(ss);
this->log.info("Connecting to %s", netloc_str.c_str());
struct bufferevent* bev = bufferevent_socket_new(this->base.get(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
if (!bev) {
throw runtime_error(phosg::string_printf("failed to open socket (%d)", EVUTIL_SOCKET_ERROR()));
}
this->channel.set_bufferevent(bev, 0);
this->channel.crypt_in.reset();
this->channel.crypt_out.reset();
if (bufferevent_socket_connect(this->channel.bev.get(), reinterpret_cast<const sockaddr*>(&ss), sizeof(struct sockaddr_in)) != 0) {
throw runtime_error(phosg::string_printf("failed to connect (%d)", EVUTIL_SOCKET_ERROR()));
}
const auto& cmd = msg.check_size_t<S_Reconnect_19>(sizeof(S_Reconnect_19), 0xFFFF);
auto new_ep = make_endpoint_ipv4(cmd.address, cmd.port);
string netloc_str = str_for_endpoint(new_ep);
this->log.info_f("Connecting to {}", netloc_str);
auto sock = make_unique<asio::ip::tcp::socket>(co_await async_connect_tcp(new_ep));
this->channel = SocketChannel::create(
this->io_context,
std::move(sock),
this->version,
this->language,
netloc_str,
this->show_command_data ? phosg::TerminalFormat::FG_GREEN : phosg::TerminalFormat::END,
this->show_command_data ? phosg::TerminalFormat::FG_YELLOW : phosg::TerminalFormat::END);
this->log.info_f("Server channel connected");
break;
}
case 0x83: {
const auto* items = check_size_vec_t<S_LobbyListEntry_83>(data, flag, true);
const auto* items = check_size_vec_t<S_LobbyListEntry_83>(msg.data, msg.flag, true);
this->lobby_menu_items.clear();
for (size_t z = 0; z < flag; z++) {
for (size_t z = 0; z < msg.flag; z++) {
this->lobby_menu_items.emplace_back(items[z]);
}
break;
@@ -574,7 +548,7 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
// 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->channel.version == Version::PC_V2) {
if (this->version == Version::PC_V2) {
C_CreateGame_PC_C1 ret;
ret.name.encode(random_name());
ret.password.encode(random_name());
@@ -582,16 +556,16 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
ret.battle_mode = (game_config.mode == GameMode::BATTLE);
ret.challenge_mode = (game_config.mode == GameMode::CHALLENGE);
ret.episode = 1;
this->channel.send(0xC1, 0x00, ret);
this->channel->send(0xC1, 0x00, ret);
} else if (!is_v4(this->channel.version)) {
} else if (!is_v4(this->version)) {
C_CreateGame_DC_V3_0C_C1_Ep3_EC ret;
ret.name.encode(random_name());
ret.password.encode(random_name());
ret.difficulty = 0;
ret.battle_mode = (game_config.mode == GameMode::BATTLE);
ret.challenge_mode = (game_config.mode == GameMode::CHALLENGE);
if (is_v1(this->channel.version)) {
if (is_v1(this->version)) {
ret.episode = 0;
} else if (game_config.episode == Episode::EP1) {
ret.episode = 1;
@@ -602,7 +576,7 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
} else {
throw std::logic_error("invalid episode");
}
this->channel.send(is_v1(this->channel.version) ? 0x0C : 0xC1, 0x00, ret);
this->channel->send(is_v1(this->version) ? 0x0C : 0xC1, 0x00, ret);
} else {
C_CreateGame_BB_C1 ret;
@@ -621,7 +595,7 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
throw std::logic_error("invalid episode");
}
ret.solo_mode = (game_config.mode == GameMode::SOLO);
this->channel.send(is_v1(this->channel.version) ? 0x0C : 0xC1, 0x00, ret);
this->channel->send(is_v1(this->version) ? 0x0C : 0xC1, 0x00, ret);
}
break;
}
@@ -634,32 +608,32 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
this->character->inventory.items[z].data.id = 0x00010000 + z;
}
if (!is_v1(this->channel.version)) {
this->channel.send(0x8A, 0x00);
if (!is_v1(this->version)) {
this->channel->send(0x8A, 0x00);
}
this->channel.send(0x6F, 0x00);
this->channel->send(0x6F, 0x00);
this->send_next_request();
break;
}
case 0xA2: {
auto handle_command = [&]<typename CmdT>() {
const auto* items = check_size_vec_t<CmdT>(data, flag);
for (size_t z = 0; z < flag; z++) {
const auto* items = check_size_vec_t<CmdT>(msg.data, msg.flag);
for (size_t z = 0; z < msg.flag; z++) {
const auto& item = items[z];
uint64_t request = (static_cast<uint64_t>(item.menu_id) << 32) | static_cast<uint64_t>(item.item_id);
if (!this->done_requests.count(request)) {
this->log.info("Adding request %016" PRIX64, request);
this->log.info_f("Adding request {:016X}", request);
this->pending_requests.emplace(request, item.name.decode());
}
}
};
if (this->channel.version == Version::PC_V2) {
if (this->version == Version::PC_V2) {
handle_command.operator()<S_QuestMenuEntry_PC_A2_A4>();
} else if (this->channel.version == Version::XB_V3) {
} else if (this->version == Version::XB_V3) {
handle_command.operator()<S_QuestMenuEntry_XB_A2_A4>();
} else if (this->channel.version == Version::BB_V4) {
} else if (this->version == Version::BB_V4) {
handle_command.operator()<S_QuestMenuEntry_BB_A2_A4>();
} else {
handle_command.operator()<S_QuestMenuEntry_DC_GC_A2_A4>();
@@ -670,26 +644,26 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
case 0x44:
case 0xA6: {
auto handle_command = [&]<typename CmdT>() {
const auto& cmd = check_size_t<CmdT>(data, 0xFFFF);
const auto& cmd = msg.check_size_t<CmdT>(0xFFFF);
string internal_name = cmd.filename.decode();
string filtered_name;
for (char ch : internal_name) {
filtered_name.push_back((isalnum(ch) || (ch == '-') || (ch == '.') || (ch == '_')) ? ch : '_');
}
string local_filename = phosg::string_printf(
"%s/%016" PRIX64 "_%" PRIu64 "_%s_%c_%s",
this->output_dir.c_str(),
string local_filename = std::format(
"{}/{:016X}_{}_{}_{}_{}",
this->output_dir,
this->current_request,
phosg::now(),
phosg::name_for_enum(this->channel.version),
char_for_language_code(this->channel.language),
filtered_name.c_str());
phosg::name_for_enum(this->version),
char_for_language_code(this->language),
filtered_name);
this->open_files.emplace(internal_name, OpenFile{.request = this->current_request, .filename = local_filename, .total_size = cmd.file_size, .data = ""});
};
if (is_dc(this->channel.version)) {
if (is_dc(this->version)) {
handle_command.operator()<S_OpenFile_DC_44_A6>();
} else if (!is_v4(this->channel.version)) {
} else if (!is_v4(this->version)) {
handle_command.operator()<S_OpenFile_PC_GC_44_A6>();
} else {
handle_command.operator()<S_OpenFile_BB_44_A6>();
@@ -698,22 +672,22 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
}
case 0x13:
case 0xA7: {
const auto& cmd = check_size_t<S_WriteFile_13_A7>(data);
const auto& cmd = msg.check_size_t<S_WriteFile_13_A7>();
string internal_filename = cmd.filename.decode();
if (!is_v1_or_v2(this->channel.version)) {
if (!is_v1_or_v2(this->version)) {
C_WriteFileConfirmation_V3_BB_13_A7 ret;
ret.filename.encode(internal_filename);
this->channel.send(command, flag, ret);
this->channel->send(msg.command, msg.flag, ret);
}
auto f_it = this->open_files.find(internal_filename.c_str());
auto f_it = this->open_files.find(internal_filename);
if (f_it == this->open_files.end()) {
this->log.warning("Received data for non-open file %s", internal_filename.c_str());
this->log.warning_f("Received data for non-open file {}", internal_filename);
break;
}
auto& f = this->open_files.at(cmd.filename.decode());
size_t block_offset = flag * 0x400;
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;
@@ -725,25 +699,25 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
memcpy(f.data.data() + block_offset, cmd.data.data(), data_size);
if (cmd.data_size != 0x400) {
phosg::save_file(f.filename, f.data);
this->log.info("Wrote file %s (%zu bytes)", f.filename.c_str(), f.data.size());
this->log.info_f("Wrote file {} ({} bytes)", f.filename, f.data.size());
this->open_files.erase(internal_filename);
if (phosg::ends_with(internal_filename, ".bin")) {
if (internal_filename.ends_with(".bin")) {
this->bin_complete = true;
} else if (phosg::ends_with(internal_filename, ".dat")) {
} else if (internal_filename.ends_with(".dat")) {
this->dat_complete = true;
}
if (this->open_files.empty() && this->bin_complete && this->dat_complete) {
if (is_v1_or_v2(this->channel.version)) {
if (is_v1_or_v2(this->version)) {
this->on_request_complete();
} else {
this->channel.send(0xAC, 0x00);
this->channel->send(0xAC, 0x00);
}
}
}
break;
}
case 0xAC: {
if (is_v1_or_v2(this->channel.version)) {
if (is_v1_or_v2(this->version)) {
throw runtime_error("unsupported version");
}
this->on_request_complete();
@@ -754,24 +728,24 @@ void DownloadSession::on_channel_input(uint16_t command, uint32_t flag, std::str
void DownloadSession::send_next_request() {
if (should_request_category_list) {
this->log.info("Requesting quest list");
this->channel.send(0xA2, 0x00);
if (is_v4(this->channel.version)) {
this->channel.send(0xA2, 0x01);
this->log.info_f("Requesting quest list");
this->channel->send(0xA2, 0x00);
if (is_v4(this->version)) {
this->channel->send(0xA2, 0x01);
}
this->should_request_category_list = false;
} else if (!this->pending_requests.empty()) {
if (interactive) {
const auto& config = this->game_configs[this->current_game_config_index];
this->log.info("Items available to expand (mode=%s, episode=%s):", name_for_mode(config.mode), name_for_episode(config.episode));
this->log.info_f("Items available to expand (mode={}, episode={}):", name_for_mode(config.mode), name_for_episode(config.episode));
for (const auto& it : this->pending_requests) {
this->log.info("%016" PRIX64 ": %s", it.first, it.second.c_str());
this->log.info_f("{:016X}: {}", it.first, it.second);
}
this->log.info("Choose item to expand by ID (q to quit; s to skip to next config):");
this->log.info_f("Choose item to expand by ID (q to quit; s to skip to next config):");
string input = phosg::fgets(stdin);
if (input.empty() || (input == "q\n")) {
this->channel.disconnect();
this->channel->disconnect();
return;
} else if (input == "s\n") {
this->pending_requests.clear();
@@ -787,22 +761,22 @@ void DownloadSession::send_next_request() {
this->current_request = item_it->first;
this->done_requests.emplace(this->current_request);
this->pending_requests.erase(item_it);
this->log.info("Sending request %016" PRIX64, this->current_request);
this->log.info_f("Sending request {:016X}", this->current_request);
}
C_MenuSelection_10_Flag00 cmd;
C_MenuSelectionBase_10 cmd;
cmd.menu_id = (this->current_request >> 32) & 0xFFFFFFFF;
cmd.item_id = this->current_request & 0xFFFFFFFF;
this->channel.send(0x10, 0x00, cmd);
this->channel->send(0x10, 0x00, cmd);
} else {
this->log.info("No pending requests with current parameters");
this->log.info_f("No pending requests with current parameters");
this->on_request_complete();
}
}
void DownloadSession::on_request_complete() {
for (const auto& data : this->on_request_complete_commands) {
this->channel.send(data);
this->channel->send(data);
}
this->send_61_98(true);
@@ -812,14 +786,14 @@ void DownloadSession::on_request_complete() {
C_LobbySelection_84 ret84;
ret84.menu_id = item.menu_id;
ret84.item_id = item.item_id;
this->channel.send(0x84, 0x00, ret84);
this->channel->send(0x84, 0x00, ret84);
if (this->pending_requests.empty()) {
// Advance to next mode/episode combination
this->current_game_config_index++;
bool v1 = is_v1(this->channel.version);
bool v2 = is_v2(this->channel.version);
bool v3 = is_v3(this->channel.version);
bool v1 = is_v1(this->version);
bool v2 = is_v2(this->version);
bool v3 = is_v3(this->version);
while ((this->current_game_config_index < this->game_configs.size()) &&
((v1 && !this->game_configs[this->current_game_config_index].v1) ||
(v2 && !this->game_configs[this->current_game_config_index].v2) ||
@@ -827,36 +801,16 @@ void DownloadSession::on_request_complete() {
this->current_game_config_index++;
}
if (this->current_game_config_index >= this->game_configs.size()) {
this->log.info("All modes complete");
this->channel.disconnect();
this->log.info_f("All modes complete");
this->channel->disconnect();
} else {
const auto& config = this->game_configs[this->current_game_config_index];
this->log.info("Advancing to %s mode in %s", name_for_mode(config.mode), name_for_episode(config.episode));
this->log.info_f("Advancing to {} mode in {}", name_for_mode(config.mode), name_for_episode(config.episode));
this->should_request_category_list = true;
}
}
}
void DownloadSession::dispatch_on_channel_error(Channel& ch, short events) {
auto* session = reinterpret_cast<DownloadSession*>(ch.context_obj);
session->on_channel_error(events);
}
void DownloadSession::on_channel_error(short events) {
if (events & BEV_EVENT_CONNECTED) {
this->log.info("Server channel connected");
}
if (events & BEV_EVENT_ERROR) {
int err = EVUTIL_SOCKET_ERROR();
this->log.warning("Error %d (%s) in server stream", err, evutil_socket_error_to_string(err));
}
if (events & (BEV_EVENT_ERROR | BEV_EVENT_EOF)) {
this->log.info("Server endpoint has disconnected");
this->channel.disconnect();
event_base_loopexit(this->base.get(), nullptr);
}
}
const std::vector<DownloadSession::GameConfig> DownloadSession::game_configs({
{.mode = GameMode::NORMAL, .episode = Episode::EP1, .v1 = true, .v2 = true, .v3 = true},
{.mode = GameMode::NORMAL, .episode = Episode::EP2, .v1 = false, .v2 = false, .v3 = true},
+26 -25
View File
@@ -1,7 +1,5 @@
#pragma once
#include <event2/event.h>
#include <functional>
#include <map>
#include <memory>
@@ -18,13 +16,14 @@
class DownloadSession {
public:
DownloadSession(
std::shared_ptr<struct event_base> base,
const struct sockaddr_storage& remote,
std::shared_ptr<asio::io_context> io_context,
const std::string& remote_host,
uint16_t remote_port,
const std::string& output_dir,
Version version,
uint8_t language,
std::shared_ptr<const PSOBBEncryption::KeyFile> bb_key_file,
uint32_t hardware_id,
uint32_t serial_number2,
uint32_t serial_number,
const std::string& access_key,
const std::string& username,
@@ -43,12 +42,19 @@ public:
DownloadSession& operator=(DownloadSession&&) = delete;
virtual ~DownloadSession() = default;
asio::awaitable<void> run();
protected:
// Config (must be set by caller)
std::string remote_host;
uint16_t remote_port;
std::string output_dir;
Version version;
uint8_t language;
bool show_command_data;
std::shared_ptr<const PSOBBEncryption::KeyFile> bb_key_file;
uint32_t hardware_id;
uint32_t serial_number;
uint32_t serial_number2;
std::string access_key;
std::string username;
std::string password;
@@ -62,16 +68,17 @@ protected:
// State (set during session)
phosg::PrefixedLogger log;
std::shared_ptr<struct event_base> base;
Channel channel;
uint32_t guild_card_number;
std::shared_ptr<asio::io_context> io_context;
std::shared_ptr<Channel> channel;
uint64_t hardware_id;
uint32_t guild_card_number = 0;
parray<uint8_t, 0x28> prev_cmd_data;
parray<uint8_t, 0x20> client_config;
bool sent_96;
bool sent_96 = false;
std::vector<S_LobbyListEntry_83> lobby_menu_items;
bool should_request_category_list;
uint64_t current_request;
bool should_request_category_list = true;
uint64_t current_request = 0;
std::map<uint64_t, std::string> pending_requests;
std::unordered_set<uint64_t> done_requests;
@@ -91,20 +98,14 @@ protected:
bool v3;
};
static const std::vector<GameConfig> game_configs;
size_t current_game_config_index;
bool in_game;
bool bin_complete;
bool dat_complete;
size_t current_game_config_index = 0;
bool in_game = false;
bool bin_complete = false;
bool dat_complete = false;
static void dispatch_on_channel_input(Channel& ch, uint16_t command, uint32_t flag, std::string& msg);
static void dispatch_on_channel_error(Channel& ch, short events);
void on_channel_input(uint16_t command, uint32_t flag, std::string& msg);
void on_channel_error(short events);
void send_next_request();
void on_request_complete();
void assign_item_ids(uint32_t base_item_id);
void send_93_9D_9E(bool extended);
void send_61_98(bool is_98);
asio::awaitable<void> on_message(Channel::Message& msg);
void send_next_request();
void on_request_complete();
};
+230 -1079
View File
File diff suppressed because it is too large Load Diff
+56 -22
View File
@@ -7,9 +7,9 @@
#include "StaticGameData.hh"
#include "Types.hh"
enum class EnemyType {
UNKNOWN = -1,
NONE = 0,
enum class EnemyType : uint8_t {
UNKNOWN = 0,
NONE,
NON_ENEMY_NPC,
AL_RAPPY,
ASTARK,
@@ -33,6 +33,7 @@ enum class EnemyType {
DARK_FALZ_2,
DARK_FALZ_3,
DARK_GUNNER,
DARK_GUNNER_CONTROL,
DARVANT,
DARVANT_ULTIMATE,
DE_ROL_LE,
@@ -40,8 +41,8 @@ enum class EnemyType {
DE_ROL_LE_MINE,
DEATH_GUNNER,
DEL_LILY,
DEL_RAPPY,
DEL_RAPPY_ALT,
DEL_RAPPY_CRATER,
DEL_RAPPY_DESERT,
DELBITER,
DELDEPTH,
DELSABER,
@@ -54,10 +55,10 @@ enum class EnemyType {
DUBCHIC,
DUBWITCH, // Has no entry in battle params
EGG_RAPPY,
EPSIGUARD,
EPSIGARD,
EPSILON,
EVIL_SHARK,
GAEL,
GAEL_OR_GIEL,
GAL_GRYPHON,
GARANZ,
GEE,
@@ -80,6 +81,7 @@ enum class EnemyType {
KONDRIEU,
LA_DIMENIAN,
LOVE_RAPPY,
MERICARAND,
MERICAROL,
MERICUS,
MERIKLE,
@@ -97,8 +99,8 @@ enum class EnemyType {
OLGA_FLOW_2,
PAL_SHARK,
PAN_ARMS,
PAZUZU,
PAZUZU_ALT,
PAZUZU_CRATER,
PAZUZU_DESERT,
PIG_RAY,
POFUILLY_SLIME,
POUILLY_SLIME,
@@ -107,12 +109,12 @@ enum class EnemyType {
RAG_RAPPY,
RECOBOX,
RECON,
SAINT_MILLION,
SAINT_MILION,
SAINT_RAPPY,
SAND_RAPPY,
SAND_RAPPY_ALT,
SATELLITE_LIZARD,
SATELLITE_LIZARD_ALT,
SAND_RAPPY_CRATER,
SAND_RAPPY_DESERT,
SATELLITE_LIZARD_CRATER,
SATELLITE_LIZARD_DESERT,
SAVAGE_WOLF,
SHAMBERTIN,
SINOW_BEAT,
@@ -129,22 +131,54 @@ enum class EnemyType {
VOL_OPT_CORE,
VOL_OPT_MONITOR,
VOL_OPT_PILLAR,
YOWIE,
YOWIE_ALT,
YOWIE_CRATER,
YOWIE_DESERT,
ZE_BOOTA,
ZOL_GIBBON,
ZU,
ZU_ALT,
ZU_CRATER,
ZU_DESERT,
MAX_ENEMY_TYPE,
};
struct EnemyTypeDefinition {
enum Flag : uint8_t {
VALID_EP1 = 0x01,
VALID_EP2 = 0x02,
VALID_EP4 = 0x04,
IS_RARE = 0x08,
};
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)
const char* enum_name;
const char* in_game_name;
const char* ultimate_name; // May be null if same as in_game_name
inline bool valid_in_episode(Episode ep) const {
switch (ep) {
case Episode::EP1:
return (this->flags & Flag::VALID_EP1);
case Episode::EP2:
return (this->flags & Flag::VALID_EP2);
case Episode::EP4:
return (this->flags & Flag::VALID_EP4);
default:
throw std::logic_error("invalid episode number");
}
}
inline bool is_rare() const {
return (this->flags & Flag::IS_RARE);
}
EnemyType rare_type(Episode episode, uint8_t event, uint8_t floor) const;
};
const EnemyTypeDefinition& type_definition_for_enemy(EnemyType type);
template <>
const char* phosg::name_for_enum<EnemyType>(EnemyType type);
template <>
EnemyType phosg::enum_for_name<EnemyType>(const char* name);
bool enemy_type_valid_for_episode(Episode episode, EnemyType enemy_type);
uint8_t battle_param_index_for_enemy_type(Episode episode, EnemyType enemy_type);
uint8_t rare_table_index_for_enemy_type(EnemyType enemy_type);
const std::vector<EnemyType>& enemy_types_for_rare_table_index(Episode episode, uint8_t rt_index);
bool enemy_type_is_rare(EnemyType type);
const std::vector<EnemyType>& enemy_types_for_battle_param_index(Episode episode, uint8_t bp_index);
+36 -42
View File
@@ -82,19 +82,19 @@ void BattleRecord::Event::serialize(phosg::StringWriter& w) const {
void BattleRecord::Event::print(FILE* stream) const {
string time_str = phosg::format_time(this->timestamp);
fprintf(stream, "Event @%016" PRIX64 " (%s) ", this->timestamp, time_str.c_str());
phosg::fwrite_fmt(stream, "Event @{:016X} ({}) ", this->timestamp, time_str);
switch (this->type) {
case Type::PLAYER_JOIN:
fprintf(stream, "PLAYER_JOIN %02" PRIX32 "\n", this->players[0].lobby_data.client_id.load());
phosg::fwrite_fmt(stream, "PLAYER_JOIN {:02X}\n", this->players[0].lobby_data.client_id);
this->players[0].print(stream);
break;
case Type::PLAYER_LEAVE:
fprintf(stream, "PLAYER_LEAVE %02hhu\n", this->leaving_client_id);
phosg::fwrite_fmt(stream, "PLAYER_LEAVE {:02}\n", this->leaving_client_id);
break;
case Type::SET_INITIAL_PLAYERS:
fprintf(stream, "SET_INITIAL_PLAYERS");
phosg::fwrite_fmt(stream, "SET_INITIAL_PLAYERS");
for (const auto& player : this->players) {
fprintf(stream, " %02" PRIX32, player.lobby_data.client_id.load());
phosg::fwrite_fmt(stream, " {:02X}", player.lobby_data.client_id);
}
fputc('\n', stream);
for (const auto& player : this->players) {
@@ -102,23 +102,23 @@ void BattleRecord::Event::print(FILE* stream) const {
}
break;
case Type::BATTLE_COMMAND:
fprintf(stream, "BATTLE_COMMAND\n");
phosg::fwrite_fmt(stream, "BATTLE_COMMAND\n");
phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
break;
case Type::GAME_COMMAND:
fprintf(stream, "GAME_COMMAND\n");
phosg::fwrite_fmt(stream, "GAME_COMMAND\n");
phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
break;
case Type::EP3_GAME_COMMAND:
fprintf(stream, "EP3_GAME_COMMAND\n");
phosg::fwrite_fmt(stream, "EP3_GAME_COMMAND\n");
phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
break;
case Type::CHAT_MESSAGE:
fprintf(stream, "CHAT_MESSAGE %08" PRIX32 "\n", this->guild_card_number);
phosg::fwrite_fmt(stream, "CHAT_MESSAGE {:08X}\n", this->guild_card_number);
phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
break;
case Type::SERVER_DATA_COMMAND:
fprintf(stream, "SERVER_DATA_COMMAND\n");
phosg::fwrite_fmt(stream, "SERVER_DATA_COMMAND\n");
phosg::print_data(stream, this->data, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
break;
default:
@@ -363,26 +363,24 @@ void BattleRecord::set_battle_end_timestamp() {
void BattleRecord::print(FILE* stream) const {
string start_str = phosg::format_time(this->battle_start_timestamp);
string end_str = phosg::format_time(this->battle_end_timestamp);
fprintf(stream, "BattleRecord %s behavior_flags=%08" PRIX32 " start=%016" PRIX64 " (%s) end=%016" PRIX64 " (%s); %zu events\n",
phosg::fwrite_fmt(stream, "BattleRecord {} behavior_flags={:08X} start={:016X} ({}) end={:016X} ({}); {} events\n",
this->is_writable ? "writable" : "read-only",
this->behavior_flags,
this->battle_start_timestamp,
start_str.c_str(),
start_str,
this->battle_end_timestamp,
end_str.c_str(), this->events.size());
end_str, this->events.size());
for (const auto& event : this->events) {
event.print(stream);
}
}
BattleRecordPlayer::BattleRecordPlayer(
shared_ptr<const BattleRecord> rec,
shared_ptr<struct event_base> base)
: record(rec),
BattleRecordPlayer::BattleRecordPlayer(std::shared_ptr<asio::io_context> io_context, shared_ptr<const BattleRecord> rec)
: io_context(io_context),
record(rec),
event_it(this->record->events.begin()),
play_start_timestamp(0),
base(base),
next_command_ev(event_new(this->base.get(), -1, EV_TIMEOUT, &BattleRecordPlayer::dispatch_schedule_events, this), event_free) {}
next_command_timer(*this->io_context) {}
shared_ptr<const BattleRecord> BattleRecordPlayer::get_record() const {
return this->record;
@@ -395,40 +393,37 @@ void BattleRecordPlayer::set_lobby(shared_ptr<Lobby> l) {
void BattleRecordPlayer::start() {
if (this->play_start_timestamp == 0) {
this->play_start_timestamp = phosg::now();
this->schedule_events();
asio::co_spawn(*this->io_context, this->play_task(), asio::detached);
}
}
void BattleRecordPlayer::dispatch_schedule_events(evutil_socket_t, short, void* ctx) {
reinterpret_cast<BattleRecordPlayer*>(ctx)->schedule_events();
}
void BattleRecordPlayer::schedule_events() {
// If the lobby is destroyed, we can't replay anything - just return without
// rescheduling
asio::awaitable<void> BattleRecordPlayer::play_task() {
auto l = this->lobby.lock();
if (!l) {
return;
}
for (;;) {
uint64_t relative_ts = phosg::now() - this->play_start_timestamp + this->record->battle_start_timestamp;
// If the lobby is destroyed, we can't replay anything
if (!l) {
co_return;
}
if (this->event_it == this->record->events.end()) {
if (relative_ts >= this->record->battle_end_timestamp) {
// If the record is complete and the end timestamp has been reached,
// send exit commands to all players in the lobby, and don't reschedule
// the event (it will be deleted along with the Player when the lobby is
// destroyed, when the last client leaves)
// the event (it will be deleted along with the Player when the lobby
// is destroyed, when the last client leaves)
send_command(l, 0xED, 0x00);
break;
} else {
// There are no more events to play, but the battle has not officially
// ended yet - reschedule the event for the end time
auto tv = phosg::usecs_to_timeval(this->record->battle_end_timestamp - relative_ts);
event_add(this->next_command_ev.get(), &tv);
// There are no more events to play, but the battle has not actually
// ended yet; wait until the end time
this->next_command_timer.expires_after(std::chrono::microseconds(this->record->battle_end_timestamp - relative_ts));
co_await this->next_command_timer.async_wait(asio::use_awaitable);
l = this->lobby.lock();
}
break;
} else {
if (this->event_it->timestamp <= relative_ts) {
@@ -464,11 +459,10 @@ void BattleRecordPlayer::schedule_events() {
this->event_it++;
} else {
// The next event should not occur yet, so reschedule for the time when
// it should occur
auto tv = phosg::usecs_to_timeval(this->event_it->timestamp - relative_ts);
event_add(this->next_command_ev.get(), &tv);
break;
// The next event should not occur yet, so wait until its time
this->next_command_timer.expires_after(std::chrono::microseconds(this->event_it->timestamp - relative_ts));
co_await this->next_command_timer.async_wait(asio::use_awaitable);
l = this->lobby.lock();
}
}
}
+6 -8
View File
@@ -1,8 +1,8 @@
#pragma once
#include <event2/event.h>
#include <stdint.h>
#include <asio.hpp>
#include <deque>
#include <memory>
#include <phosg/Strings.hh>
@@ -108,7 +108,7 @@ private:
class BattleRecordPlayer {
public:
BattleRecordPlayer(std::shared_ptr<const BattleRecord> rec, std::shared_ptr<struct event_base> base);
BattleRecordPlayer(std::shared_ptr<asio::io_context> io_context, std::shared_ptr<const BattleRecord> rec);
~BattleRecordPlayer() = default;
std::shared_ptr<const BattleRecord> get_record() const;
@@ -117,16 +117,14 @@ public:
void start();
private:
static void dispatch_schedule_events(evutil_socket_t, short, void* ctx);
void schedule_events();
std::shared_ptr<asio::io_context> io_context;
std::shared_ptr<const BattleRecord> record;
std::deque<BattleRecord::Event>::const_iterator event_it;
uint64_t play_start_timestamp;
std::shared_ptr<struct event_base> base;
std::weak_ptr<Lobby> lobby;
std::shared_ptr<struct event> next_command_ev;
phosg::StringReader random_r;
asio::steady_timer next_command_timer;
asio::awaitable<void> play_task();
};
} // namespace Episode3
+87 -86
View File
@@ -123,7 +123,7 @@ ssize_t Card::apply_abnormal_condition(
int8_t dice_roll_value,
int8_t random_percent) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("apply_abnormal_condition(%02hhX, @%04X, @%04X, %hd, %hhd, %hhd): ", def_effect_index, target_card_ref, sc_card_ref, value, dice_roll_value, random_percent));
auto log = s->log_stack(std::format("apply_abnormal_condition({:02X}, @{:04X}, @{:04X}, {}, {}, {}): ", def_effect_index, target_card_ref, sc_card_ref, value, dice_roll_value, random_percent));
bool is_nte = s->options.is_nte();
ssize_t existing_cond_index;
@@ -150,13 +150,13 @@ ssize_t Card::apply_abnormal_condition(
break;
}
}
log.debug("existing_cond_index < 0 (new condition) => cond_index = %zd", cond_index);
log.debug_f("existing_cond_index < 0 (new condition) => cond_index = {}", cond_index);
} else {
log.debug("existing_cond_index = %zd (existing condition)", existing_cond_index);
log.debug_f("existing_cond_index = {} (existing condition)", existing_cond_index);
}
if (cond_index < 0) {
log.debug("no space for condition");
log.debug_f("no space for condition");
return -1;
}
@@ -164,7 +164,7 @@ ssize_t Card::apply_abnormal_condition(
auto& cond = this->action_chain.conditions[cond_index];
if ((eff.type == ConditionType::MV_BONUS) && (cond.type == ConditionType::MV_BONUS)) {
existing_cond_value = clamp<int16_t>(cond.value, -99, 99);
log.debug("MV_BONUS combines => existing_cond_value = %hd", existing_cond_value);
log.debug_f("MV_BONUS combines => existing_cond_value = {}", existing_cond_value);
}
s->card_special->apply_stat_deltas_to_card_from_condition_and_clear_cond(cond, this->shared_from_this());
@@ -205,7 +205,7 @@ ssize_t Card::apply_abnormal_condition(
}
string cond_str = cond.str(s);
log.debug("wrote condition %zd => %s", cond_index, cond_str.c_str());
log.debug_f("wrote condition {} => {}", cond_index, cond_str);
if (!is_nte) {
s->card_special->update_condition_orders(this->shared_from_this());
@@ -214,7 +214,7 @@ ssize_t Card::apply_abnormal_condition(
continue;
}
string cond_str = cond.str(s);
log.debug("sorted conditions: [%zu] => %s", z, cond_str.c_str());
log.debug_f("sorted conditions: [{}] => {}", z, cond_str);
}
}
@@ -298,13 +298,13 @@ void Card::commit_attack(
size_t strike_number,
int16_t* out_effective_damage) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("commit_attack(@%04hX #%04hX, @%04hX #%04hX => %hd (str%zu)): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id(), damage, strike_number));
auto log = s->log_stack(std::format("commit_attack(@{:04X} #{:04X}, @{:04X} #{:04X} => {} (str{})): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id(), damage, strike_number));
bool is_nte = s->options.is_nte();
int16_t effective_damage = damage;
s->card_special->adjust_attack_damage_due_to_conditions(
this->shared_from_this(), &effective_damage, attacker_card->get_card_ref());
log.debug("adjusted damage = %hd", effective_damage);
log.debug_f("adjusted damage = {}", effective_damage);
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++) {
@@ -324,36 +324,36 @@ void Card::commit_attack(
}
}
}
log.debug("after assists = %hd", effective_damage);
log.debug_f("after assists = {}", effective_damage);
if (this->action_metadata.check_flag(0x10)) {
effective_damage = 0;
log.debug("flag 0x10 => effective damage = %hd", effective_damage);
log.debug_f("flag 0x10 => effective damage = {}", effective_damage);
}
auto attacker_ps = attacker_card->player_state();
attacker_ps->stats.damage_given += effective_damage;
this->player_state()->stats.damage_taken += effective_damage;
log.debug("updated stats");
log.debug_f("updated stats");
this->current_hp = clamp<int16_t>(this->current_hp - effective_damage, 0, this->max_hp);
log.debug("hp set to %hd", this->current_hp);
log.debug_f("hp set to {}", this->current_hp);
if ((effective_damage > 0) &&
(attacker_ps->stats.max_attack_damage < effective_damage)) {
attacker_ps->stats.max_attack_damage = effective_damage;
log.debug("attacker new max damage %hd", effective_damage);
log.debug_f("attacker new max damage {}", effective_damage);
}
this->last_attack_final_damage = effective_damage;
log.debug("last attack final damage = %hd", effective_damage);
log.debug_f("last attack final damage = {}", effective_damage);
if (effective_damage > 0) {
this->card_flags = this->card_flags | 4;
log.debug("set flag 4");
log.debug_f("set flag 4");
}
if (this->current_hp < 1) {
this->destroy_set_card(attacker_card);
log.debug("card destroyed");
log.debug_f("card destroyed");
}
G_ApplyConditionEffect_Ep3_6xB4x06 cmd_to_send;
@@ -507,19 +507,19 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
}
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("execute_attack(@%04X #%04X, @%04X #%04X): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id()));
auto log = s->log_stack(std::format("execute_attack(@{:04X} #{:04X}, @{:04X} #{:04X}): ", this->get_card_ref(), this->get_card_id(), attacker_card->get_card_ref(), attacker_card->get_card_id()));
bool is_nte = s->options.is_nte();
this->card_flags &= 0xFFFFFFF3;
int16_t attack_ap = this->action_metadata.attack_bonus;
int16_t attack_tp = 0;
int16_t defense_power = is_nte ? 0 : this->compute_defense_power_for_attacker_card(attacker_card);
log.debug("ap=%hd, tp=%hd", attack_ap, attack_tp);
log.debug_f("ap={}, tp={}", attack_ap, attack_tp);
if (!is_nte && (attack_ap == 0) && !this->action_metadata.check_flag(0x20)) {
log.debug("ap == 0 and flag 0x20 not set");
log.debug_f("ap == 0 and flag 0x20 not set");
return;
} else {
log.debug("ap != 0 or flag 0x20 set; continuing...");
log.debug_f("ap != 0 or flag 0x20 set; continuing...");
}
G_ApplyConditionEffect_Ep3_6xB4x06 cmd;
@@ -542,7 +542,7 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
if (is_nte) {
defense_power = this->compute_defense_power_for_attacker_card(attacker_card);
log.debug("ap=%hd, tp=%hd, defense=%hd", attack_ap, attack_tp, defense_power);
log.debug_f("ap={}, tp={}, defense={}", attack_ap, attack_tp, defense_power);
attacker_card->compute_action_chain_results(true, false);
attack_ap = attacker_card->action_chain.chain.damage;
if (this->action_chain.chain.attack_medium == AttackMedium::TECH) {
@@ -553,14 +553,14 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
}
s->card_special->compute_attack_ap(this->shared_from_this(), &attack_ap, attacker_card->get_card_ref());
log.debug("computed ap %hd", attack_ap);
log.debug_f("computed ap {}", attack_ap);
this->apply_ap_and_tp_adjust_assists_to_attack(attacker_card, &attack_ap, &defense_power, &attack_tp);
log.debug("assist adjusts ap=%hd, defense=%hd", attack_ap, defense_power);
log.debug_f("assist adjusts ap={}, defense={}", attack_ap, defense_power);
int16_t raw_damage = attack_ap - defense_power;
int16_t preliminary_damage = max<int16_t>(raw_damage, 0) - attack_tp;
this->last_attack_preliminary_damage = preliminary_damage;
log.debug("raw_damage=%hd, preliminary_damange=%hd", raw_damage, preliminary_damage);
log.debug_f("raw_damage={}, preliminary_damange={}", raw_damage, preliminary_damage);
uint32_t unknown_a9 = 0;
auto target = s->card_special->compute_replaced_target_based_on_conditions(
@@ -568,19 +568,19 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
if (!target) {
target = this->shared_from_this();
log.debug("target is not replaced");
log.debug_f("target is not replaced");
} else {
log.debug("target replaced with @%04hX #%04hX", target->get_card_ref(), target->get_card_id());
log.debug_f("target replaced with @{:04X} #{:04X}", target->get_card_ref(), target->get_card_id());
}
if (!is_nte) {
if (unknown_a9 != 0) {
preliminary_damage = 0;
log.debug("a9 nonzero; preliminary_damage = 0");
log.debug_f("a9 nonzero; preliminary_damage = 0");
}
if (!(this->card_flags & 2) && (!attacker_card || !(attacker_card->card_flags & 2))) {
s->card_special->check_for_defense_interference(attacker_card, this->shared_from_this(), &preliminary_damage);
log.debug("checked for defense interference");
log.debug_f("checked for defense interference");
}
}
@@ -592,19 +592,19 @@ void Card::execute_attack(shared_ptr<Card> attacker_card) {
ps->stats.num_attacks_taken++;
if (!(target->card_flags & 2)) {
log.debug("flag 2 not set");
log.debug_f("flag 2 not set");
for (size_t strike_num = 0; strike_num < attacker_card->action_chain.chain.strike_count; strike_num++) {
int16_t final_effective_damage = 0;
target->commit_attack(preliminary_damage, attacker_card, &cmd, strike_num, &final_effective_damage);
ps->stats.action_card_negated_damage += max<int16_t>(0, this->current_defense_power - final_effective_damage);
}
} else {
log.debug("flag 2 set; committing zero-damage attack");
log.debug_f("flag 2 set; committing zero-damage attack");
target->commit_attack(0, attacker_card, &cmd, 0, nullptr);
}
if (!is_nte && (this != target.get())) {
log.debug("target was replaced; committing zero-damage attack on original card");
log.debug_f("target was replaced; committing zero-damage attack on original card");
this->commit_attack(0, attacker_card, &cmd, 0, nullptr);
}
@@ -717,7 +717,7 @@ int32_t Card::move_to_location(const Location& loc) {
G_EnqueueAnimation_Ep3_6xB4x2C cmd;
cmd.change_type = 1;
cmd.client_id = other_ps->client_id;
cmd.unknown_a2[0] = trap_card_id;
cmd.trap_card_id = trap_card_id;
s->send(cmd);
}
}
@@ -736,7 +736,8 @@ int32_t Card::move_to_location(const Location& loc) {
cmd.change_type = 0;
cmd.card_refs.clear(0xFFFF);
cmd.card_refs[0] = this->card_ref;
cmd.unknown_a2.clear(0xFFFFFFFF);
cmd.trap_card_id = 0xFFFFFFFF;
cmd.unknown_a3 = 0xFFFFFFFF;
s->send(cmd);
return 0;
}
@@ -905,7 +906,7 @@ 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(phosg::string_printf("compute_action_chain_results(@%04hX #%04hX): ", 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);
@@ -913,7 +914,7 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
this->action_chain.chain.ap_effect_bonus = 0;
this->action_chain.chain.tp_effect_bonus = 0;
log.debug("(initial) medium=%s, strike_count=%hhu, ap_effect_bonus=%hhd, tp_effect_bonus=%hhd",
log.debug_f("(initial) medium={}, strike_count={}, ap_effect_bonus={}, tp_effect_bonus={}",
phosg::name_for_enum(this->action_chain.chain.attack_medium),
this->action_chain.chain.strike_count,
this->action_chain.chain.ap_effect_bonus,
@@ -928,9 +929,9 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
stat_swap_type = StatSwapType::NONE;
} else {
stat_swap_type = s->card_special->compute_stat_swap_type(this->shared_from_this());
log.debug("stat_swap_type = %zu (0=none, 1=a/t, 2=a/h)", static_cast<size_t>(stat_swap_type));
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);
log.debug("effective_ap = %hd, effective_tp = %hd", effective_ap, effective_tp);
log.debug_f("effective_ap = {}, effective_tp = {}", effective_ap, effective_tp);
}
// This option doesn't exist in NTE
@@ -941,7 +942,7 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
if (ce) {
effective_ap += ce->def.ap.stat;
effective_tp += ce->def.tp.stat;
log.debug("(action card @%04hX) updated effective_ap = %hd, effective_tp = %hd", this->action_chain.chain.attack_action_card_refs[z].load(), effective_ap, effective_tp);
log.debug_f("(action card @{:04X}) updated effective_ap = {}, effective_tp = {}", this->action_chain.chain.attack_action_card_refs[z], effective_ap, effective_tp);
}
}
@@ -956,7 +957,7 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
stat_swap_type, &card_ap, &card_tp, card->get_current_hp(), card->ap, card->tp);
effective_ap += card_ap;
effective_tp += card_tp;
log.debug("(mag card set_index %zu @%04hX) updated effective_ap = %hd, effective_tp = %hd",
log.debug_f("(mag card set_index {} @{:04X}) updated effective_ap = {}, effective_tp = {}",
set_index, card->get_card_ref(), effective_ap, effective_tp);
}
}
@@ -967,25 +968,25 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
sc_card->compute_action_chain_results(apply_action_conditions, true);
effective_ap += sc_card->action_chain.chain.effective_ap + sc_card->action_chain.chain.ap_effect_bonus;
effective_tp += sc_card->action_chain.chain.effective_tp + sc_card->action_chain.chain.tp_effect_bonus;
log.debug("(item is attacking; adding SC stats) updated effective_ap = %hd, effective_tp = %hd",
log.debug_f("(item is attacking; adding SC stats) updated effective_ap = {}, effective_tp = {}",
effective_ap, effective_tp);
}
if (!this->action_chain.check_flag(0x10)) {
this->action_chain.chain.effective_ap = is_nte ? effective_ap : min<int16_t>(effective_ap, 99);
log.debug("set chain effective_ap = %hd", this->action_chain.chain.effective_ap);
log.debug_f("set chain effective_ap = {}", this->action_chain.chain.effective_ap);
}
if (!this->action_chain.check_flag(0x20)) {
this->action_chain.chain.effective_tp = is_nte ? effective_tp : min<int16_t>(effective_tp, 99);
log.debug("set chain effective_tp = %hd", this->action_chain.chain.effective_tp);
log.debug_f("set chain effective_tp = {}", this->action_chain.chain.effective_tp);
}
if (apply_action_conditions) {
auto this_sh = this->shared_from_this();
s->card_special->apply_action_conditions(EffectWhen::BEFORE_ANY_CARD_ATTACK, this_sh, this_sh, 1, nullptr);
log.debug("applied action conditions (1)");
log.debug_f("applied action conditions (1)");
} else {
log.debug("skipped applying action conditions (1)");
log.debug_f("skipped applying action conditions (1)");
}
size_t num_assists = s->assist_server->compute_num_assist_effects_for_client(this->client_id);
@@ -1105,29 +1106,29 @@ 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("(tech) damage = %hhd (eff) + %hhd (bonus) = %hd", 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("(physical) damage = %hhd (eff) + %hhd (bonus) = %hd", 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("(unknown attack medium) damage = 0");
log.debug_f("(unknown attack medium) damage = 0");
}
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("overall chain damage = %hd (base) * %hhd (mult) = %hhd", 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();
s->card_special->apply_action_conditions(EffectWhen::BEFORE_ANY_CARD_ATTACK, this_sh, this_sh, 2, nullptr);
log.debug("applied action conditions (2)");
log.debug_f("applied action conditions (2)");
if (!is_nte && this->action_chain.check_flag(0x100)) {
this->action_chain.chain.damage = min<int16_t>(this->action_chain.chain.damage + 5, 99);
log.debug("(has flag 0x100) chain damage = %hhd", this->action_chain.chain.damage);
log.debug_f("(has flag 0x100) chain damage = {}", this->action_chain.chain.damage);
}
} else {
log.debug("skipped applying action conditions (2)");
log.debug_f("skipped applying action conditions (2)");
}
if (!is_nte) {
@@ -1155,9 +1156,9 @@ void Card::compute_action_chain_results(bool apply_action_conditions, bool ignor
}
}
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string chain_str = this->action_chain.str(s);
log.debug("result computed as %s", chain_str.c_str());
log.debug_f("result computed as {}", chain_str);
}
}
@@ -1225,24 +1226,24 @@ void Card::move_phase_before() {
void Card::unknown_80236374(shared_ptr<Card> other_card, const ActionState* as) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("unknown_80236374(@%04hX #%04hX, @%04hX #%04hX): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id()));
auto log = s->log_stack(std::format("unknown_80236374(@{:04X} #{:04X}, @{:04X} #{:04X}): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id()));
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
if (as) {
string as_str = as->str(s);
log.debug("as = %s", as_str.c_str());
log.debug_f("as = {}", as_str);
} else {
log.debug("as = null");
log.debug_f("as = null");
}
}
auto check_card = [&](shared_ptr<Card> card) -> void {
if (card) {
if (!card->unknown_80236554(other_card, as)) {
log.debug("check_card @%04hX #%04hX => false", card->get_card_ref(), card->get_card_id());
log.debug_f("check_card @{:04X} #{:04X} => false", card->get_card_ref(), card->get_card_id());
card->action_metadata.clear_flags(0x20);
} else {
log.debug("check_card @%04hX #%04hX => true", card->get_card_ref(), card->get_card_id());
log.debug_f("check_card @{:04X} #{:04X} => true", card->get_card_ref(), card->get_card_id());
card->action_metadata.set_flags(0x20);
}
}
@@ -1377,14 +1378,14 @@ bool Card::is_guard_item() const {
bool Card::unknown_80236554(shared_ptr<Card> other_card, const ActionState* as) {
auto s = this->server();
auto log = s->log_stack(other_card
? phosg::string_printf("unknown_80236554(@%04hX #%04hX, @%04hX #%04hX): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id())
: phosg::string_printf("unknown_80236554(@%04hX #%04hX, null): ", this->get_card_ref(), this->get_card_id()));
if (log.should_log(phosg::LogLevel::DEBUG)) {
? std::format("unknown_80236554(@{:04X} #{:04X}, @{:04X} #{:04X}): ", this->get_card_ref(), this->get_card_id(), other_card->get_card_ref(), other_card->get_card_id())
: 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("as = %s", as_str.c_str());
log.debug_f("as = {}", as_str);
} else {
log.debug("as = null");
log.debug_f("as = null");
}
}
@@ -1397,7 +1398,7 @@ bool Card::unknown_80236554(shared_ptr<Card> other_card, const ActionState* as)
if (other_card->action_chain.chain.target_card_refs[z] == this->get_card_ref()) {
attack_bonus = other_card->action_chain.chain.damage;
ret = true;
log.debug("attack_bonus = %hd (matched other_card->action_chain.chain.target_card_refs)", attack_bonus);
log.debug_f("attack_bonus = {} (matched other_card->action_chain.chain.target_card_refs)", attack_bonus);
break;
}
}
@@ -1405,7 +1406,7 @@ bool Card::unknown_80236554(shared_ptr<Card> other_card, const ActionState* as)
for (size_t z = 0; (z < 4 * 9) && (as->target_card_refs[z] != 0xFFFF); z++) {
if (as->target_card_refs[z] == this->get_card_ref()) {
attack_bonus = other_card->action_chain.chain.damage;
log.debug("attack_bonus = %hd (matched as->target_card_refs)", attack_bonus);
log.debug_f("attack_bonus = {} (matched as->target_card_refs)", attack_bonus);
ret = true;
break;
}
@@ -1414,26 +1415,26 @@ bool Card::unknown_80236554(shared_ptr<Card> other_card, const ActionState* as)
}
this->action_metadata.attack_bonus = max<int16_t>(attack_bonus, 0);
log.debug("attack_bonus = %hhd", this->action_metadata.attack_bonus);
log.debug_f("attack_bonus = {}", this->action_metadata.attack_bonus);
this->last_attack_preliminary_damage = 0;
this->last_attack_final_damage = 0;
log.debug("last attack damage stats cleared");
log.debug_f("last attack damage stats cleared");
if (other_card) {
log.debug("applying BEFORE_ANY_CARD_ATTACK conditions");
log.debug_f("applying BEFORE_ANY_CARD_ATTACK conditions");
s->card_special->apply_action_conditions(
EffectWhen::BEFORE_ANY_CARD_ATTACK, other_card, this->shared_from_this(), 0x20, as);
log.debug("applying BEFORE_THIS_CARD_ATTACKED conditions");
log.debug_f("applying BEFORE_THIS_CARD_ATTACKED conditions");
s->card_special->apply_action_conditions(
EffectWhen::BEFORE_THIS_CARD_ATTACKED, other_card, this->shared_from_this(), 0x40, as);
if (other_card->action_chain.check_flag(0x20000)) {
log.debug("attack_bonus cleared due to cancellation");
log.debug_f("attack_bonus cleared due to cancellation");
this->action_metadata.attack_bonus = 0;
return ret;
}
}
if (this->card_flags & 2) {
log.debug("attack_bonus cleared due to destruction");
log.debug_f("attack_bonus cleared due to destruction");
this->action_metadata.attack_bonus = 0;
}
return ret;
@@ -1463,7 +1464,7 @@ void Card::apply_attack_result() {
auto ps = this->player_state();
bool is_nte = s->options.is_nte();
auto log = s->log_stack(phosg::string_printf("apply_attack_result(@%04hX #%04hX): ", this->get_card_ref(), this->get_card_id()));
auto log = s->log_stack(std::format("apply_attack_result(@{:04X} #{:04X}): ", this->get_card_ref(), this->get_card_id()));
if (!this->action_chain.can_apply_attack()) {
return;
}
@@ -1572,9 +1573,9 @@ void Card::apply_attack_result() {
}
}
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string as_str = as.str(s);
log.debug("as constructed as %s", as_str.c_str());
log.debug_f("as constructed as {}", as_str);
}
for (size_t z = 0; z < this->action_chain.chain.target_card_ref_count; z++) {
@@ -1582,36 +1583,36 @@ void Card::apply_attack_result() {
if (card) {
card->current_defense_power = card->action_metadata.attack_bonus;
if (!this->action_chain.check_flag(0x40)) {
log.debug("unknown_8024A6DC(@%04hX #%04hX) ...", card->get_card_ref(), card->get_card_id());
log.debug_f("unknown_8024A6DC(@{:04X} #{:04X}) ...", card->get_card_ref(), card->get_card_id());
s->card_special->unknown_8024A6DC(this->shared_from_this(), card);
}
}
}
log.debug("compute_action_chain_results 1 ...");
log.debug_f("compute_action_chain_results 1 ...");
this->compute_action_chain_results(true, false);
if (!this->action_chain.check_flag(0x40)) {
log.debug("apply_effects_before_attack ...");
log.debug_f("apply_effects_before_attack ...");
s->card_special->apply_effects_before_attack(this->shared_from_this());
}
if (!(this->card_flags & 2)) {
log.debug("compute_action_chain_results 2 ...");
log.debug_f("compute_action_chain_results 2 ...");
this->compute_action_chain_results(true, false);
log.debug("check_for_attack_interference ...");
log.debug_f("check_for_attack_interference ...");
s->card_special->check_for_attack_interference(this->shared_from_this());
}
log.debug("compute_action_chain_results 3 ...");
log.debug_f("compute_action_chain_results 3 ...");
this->compute_action_chain_results(true, false);
log.debug("unknown_80236374 ...");
log.debug_f("unknown_80236374 ...");
this->unknown_80236374(this->shared_from_this(), nullptr);
log.debug("execute_attack_on_all_valid_targets ...");
log.debug_f("execute_attack_on_all_valid_targets ...");
this->execute_attack_on_all_valid_targets(this->shared_from_this());
}
if (!this->action_chain.check_flag(0x40)) {
log.debug("apply_effects_after_attack ...");
log.debug_f("apply_effects_after_attack ...");
s->card_special->apply_effects_after_attack(this->shared_from_this());
}
ps->stats.num_attacks_given++;
@@ -1624,7 +1625,7 @@ void Card::apply_attack_result() {
for (size_t client_id = 0; client_id < 4; client_id++) {
auto ps = s->player_states[client_id];
if (ps) {
log.debug("unknown_8023C110(%zu) ...", client_id);
log.debug_f("unknown_8023C110({}) ...", client_id);
ps->unknown_8023C110();
}
}
+195 -195
View File
@@ -21,7 +21,7 @@ static string refs_str_for_cards_vector(const vector<shared_ptr<T>>& cards) {
if (!ret.empty()) {
ret += ", ";
}
ret += phosg::string_printf("@%04hX", ref_for_card(card));
ret += std::format("@{:04X}", ref_for_card(card));
}
return ret;
}
@@ -89,45 +89,45 @@ uint32_t CardSpecial::AttackEnvStats::at(size_t index) const {
}
void CardSpecial::AttackEnvStats::print(FILE* stream) const {
fprintf(stream, "(a) total_num_set_cards = %" PRIu32 "\n", this->total_num_set_cards);
fprintf(stream, "(ab) num_a_beast_creatures = %" PRIu32 "\n", this->num_a_beast_creatures);
fprintf(stream, "(ac) player_num_atk_points = %" PRIu32 "\n", this->player_num_atk_points);
fprintf(stream, "(adm) sc_effective_ap = %" PRIu32 "\n", this->sc_effective_ap);
fprintf(stream, "(ap) effective_ap = %" PRIu32 "\n", this->effective_ap);
fprintf(stream, "(bi) num_native_creatures = %" PRIu32 "\n", this->num_native_creatures);
fprintf(stream, "(cs) card_cost = %" PRIu32 "\n", this->card_cost);
fprintf(stream, "(d) dice_roll_value1 = %" PRIu32 "\n", this->dice_roll_value1);
fprintf(stream, "(dc) dice_roll_value2 = %" PRIu32 "\n", this->dice_roll_value2);
fprintf(stream, "(ddm) attack_bonus = %" PRIu32 "\n", this->attack_bonus);
fprintf(stream, "(df) num_destroyed_ally_fcs = %" PRIu32 "\n", this->num_destroyed_ally_fcs);
fprintf(stream, "(dk) num_dark_creatures = %" PRIu32 "\n", this->num_dark_creatures);
fprintf(stream, "(dm) effective_ap_if_not_tech = %" PRIu32 "\n", this->effective_ap_if_not_tech);
fprintf(stream, "(dn) unknown_a1 = %" PRIu32 "\n", this->unknown_a1);
fprintf(stream, "(edm) target_attack_bonus = %" PRIu32 "\n", this->target_attack_bonus);
fprintf(stream, "(ef) non_target_team_num_set_cards = %" PRIu32 "\n", this->non_target_team_num_set_cards);
fprintf(stream, "(ehp) target_current_hp = %" PRIu32 "\n", this->target_current_hp);
fprintf(stream, "(f) num_set_cards = %" PRIu32 "\n", this->num_set_cards);
fprintf(stream, "(fdm) final_last_attack_damage = %" PRIu32 "\n", this->final_last_attack_damage);
fprintf(stream, "(ff) target_team_num_set_cards = %" PRIu32 "\n", this->target_team_num_set_cards);
fprintf(stream, "(gn) num_gun_type_items = %" PRIu32 "\n", this->num_gun_type_items);
fprintf(stream, "(hf) num_item_or_creature_cards_in_hand = %" PRIu32 "\n", this->num_item_or_creature_cards_in_hand);
fprintf(stream, "(hp) current_hp = %" PRIu32 "\n", this->current_hp);
fprintf(stream, "(kap) action_cards_ap = %" PRIu32 "\n", this->action_cards_ap);
fprintf(stream, "(ktp) action_cards_tp = %" PRIu32 "\n", this->action_cards_tp);
fprintf(stream, "(ldm) last_attack_preliminary_damage = %" PRIu32 "\n", this->last_attack_preliminary_damage);
fprintf(stream, "(lv) team_dice_bonus = %" PRIu32 "\n", this->team_dice_bonus);
fprintf(stream, "(mc) num_machine_creatures = %" PRIu32 "\n", this->num_machine_creatures);
fprintf(stream, "(mhp) max_hp = %" PRIu32 "\n", this->max_hp);
fprintf(stream, "(ndm) last_attack_damage_count = %" PRIu32 "\n", this->last_attack_damage_count);
fprintf(stream, "(php) defined_max_hp = %" PRIu32 "\n", this->defined_max_hp);
fprintf(stream, "(rdm) last_attack_damage = %" PRIu32 "\n", this->last_attack_damage);
fprintf(stream, "(sa) num_sword_type_items = %" PRIu32 "\n", this->num_sword_type_items);
fprintf(stream, "(sat) num_sword_type_items_on_team = %" PRIu32 "\n", this->num_sword_type_items_on_team);
fprintf(stream, "(tdm) effective_ap_if_not_physical = %" PRIu32 "\n", this->effective_ap_if_not_physical);
fprintf(stream, "(tf) player_num_destroyed_fcs = %" PRIu32 "\n", this->player_num_destroyed_fcs);
fprintf(stream, "(tp) effective_tp = %" PRIu32 "\n", this->effective_tp);
fprintf(stream, "(tt) effective_ap_if_not_tech2 = %" PRIu32 "\n", this->effective_ap_if_not_tech2);
fprintf(stream, "(wd) num_cane_type_items = %" PRIu32 "\n", this->num_cane_type_items);
phosg::fwrite_fmt(stream, "(a) total_num_set_cards = {}\n", this->total_num_set_cards);
phosg::fwrite_fmt(stream, "(ab) num_a_beast_creatures = {}\n", this->num_a_beast_creatures);
phosg::fwrite_fmt(stream, "(ac) player_num_atk_points = {}\n", this->player_num_atk_points);
phosg::fwrite_fmt(stream, "(adm) sc_effective_ap = {}\n", this->sc_effective_ap);
phosg::fwrite_fmt(stream, "(ap) effective_ap = {}\n", this->effective_ap);
phosg::fwrite_fmt(stream, "(bi) num_native_creatures = {}\n", this->num_native_creatures);
phosg::fwrite_fmt(stream, "(cs) card_cost = {}\n", this->card_cost);
phosg::fwrite_fmt(stream, "(d) dice_roll_value1 = {}\n", this->dice_roll_value1);
phosg::fwrite_fmt(stream, "(dc) dice_roll_value2 = {}\n", this->dice_roll_value2);
phosg::fwrite_fmt(stream, "(ddm) attack_bonus = {}\n", this->attack_bonus);
phosg::fwrite_fmt(stream, "(df) num_destroyed_ally_fcs = {}\n", this->num_destroyed_ally_fcs);
phosg::fwrite_fmt(stream, "(dk) num_dark_creatures = {}\n", this->num_dark_creatures);
phosg::fwrite_fmt(stream, "(dm) effective_ap_if_not_tech = {}\n", this->effective_ap_if_not_tech);
phosg::fwrite_fmt(stream, "(dn) unknown_a1 = {}\n", this->unknown_a1);
phosg::fwrite_fmt(stream, "(edm) target_attack_bonus = {}\n", this->target_attack_bonus);
phosg::fwrite_fmt(stream, "(ef) non_target_team_num_set_cards = {}\n", this->non_target_team_num_set_cards);
phosg::fwrite_fmt(stream, "(ehp) target_current_hp = {}\n", this->target_current_hp);
phosg::fwrite_fmt(stream, "(f) num_set_cards = {}\n", this->num_set_cards);
phosg::fwrite_fmt(stream, "(fdm) final_last_attack_damage = {}\n", this->final_last_attack_damage);
phosg::fwrite_fmt(stream, "(ff) target_team_num_set_cards = {}\n", this->target_team_num_set_cards);
phosg::fwrite_fmt(stream, "(gn) num_gun_type_items = {}\n", this->num_gun_type_items);
phosg::fwrite_fmt(stream, "(hf) num_item_or_creature_cards_in_hand = {}\n", this->num_item_or_creature_cards_in_hand);
phosg::fwrite_fmt(stream, "(hp) current_hp = {}\n", this->current_hp);
phosg::fwrite_fmt(stream, "(kap) action_cards_ap = {}\n", this->action_cards_ap);
phosg::fwrite_fmt(stream, "(ktp) action_cards_tp = {}\n", this->action_cards_tp);
phosg::fwrite_fmt(stream, "(ldm) last_attack_preliminary_damage = {}\n", this->last_attack_preliminary_damage);
phosg::fwrite_fmt(stream, "(lv) team_dice_bonus = {}\n", this->team_dice_bonus);
phosg::fwrite_fmt(stream, "(mc) num_machine_creatures = {}\n", this->num_machine_creatures);
phosg::fwrite_fmt(stream, "(mhp) max_hp = {}\n", this->max_hp);
phosg::fwrite_fmt(stream, "(ndm) last_attack_damage_count = {}\n", this->last_attack_damage_count);
phosg::fwrite_fmt(stream, "(php) defined_max_hp = {}\n", this->defined_max_hp);
phosg::fwrite_fmt(stream, "(rdm) last_attack_damage = {}\n", this->last_attack_damage);
phosg::fwrite_fmt(stream, "(sa) num_sword_type_items = {}\n", this->num_sword_type_items);
phosg::fwrite_fmt(stream, "(sat) num_sword_type_items_on_team = {}\n", this->num_sword_type_items_on_team);
phosg::fwrite_fmt(stream, "(tdm) effective_ap_if_not_physical = {}\n", this->effective_ap_if_not_physical);
phosg::fwrite_fmt(stream, "(tf) player_num_destroyed_fcs = {}\n", this->player_num_destroyed_fcs);
phosg::fwrite_fmt(stream, "(tp) effective_tp = {}\n", this->effective_tp);
phosg::fwrite_fmt(stream, "(tt) effective_ap_if_not_tech2 = {}\n", this->effective_ap_if_not_tech2);
phosg::fwrite_fmt(stream, "(wd) num_cane_type_items = {}\n", this->num_cane_type_items);
}
CardSpecial::CardSpecial(shared_ptr<Server> server) : w_server(server) {}
@@ -251,14 +251,14 @@ void CardSpecial::apply_action_conditions(
if (attacker_card == defender_card) {
temp_as = this->create_attack_state_from_card_action_chain(attacker_card);
if (as) {
log.debug("using action state from override");
log.debug_f("using action state from override");
temp_as = *as;
} else {
log.debug("using action state from attacker card");
log.debug_f("using action state from attacker card");
}
} else {
temp_as = this->create_defense_state_for_card_pair_action_chains(attacker_card, defender_card);
log.debug("using action state from card pair");
log.debug_f("using action state from card pair");
}
this->apply_defense_conditions(temp_as, when, defender_card, flags);
@@ -307,9 +307,9 @@ bool CardSpecial::apply_defense_condition(
bool is_nte = s->options.is_nte();
auto log = s->log_stack("apply_defense_condition: ");
if (log.should_log(phosg::LogLevel::DEBUG)) {
log.debug(
"when=%s, cond_index=%hhu, defender_card=(@%04hX #%04hX), flags=%08" PRIX32 ", p8=%s",
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
log.debug_f(
"when={}, cond_index={}, defender_card=(@{:04X} #{:04X}), flags={:08X}, p8={}",
phosg::name_for_enum(when),
cond_index,
defender_card->get_card_ref(),
@@ -318,32 +318,32 @@ bool CardSpecial::apply_defense_condition(
unknown_p8 ? "true" : "false");
auto defender_cond_str = defender_cond->str(s);
auto defense_state_str = defense_state.str(s);
log.debug("defender_cond = %s", defender_cond_str.c_str());
log.debug("defense_state = %s", defense_state_str.c_str());
log.debug_f("defender_cond = {}", defender_cond_str);
log.debug_f("defense_state = {}", defense_state_str);
}
if (defender_cond->type == ConditionType::NONE) {
log.debug("no condition");
log.debug_f("no condition");
return false;
}
auto orig_eff = this->original_definition_for_condition(*defender_cond);
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
auto orig_eff_str = orig_eff->str();
log.debug("orig_eff = %s", orig_eff_str.c_str());
log.debug_f("orig_eff = {}", orig_eff_str);
}
uint16_t attacker_card_ref = defense_state.attacker_card_ref;
if (attacker_card_ref == 0xFFFF) {
attacker_card_ref = defense_state.original_attacker_card_ref;
}
log.debug("attacker_card_ref = @%04hX", attacker_card_ref);
log.debug_f("attacker_card_ref = @{:04X}", attacker_card_ref);
bool defender_has_ability_trap = !is_nte && this->card_ref_has_ability_trap(*defender_cond);
log.debug("defender_has_ability_trap = %s", defender_has_ability_trap ? "true" : "false");
log.debug_f("defender_has_ability_trap = {}", defender_has_ability_trap ? "true" : "false");
if ((is_nte || (flags & 4)) && !this->is_card_targeted_by_condition(*defender_cond, defense_state, defender_card)) {
log.debug("not targeted by condition");
log.debug_f("not targeted by condition");
if (defender_cond->type != ConditionType::NONE) {
G_ApplyConditionEffect_Ep3_6xB4x06 cmd;
cmd.effect.flags = 0x04;
@@ -359,7 +359,7 @@ bool CardSpecial::apply_defense_condition(
}
if ((when == EffectWhen::AFTER_ANY_CARD_ATTACK) && (defender_cond->type == ConditionType::GUOM) && (flags & 4)) {
log.debug("deleting guom condition");
log.debug_f("deleting guom condition");
CardShortStatus stat = defender_card->get_short_status();
if (stat.card_flags & 4) {
G_ApplyConditionEffect_Ep3_6xB4x06 cmd;
@@ -396,7 +396,7 @@ bool CardSpecial::apply_defense_condition(
}
if ((when == EffectWhen::BEFORE_DICE_PHASE_THIS_TEAM_TURN) && (flags & 4) && !defender_has_ability_trap && (defender_cond->type == ConditionType::ACID)) {
log.debug("applying acid");
log.debug_f("applying acid");
int16_t hp = defender_card->get_current_hp();
if (hp > 0) {
this->send_6xB4x06_for_stat_delta(defender_card, defender_cond->card_ref, 0x20, -1, 0, 1);
@@ -406,11 +406,11 @@ bool CardSpecial::apply_defense_condition(
}
if (!orig_eff || (orig_eff->when != when)) {
log.debug("unsetting flag 4");
log.debug_f("unsetting flag 4");
flags &= ~4;
}
if ((flags == 0) || defender_has_ability_trap) {
log.debug("no condition remains to apply");
log.debug_f("no condition remains to apply");
return false;
}
@@ -427,10 +427,10 @@ bool CardSpecial::apply_defense_condition(
string expr = orig_eff->expr.decode();
int16_t expr_value = this->evaluate_effect_expr(astats, expr.c_str(), dice_roll);
log.debug("execute_effect ...");
log.debug_f("execute_effect ...");
this->execute_effect(*defender_cond, defender_card, expr_value, defender_cond->value, orig_eff->type, flags, attacker_card_ref);
if (flags & 4) {
log.debug("recomputing action chaing results");
log.debug_f("recomputing action chaing results");
if (is_nte || !(defender_card->card_flags & 2)) {
defender_card->compute_action_chain_results(true, false);
}
@@ -440,7 +440,7 @@ bool CardSpecial::apply_defense_condition(
}
if (dice_roll.value_used_in_expr && !(original_cond_flags & 1) && !unknown_p8) {
log.debug("dice roll was used; setting dice display flag");
log.debug_f("dice roll was used; setting dice display flag");
defender_cond->flags |= 1;
G_ApplyConditionEffect_Ep3_6xB4x06 cmd;
cmd.effect.flags = 0x08;
@@ -491,11 +491,11 @@ bool CardSpecial::apply_stat_deltas_to_all_cards_from_all_conditions_with_card_r
bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condition& cond, shared_ptr<Card> card) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("apply_stat_deltas_to_card_from_condition_and_clear_cond(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id()));
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("cond: %s", cond_str.c_str());
log.debug_f("cond: {}", cond_str);
ConditionType cond_type = cond.type;
int16_t cond_value = is_nte ? cond.value.load() : clamp<int16_t>(cond.value, -99, 99);
@@ -508,7 +508,7 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
if (cond_flags & 2) {
int16_t ap = clamp<int16_t>(card->ap, -99, 99);
int16_t tp = clamp<int16_t>(card->tp, -99, 99);
log.debug("A_T_SWAP_0C: swapping AP (%hd) and TP (%hd)", ap, tp);
log.debug_f("A_T_SWAP_0C: swapping AP ({}) and TP ({})", ap, tp);
if (!is_nte) {
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0xA0, tp - ap, 0, 0);
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0x80, ap - tp, 0, 0);
@@ -516,7 +516,7 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
card->ap = tp;
card->tp = ap;
} else {
log.debug("A_T_SWAP_0C: required flag is missing");
log.debug_f("A_T_SWAP_0C: required flag is missing");
}
break;
case ConditionType::A_H_SWAP:
@@ -524,7 +524,7 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
int16_t ap = clamp<int16_t>(card->ap, -99, 99);
int16_t hp = clamp<int16_t>(card->get_current_hp(), -99, 99);
if (hp != ap) {
log.debug("A_H_SWAP: swapping AP (%hd) and HP (%hd)", ap, hp);
log.debug_f("A_H_SWAP: swapping AP ({}) and HP ({})", ap, hp);
if (!is_nte) {
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0xA0, hp - ap, 0, 0);
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0x20, ap - hp, 0, 0);
@@ -533,10 +533,10 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
card->ap = hp;
this->destroy_card_if_hp_zero(card, cond_card_ref);
} else {
log.debug("A_H_SWAP: AP (%hd) == HP (%hd)", ap, hp);
log.debug_f("A_H_SWAP: AP ({}) == HP ({})", ap, hp);
}
} else {
log.debug("A_H_SWAP: required flag is missing");
log.debug_f("A_H_SWAP: required flag is missing");
}
break;
case ConditionType::AP_OVERRIDE:
@@ -550,12 +550,12 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0xA0, -cond_value, 0, 0);
}
card->ap = max<int16_t>(card->ap - cond_value, 0);
log.debug("AP_OVERRIDE: subtracting %hd from AP => %hd", cond_value, card->ap);
log.debug_f("AP_OVERRIDE: subtracting {} from AP => {}", cond_value, card->ap);
} else {
other_cond->value = clamp<int16_t>(other_cond->value + cond_value, -99, 99);
}
} else {
log.debug("AP_OVERRIDE: required flag is missing");
log.debug_f("AP_OVERRIDE: required flag is missing");
}
break;
case ConditionType::TP_OVERRIDE:
@@ -567,12 +567,12 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0x80, -cond_value, 0, 0);
}
card->tp = max<int16_t>(card->tp - cond_value, 0);
log.debug("TP_OVERRIDE: subtracting %hd from TP => %hd", cond_value, card->tp);
log.debug_f("TP_OVERRIDE: subtracting {} from TP => {}", cond_value, card->tp);
} else {
other_cond->value = clamp<int16_t>(other_cond->value + cond_value, -99, 99);
}
} else {
log.debug("TP_OVERRIDE: required flag is missing");
log.debug_f("TP_OVERRIDE: required flag is missing");
}
break;
case ConditionType::MISC_AP_BONUSES:
@@ -581,9 +581,9 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0xA0, -cond_value, 0, 0);
}
card->ap = max<int16_t>(card->ap - cond_value, 0);
log.debug("MISC_AP_BONUSES: subtracting %hd from AP => %hd", cond_value, card->ap);
log.debug_f("MISC_AP_BONUSES: subtracting {} from AP => {}", cond_value, card->ap);
} else {
log.debug("MISC_AP_BONUSES: required flag is missing");
log.debug_f("MISC_AP_BONUSES: required flag is missing");
}
break;
case ConditionType::MISC_TP_BONUSES:
@@ -592,9 +592,9 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0x80, -cond_value, 0, 0);
}
card->tp = max<int16_t>(card->tp - cond_value, 0);
log.debug("MISC_TP_BONUSES: subtracting %hd from TP => %hd", cond_value, card->tp);
log.debug_f("MISC_TP_BONUSES: subtracting {} from TP => {}", cond_value, card->tp);
} else {
log.debug("MISC_TP_BONUSES: required flag is missing");
log.debug_f("MISC_TP_BONUSES: required flag is missing");
}
break;
case ConditionType::AP_SILENCE:
@@ -604,9 +604,9 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
if (cond_flags & 2) {
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0xA0, cond_value, 0, 0);
card->ap = max<int16_t>(card->ap + cond_value, 0);
log.debug("AP_SILENCE: adding %hd to AP => %hd", cond_value, card->ap);
log.debug_f("AP_SILENCE: adding {} to AP => {}", cond_value, card->ap);
} else {
log.debug("AP_SILENCE: required flag is missing");
log.debug_f("AP_SILENCE: required flag is missing");
}
break;
case ConditionType::TP_SILENCE:
@@ -616,14 +616,14 @@ bool CardSpecial::apply_stat_deltas_to_card_from_condition_and_clear_cond(Condit
if (cond_flags & 2) {
this->send_6xB4x06_for_stat_delta(card, cond_card_ref, 0x80, cond_value, 0, 0);
card->tp = max<int16_t>(card->tp + cond_value, 0);
log.debug("TP_SILENCE: adding %hd to TP => %hd", cond_value, card->tp);
log.debug_f("TP_SILENCE: adding {} to TP => {}", cond_value, card->tp);
} else {
log.debug("TP_SILENCE: required flag is missing");
log.debug_f("TP_SILENCE: required flag is missing");
}
break;
trial_unimplemented:
default:
log.debug("%s: no adjustments for condition type", phosg::name_for_enum(cond_type));
log.debug_f("{}: no adjustments for condition type", phosg::name_for_enum(cond_type));
break;
}
@@ -741,22 +741,22 @@ CardSpecial::AttackEnvStats CardSpecial::compute_attack_env_stats(
bool is_nte = s->options.is_nte();
string pa_str = pa.str(s);
log.debug("pa=%s, card=@%04hX #%04hX, dice_roll=%hhu, target=@%04hX, condition_giver=@%04hX", pa_str.c_str(), card->get_card_ref(), card->get_card_id(), dice_roll.value, target_card_ref, condition_giver_card_ref);
log.debug_f("pa={}, card=@{:04X} #{:04X}, dice_roll={}, target=@{:04X}, condition_giver=@{:04X}", pa_str, card->get_card_ref(), card->get_card_id(), dice_roll.value, target_card_ref, condition_giver_card_ref);
auto attacker_card = s->card_for_set_card_ref(pa.attacker_card_ref);
if (!attacker_card && (pa.original_attacker_card_ref != 0xFFFF)) {
attacker_card = s->card_for_set_card_ref(pa.original_attacker_card_ref);
log.debug("attacker=@%04hX #%04hX (from original)", attacker_card->get_card_ref(), attacker_card->get_card_id());
log.debug_f("attacker=@{:04X} #{:04X} (from original)", attacker_card->get_card_ref(), attacker_card->get_card_id());
} else if (attacker_card) {
log.debug("attacker=@%04hX #%04hX (from set)", attacker_card->get_card_ref(), attacker_card->get_card_id());
log.debug_f("attacker=@{:04X} #{:04X} (from set)", attacker_card->get_card_ref(), attacker_card->get_card_id());
} else {
log.debug("attacker=null (from set)");
log.debug_f("attacker=null (from set)");
}
AttackEnvStats ast;
auto ps = card->player_state();
log.debug("base ps = %hhu", ps->client_id);
log.debug_f("base ps = {}", ps->client_id);
ast.num_set_cards = is_nte ? ps->count_set_cards_for_env_stats_nte() : ps->count_set_cards();
auto condition_giver_card = s->card_for_set_card_ref(condition_giver_card_ref);
auto target_card = s->card_for_set_card_ref(target_card_ref);
@@ -871,8 +871,8 @@ CardSpecial::AttackEnvStats CardSpecial::compute_attack_env_stats(
// 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++) {
((target_card_ref != z_ref) && (z < 8) && ((z_ref = pa.action_card_refs[z]) != 0xFFFF));
z++) {
}
ast.action_cards_ap = 0;
@@ -1227,9 +1227,9 @@ shared_ptr<Card> CardSpecial::compute_replaced_target_based_on_conditions(
StatSwapType CardSpecial::compute_stat_swap_type(shared_ptr<const Card> card) const {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("compute_stat_swap_type(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id()));
auto log = s->log_stack(std::format("compute_stat_swap_type(@{:04X} #{:04X}): ", card->get_card_ref(), card->get_card_id()));
if (!card) {
log.debug("card is missing");
log.debug_f("card is missing");
return StatSwapType::NONE;
}
@@ -1237,33 +1237,33 @@ StatSwapType CardSpecial::compute_stat_swap_type(shared_ptr<const Card> card) co
for (size_t cond_index = 0; cond_index < 9; cond_index++) {
auto& cond = card->action_chain.conditions[cond_index];
if (cond.type != ConditionType::NONE) {
auto cond_log = log.sub(phosg::string_printf("(%zu) ", cond_index));
auto cond_log = log.sub(std::format("({}) ", cond_index));
string cond_str = cond.str(s);
cond_log.debug("%s", cond_str.c_str());
cond_log.debug_f("{}", cond_str);
if (!this->card_ref_has_ability_trap(cond)) {
if (cond.type == ConditionType::UNKNOWN_75) {
if (ret == StatSwapType::A_H_SWAP) {
log.debug("UNKNOWN_75: clearing");
log.debug_f("UNKNOWN_75: clearing");
ret = StatSwapType::NONE;
} else {
log.debug("UNKNOWN_75: setting A_H_SWAP");
log.debug_f("UNKNOWN_75: setting A_H_SWAP");
ret = StatSwapType::A_H_SWAP;
}
} else if (cond.type == ConditionType::A_T_SWAP) {
if (ret == StatSwapType::A_T_SWAP) {
log.debug("A_T_SWAP: clearing");
log.debug_f("A_T_SWAP: clearing");
ret = StatSwapType::NONE;
} else {
log.debug("A_T_SWAP: setting A_T_SWAP");
log.debug_f("A_T_SWAP: setting A_T_SWAP");
ret = StatSwapType::A_T_SWAP;
}
}
} else {
log.debug("skipping due to ability trap");
log.debug_f("skipping due to ability trap");
}
}
}
log.debug("ret = %zu", static_cast<size_t>(ret));
log.debug_f("ret = {}", static_cast<size_t>(ret));
return ret;
}
@@ -1713,8 +1713,8 @@ int32_t CardSpecial::evaluate_effect_expr(
const char* expr,
DiceRoll& dice_roll) const {
auto log = this->server()->log_stack("evaluate_effect_expr: ");
if (log.min_level == phosg::LogLevel::DEBUG) {
log.debug("ast, expr=\"%s\", dice_roll=(client_id=%02hhX, a2=%02hhX, value=%02hhX, value_used_in_expr=%s, a5=%04hX)", expr, dice_roll.client_id, dice_roll.unknown_a2, dice_roll.value, dice_roll.value_used_in_expr ? "true" : "false", dice_roll.unknown_a5);
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);
ast.print(stderr);
}
@@ -1747,7 +1747,7 @@ int32_t CardSpecial::evaluate_effect_expr(
// Operators are evaluated left-to-right - there are no operator precedence
// rules
int32_t value = 0;
log.debug("value=%" PRId32 " (start)", value);
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;
@@ -1756,7 +1756,7 @@ int32_t CardSpecial::evaluate_effect_expr(
}
if (token_type == ExpressionTokenType::NUMBER) {
value = token_value;
log.debug("value=%" PRId32 " (token_type=NUMBER, token_value=%" PRId32 ")", 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");
@@ -1770,23 +1770,23 @@ int32_t CardSpecial::evaluate_effect_expr(
switch (token_type) {
case ExpressionTokenType::ROUND_DIVIDE:
value = lround(static_cast<double>(value) / right_value);
log.debug("value=%" PRId32 " (token_type=ROUND_DIVIDE, right_token_value=%" PRId32 ")", value, right_value);
log.debug_f("value={} (token_type=ROUND_DIVIDE, right_token_value={})", value, right_value);
break;
case ExpressionTokenType::SUBTRACT:
value -= right_value;
log.debug("value=%" PRId32 " (token_type=SUBTRACT, right_token_value=%" PRId32 ")", value, right_value);
log.debug_f("value={} (token_type=SUBTRACT, right_token_value={})", value, right_value);
break;
case ExpressionTokenType::ADD:
value += right_value;
log.debug("value=%" PRId32 " (token_type=ADD, right_token_value=%" PRId32 ")", value, right_value);
log.debug_f("value={} (token_type=ADD, right_token_value={})", value, right_value);
break;
case ExpressionTokenType::MULTIPLY:
value *= right_value;
log.debug("value=%" PRId32 " (token_type=MULTIPLY, right_token_value=%" PRId32 ")", value, right_value);
log.debug_f("value={} (token_type=MULTIPLY, right_token_value={})", value, right_value);
break;
case ExpressionTokenType::FLOOR_DIVIDE:
value = floor(value / right_value);
log.debug("value=%" PRId32 " (token_type=FLOOR_DIVIDE, right_token_value=%" PRId32 ")", value, right_value);
log.debug_f("value={} (token_type=FLOOR_DIVIDE, right_token_value={})", value, right_value);
break;
default:
throw logic_error("invalid binary operator");
@@ -1794,7 +1794,7 @@ int32_t CardSpecial::evaluate_effect_expr(
}
}
log.debug("value=%" PRId32 " (result)", value);
log.debug_f("value={} (result)", value);
return value;
}
@@ -1807,10 +1807,10 @@ bool CardSpecial::execute_effect(
uint32_t unknown_p7,
uint16_t attacker_card_ref) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("execute_effect(@%04hX #%04hX): ", card->get_card_ref(), card->get_card_id()));
auto log = s->log_stack(std::format("execute_effect(@{:04X} #{:04X}): ", card->get_card_ref(), card->get_card_id()));
{
string cond_str = cond.str(s);
log.debug("cond=%s, card=@%04hX, expr_value=%hd, unknown_p5=%hd, cond_type=%s, unknown_p7=%" PRIu32 ", attacker_card_ref=@%04hX", cond_str.c_str(), ref_for_card(card), expr_value, unknown_p5, phosg::name_for_enum(cond_type), unknown_p7, attacker_card_ref);
log.debug_f("cond={}, card=@{:04X}, expr_value={}, unknown_p5={}, cond_type={}, unknown_p7={} attacker_card_ref=@{:04X}", cond_str, ref_for_card(card), expr_value, unknown_p5, phosg::name_for_enum(cond_type), unknown_p7, attacker_card_ref);
}
bool is_nte = s->options.is_nte();
@@ -1959,7 +1959,7 @@ bool CardSpecial::execute_effect(
if (unknown_p7 & 4) {
int16_t hp = is_nte ? card->get_current_hp() : clamp<int16_t>(card->get_current_hp(), -99, 99);
int16_t new_hp = is_nte ? (hp + positive_expr_value) : clamp<int16_t>(hp + positive_expr_value, -99, 99);
log.debug("HEAL: hp=%hd, positive_expr_value=%hd, new_hp=%hd", hp, positive_expr_value, new_hp);
log.debug_f("HEAL: hp={}, positive_expr_value={}, new_hp={}", hp, positive_expr_value, new_hp);
this->send_6xB4x06_for_stat_delta(card, attacker_card_ref, 0x20, new_hp - hp, true, true);
if (new_hp != hp) {
card->set_current_hp(new_hp);
@@ -2842,8 +2842,8 @@ 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(phosg::string_printf("get_targeted_cards_for_condition(@%04hX, %hhu, @%04hX): ", card_ref, def_effect_index, setter_card_ref));
log.debug("card_ref=@%04hX, def_effect_index=%02hhX, setter_card_ref=@%04hX, as, p_target_type=%hd, apply_usability_filters=%s", 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;
@@ -2852,12 +2852,12 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
if (!card1) {
card1 = s->card_for_set_card_ref(setter_card_ref);
}
log.debug("card1=@%04hX", ref_for_card(card1));
log.debug_f("card1=@{:04X}", ref_for_card(card1));
auto card2 = s->card_for_set_card_ref((as.attacker_card_ref == 0xFFFF)
? as.original_attacker_card_ref
: as.attacker_card_ref);
log.debug("card2=@%04hX", ref_for_card(card2));
log.debug_f("card2=@{:04X}", ref_for_card(card2));
Location card1_loc;
if (!card1) {
@@ -2868,13 +2868,13 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
this->get_card1_loc_with_card2_opposite_direction(&card1_loc, card1, card2);
string card1_loc_str = card1_loc.str();
log.debug("card1_loc=%s", card1_loc_str.c_str());
log.debug_f("card1_loc={}", card1_loc_str);
}
AttackMedium attack_medium = card2
? card2->action_chain.chain.attack_medium
: AttackMedium::UNKNOWN;
log.debug("attack_medium=%s", phosg::name_for_enum(attack_medium));
log.debug_f("attack_medium={}", phosg::name_for_enum(attack_medium));
auto add_card_refs = [&](const vector<uint16_t>& result_card_refs) -> void {
for (uint16_t result_card_ref : result_card_refs) {
@@ -2890,10 +2890,10 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
case 0x05: { // p05
auto result_card = s->card_for_set_card_ref(setter_card_ref);
if (result_card) {
log.debug("(p01/p05) result_card=@%04hX", ref_for_card(result_card));
log.debug_f("(p01/p05) result_card=@{:04X}", ref_for_card(result_card));
ret.emplace_back(result_card);
} else {
log.debug("(p01/p05) result_card=null");
log.debug_f("(p01/p05) result_card=null");
}
break;
}
@@ -3073,28 +3073,28 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
if (def && ps) {
// TODO: Again with the Gifoie hardcoding...
uint16_t range_card_id = this->get_card_id_with_effective_range(card1, 0x00D9, card2);
log23.debug("effective range card ID is #%04hX", range_card_id);
log23.debug_f("effective range card ID is #{:04X}", range_card_id);
parray<uint8_t, 9 * 9> range;
compute_effective_range(range, s->options.card_index, range_card_id, card1_loc, s->map_and_rules, &log23);
auto result_card_refs = ps->get_all_cards_within_range(range, card1_loc, 0xFF);
log23.debug("%zu result card refs", result_card_refs.size());
log23.debug_f("{} result card refs", result_card_refs.size());
for (uint16_t result_card_ref : result_card_refs) {
auto result_log = log23.subf("(result @%04hX) ", result_card_ref);
auto result_log = log23.sub(std::format("(result @{:04X}) ", result_card_ref));
auto result_card = s->card_for_set_card_ref(result_card_ref);
if (!result_card) {
result_log.debug("result card not found");
result_log.debug_f("result card not found");
} else if (result_card->get_definition()->def.type == CardType::ITEM) {
result_log.debug("result card is item");
result_log.debug_f("result card is item");
} else {
result_log.debug("result card found and is not item");
result_log.debug_f("result card found and is not item");
ret.emplace_back(result_card);
}
}
} else {
log23.debug("def or ps is missing");
log23.debug_f("def or ps is missing");
}
} else {
log23.debug("card1 is missing");
log23.debug_f("card1 is missing");
}
break;
}
@@ -3194,28 +3194,28 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
};
bool is_nte = s->options.is_nte();
if (as.original_attacker_card_ref == 0xFFFF) {
log36.debug("original_attacker_card_ref missing");
log36.debug_f("original_attacker_card_ref missing");
// debug_str_for_card_ref
for (size_t z = 0; (z < 4 * 9) && (as.target_card_refs[z] != 0xFFFF); z++) {
string debug_ref_str = s->debug_str_for_card_ref(as.target_card_refs[z]);
log36.debug("examining %s", debug_ref_str.c_str());
log36.debug_f("examining {}", debug_ref_str);
auto result_card = s->card_for_set_card_ref(as.target_card_refs[z]);
if (result_card && should_include(result_card->get_definition(), is_nte)) {
log36.debug("adding %s", debug_ref_str.c_str());
log36.debug_f("adding {}", debug_ref_str);
ret.emplace_back(result_card);
} else {
log36.debug("skipping %s", debug_ref_str.c_str());
log36.debug_f("skipping {}", debug_ref_str);
}
}
} else if (card2 && should_include(card2->get_definition(), is_nte)) {
string debug_ref_str = s->debug_str_for_card_ref(card2->get_card_ref());
log36.debug("original_attacker_card_ref present; adding card2 = %s", debug_ref_str.c_str());
log36.debug_f("original_attacker_card_ref present; adding card2 = {}", debug_ref_str);
ret.emplace_back(card2);
} else if (card2) {
string debug_ref_str = s->debug_str_for_card_ref(card2->get_card_ref());
log36.debug("original_attacker_card_ref present and card2 (%s) not eligible", debug_ref_str.c_str());
log36.debug_f("original_attacker_card_ref present and card2 ({}) not eligible", debug_ref_str);
} else {
log36.debug("original_attacker_card_ref present and card2 missing");
log36.debug_f("original_attacker_card_ref present and card2 missing");
}
break;
}
@@ -3252,17 +3252,17 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
ret = this->find_all_set_cards_with_cost_in_range(
(p_target_type == 0x27) ? 4 : 0,
(p_target_type == 0x27) ? 99 : 3);
if (log3940.should_log(phosg::LogLevel::DEBUG)) {
if (log3940.should_log(phosg::LogLevel::L_DEBUG)) {
for (const auto& card : ret) {
log3940.debug("found target @%04hX #%04hX", card->get_card_ref(), card->get_card_id());
log3940.debug_f("found target @{:04X} #{:04X}", card->get_card_ref(), card->get_card_id());
}
}
if (!s->options.is_nte()) {
log3940.debug("filtering targets");
log3940.debug_f("filtering targets");
ret = this->filter_cards_by_range(ret, card1, card1_loc, card2);
if (log3940.should_log(phosg::LogLevel::DEBUG)) {
if (log3940.should_log(phosg::LogLevel::L_DEBUG)) {
for (const auto& card : ret) {
log3940.debug("retained target @%04hX #%04hX", card->get_card_ref(), card->get_card_id());
log3940.debug_f("retained target @{:04X} #{:04X}", card->get_card_ref(), card->get_card_id());
}
}
}
@@ -3497,9 +3497,9 @@ vector<shared_ptr<const Card>> CardSpecial::get_targeted_cards_for_condition(
if (s->ruler_server->check_usability_or_apply_condition_for_card_refs(
card_ref, setter_card_ref, c->get_card_ref(), def_effect_index, attack_medium)) {
filtered_ret.emplace_back(c);
log.debug("usability filter: kept card @%04hX", ref_for_card(c));
log.debug_f("usability filter: kept card @{:04X}", ref_for_card(c));
} else {
log.debug("usability filter: removed card @%04hX", ref_for_card(c));
log.debug_f("usability filter: removed card @{:04X}", ref_for_card(c));
}
}
return filtered_ret;
@@ -3526,16 +3526,16 @@ bool CardSpecial::is_card_targeted_by_condition(
auto s = this->server();
auto log = s->log_stack("is_card_targeted_by_condition: ");
if (log.should_log(phosg::LogLevel::DEBUG)) {
log.debug("card=(@%04hX #%04hX)", card->get_card_ref(), card->get_card_id());
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
log.debug_f("card=(@{:04X} #{:04X})", card->get_card_ref(), card->get_card_id());
auto cond_str = cond.str(s);
auto as_str = as.str(s);
log.debug("cond = %s", cond_str.c_str());
log.debug("as = %s", as_str.c_str());
log.debug_f("cond = {}", cond_str);
log.debug_f("as = {}", as_str);
}
if (cond.type == ConditionType::NONE) {
log.debug("condition is NONE (=> true)");
log.debug_f("condition is NONE (=> true)");
return true;
}
@@ -3546,12 +3546,12 @@ bool CardSpecial::is_card_targeted_by_condition(
((ce->def.type == CardType::ITEM) || ce->def.is_sc()) &&
(cond.remaining_turns != 100) &&
(s->options.is_nte() || (client_id_for_card_ref(card->get_card_ref()) == client_id_for_card_ref(cond.card_ref)))) {
log.debug("failed item or SC check (=> false)");
log.debug_f("failed item or SC check (=> false)");
return false;
}
if (cond.remaining_turns != 102) {
log.debug("remaining_turns != 102 (=> true)");
log.debug_f("remaining_turns != 102 (=> true)");
return true;
}
@@ -3569,15 +3569,15 @@ bool CardSpecial::is_card_targeted_by_condition(
0);
for (auto c : target_cards) {
if (c == card) {
log.debug("targeted by p condition (=> true)");
log.debug_f("targeted by p condition (=> true)");
return true;
}
}
log.debug("not targeted by p condition (=> false)");
log.debug_f("not targeted by p condition (=> false)");
return false;
} else {
log.debug("SC check does not apply");
log.debug_f("SC check does not apply");
return false;
}
}
@@ -3806,7 +3806,7 @@ size_t CardSpecial::sum_last_attack_damage(
size_t damage_count = 0;
auto check_card = [&](shared_ptr<const Card> c) -> void {
if (c && (c->last_attack_final_damage > 0)) {
log.debug("check_card @%04hX #%04hX => %hd", c->get_card_ref(), c->get_card_id(), c->last_attack_final_damage);
log.debug_f("check_card @{:04X} #{:04X} => {}", c->get_card_ref(), c->get_card_id(), c->last_attack_final_damage);
if (out_damage_sum) {
*out_damage_sum += c->last_attack_final_damage;
}
@@ -4013,13 +4013,13 @@ void CardSpecial::evaluate_and_apply_effects(
bool apply_defense_condition_to_all_cards,
uint16_t apply_defense_condition_to_card_ref) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("evaluate_and_apply_effects(%s, @%04hX, @%04hX): ", phosg::name_for_enum(when), set_card_ref, sc_card_ref));
auto log = s->log_stack(std::format("evaluate_and_apply_effects({}, @{:04X}, @{:04X}): ", phosg::name_for_enum(when), set_card_ref, sc_card_ref));
bool is_nte = s->options.is_nte();
{
string as_str = as.str(s);
log.debug("when=%s, set_card_ref=@%04hX, as=%s, sc_card_ref=@%04hX, apply_defense_condition_to_all_cards=%s, apply_defense_condition_to_card_ref=@%04hX",
phosg::name_for_enum(when), set_card_ref, as_str.c_str(), sc_card_ref, apply_defense_condition_to_all_cards ? "true" : "false", apply_defense_condition_to_card_ref);
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);
}
if (!is_nte) {
@@ -4028,7 +4028,7 @@ void CardSpecial::evaluate_and_apply_effects(
auto ce = this->server()->definition_for_card_ref(set_card_ref);
if (!ce) {
log.debug("ce missing");
log.debug_f("ce missing");
return;
}
@@ -4076,15 +4076,15 @@ void CardSpecial::evaluate_and_apply_effects(
dice_roll.unknown_a2 = 3;
dice_roll.value_used_in_expr = false;
log.debug("inputs: dice_roll=%02hhX, random_percent=%hhu, unknown_v1=%s", 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++) {
auto effect_log = log.sub(phosg::string_printf("(effect:%zu) ", 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("effect: %s", card_effect_str.c_str());
effect_log.debug_f("effect: {}", card_effect_str);
if (card_effect.when != when) {
effect_log.debug("does not apply (effect.when=%s, when=%s)", phosg::name_for_enum(card_effect.when), phosg::name_for_enum(when));
effect_log.debug_f("does not apply (effect.when={}, when={})", phosg::name_for_enum(card_effect.when), phosg::name_for_enum(when));
continue;
}
@@ -4093,18 +4093,18 @@ void CardSpecial::evaluate_and_apply_effects(
throw runtime_error("card effect arg3 is missing");
}
int16_t arg3_value = atoi(arg3_s.c_str() + 1);
effect_log.debug("arg3_value=%hd", arg3_value);
effect_log.debug_f("arg3_value={}", arg3_value);
auto targeted_cards = this->get_targeted_cards_for_condition(
set_card_ref, def_effect_index, sc_card_ref, as, arg3_value, 1);
string refs_str = refs_str_for_cards_vector(targeted_cards);
effect_log.debug("targeted_cards=[%s]", refs_str.c_str());
effect_log.debug_f("targeted_cards=[{}]", refs_str);
bool all_targets_matched = false;
if (!is_nte &&
!targeted_cards.empty() &&
((card_effect.type == ConditionType::UNKNOWN_64) ||
(card_effect.type == ConditionType::MISC_DEFENSE_BONUSES) ||
(card_effect.type == ConditionType::MOSTLY_HALFGUARDS))) {
effect_log.debug("special targeting applies");
effect_log.debug_f("special targeting applies");
size_t count = 0;
for (size_t z = 0; z < targeted_cards.size(); z++) {
dice_roll.value_used_in_expr = false;
@@ -4132,22 +4132,22 @@ void CardSpecial::evaluate_and_apply_effects(
targeted_cards.clear();
}
} else {
effect_log.debug("special targeting does not apply");
effect_log.debug_f("special targeting does not apply");
}
for (size_t z = 0; z < targeted_cards.size(); z++) {
auto target_log = effect_log.sub(phosg::string_printf("(target:@%04hX) ", targeted_cards[z]->get_card_ref()));
auto target_log = effect_log.sub(std::format("(target:@{:04X}) ", targeted_cards[z]->get_card_ref()));
dice_roll.value_used_in_expr = false;
string arg2_str = card_effect.arg2.decode();
target_log.debug("arg2_str = %s", arg2_str.c_str());
target_log.debug_f("arg2_str = {}", arg2_str);
if (all_targets_matched ||
this->evaluate_effect_arg2_condition(
as, targeted_cards[z], arg2_str.c_str(), dice_roll, set_card_ref, sc_card_ref, random_percent, when)) {
target_log.debug("arg2 condition passed");
target_log.debug_f("arg2 condition passed");
auto env_stats = this->compute_attack_env_stats(as, targeted_cards[z], dice_roll, set_card_ref, sc_card_ref);
string expr_str = card_effect.expr.decode();
int16_t value = this->evaluate_effect_expr(env_stats, expr_str.c_str(), dice_roll);
target_log.debug("expr = %s, value = %hd", expr_str.c_str(), value);
target_log.debug_f("expr = {}, value = {}", expr_str, value);
uint32_t unknown_v1 = 0;
auto target_card = this->compute_replaced_target_based_on_conditions(
@@ -4163,16 +4163,16 @@ void CardSpecial::evaluate_and_apply_effects(
sc_card_ref);
if (!target_card) {
target_card = targeted_cards[z];
target_log.debug("target card (not replaced) = @%04hX", target_card->get_card_ref());
target_log.debug_f("target card (not replaced) = @{:04X}", target_card->get_card_ref());
} else {
target_log.debug("target card (replaced) = @%04hX", target_card->get_card_ref());
target_log.debug_f("target card (replaced) = @{:04X}", target_card->get_card_ref());
}
ssize_t applied_cond_index = -1;
if ((unknown_v1 == 0) && !this->should_cancel_condition_due_to_anti_abnormality(card_effect, target_card, dice_cmd.effect.target_card_ref, sc_card_ref)) {
applied_cond_index = target_card->apply_abnormal_condition(
card_effect, def_effect_index, dice_cmd.effect.target_card_ref, sc_card_ref, value, dice_roll.value, random_percent);
target_log.debug("applied abnormal condition");
target_log.debug_f("applied abnormal condition");
// This debug_print call is in the original code.
// this->debug_print(when, 4, &env_stats, "!set_abnormal..", target_card, card_effect.type);
}
@@ -4202,12 +4202,12 @@ void CardSpecial::evaluate_and_apply_effects(
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);
target_log.debug("applied defense condition");
target_log.debug_f("applied defense condition");
}
}
target_card->send_6xB4x4E_4C_4D_if_needed(0);
} else {
target_log.debug("arg2 condition failed");
target_log.debug_f("arg2 condition failed");
}
if (dice_roll.value_used_in_expr) {
any_expr_used_dice_roll = true;
@@ -4712,73 +4712,73 @@ vector<shared_ptr<const Card>> CardSpecial::filter_cards_by_range(
shared_ptr<const Card> card2) const {
auto log = this->server()->log_stack("filter_cards_by_range: ");
if (log.should_log(phosg::LogLevel::DEBUG)) {
auto card1_str = card1 ? phosg::string_printf("@%04hX #%04hX", card1->get_card_ref(), card1->get_card_id()) : "null";
auto card2_str = card2 ? phosg::string_printf("@%04hX #%04hX", card2->get_card_ref(), card2->get_card_id()) : "null";
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
auto card1_str = card1 ? std::format("@{:04X} #{:04X}", card1->get_card_ref(), card1->get_card_id()) : "null";
auto card2_str = card2 ? std::format("@{:04X} #{:04X}", card2->get_card_ref(), card2->get_card_id()) : "null";
auto loc_str = card1_loc.str();
log.debug("card1=(%s), card2=(%s), loc=%s", card1_str.c_str(), card2_str.c_str(), loc_str.c_str());
log.debug_f("card1=({}), card2=({}), loc={}", card1_str, card2_str, loc_str);
for (const auto& card : cards) {
if (card) {
log.debug("input card: @%04hX #%04hX", card->get_card_ref(), card->get_card_id());
log.debug_f("input card: @{:04X} #{:04X}", card->get_card_ref(), card->get_card_id());
} else {
log.debug("input card: null");
log.debug_f("input card: null");
}
}
}
vector<shared_ptr<const Card>> ret;
if (!card1 || cards.empty()) {
log.debug("card1 missing or input list is blank");
log.debug_f("card1 missing or input list is blank");
return ret;
}
auto ps = card1->player_state();
if (!ps) {
log.debug("ps is missing");
log.debug_f("ps is missing");
return ret;
}
// TODO: Remove hardcoded card ID here (Earthquake)
uint16_t card_id = this->get_card_id_with_effective_range(card1, 0x00ED, card2);
log.debug("card_id = #%04hX", card_id);
log.debug_f("card_id = #{:04X}", card_id);
parray<uint8_t, 9 * 9> range;
compute_effective_range(range, this->server()->options.card_index, card_id, card1_loc, this->server()->map_and_rules);
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
auto loc_str = card1_loc.str();
log.debug("compute_effective_range(range, ci, #%04hX, %s, map) =>", card_id, loc_str.c_str());
log.debug_f("compute_effective_range(range, ci, #{:04X}, {}, map) =>", card_id, loc_str);
for (size_t y = 0; y < 9; y++) {
const uint8_t* row = &range[y * 9];
log.debug(" range[%zu] = %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX %02hhX",
log.debug_f(" range[{}] = {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}",
y, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]);
}
}
auto card_refs_in_range = ps->get_card_refs_within_range_from_all_players(range, card1_loc, CardType::ITEM);
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
for (uint16_t card_ref : card_refs_in_range) {
log.debug("ref in range: @%04hX", card_ref);
log.debug_f("ref in range: @{:04X}", card_ref);
}
}
for (auto card : cards) {
if (!card || (card->get_card_ref() == 0xFFFF)) {
if (card) {
log.debug("(@%04hX #%04hX) out of range", card->get_card_ref(), card->get_card_id());
log.debug_f("(@{:04X} #{:04X}) out of range", card->get_card_ref(), card->get_card_id());
} else {
log.debug("(null) card missing");
log.debug_f("(null) card missing");
}
continue;
}
for (uint16_t card_ref_in_range : card_refs_in_range) {
if (card_ref_in_range == card->get_card_ref()) {
log.debug("(@%04hX #%04hX) in range", card->get_card_ref(), card->get_card_id());
log.debug_f("(@{:04X} #{:04X}) in range", card->get_card_ref(), card->get_card_id());
ret.emplace_back(card);
break;
}
}
log.debug("(@%04hX #%04hX) out of range", card->get_card_ref(), card->get_card_id());
log.debug_f("(@{:04X} #{:04X}) out of range", card->get_card_ref(), card->get_card_id());
}
return ret;
}
@@ -4787,7 +4787,7 @@ void CardSpecial::apply_effects_after_attack_target_resolution(const ActionState
auto s = this->server();
auto log = s->log_stack("apply_effects_after_attack_target_resolution: ");
string as_str = as.str(s);
log.debug("as=%s", as_str.c_str());
log.debug_f("as={}", as_str);
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 +4878,7 @@ 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(phosg::string_printf("apply_effects_on_phase_change_t<%s, %s>(@%04hX #%04hX): ", 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;
@@ -4929,7 +4929,7 @@ void CardSpecial::unknown_8024945C(shared_ptr<Card> unknown_p2, const ActionStat
}
void CardSpecial::unknown_8024966C(shared_ptr<Card> unknown_p2, const ActionState* existing_as) {
auto log = this->server()->log_stack(phosg::string_printf("unknown_8024966C(@%04hX #%04hX): ", 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) {
@@ -5080,7 +5080,7 @@ template <
EffectWhen WhenTargetsAndActionCards>
void CardSpecial::apply_effects_before_or_after_attack(shared_ptr<Card> unknown_p2) {
auto s = this->server();
auto log = s->log_stack(phosg::string_printf("apply_effects_before_or_after_attack<%s, %s, %s, %s>(@%04hX #%04hX): ",
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()));
ActionState as = this->create_attack_state_from_card_action_chain(unknown_p2);
File diff suppressed because it is too large Load Diff
+40 -25
View File
@@ -3,6 +3,7 @@
#include <stdint.h>
#include <array>
#include <filesystem>
#include <map>
#include <memory>
#include <phosg/Encoding.hh>
@@ -13,6 +14,7 @@
#include <string>
#include <unordered_map>
#include "../CommonFileFormats.hh"
#include "../PlayerSubordinates.hh"
#include "../Text.hh"
#include "../TextIndex.hh"
@@ -603,9 +605,10 @@ struct CardDefinition {
// actions, and assist cards have 1 here.
/* 008F */ uint8_t cannot_attack;
/* 0090 */ uint8_t unused3;
// If cannot_drop is 0, this card can't appear in post-battle rewards. A
// value of 0 here also prevents the card from being used as a God Whim
// random assist.
// If cannot_drop is 1, this card can't appear in post-battle rewards and is
// considered unobtainable by players, so the game will remove it from the
// player's collection if they have any copies of it. A value of 1 here also
// prevents the card from being used as a God Whim random assist.
/* 0091 */ uint8_t cannot_drop;
// This criterion code specifies who can use the card, and when it can be
// used. This specifies which Hero-side SCs can use which items, for example,
@@ -814,18 +817,12 @@ struct CardDefinition {
} __packed_ws__(CardDefinition, 0x128);
struct CardDefinitionsFooter {
// Technically the card definitions file is a REL file, so the last 0x20 bytes
// here should be a separate structure.
/* 00 */ be_uint32_t num_cards1;
/* 04 */ be_uint32_t cards_offset; // == 0
/* 08 */ be_uint32_t num_cards2;
/* 0C */ parray<be_uint32_t, 3> unknown_a2;
/* 18 */ parray<be_uint16_t, 0x10> relocations;
/* 38 */ be_uint32_t relocations_offset;
/* 3C */ be_uint32_t num_relocations;
/* 40 */ parray<be_uint32_t, 2> unused1;
/* 48 */ be_uint32_t footer_offset;
/* 4C */ parray<be_uint32_t, 3> unused2;
/* 38 */ RELFileFooterBE rel_footer;
/* 58 */
} __packed_ws__(CardDefinitionsFooter, 0x58);
@@ -868,7 +865,8 @@ struct PlayerConfig {
/* 0138:---- */ PlayerRecordsBattleBE unused_offline_records;
/* 0150:---- */ parray<uint8_t, 4> unknown_a4;
// The PlayerDataSegment structure begins here. In newserv, we combine this
// structure into PlayerConfig since the two are always used together.
// structure into PlayerConfig since the two are always used together on the
// server side.
/* 0154:0000 */ uint8_t is_encrypted;
/* 0155:0001 */ uint8_t basis;
/* 0156:0002 */ parray<uint8_t, 2> unused;
@@ -941,6 +939,8 @@ struct PlayerConfig {
void decrypt();
void encrypt(uint8_t basis);
bool card_count_checksums_correct() const;
} __packed_ws__(PlayerConfig, 0x2350);
struct PlayerConfigNTE {
@@ -1136,9 +1136,16 @@ struct CompressedMapHeader { // .mnm file format
struct OverlayState {
// In the tiles array, the high 4 bits of each value are the tile type, and
// the low 4 bits are the subtype. The types are:
// 10: blocked by rock (as if the corresponding map_tiles value was 00)
// 20: blocked by fence (as if the corresponding map_tiles value was 00)
// 30-34: teleporters (2 of each value may be present)
// 10-1F: blocked by rock (as if the corresponding map_tiles value was 00;
// low 4 bits specify rotation in increments of 1/4 turn)
// 20-2F: blocked by fence (as if the corresponding map_tiles value was 00;
// low 4 bits specify rotation in increments of 1/4 turn)
// 30-34: teleporters (each value should appear exactly twice or not at all):
// 30: purple teleporters
// 31: red teleporters
// 32: green teleporters
// 33: blue teleporters
// 34: purple teleporters (appears the same as 30 but is a distinct set)
// 40-4F: traps on NTE
// 40-44: traps on non-NTE (there may be up to 8 of each type, and one of
// each is chosen to be a real trap at battle start); the trap types are:
@@ -1172,7 +1179,8 @@ struct OverlayState {
struct MapDefinition { // .mnmd format; also the format of (decompressed) quests
// If tag is not 0x00000100, the game considers the map to be corrupt in
// offline mode and will delete it (if it's a download quest). The tag field
// doesn't seem to have any other use.
// doesn't seem to have any other use. In Trial Edition, download quests are
// expected to have 0x96 here instead.
/* 0000 */ be_uint32_t tag;
/* 0004 */ be_uint32_t map_number; // Must be unique across all maps
@@ -1219,7 +1227,6 @@ struct MapDefinition { // .mnmd format; also the format of (decompressed) quests
// 19 = View Battle waiting room
// 1A = TCard00_Select (debug battle setup menu)
// 1B = nothing (softlocks at black screen)
// TCard00_Select is accessible on newserv with the $ep3battledebug command.
/* 000A */ uint8_t environment_number;
// This field specifies how many of the camera_zone_maps are used.
@@ -1565,8 +1572,8 @@ public:
std::shared_ptr<const CardEntry> definition_for_name(const std::string& name) const;
std::shared_ptr<const CardEntry> definition_for_name_normalized(const std::string& name) const;
std::set<uint32_t> all_ids() const;
uint64_t definitions_mtime() const;
phosg::JSON definitions_json() const;
uint64_t definitions_hash() const;
private:
static std::string normalize_card_name(const std::string& name);
@@ -1575,7 +1582,7 @@ private:
std::unordered_map<uint32_t, std::shared_ptr<CardEntry>> card_definitions;
std::unordered_map<std::string, std::shared_ptr<CardEntry>> card_definitions_by_name;
std::unordered_map<std::string, std::shared_ptr<CardEntry>> card_definitions_by_name_normalized;
uint64_t mtime_for_card_definitions;
uint64_t defs_hash;
};
class MapIndex {
@@ -1591,12 +1598,14 @@ public:
VersionedMap(std::string&& compressed_data, uint8_t language);
std::shared_ptr<const MapDefinitionTrial> trial() const;
const std::string& compressed(bool is_nte) const;
std::shared_ptr<const std::string> compressed(bool trial) const;
std::shared_ptr<const std::string> trial_download() const;
private:
mutable std::shared_ptr<const MapDefinitionTrial> trial_map;
mutable std::string compressed_data;
mutable std::string compressed_trial_data;
mutable std::shared_ptr<std::string> compressed_data;
mutable std::shared_ptr<std::string> compressed_data_trial;
mutable std::shared_ptr<std::string> download_data_trial;
};
class Map {
@@ -1618,14 +1627,20 @@ public:
};
const std::string& get_compressed_list(size_t num_players, uint8_t language) const;
std::shared_ptr<const Map> for_number(uint32_t id) const;
std::shared_ptr<const Map> for_name(const std::string& name) const;
std::set<uint32_t> all_numbers() const;
inline std::shared_ptr<const Map> get(uint32_t id) const {
return this->maps.at(id);
}
inline std::shared_ptr<const Map> get(const std::string& name) const {
return this->maps_by_name.at(name);
}
inline const std::map<uint32_t, std::shared_ptr<const Map>>& all() const {
return this->maps;
}
private:
// The compressed map lists are generated on demand from the maps map below
mutable std::vector<std::array<std::string, 4>> compressed_map_lists;
std::map<uint32_t, std::shared_ptr<Map>> maps;
std::map<uint32_t, std::shared_ptr<const Map>> maps;
std::unordered_map<std::string, std::shared_ptr<Map>> maps_by_name;
};
+5 -5
View File
@@ -187,7 +187,7 @@ void DeckState::restart() {
this->shuffle();
}
void DeckState::do_mulligan(bool is_nte) {
void DeckState::redraw_initial_hand(bool is_nte) {
for (size_t z = 0; z < this->entries.size(); z++) {
if (this->entries[z].state == CardState::DISCARDED) {
this->entries[z].state = CardState::DRAWABLE;
@@ -308,7 +308,7 @@ static const char* name_for_card_state(DeckState::CardState st) {
}
void DeckState::print(FILE* stream, std::shared_ptr<const CardIndex> card_index) const {
fprintf(stream, "DeckState: client_id=%hhu draw_index=%hhu card_ref_base=@%04hX shuffle=%s loop=%s\n",
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");
for (size_t z = 0; z < 31; z++) {
const auto& e = this->entries[z];
@@ -321,10 +321,10 @@ void DeckState::print(FILE* stream, std::shared_ptr<const CardIndex> card_index)
}
if (ce) {
string name = ce->def.en_name.decode(1);
fprintf(stream, " (%02zu) index=%02hhX ref=@%04hX card_id=#%04hX \"%s\" %s\n",
z, e.deck_index, this->card_refs[z], e.card_id, name.c_str(), name_for_card_state(e.state));
phosg::fwrite_fmt(stream, " ({:02}) index={:02X} ref=@{:04X} card_id=#{:04X} \"{}\" {}\n",
z, e.deck_index, this->card_refs[z], e.card_id, name, name_for_card_state(e.state));
} else {
fprintf(stream, " (%02zu) index=%02hhX ref=@%04hX card_id=#%04hX %s\n",
phosg::fwrite_fmt(stream, " ({:02}) index={:02X} ref=@{:04X} card_id=#{:04X} {}\n",
z, e.deck_index, this->card_refs[z], e.card_id, name_for_card_state(e.state));
}
}
+1 -1
View File
@@ -96,7 +96,7 @@ public:
void restart();
void shuffle();
void do_mulligan(bool is_nte);
void redraw_initial_hand(bool is_nte);
void print(FILE* stream, std::shared_ptr<const CardIndex> card_index = nullptr) const;
+2 -2
View File
@@ -20,11 +20,11 @@ void MapState::clear() {
}
void MapState::print(FILE* stream) const {
fprintf(stream, "[Map: w=%hu h=%hu]\n", this->width.load(), this->height.load());
phosg::fwrite_fmt(stream, "[Map: w={} h={}]\n", this->width, this->height);
for (size_t y = 0; y < this->height; y++) {
fputc(' ', stream);
for (size_t x = 0; x < this->width; x++) {
fprintf(stream, " %02hhX", this->tiles[y][x]);
phosg::fwrite_fmt(stream, " {:02X}", this->tiles[y][x]);
}
fputc('\n', stream);
}
+25 -23
View File
@@ -9,7 +9,7 @@ namespace Episode3 {
PlayerState::PlayerState(uint8_t client_id, shared_ptr<Server> server)
: w_server(server),
client_id(client_id),
num_mulligans_allowed(1),
num_hand_redraws_allowed(1),
sc_card_type(CardType::HUNTERS_SC),
team_id(0xFF),
atk_points(0),
@@ -617,7 +617,8 @@ void PlayerState::discard_and_redraw_hand() {
cmd.change_type = 3;
cmd.client_id = this->client_id;
cmd.card_refs.clear(0xFFFF);
cmd.unknown_a2.clear(0xFFFFFFFF);
cmd.trap_card_id = 0xFFFFFFFF;
cmd.unknown_a3 = 0xFFFFFFFF;
s->send(cmd);
}
@@ -704,14 +705,14 @@ void PlayerState::discard_set_assist_card() {
s->destroy_cards_with_zero_hp();
}
bool PlayerState::do_mulligan() {
if (!this->is_mulligan_allowed()) {
bool PlayerState::redraw_initial_hand() {
if (!this->is_hand_redraw_allowed()) {
return false;
}
auto s = this->server();
this->num_mulligans_allowed--;
this->num_hand_redraws_allowed--;
while (this->card_refs[0] != 0xFFFF) {
this->discard_ref_from_hand(this->card_refs[0]);
}
@@ -721,11 +722,12 @@ bool PlayerState::do_mulligan() {
cmd.change_type = 3;
cmd.client_id = this->client_id;
cmd.card_refs.clear(0xFFFF);
cmd.unknown_a2.clear(0xFFFFFFFF);
cmd.trap_card_id = 0xFFFFFFFF;
cmd.unknown_a3 = 0xFFFFFFFF;
s->send(cmd);
}
this->deck_state->do_mulligan(s->options.is_nte());
this->deck_state->redraw_initial_hand(s->options.is_nte());
this->draw_hand(5);
if (!s->options.is_nte()) {
@@ -839,7 +841,7 @@ vector<uint16_t> PlayerState::get_all_cards_within_range(
auto log = s->log_stack("get_all_cards_within_range: ");
string loc_str = loc.str();
log.debug("loc=%s, target_team_id=%02hhX", loc_str.c_str(), target_team_id);
log.debug_f("loc={}, target_team_id={:02X}", loc_str, target_team_id);
vector<uint16_t> ret;
for (size_t client_id = 0; client_id < 4; client_id++) {
@@ -937,8 +939,8 @@ size_t PlayerState::set_index_for_card_ref(uint16_t card_ref) const {
return -1;
}
bool PlayerState::is_mulligan_allowed() const {
return (this->num_mulligans_allowed > 0);
bool PlayerState::is_hand_redraw_allowed() const {
return (this->num_hand_redraws_allowed > 0);
}
bool PlayerState::is_team_turn() const {
@@ -1764,20 +1766,20 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) {
auto attacker_card = s->card_for_set_card_ref(pa.attacker_card_ref);
if (attacker_card) {
log.debug("attacker card present");
log.debug_f("attacker card present");
attacker_card->card_flags |= 0x100;
}
auto action_type = s->ruler_server->get_pending_action_type(pa);
if (action_type == ActionType::DEFENSE) {
log.debug("action type is DEFENSE");
log.debug_f("action type is DEFENSE");
} else if (action_type == ActionType::ATTACK) {
log.debug("action type is ATTACK");
log.debug_f("action type is ATTACK");
} else {
log.debug("action type is UNKNOWN");
log.debug_f("action type is UNKNOWN");
}
if (!is_nte) {
log.debug("(non-nte) subtracting action points");
log.debug_f("(non-nte) subtracting action points");
this->subtract_or_check_atk_or_def_points_for_action(pa, true);
}
@@ -1785,7 +1787,7 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) {
auto card = s->card_for_set_card_ref(pa.attacker_card_ref);
if (card) {
card->loc.direction = pa.facing_direction;
log.debug("set facing direction to %s", phosg::name_for_enum(card->loc.direction));
log.debug_f("set facing direction to {}", phosg::name_for_enum(card->loc.direction));
G_AddToSetCardLog_Ep3_6xB4x4A cmd;
cmd.card_refs.clear(0xFFFF);
@@ -1794,9 +1796,9 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) {
cmd.entry_count = 0;
size_t z = 0;
do {
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string ref_str = s->debug_str_for_card_ref(pa.action_card_refs[z]);
log.debug("on action card ref %s", ref_str.c_str());
log.debug_f("on action card ref {}", ref_str);
}
card->unknown_80237A90(pa, pa.action_card_refs[z]);
card->unknown_802379BC(pa.action_card_refs[z]);
@@ -1831,9 +1833,9 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) {
for (size_t z = 0; (z < 4 * 9) && (pa.target_card_refs[z] != 0xFFFF); z++) {
auto target_card = s->card_for_set_card_ref(pa.target_card_refs[z]);
if (target_card) {
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string ref_str = s->debug_str_for_card_ref(pa.target_card_refs[z]);
log.debug("on target card ref %s", ref_str.c_str());
log.debug_f("on target card ref {}", ref_str);
}
target_card->unknown_802379DC(pa);
if (!is_nte) {
@@ -1857,13 +1859,13 @@ bool PlayerState::set_action_cards_for_action_state(const ActionState& pa) {
}
}
if (is_nte) {
log.debug("(nte) subtracting action points");
log.debug_f("(nte) subtracting action points");
this->subtract_or_check_atk_or_def_points_for_action(pa, 1);
}
for (size_t z = 0; (z < pa.action_card_refs.size()) && (pa.action_card_refs[z] != 0xFFFF); z++) {
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string ref_str = s->debug_str_for_card_ref(pa.action_card_refs[z]);
log.debug("discarding %s from hand", ref_str.c_str());
log.debug_f("discarding {} from hand", ref_str);
}
this->discard_ref_from_hand(pa.action_card_refs[z]);
}
+3 -3
View File
@@ -66,7 +66,7 @@ public:
void discard_random_hand_card();
bool discard_ref_from_hand(uint16_t card_ref);
void discard_set_assist_card();
bool do_mulligan();
bool redraw_initial_hand();
void draw_hand(ssize_t override_count = 0);
void draw_initial_hand();
int32_t error_code_for_client_setting_card(
@@ -95,7 +95,7 @@ public:
uint8_t get_team_id() const;
ssize_t hand_index_for_card_ref(uint16_t card_ref) const;
size_t set_index_for_card_ref(uint16_t card_ref) const;
bool is_mulligan_allowed() const;
bool is_hand_redraw_allowed() const;
bool is_team_turn() const;
void log_discard(uint16_t card_ref, uint16_t reason);
uint16_t pop_from_discard_log(uint16_t reason);
@@ -152,7 +152,7 @@ public:
std::shared_ptr<Card> sc_card;
bcarray<std::shared_ptr<Card>, 8> set_cards;
uint8_t client_id;
uint16_t num_mulligans_allowed;
uint16_t num_hand_redraws_allowed;
CardType sc_card_type;
uint8_t team_id;
uint8_t atk_points;
+90 -90
View File
@@ -64,19 +64,19 @@ 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 phosg::string_printf(
"Condition[type=%s, turns=%hhu, a_arg=%hhd, dice=%hhu, flags=%02hhX, "
"def_eff_index=%hhu, ref=%s, value=%hd, giver_ref=%s "
"percent=%hhu value8=%hd order=%hu a8=%hu]",
return std::format(
"Condition[type={}, turns={}, a_arg={}, dice={}, flags={:02X}, "
"def_eff_index={}, ref={}, value={}, giver_ref={} "
"percent={} value8={} order={} a8={}]",
phosg::name_for_enum(this->type),
this->remaining_turns,
this->a_arg_value,
this->dice_roll_value,
this->flags,
this->card_definition_effect_index,
card_ref_str.c_str(),
this->value.load(),
giver_ref_str.c_str(),
card_ref_str,
this->value,
giver_ref_str,
this->random_percent,
this->value8,
this->order,
@@ -103,12 +103,12 @@ 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 phosg::string_printf(
"EffectResult[att_ref=%s, target_ref=%s, value=%hhd, "
"cur_hp=%hhd, ap=%hhd, tp=%hhd, flags=%02hhX, op=%hhd, "
"cond_index=%hhu, dice=%hhu]",
attacker_ref_str.c_str(),
target_ref_str.c_str(),
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,
this->value,
this->current_hp,
this->ap,
@@ -139,14 +139,14 @@ 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 phosg::string_printf(
"CardShortStatus[ref=%s, cur_hp=%hd, flags=%08" PRIX32 ", loc=%s, "
"u1=%04hX, max_hp=%hhd, u2=%hhu]",
ref_str.c_str(),
this->current_hp.load(),
this->card_flags.load(),
loc_s.c_str(),
this->unused1.load(),
return std::format(
"CardShortStatus[ref={}, cur_hp={}, flags={:08X}, loc={}, "
"u1={:04X}, max_hp={}, u2={}]",
ref_str,
this->current_hp,
this->card_flags,
loc_s,
this->unused1,
this->max_hp,
this->unused2);
}
@@ -193,18 +193,18 @@ std::string ActionState::str(shared_ptr<const Server> s) const {
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 phosg::string_printf(
"ActionState[client=%hX, u=%hhu, facing=%s, attacker_ref=%s, "
"def_ref=%s, target_refs=%s, action_refs=%s, "
"orig_attacker_ref=%s]",
this->client_id.load(),
return std::format(
"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.c_str(),
defense_ref_s.c_str(),
target_refs_s.c_str(),
action_refs_s.c_str(),
original_attacker_ref_s.c_str());
attacker_ref_s,
defense_ref_s,
target_refs_s,
action_refs_s,
original_attacker_ref_s);
}
ActionChain::ActionChain() {
@@ -243,20 +243,20 @@ std::string ActionChain::str(shared_ptr<const Server> s) const {
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 phosg::string_printf(
"ActionChain[eff_ap=%hhd, eff_tp=%hhd, ap_bonus=%hhd, damage=%hhd, "
"acting_ref=%s, unknown_ref_a3=%s, attack_action_refs=%s, "
"attack_action_ref_count=%hhu, medium=%s, target_ref_count=%hhu, "
"subphase=%s, strikes=%hhu, damage_mult=%hhd, attack_num=%hhu, "
"tp_bonus=%hhd, phys_bonus_nte=%hhu, tech_bonus_nte=%hhu, card_ap=%hhd, "
"card_tp=%hhd, flags=%08" PRIX32 ", target_refs=%s]",
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={}]",
this->effective_ap,
this->effective_tp,
this->ap_effect_bonus,
this->damage,
acting_card_ref_s.c_str(),
unknown_card_ref_a3_s.c_str(),
attack_action_card_refs_s.c_str(),
acting_card_ref_s,
unknown_card_ref_a3_s,
attack_action_card_refs_s,
this->attack_action_card_ref_count,
phosg::name_for_enum(this->attack_medium),
this->target_card_ref_count,
@@ -269,8 +269,8 @@ std::string ActionChain::str(shared_ptr<const Server> s) const {
this->tech_attack_bonus_nte,
this->card_ap,
this->card_tp,
this->flags.load(),
target_card_refs_s.c_str());
this->flags,
target_card_refs_s);
}
void ActionChain::clear() {
@@ -341,7 +341,7 @@ std::string ActionChainWithConds::str(shared_ptr<const Server> s) const {
if (ret.back() != '[') {
ret += ", ";
}
ret += phosg::string_printf("%zu:", z);
ret += std::format("{}:", z);
ret += this->conditions[z].str(s);
}
}
@@ -580,22 +580,22 @@ std::string ActionMetadata::str(shared_ptr<const Server> s) const {
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 phosg::string_printf(
"ActionMetadata[ref=%s, target_ref_count=%hhu, def_ref_count=%hhu, "
"subphase=%s, def_power=%hhd, def_bonus=%hhd, "
"att_bonus=%hhd, flags=%08" PRIX32 ", target_refs=%s, "
"defense_refs=%s, original_attacker_refs=%s]",
card_ref_s.c_str(),
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,
this->target_card_ref_count,
this->defense_card_ref_count,
phosg::name_for_enum(this->action_subphase),
this->defense_power,
this->defense_bonus,
this->attack_bonus,
this->flags.load(),
target_card_refs_s.c_str(),
defense_card_refs_s.c_str(),
original_attacker_card_refs_s.c_str());
this->flags,
target_card_refs_s,
defense_card_refs_s,
original_attacker_card_refs_s);
}
void ActionMetadata::clear() {
@@ -683,13 +683,13 @@ std::string HandAndEquipState::str(shared_ptr<const Server> s) const {
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 phosg::string_printf(
"HandAndEquipState[dice=[%hhu, %hhu], atk=%hhu, def=%hhu, atk2=%hhu, "
"a1=%hhu, total_set_cost=%hhu, is_cpu=%hhu, assist_flags=%08" PRIX32 ", "
"hand_refs=%s, assist_ref=%s, set_refs=%s, sc_ref=%s, hand_refs2=%s, "
"set_refs2=%s, assist_ref2=%s, assist_set_num=%hu, assist_card_id=%s, "
"assist_turns=%hhu, assist_delay=%hhu, atk_bonus=%hhu, def_bonus=%hhu, "
"u2=[%hhu, %hhu]]",
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=[{}, {}]]",
this->dice_results[0],
this->dice_results[1],
this->atk_points,
@@ -698,16 +698,16 @@ std::string HandAndEquipState::str(shared_ptr<const Server> s) const {
this->unknown_a1,
this->total_set_cards_cost,
this->is_cpu_player,
this->assist_flags.load(),
hand_card_refs_s.c_str(),
assist_card_ref_s.c_str(),
set_card_refs_s.c_str(),
sc_card_ref_s.c_str(),
hand_card_refs2_s.c_str(),
set_card_refs2_s.c_str(),
assist_card_ref2_s.c_str(),
this->assist_card_set_number.load(),
assist_card_id_s.c_str(),
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,
this->assist_card_set_number,
assist_card_id_s,
this->assist_remaining_turns,
this->assist_delay_turns,
this->atk_bonuses,
@@ -838,19 +838,19 @@ const char* PlayerBattleStats::name_for_rank(uint8_t rank) {
}
PlayerBattleStatsTrial::PlayerBattleStatsTrial(const PlayerBattleStats& data)
: damage_given(data.damage_given.load()),
damage_taken(data.damage_taken.load()),
num_opponent_cards_destroyed(data.num_opponent_cards_destroyed.load()),
num_owned_cards_destroyed(data.num_owned_cards_destroyed.load()),
total_move_distance(data.total_move_distance.load()) {}
: damage_given(data.damage_given),
damage_taken(data.damage_taken),
num_opponent_cards_destroyed(data.num_opponent_cards_destroyed),
num_owned_cards_destroyed(data.num_owned_cards_destroyed),
total_move_distance(data.total_move_distance) {}
PlayerBattleStatsTrial::operator PlayerBattleStats() const {
PlayerBattleStats ret;
ret.damage_given = this->damage_given.load();
ret.damage_taken = this->damage_taken.load();
ret.num_opponent_cards_destroyed = this->num_opponent_cards_destroyed.load();
ret.num_owned_cards_destroyed = this->num_owned_cards_destroyed.load();
ret.total_move_distance = this->total_move_distance.load();
ret.damage_given = this->damage_given;
ret.damage_taken = this->damage_taken;
ret.num_opponent_cards_destroyed = this->num_opponent_cards_destroyed;
ret.num_owned_cards_destroyed = this->num_owned_cards_destroyed;
ret.total_move_distance = this->total_move_distance;
return ret;
}
@@ -861,26 +861,26 @@ static bool is_card_within_range(
phosg::PrefixedLogger* log) {
if (ss.card_ref == 0xFFFF) {
if (log) {
log->debug("is_card_within_range: (false) ss.card_ref missing");
log->debug_f("is_card_within_range: (false) ss.card_ref missing");
}
return false;
}
if (range[0] == 2) {
if (log) {
log->debug("is_card_within_range: (true) range is entire field");
log->debug_f("is_card_within_range: (true) range is entire field");
}
return true;
}
if ((ss.loc.x < anchor_loc.x - 4) || (ss.loc.x > anchor_loc.x + 4)) {
if (log) {
log->debug("is_card_within_range: (false) outside x range (ss.loc.x=%hhu, anchor_loc.x=%hhu)", 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("is_card_within_range: (false) outside y range (ss.loc.y=%hhu, anchor_loc.y=%hhu)", 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;
}
@@ -889,7 +889,7 @@ static bool is_card_within_range(
uint8_t x_index = (ss.loc.x - anchor_loc.x) + 4;
bool ret = (range[y_index * 9 + x_index] != 0);
if (log) {
log->debug("is_card_within_range: (%s) (ss.loc=(%hhu,%hhu), anchor_loc=(%hhu,%hhu), indexes=(%hhu,%hhu))",
log->debug_f("is_card_within_range: ({}) (ss.loc=({},{}), anchor_loc=({},{}), indexes=({},{}))",
ret ? "true" : "false", ss.loc.x, ss.loc.y, anchor_loc.x, anchor_loc.y, x_index, y_index);
}
return ret;
@@ -903,24 +903,24 @@ vector<uint16_t> get_card_refs_within_range(
vector<uint16_t> ret;
if (is_card_within_range(range, loc, short_statuses[0], log)) {
if (log) {
log->debug("get_card_refs_within_range: sc card @%04hX within range", short_statuses[0].card_ref.load());
log->debug_f("get_card_refs_within_range: sc card @{:04X} within range", short_statuses[0].card_ref);
}
ret.emplace_back(short_statuses[0].card_ref);
} else {
if (log) {
log->debug("get_card_refs_within_range: sc card @%04hX not within range", short_statuses[0].card_ref.load());
log->debug_f("get_card_refs_within_range: sc card @{:04X} not within range", short_statuses[0].card_ref);
}
}
for (size_t card_index = 7; card_index < 15; card_index++) {
const auto& ss = short_statuses[card_index];
if (is_card_within_range(range, loc, ss, log)) {
if (log) {
log->debug("get_card_refs_within_range: card @%04hX within range", ss.card_ref.load());
log->debug_f("get_card_refs_within_range: card @{:04X} within range", ss.card_ref);
}
ret.emplace_back(ss.card_ref);
} else {
if (log) {
log->debug("get_card_refs_within_range: card @%04hX not within range", ss.card_ref.load());
log->debug_f("get_card_refs_within_range: card @{:04X} not within range", ss.card_ref);
}
}
}
+34 -34
View File
@@ -16,10 +16,10 @@ void compute_effective_range(
const Location& loc,
shared_ptr<const MapAndRulesState> map_and_rules,
phosg::PrefixedLogger* log) {
if (log && log->should_log(phosg::LogLevel::DEBUG)) {
if (log && log->should_log(phosg::LogLevel::L_DEBUG)) {
string loc_str = loc.str();
log->debug("compute_effective_range: card_id=#%04hX, loc=%s", card_id, loc_str.c_str());
log->debug("compute_effective_range: map_and_rules->map:");
log->debug_f("compute_effective_range: card_id=#{:04X}, loc={}", card_id, loc_str);
log->debug_f("compute_effective_range: map_and_rules->map:");
map_and_rules->map.print(stderr);
}
ret.clear(0);
@@ -40,14 +40,14 @@ void compute_effective_range(
}
}
if (log) {
log->debug("compute_effective_range: range_def: %05" PRIX32 " %05" PRIX32 " %05" PRIX32 " %05" PRIX32 " %05" PRIX32 " %05" PRIX32, 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
ret.clear(2);
if (log) {
log->debug("compute_effective_range: entire field (2)");
log->debug_f("compute_effective_range: entire field (2)");
}
return;
}
@@ -64,7 +64,7 @@ void compute_effective_range(
}
if (log) {
for (size_t y = 0; y < 9; y++) {
log->debug("compute_effective_range: decoded_range: %hhX %hhX %hhX %hhX %hhX %hhX %hhX %hhX %hhX",
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]);
}
}
@@ -98,7 +98,7 @@ void compute_effective_range(
}
ret[y * 9 + x] = decoded_range[up_y * 9 + up_x];
if (log) {
log->debug("compute_effective_range: x=%hd y=%hd up_x=%hd up_y=%hd v=%hhX", 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]);
}
}
}
@@ -107,7 +107,7 @@ void compute_effective_range(
if (log) {
for (size_t y = 0; y < 9; y++) {
log->debug("compute_effective_range: ret: %hhX %hhX %hhX %hhX %hhX %hhX %hhX %hhX %hhX",
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]);
}
}
@@ -941,7 +941,7 @@ bool RulerServer::check_usability_or_condition_apply(
AttackMedium attack_medium) const {
auto s = this->server();
bool is_nte = s->options.is_nte();
auto log = s->log_stack(phosg::string_printf("check_usability_or_condition_apply(%02hhX, #%04hX, %02hhX, #%04hX, #%04hX, %02hhX, %s, %s): ", client_id1, card_id1, client_id2, card_id2, card_id3, def_effect_index, is_item_usability_check ? "true" : "false", phosg::name_for_enum(attack_medium)));
auto log = s->log_stack(std::format("check_usability_or_condition_apply({:02X}, #{:04X}, {:02X}, #{:04X}, #{:04X}, {:02X}, {}, {}): ", client_id1, card_id1, client_id2, card_id2, card_id3, def_effect_index, is_item_usability_check ? "true" : "false", phosg::name_for_enum(attack_medium)));
if (static_cast<uint8_t>(attack_medium) & 0x80) {
attack_medium = AttackMedium::UNKNOWN;
@@ -951,11 +951,11 @@ bool RulerServer::check_usability_or_condition_apply(
auto ce2 = this->definition_for_card_id(card_id2);
auto ce3 = this->definition_for_card_id(card_id3);
if (!ce1) {
log.debug("ce1 missing");
log.debug_f("ce1 missing");
return false;
}
if (!is_nte && (ce1->def.type == CardType::ITEM) && this->card_id_is_boss_sc(card_id2)) {
log.debug("ce1 is item and card_id2 is boss sc");
log.debug_f("ce1 is item and card_id2 is boss sc");
return false;
}
@@ -964,12 +964,12 @@ bool RulerServer::check_usability_or_condition_apply(
criterion_code = ce1->def.usable_criterion;
} else {
if (def_effect_index > 2) {
log.debug("invalid def_effect_index");
log.debug_f("invalid def_effect_index");
return false;
}
criterion_code = ce1->def.effects[def_effect_index].apply_criterion;
}
log.debug("criterion_code=%s", phosg::name_for_enum(criterion_code));
log.debug_f("criterion_code={}", phosg::name_for_enum(criterion_code));
// For item usability checks, prevent criteria that depend on player
// positioning/team setup
@@ -980,7 +980,7 @@ bool RulerServer::check_usability_or_condition_apply(
(criterion_code == CriterionCode::FC) ||
(criterion_code == CriterionCode::NOT_SC) ||
(criterion_code == CriterionCode::SC))) {
log.debug("criterion is forbidden");
log.debug_f("criterion is forbidden");
criterion_code = CriterionCode::NONE;
}
@@ -1354,7 +1354,7 @@ bool RulerServer::check_usability_or_condition_apply(
}
}
log.debug("default return (false)");
log.debug_f("default return (false)");
return false;
}
@@ -1478,43 +1478,43 @@ bool RulerServer::compute_effective_range_and_target_mode_for_attack(
for (z = 0; (z < 8) && (pa.action_card_refs[z] != 0xFFFF); z++) {
}
if (z >= 8) {
log.debug("too many action card refs");
log.debug_f("too many action card refs");
return false;
}
log.debug("%zu action card refs", z);
log.debug_f("{} action card refs", z);
uint16_t card_ref = (z == 0) ? pa.attacker_card_ref : pa.action_card_refs[z - 1];
log.debug("base card ref = @%04hX", card_ref);
log.debug_f("base card ref = @{:04X}", card_ref);
uint16_t card_id = this->card_id_for_card_ref(card_ref);
if (card_id == 0xFFFF) {
log.debug("card ref is broken");
log.debug_f("card ref is broken");
return false;
}
auto ce = this->definition_for_card_id(card_id);
uint8_t client_id = client_id_for_card_ref(pa.attacker_card_ref);
if ((client_id == 0xFF) || !ce) {
log.debug("card ref is broken or definition is missing");
log.debug_f("card ref is broken or definition is missing");
return false;
}
if (out_orig_card_ref) {
log.debug("orig_card_ref = @%04hX", card_ref);
log.debug_f("orig_card_ref = @{:04X}", card_ref);
*out_orig_card_ref = card_ref;
}
auto target_mode = ce->def.target_mode;
if (this->card_ref_or_sc_has_fixed_range(pa.attacker_card_ref)) {
const char* target_mode_name = name_for_target_mode(target_mode);
log.debug("attacker card ref @%04hX has fixed range; target mode is %s (%hhu)",
pa.attacker_card_ref.load(), target_mode_name, static_cast<uint8_t>(target_mode));
log.debug_f("attacker card ref @{:04X} has fixed range; target mode is {} ({})",
pa.attacker_card_ref, target_mode_name, static_cast<uint8_t>(target_mode));
card_id = this->card_id_for_card_ref(pa.attacker_card_ref);
if (!is_nte) {
auto sc_ce = this->definition_for_card_id(card_id);
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("sc_ce overrides target mode with %s (%hhu)",
log.debug_f("sc_ce overrides target mode with {} ({})",
target_mode_name, static_cast<uint8_t>(target_mode));
}
}
@@ -1525,10 +1525,10 @@ bool RulerServer::compute_effective_range_and_target_mode_for_attack(
auto assist_effect = this->assist_server->get_active_assist_by_index(z);
if (assist_effect == AssistEffect::SIMPLE) {
card_id = this->card_id_for_card_ref(pa.attacker_card_ref);
log.debug("SIMPLE assist overrides card id with #%04hX", card_id);
log.debug_f("SIMPLE assist overrides card id with #{:04X}", card_id);
} else if (assist_effect == AssistEffect::HEAVY_FOG) {
card_id = 0xFFFE;
log.debug("HEAVY_FOG assist overrides card id with #%04hX", card_id);
log.debug_f("HEAVY_FOG assist overrides card id with #{:04X}", card_id);
}
}
@@ -2059,27 +2059,27 @@ shared_ptr<const CardIndex::CardEntry> RulerServer::definition_for_card_id(uint3
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(phosg::string_printf("get_card_id_with_effective_range(@%04hX, #%04hX): ", card_ref, card_id_override));
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;
log.debug("card_id=#%04hX", card_id);
log.debug_f("card_id=#{:04X}", card_id);
if (card_id != 0xFFFF) {
auto ce = this->definition_for_card_id(card_id);
uint8_t client_id = client_id_for_card_ref(card_ref);
if ((client_id != 0xFF) && ce) {
TargetMode effective_target_mode = ce->def.target_mode;
log.debug("ce valid for #%04hX with effective target mode %s", card_id, name_for_target_mode(effective_target_mode));
log.debug_f("ce valid for #{:04X} with effective target mode {}", card_id, name_for_target_mode(effective_target_mode));
if (this->card_ref_or_sc_has_fixed_range(card_ref)) {
// Undo the override that may have been passed in
log.debug("@%04hX has FIXED_RANGE", card_ref);
log.debug_f("@{:04X} has FIXED_RANGE", card_ref);
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("ce valid for #%04hX with effective target mode %s; overriding to %s", 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;
}
}
@@ -2089,17 +2089,17 @@ uint32_t RulerServer::get_card_id_with_effective_range(
auto eff = this->assist_server->get_active_assist_by_index(z);
if (eff == AssistEffect::SIMPLE) {
card_id = this->card_id_for_card_ref(card_ref);
log.debug("SIMPLE assist effect is active; using #%04hX for range", card_id);
log.debug_f("SIMPLE assist effect is active; using #{:04X} for range", card_id);
} else if (eff == AssistEffect::HEAVY_FOG) {
card_id = 0xFFFE;
log.debug("HEAVY_FOG assist effect is active; limiting range to one tile in front");
log.debug_f("HEAVY_FOG assist effect is active; limiting range to one tile in front");
}
}
if (out_target_mode) {
*out_target_mode = effective_target_mode;
}
log.debug("results: card_id=#%04hX, target_mode=%s", card_id, name_for_target_mode(effective_target_mode));
log.debug_f("results: card_id=#{:04X}, target_mode={}", card_id, name_for_target_mode(effective_target_mode));
}
}
+82 -102
View File
@@ -58,7 +58,7 @@ Server::Server(shared_ptr<Lobby> lobby, Options&& options)
battle_start_usecs(0),
should_copy_prev_states_to_current_states(0),
card_special(nullptr),
clients_done_in_mulligan_phase(false),
clients_done_in_redraw_initial_hand_phase(false),
num_pending_attacks_with_cards(0),
unknown_a14(0),
unknown_a15(0),
@@ -83,12 +83,14 @@ Server::Server(shared_ptr<Lobby> lobby, Options&& options)
Server::~Server() noexcept(false) {
if (this->logger_stack.size() != 1) {
throw logic_error(phosg::string_printf("incorrect logger stack size: expected 1, received %zu", this->logger_stack.size()));
throw logic_error(std::format("incorrect logger stack size: expected 1, received {}", this->logger_stack.size()));
}
delete this->logger_stack.back();
}
void Server::init() {
this->log().info_f("Creating server with random seed {:08X}", this->options.rand_crypt->seed());
this->map_and_rules = make_shared<MapAndRulesState>();
this->num_clients_present = 0;
this->overlay_state.clear();
@@ -173,9 +175,9 @@ std::string Server::debug_str_for_card_ref(uint16_t card_ref) const {
auto ce = this->definition_for_card_ref(card_ref);
if (ce) {
string name = ce->def.en_name.decode();
return phosg::string_printf("@%04hX (#%04" PRIX32 " %s)", card_ref, ce->def.card_id.load(), name.c_str());
return std::format("@{:04X} (#{:04X} {})", card_ref, ce->def.card_id, name);
} else {
return phosg::string_printf("@%04hX (missing)", card_ref);
return std::format("@{:04X} (missing)", card_ref);
}
}
@@ -186,9 +188,9 @@ std::string Server::debug_str_for_card_id(uint16_t card_id) const {
auto ce = this->definition_for_card_id(card_id);
if (ce) {
string name = ce->def.en_name.decode();
return phosg::string_printf("#%04hX (%s)", card_id, name.c_str());
return std::format("#{:04X} ({})", card_id, name);
} else {
return phosg::string_printf("#%04hX (missing)", card_id);
return std::format("#{:04X} (missing)", card_id);
}
}
@@ -260,7 +262,7 @@ void Server::send(const void* data, size_t size, uint8_t command, bool enable_ma
}
} else if ((this->options.behavior_flags & BehaviorFlag::LOG_COMMANDS_IF_LOBBY_MISSING) &&
this->log().info("Generated command")) {
this->log().info_f("Generated command")) {
phosg::print_data(stderr, data, size, 0, nullptr, phosg::PrintDataFlags::PRINT_ASCII | phosg::PrintDataFlags::DISABLE_COLOR | phosg::PrintDataFlags::OFFSET_16_BITS);
}
}
@@ -273,9 +275,9 @@ void Server::send_6xB4x46() const {
// debugging easier.
G_ServerVersionStrings_Ep3_6xB4x46 cmd;
cmd.version_signature.encode(this->options.is_nte() ? VERSION_SIGNATURE_NTE : VERSION_SIGNATURE, 1);
cmd.date_str1.encode(phosg::format_time(this->options.card_index->definitions_mtime() * 1000000), 1);
cmd.date_str1.encode(std::format("Card definitions: {:016X}", this->options.card_index->definitions_hash()), 1);
string build_date = phosg::format_time(BUILD_TIMESTAMP);
cmd.date_str2.encode(phosg::string_printf("newserv %s compiled at %s", GIT_REVISION_HASH, build_date.c_str()), 1);
cmd.date_str2.encode(std::format("newserv {} compiled at {}", GIT_REVISION_HASH, build_date), 1);
this->send(cmd);
}
@@ -285,13 +287,13 @@ string Server::prepare_6xB6x41_map_definition(shared_ptr<const MapIndex::Map> ma
const auto& compressed = vm->compressed(is_nte);
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.write(compressed);
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.write(*compressed);
return std::move(w.str());
}
void Server::send_commands_for_joining_spectator(Channel& ch) const {
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
@@ -303,84 +305,62 @@ void Server::send_commands_for_joining_spectator(Channel& ch) const {
}
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("Sending %c version of map %08" PRIX32, char_for_language_code(ch.language), this->last_chosen_map->map_number);
ch.send(0x6C, 0x00, data);
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}", char_for_language_code(ch->language), this->last_chosen_map->map_number);
ch->send(0x6C, 0x00, data);
}
if (should_send_state) {
ch.send(0xC9, 0x00, this->prepare_6xB4x03());
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];
if (ps) {
ch.send(0xC9, 0x00, ps->prepare_6xB4x02());
ch.send(0xC9, 0x00, ps->prepare_6xB4x04());
ch->send(0xC9, 0x00, ps->prepare_6xB4x02());
ch->send(0xC9, 0x00, ps->prepare_6xB4x04());
}
}
if (ch.version == Version::GC_EP3_NTE) {
if (ch->version == Version::GC_EP3_NTE) {
G_UpdateMap_Ep3NTE_6xB4x05 cmd;
cmd.state = *this->map_and_rules;
ch.send(0xC9, 0x00, cmd);
ch->send(0xC9, 0x00, cmd);
} else {
G_UpdateMap_Ep3_6xB4x05 cmd;
cmd.state = *this->map_and_rules;
ch.send(0xC9, 0x00, cmd);
ch->send(0xC9, 0x00, cmd);
}
// TODO: Sega does something like this; do we have to do this too?
// for (uint8_t client_id = 0; client_id < 4; client_id++) {
// (send 6xB4x4E, 6xB4x4C, 6xB4x4D for each set card)
// (send 6xB4x4F for client_id)
// }
ch.send(0xC9, 0x00, this->prepare_6xB4x07_decks_update());
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)
ch.send(0xC9, 0x00, this->prepare_6xB4x1C_names_update());
ch.send(0xC9, 0x00, this->prepare_6xB4x50_trap_tile_locations());
ch->send(0xC9, 0x00, this->prepare_6xB4x1C_names_update());
ch->send(0xC9, 0x00, this->prepare_6xB4x50_trap_tile_locations());
{
G_LoadCurrentEnvironment_Ep3_6xB4x3B cmd_3B;
ch.send(0xC9, 0x00, &cmd_3B, sizeof(cmd_3B));
ch->send(0xC9, 0x00, &cmd_3B, sizeof(cmd_3B));
}
}
}
__attribute__((format(printf, 2, 3))) void Server::send_debug_message_printf(const char* fmt, ...) const {
auto l = this->lobby.lock();
if (l && (this->options.behavior_flags & Episode3::BehaviorFlag::ENABLE_STATUS_MESSAGES)) {
va_list va;
va_start(va, fmt);
std::string buf = phosg::string_vprintf(fmt, va);
va_end(va);
send_text_message(l, buf);
}
}
__attribute__((format(printf, 2, 3))) void Server::send_info_message_printf(const char* fmt, ...) const {
auto l = this->lobby.lock();
if (l) {
va_list va;
va_start(va, fmt);
std::string buf = phosg::string_vprintf(fmt, va);
va_end(va);
send_text_message(l, buf);
}
}
void Server::send_debug_command_received_message(
uint8_t client_id, uint8_t subsubcommand, const char* description) const {
this->log().debug("%hhu/CAx%02hhX %s", client_id, subsubcommand, description);
this->send_debug_message_printf("$C5%hhu/CAx%02hhX %s", client_id, subsubcommand, description);
this->log().debug_f("{}/CAx{:02X} {}", client_id, subsubcommand, description);
this->send_debug_message("$C5{}/CAx{:02X} {}", client_id, subsubcommand, description);
}
void Server::send_debug_command_received_message(uint8_t subsubcommand, const char* description) const {
this->log().debug("*/CAx%02hhX %s", subsubcommand, description);
this->send_debug_message_printf("$C5*/CAx%02hhX %s", subsubcommand, description);
this->log().debug_f("*/CAx{:02X} {}", subsubcommand, description);
this->send_debug_message("$C5*/CAx{:02X} {}", subsubcommand, description);
}
void Server::send_debug_message_if_error_code_nonzero(uint8_t client_id, int32_t error_code) const {
if (error_code < 0) {
this->send_debug_message_printf("$C4%hhu/ERROR -0x%zX", client_id, static_cast<ssize_t>(-error_code));
this->send_debug_message("$C4{}/ERROR -0x{:X}", client_id, static_cast<ssize_t>(-error_code));
} else if (error_code > 0) {
this->send_debug_message_printf("$C4%hhu/ERROR 0x%zX", client_id, static_cast<ssize_t>(error_code));
this->send_debug_message("$C4{}/ERROR 0x{:X}", client_id, static_cast<ssize_t>(error_code));
}
}
@@ -949,62 +929,62 @@ void Server::end_action_phase() {
bool Server::enqueue_attack_or_defense(uint8_t client_id, ActionState* pa) {
auto log = this->log_stack("enqueue_attack_or_defense: ");
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string s = pa->str(this->shared_from_this());
log.debug("input: %s", s.c_str());
log.debug_f("input: {}", s);
}
if (client_id >= 4) {
this->ruler_server->error_code3 = -0x78;
log.debug("failed: invalid client ID");
log.debug_f("failed: invalid client ID");
return false;
}
auto ps = this->player_states[client_id];
if (!ps) {
this->ruler_server->error_code3 = -0x72;
log.debug("failed: player not present");
log.debug_f("failed: player not present");
return false;
}
if (pa->action_card_refs[0] == 0xFFFF) {
if (pa->defense_card_ref != 0xFFFF) {
pa->action_card_refs[0] = pa->defense_card_ref;
log.debug("moved defense card ref to action card ref 0");
log.debug_f("moved defense card ref to action card ref 0");
}
} else {
pa->defense_card_ref = pa->action_card_refs[0];
log.debug("moved action card ref 0 to defense card ref");
log.debug_f("moved action card ref 0 to defense card ref");
}
if (!this->ruler_server->is_attack_or_defense_valid(*pa)) {
log.debug("failed: attack or defense not valid");
log.debug_f("failed: attack or defense not valid");
return false;
}
int16_t ally_atk_result = this->send_6xB4x33_remove_ally_atk_if_needed(*pa);
if (ally_atk_result == 1) {
log.debug("pending: need ally approval");
log.debug_f("pending: need ally approval");
return true;
} else if (ally_atk_result == -1) {
log.debug("failed: ally declined");
log.debug_f("failed: ally declined");
return false;
}
if (this->num_pending_attacks >= 0x20) {
this->ruler_server->error_code3 = -0x71;
log.debug("failed: too many pending attacks");
log.debug_f("failed: too many pending attacks");
return false;
}
size_t attack_index = this->num_pending_attacks++;
this->pending_attacks[attack_index] = *pa;
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string pa_str = this->pending_attacks[attack_index].str(this->shared_from_this());
log.debug("set pending attack %zu: %s", attack_index, pa_str.c_str());
log.debug_f("set pending attack {}: {}", attack_index, pa_str);
}
ps->set_action_cards_for_action_state(*pa);
log.debug("set action cards");
log.debug_f("set action cards");
auto card = this->card_for_set_card_ref(this->send_6xB4x06_if_card_ref_invalid(pa->attacker_card_ref, 1));
if (card) {
card->card_flags |= 0x400;
@@ -1056,7 +1036,7 @@ uint32_t Server::get_random_raw() {
if (this->options.opt_rand_stream) {
this->options.opt_rand_stream->readx(&ret, sizeof(ret));
} else {
ret = random_from_optional_crypt(this->options.opt_rand_crypt);
ret = this->options.rand_crypt->next();
}
if (this->battle_record && this->battle_record->writable()) {
@@ -1164,8 +1144,8 @@ void Server::move_phase_after() {
cmd.loc.x = trap_x;
cmd.loc.y = trap_y;
cmd.loc.direction = static_cast<Direction>(trap_type);
cmd.unknown_a2[0] = trap_card_id;
cmd.unknown_a2[1] = 0xFFFFFFFF;
cmd.trap_card_id = trap_card_id;
cmd.unknown_a3 = 0xFFFFFFFF;
this->send(cmd);
}
}
@@ -1740,20 +1720,20 @@ bool Server::update_registration_phase() {
auto log = this->log_stack("update_registration_phase: ");
if (this->setup_phase != SetupPhase::REGISTRATION) {
log.debug("setup_phase is not REGISTRATION");
log.debug_f("setup_phase is not REGISTRATION");
return false;
}
if (this->map_and_rules->num_players == 0) {
this->registration_phase = RegistrationPhase::AWAITING_NUM_PLAYERS;
log.debug("registration_phase set to AWAITING_NUM_PLAYERS");
log.debug_f("registration_phase set to AWAITING_NUM_PLAYERS");
this->update_battle_state_flags_and_send_6xB4x03_if_needed();
return false;
}
if (this->map_and_rules->num_players != this->num_clients_present) {
this->registration_phase = RegistrationPhase::AWAITING_PLAYERS;
log.debug("registration_phase set to AWAITING_PLAYERS");
log.debug_f("registration_phase set to AWAITING_PLAYERS");
this->update_battle_state_flags_and_send_6xB4x03_if_needed();
return false;
}
@@ -1767,20 +1747,20 @@ bool Server::update_registration_phase() {
if (num_team0_registered_players != this->map_and_rules->num_team0_players) {
this->registration_phase = RegistrationPhase::AWAITING_DECKS;
log.debug("registration_phase set to AWAITING_DECKS");
log.debug_f("registration_phase set to AWAITING_DECKS");
this->update_battle_state_flags_and_send_6xB4x03_if_needed();
return false;
}
this->registration_phase = RegistrationPhase::REGISTERED;
this->update_battle_state_flags_and_send_6xB4x03_if_needed();
log.debug("battle can begin");
log.debug_f("battle can begin");
return true;
}
const unordered_map<uint8_t, Server::handler_t> Server::subcommand_handlers({
{0x0B, &Server::handle_CAx0B_mulligan_hand},
{0x0C, &Server::handle_CAx0C_end_mulligan_phase},
{0x0B, &Server::handle_CAx0B_redraw_initial_hand},
{0x0C, &Server::handle_CAx0C_end_redraw_initial_hand_phase},
{0x0D, &Server::handle_CAx0D_end_non_action_phase},
{0x0E, &Server::handle_CAx0E_discard_card_from_hand},
{0x0F, &Server::handle_CAx0F_set_card_from_hand},
@@ -1809,7 +1789,7 @@ 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(phosg::string_printf("command is incomplete: expected %zX bytes, received %zX 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");
@@ -1835,7 +1815,7 @@ void Server::on_server_data_input(shared_ptr<Client> sender_c, const string& dat
}
}
void Server::handle_CAx0B_mulligan_hand(shared_ptr<Client>, const string& data) {
void Server::handle_CAx0B_redraw_initial_hand(shared_ptr<Client>, const string& data) {
const auto& in_cmd = check_size_t<G_RedrawInitialHand_Ep3_CAx0B>(data);
this->send_debug_command_received_message(in_cmd.client_id, in_cmd.header.subsubcommand, "REDRAW");
if (in_cmd.client_id >= 4) {
@@ -1854,22 +1834,22 @@ void Server::handle_CAx0B_mulligan_hand(shared_ptr<Client>, const string& data)
if (!ps) {
error_code = -0x72;
} else {
ps->do_mulligan();
ps->redraw_initial_hand();
}
}
if (!this->options.is_nte() || (error_code == 0)) {
G_ActionResult_Ep3_6xB4x1E out_cmd;
out_cmd.sequence_num = in_cmd.header.sequence_num.load();
out_cmd.sequence_num = in_cmd.header.sequence_num;
out_cmd.error_code = error_code;
this->send(out_cmd);
}
this->send_debug_message_if_error_code_nonzero(in_cmd.client_id, error_code);
}
void Server::handle_CAx0C_end_mulligan_phase(shared_ptr<Client>, const string& data) {
void Server::handle_CAx0C_end_redraw_initial_hand_phase(shared_ptr<Client>, const string& data) {
const auto& in_cmd = check_size_t<G_EndInitialRedrawPhase_Ep3_CAx0C>(data);
this->send_debug_command_received_message(in_cmd.client_id, in_cmd.header.subsubcommand, "SETUP ADV 2");
this->send_debug_command_received_message(in_cmd.client_id, in_cmd.header.subsubcommand, "HAND READY");
if (in_cmd.client_id >= 4) {
throw runtime_error("invalid client ID");
}
@@ -1898,13 +1878,13 @@ void Server::handle_CAx0C_end_mulligan_phase(shared_ptr<Client>, const string& d
if (!ps) {
error_code = -0x72;
} else {
this->clients_done_in_mulligan_phase[in_cmd.client_id] = true;
this->clients_done_in_redraw_initial_hand_phase[in_cmd.client_id] = true;
ps->assist_flags |= AssistFlag::READY_TO_END_PHASE;
ps->update_hand_and_equip_state_and_send_6xB4x02_if_needed();
bool all_clients_ready = true;
for (size_t z = 0; z < 4; z++) {
if (this->player_states[z] && !this->clients_done_in_mulligan_phase[z]) {
if (this->player_states[z] && !this->clients_done_in_redraw_initial_hand_phase[z]) {
all_clients_ready = false;
break;
}
@@ -2229,7 +2209,7 @@ void Server::handle_CAx14_update_deck_during_setup(shared_ptr<Client>, const str
}
}
if (verify_error) {
throw runtime_error(phosg::string_printf("invalid deck: -0x%" PRIX32, verify_error));
throw runtime_error(std::format("invalid deck: -0x{:X}", verify_error));
}
if (!this->options.is_nte() && !(this->options.behavior_flags & BehaviorFlag::SKIP_D1_D2_REPLACE)) {
this->ruler_server->replace_D1_D2_rank_cards_with_Attack(entry.card_ids);
@@ -2335,7 +2315,7 @@ void Server::handle_CAx1D_start_battle(shared_ptr<Client>, const string& data) {
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.
if ((l->base_version != Version::GC_EP3_NTE) && l->ep3_ex_result_values) {
if (!this->options.is_nte() && l->ep3_ex_result_values) {
this->send(*l->ep3_ex_result_values);
}
}
@@ -2495,7 +2475,7 @@ void Server::handle_CAx34_subtract_ally_atk_points(shared_ptr<Client>, const str
void Server::handle_CAx37_client_ready_to_advance_from_starter_roll_phase(shared_ptr<Client>, const string& data) {
const auto& in_cmd = check_size_t<G_AdvanceFromStartingRollsPhase_Ep3_CAx37>(data);
this->send_debug_command_received_message(in_cmd.client_id, in_cmd.header.subsubcommand, "SETUP ADV 1");
this->send_debug_command_received_message(in_cmd.client_id, in_cmd.header.subsubcommand, "CHOOSE ORDER");
if (in_cmd.client_id >= 4) {
throw runtime_error("invalid client ID");
}
@@ -2573,7 +2553,7 @@ void Server::send_6xB6x41_to_all_clients() const {
map_commands_by_language[c->language()] = this->prepare_6xB6x41_map_definition(
this->last_chosen_map, c->language(), this->options.is_nte());
}
this->log().info("Sending %c version of map %08" PRIX32, char_for_language_code(c->language()), this->last_chosen_map->map_number);
this->log().info_f("Sending {} version of map {:08X}", char_for_language_code(c->language()), this->last_chosen_map->map_number);
send_command(c, 0x6C, 0x00, map_commands_by_language[c->language()]);
};
for (const auto& c : l->clients) {
@@ -2608,7 +2588,7 @@ void Server::handle_CAx41_map_request(shared_ptr<Client>, const string& data) {
const auto& cmd = check_size_t<G_MapDataRequest_Ep3_CAx41>(data);
this->send_debug_command_received_message(cmd.header.subsubcommand, "MAP DATA");
if (!this->options.tournament || (this->options.tournament->get_map()->map_number == cmd.map_number)) {
this->last_chosen_map = this->options.map_index->for_number(cmd.map_number);
this->last_chosen_map = this->options.map_index->get(cmd.map_number);
this->send_6xB6x41_to_all_clients();
}
}
@@ -2782,7 +2762,7 @@ void Server::unknown_8023EEF4() {
auto log = this->log_stack("unknown_8023EEF4: ");
if (this->unknown_a14 >= 0x20) {
log.debug("unknown_a14 too large (0x%" PRIX32 ")", this->unknown_a14);
log.debug_f("unknown_a14 too large (0x{:X})", this->unknown_a14);
return;
}
@@ -2791,34 +2771,34 @@ void Server::unknown_8023EEF4() {
auto card = this->attack_cards[this->unknown_a14];
if (this->get_current_team_turn() == card->get_team_id()) {
ActionState as = this->pending_attacks_with_cards[this->unknown_a14];
if (log.should_log(phosg::LogLevel::DEBUG)) {
log.debug("card @%04hX #%04hX can attack", card->get_card_ref(), card->get_card_id());
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
log.debug_f("card @{:04X} #{:04X} can attack", card->get_card_ref(), card->get_card_id());
string as_str = as.str(this->shared_from_this());
log.debug("as: %s", as_str.c_str());
log.debug_f("as: {}", as_str);
}
if (is_nte) {
this->replace_targets_due_to_destruction_nte(&as);
} else {
this->replace_targets_due_to_destruction_or_conditions(&as);
}
if (log.should_log(phosg::LogLevel::DEBUG)) {
if (log.should_log(phosg::LogLevel::L_DEBUG)) {
string as_str = as.str(this->shared_from_this());
log.debug("as after target replacement: %s", as_str.c_str());
log.debug_f("as after target replacement: {}", as_str);
}
if (this->any_target_exists_for_attack(as)) {
log.debug("as is valid");
log.debug_f("as is valid");
break;
} else {
log.debug("as is not valid");
log.debug_f("as is not valid");
}
} else {
log.debug("card @%04hX #%04hX cannot attack (wrong turn)", card->get_card_ref(), card->get_card_id());
log.debug_f("card @{:04X} #{:04X} cannot attack (wrong turn)", card->get_card_ref(), card->get_card_id());
}
this->unknown_a14++;
}
if (this->unknown_a14 < this->num_pending_attacks_with_cards) {
log.debug("a14 (%" PRIu32 ") < num_pending_attacks_with_cards (%" PRIu32 ")", this->unknown_a14, this->num_pending_attacks_with_cards);
log.debug_f("a14 ({}) < num_pending_attacks_with_cards ({})", this->unknown_a14, this->num_pending_attacks_with_cards);
this->defense_list_ended_for_client.clear(false);
G_UpdateAttackTargets_Ep3_6xB4x29 cmd;
@@ -3142,13 +3122,13 @@ void Server::unknown_802402F4() {
if (ps && (this->current_team_turn2 == ps->get_team_id())) {
auto card = ps->get_sc_card();
if (card) {
log.debug("SC card has action chain");
log.debug_f("SC card has action chain");
card->compute_action_chain_results(true, false);
}
for (size_t set_index = 0; set_index < 8; set_index++) {
card = ps->get_set_card(set_index);
if (card) {
log.debug("set card %zu has action chain", set_index);
log.debug_f("set card {} has action chain", set_index);
card->compute_action_chain_results(true, false);
}
}
+17 -14
View File
@@ -73,7 +73,7 @@ public:
std::shared_ptr<const MapIndex> map_index;
uint32_t behavior_flags;
std::shared_ptr<phosg::StringReader> opt_rand_stream;
std::shared_ptr<PSOLFGEncryption> opt_rand_crypt;
std::shared_ptr<RandomGenerator> rand_crypt;
std::shared_ptr<const Tournament> tournament;
std::array<std::vector<uint16_t>, 5> trap_card_ids;
@@ -109,7 +109,7 @@ public:
for (size_t z = 0; z < count; z++) {
if (refs[z] != 0xFFFF) {
std::string ref_str = this->debug_str_for_card_ref(refs[z]);
ret += phosg::string_printf("%zu:%s ", z, ref_str.c_str());
ret += std::format("{}:{} ", z, ref_str);
}
}
if (ret.size() > 1) {
@@ -145,20 +145,23 @@ public:
this->send(&cmd, cmd.header.size * 4, command, enable_masking);
}
void send(const void* data, size_t size, uint8_t command = 0xC9, bool enable_masking = true) const;
void send_commands_for_joining_spectator(Channel& ch) const;
void send_commands_for_joining_spectator(std::shared_ptr<Channel> ch) const;
void force_battle_result(uint8_t surrendered_client_id, bool set_winner);
void force_replace_assist_card(uint8_t client_id, uint16_t card_id);
void force_destroy_field_character(uint8_t client_id, size_t set_index);
__attribute__((format(printf, 2, 3))) void send_debug_message_printf(const char* fmt, ...) const;
__attribute__((format(printf, 2, 3))) void send_info_message_printf(const char* fmt, ...) const;
void send_debug_command_received_message(
uint8_t client_id, uint8_t subsubcommand, const char* description) const;
void send_debug_command_received_message(
uint8_t subsubcommand, const char* description) const;
void send_debug_message_if_error_code_nonzero(
uint8_t client_id, int32_t error_code) const;
template <typename... ArgTs>
void send_debug_message(std::format_string<ArgTs...> fmt, ArgTs&&... args) const {
auto l = this->lobby.lock();
if (l && (this->options.behavior_flags & Episode3::BehaviorFlag::ENABLE_STATUS_MESSAGES)) {
send_text_message(l, std::format(std::forward<std::format_string<ArgTs...>>(fmt), std::forward<ArgTs>(args)...));
}
}
void send_debug_command_received_message(uint8_t client_id, uint8_t subsubcommand, const char* description) const;
void send_debug_command_received_message(uint8_t subsubcommand, const char* description) const;
void send_debug_message_if_error_code_nonzero(uint8_t client_id, int32_t error_code) const;
void send_6xB4x46() const;
@@ -218,8 +221,8 @@ public:
void update_battle_state_flags_and_send_6xB4x03_if_needed(bool always_send = false);
bool update_registration_phase();
void on_server_data_input(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0B_mulligan_hand(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0C_end_mulligan_phase(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0B_redraw_initial_hand(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0C_end_redraw_initial_hand_phase(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0D_end_non_action_phase(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0E_discard_card_from_hand(std::shared_ptr<Client> sender_c, const std::string& data);
void handle_CAx0F_set_card_from_hand(std::shared_ptr<Client> sender_c, const std::string& data);
@@ -330,7 +333,7 @@ public:
std::shared_ptr<CardSpecial> card_special;
std::shared_ptr<StateFlags> state_flags;
std::array<std::shared_ptr<PlayerState>, 4> player_states;
parray<uint32_t, 4> clients_done_in_mulligan_phase;
parray<uint32_t, 4> clients_done_in_redraw_initial_hand_phase;
uint32_t num_pending_attacks_with_cards;
bcarray<std::shared_ptr<Card>, 0x20> attack_cards;
bcarray<ActionState, 0x20> pending_attacks_with_cards;
+51 -40
View File
@@ -3,7 +3,9 @@
#include <phosg/Random.hh>
#include "../CommandFormats.hh"
#include "../GameServer.hh"
#include "../SendCommands.hh"
#include "../ServerState.hh"
using namespace std;
@@ -16,7 +18,7 @@ Tournament::PlayerEntry::PlayerEntry(uint32_t account_id, const string& player_n
Tournament::PlayerEntry::PlayerEntry(shared_ptr<Client> c)
: account_id(c->login->account->account_id),
client(c),
player_name(c->character()->disp.name.decode(c->language())) {}
player_name(c->character_file()->disp.name.decode(c->language())) {}
Tournament::PlayerEntry::PlayerEntry(
shared_ptr<const COMDeckDefinition> com_deck)
@@ -49,16 +51,16 @@ string Tournament::Team::str() const {
num_com_players += player.is_com();
}
string ret = phosg::string_printf("[Team/%zu %s %zuH/%zuC/%zuP name=%s pass=%s rounds=%zu",
string ret = std::format("[Team/{} {} {}H/{}C/{}P name={} pass={} rounds={}",
this->index, this->is_active ? "active" : "inactive",
num_human_players, num_com_players, this->max_players, this->name.c_str(),
this->password.c_str(), this->num_rounds_cleared);
num_human_players, num_com_players, this->max_players, this->name,
this->password, this->num_rounds_cleared);
for (const auto& player : this->players) {
if (player.is_human()) {
if (player.player_name.empty()) {
ret += phosg::string_printf(" %08" PRIX32, player.account_id);
ret += std::format(" {:08X}", player.account_id);
} else {
ret += phosg::string_printf(" %08" PRIX32 " (%s)", player.account_id, player.player_name.c_str());
ret += std::format(" {:08X} ({})", player.account_id, player.player_name);
}
}
}
@@ -206,7 +208,7 @@ Tournament::Match::Match(
string Tournament::Match::str() const {
string winner_str = this->winner_team ? this->winner_team->str() : "(none)";
return phosg::string_printf("[Match round=%zu winner=%s]", this->round_num, winner_str.c_str());
return std::format("[Match round={} winner={}]", this->round_num, winner_str);
}
bool Tournament::Match::resolve_if_skippable() {
@@ -318,7 +320,7 @@ Tournament::Tournament(
const Rules& rules,
size_t num_teams,
uint8_t flags)
: log(phosg::string_printf("[Tournament:%s] ", name.c_str())),
: log(std::format("[Tournament:{}] ", name)),
map_index(map_index),
com_deck_index(com_deck_index),
name(name),
@@ -343,7 +345,7 @@ Tournament::Tournament(
shared_ptr<const MapIndex> map_index,
shared_ptr<const COMDeckIndex> com_deck_index,
const phosg::JSON& json)
: log(phosg::string_printf("[Tournament:%s] ", json.get_string("name").c_str())),
: log(std::format("[Tournament:{}] ", json.get_string("name"))),
map_index(map_index),
com_deck_index(com_deck_index),
source_json(json),
@@ -355,7 +357,7 @@ void Tournament::init() {
bool is_registration_complete;
if (!this->source_json.is_null()) {
this->name = this->source_json.get_string("name");
this->map = this->map_index->for_number(this->source_json.get_int("map_number"));
this->map = this->map_index->get(this->source_json.get_int("map_number"));
this->rules = Rules(this->source_json.at("rules"));
this->flags = this->source_json.get_int("flags", 0x02);
if (this->source_json.get_bool("is_2v2", false)) {
@@ -665,7 +667,7 @@ void Tournament::start() {
auto m = this->zero_round_matches[z];
auto t = m->winner_team;
if (t->name.empty()) {
t->name = has_com_teams ? phosg::string_printf("COM:%zu", z) : "(no entrant)";
t->name = has_com_teams ? std::format("COM:{}", z) : "(no entrant)";
}
for (const auto& player : t->players) {
if (player.is_com()) {
@@ -717,66 +719,71 @@ void Tournament::send_all_state_updates_on_deletion() const {
}
}
void Tournament::print_bracket(FILE* stream) const {
function<void(shared_ptr<Match>, size_t)> print_match = [&](shared_ptr<Match> m, size_t indent_level) -> void {
for (size_t z = 0; z < indent_level; z++) {
fputc(' ', stream);
fputc(' ', stream);
string Tournament::bracket_str() const {
string ret = std::format("Tournament \"{}\"\n", this->name);
function<void(shared_ptr<Match>, size_t)> add_match = [&](shared_ptr<Match> m, size_t indent_level) -> void {
ret.append(2 * indent_level, ' ');
ret += m->str();
if (this->pending_matches.count(m)) {
ret += " (PENDING)";
}
string match_str = m->str();
fprintf(stream, "%s%s\n", match_str.c_str(), this->pending_matches.count(m) ? " (PENDING)" : "");
ret.push_back('\n');
if (m->preceding_a) {
print_match(m->preceding_a, indent_level + 1);
add_match(m->preceding_a, indent_level + 1);
}
if (m->preceding_b) {
print_match(m->preceding_b, indent_level + 1);
add_match(m->preceding_b, indent_level + 1);
}
};
fprintf(stream, "Tournament \"%s\"\n", this->name.c_str());
auto en_vm = this->map->version(1);
if (en_vm) {
string map_name = en_vm->map->name.decode(en_vm->language);
fprintf(stream, " Map: %08" PRIX32 " (%s)\n", this->map->map_number, map_name.c_str());
ret += std::format(" Map: {:08X} ({})\n", this->map->map_number, map_name);
} else {
fprintf(stream, " Map: %08" PRIX32 "\n", this->map->map_number);
ret += std::format(" Map: {:08X}\n", this->map->map_number);
}
string rules_str = this->rules.str();
fprintf(stream, " Rules: %s\n", rules_str.c_str());
fprintf(stream, " Structure: %s, %zu entries\n", (this->flags & Flag::IS_2V2) ? "2v2" : "1v1", this->num_teams);
fprintf(stream, " COM teams: %s\n", (this->flags & Flag::HAS_COM_TEAMS) ? "allowed" : "forbidden");
fprintf(stream, " Shuffle entries: %s\n", (this->flags & Flag::SHUFFLE_ENTRIES) ? "yes" : "no");
fprintf(stream, " Resize on start: %s\n", (this->flags & Flag::RESIZE_ON_START) ? "yes" : "no");
ret += std::format(" Rules: {}\n", rules_str);
ret += std::format(" Structure: {}, {} entries\n", (this->flags & Flag::IS_2V2) ? "2v2" : "1v1", this->num_teams);
ret += std::format(" COM teams: {}\n", (this->flags & Flag::HAS_COM_TEAMS) ? "allowed" : "forbidden");
ret += std::format(" Shuffle entries: {}\n", (this->flags & Flag::SHUFFLE_ENTRIES) ? "yes" : "no");
ret += std::format(" Resize on start: {}\n", (this->flags & Flag::RESIZE_ON_START) ? "yes" : "no");
switch (this->current_state) {
case State::REGISTRATION:
fprintf(stream, " State: REGISTRATION\n");
ret += " State: REGISTRATION\n";
break;
case State::IN_PROGRESS:
fprintf(stream, " State: IN_PROGRESS\n");
ret += " State: IN_PROGRESS\n";
break;
case State::COMPLETE:
fprintf(stream, " State: COMPLETE\n");
ret += " State: COMPLETE\n";
break;
default:
fprintf(stream, " State: UNKNOWN\n");
ret += " State: UNKNOWN\n";
break;
}
if (this->final_match) {
fprintf(stream, " Standings:\n");
print_match(this->final_match, 2);
ret += " Standings:\n";
add_match(this->final_match, 2);
}
if (this->current_state == State::REGISTRATION) {
fprintf(stream, " Teams:\n");
ret += " Teams:\n";
for (const auto& team : this->teams) {
string team_str = team->str();
fprintf(stream, " %s\n", team_str.c_str());
ret += std::format(" {}\n", team_str);
}
} else {
fprintf(stream, " Pending matches:\n");
ret += " Pending matches:\n";
for (const auto& match : this->pending_matches) {
string match_str = match->str();
fprintf(stream, " %s\n", match_str.c_str());
ret += std::format(" {}\n", match_str);
}
}
phosg::strip_trailing_whitespace(ret);
return ret;
}
TournamentIndex::TournamentIndex(
@@ -935,8 +942,12 @@ void TournamentIndex::link_client(shared_ptr<Client> c) {
}
void TournamentIndex::link_all_clients(std::shared_ptr<ServerState> s) {
for (const auto& c_it : s->channel_to_client) {
this->link_client(c_it.second);
// 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);
}
}
}
+1 -2
View File
@@ -1,6 +1,5 @@
#pragma once
#include <event2/event.h>
#include <stdint.h>
#include <memory>
@@ -160,7 +159,7 @@ public:
void send_all_state_updates() const;
void send_all_state_updates_on_deletion() const;
void print_bracket(FILE* stream) const;
std::string bracket_str() const;
private:
void create_bracket_matches();
-43
View File
@@ -1,43 +0,0 @@
#include "EventUtils.hh"
#include <event2/event.h>
#include <deque>
#include <functional>
#include <memory>
#include <stdexcept>
static void dispatch_forward_to_event_thread(evutil_socket_t, short, void* ctx) {
auto* fn = reinterpret_cast<std::function<void()>*>(ctx);
(*fn)();
delete fn;
}
void forward_to_event_thread(std::shared_ptr<struct event_base> base, std::function<void()>&& fn) {
struct timeval tv = {0, 0};
std::function<void()>* new_fn = new std::function<void()>(std::move(fn));
event_base_once(base.get(), -1, EV_TIMEOUT, dispatch_forward_to_event_thread, new_fn, &tv);
}
template <>
void call_on_event_thread<void>(std::shared_ptr<struct event_base> base, std::function<void()>&& compute) {
bool succeeded = false;
std::string exc_what;
std::mutex ret_lock;
std::condition_variable ret_cv;
std::unique_lock<std::mutex> g(ret_lock);
forward_to_event_thread(base, [&]() -> void {
std::lock_guard<std::mutex> g(ret_lock);
try {
compute();
succeeded = true;
} catch (const std::exception& e) {
exc_what = e.what();
}
ret_cv.notify_one();
});
ret_cv.wait(g);
if (!succeeded) {
throw std::runtime_error(exc_what);
}
}
-42
View File
@@ -1,42 +0,0 @@
#pragma once
#include <event2/event.h>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
// Calls a function on the given base's event thread. This function returns
// when the call has been enqueued, not necessarily after it returns.
void forward_to_event_thread(std::shared_ptr<struct event_base> base, std::function<void()>&& fn);
// Calls a function on the given base's event thread and waits for it to
// return. Returns the value returned on that thread.
template <typename T>
T call_on_event_thread(std::shared_ptr<struct event_base> base, std::function<T()>&& compute) {
std::optional<T> ret;
std::string exc_what;
std::mutex ret_lock;
std::condition_variable ret_cv;
std::unique_lock<std::mutex> g(ret_lock);
forward_to_event_thread(base, [&]() -> void {
std::lock_guard<std::mutex> g(ret_lock);
try {
ret = compute();
} catch (const std::exception& e) {
exc_what = e.what();
}
ret_cv.notify_one();
});
ret_cv.wait(g);
if (!ret.has_value()) {
throw std::runtime_error(exc_what);
}
return ret.value();
}
template <>
void call_on_event_thread<void>(std::shared_ptr<struct event_base> base, std::function<void()>&& compute);

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