Compare commits

..
Author SHA1 Message Date
apion 6d67256632 Added delta functions and some cleanup 2024-11-03 01:55:44 -04:00
apion be0753109c Merge branch 'refs/heads/implement_pokemon' into action-effects-improved 2024-11-02 03:48:43 -04:00
apion 0ee36b705e Merge remote-tracking branch 'refs/remotes/origin/move-effects' into action-effects-improved 2024-11-02 03:48:34 -04:00
apion 396a827b37 Added molang query for distance between entities 2024-11-02 03:01:56 -04:00
apion b146892b50 Exposed entity info in action effect 2024-11-02 00:17:09 -04:00
apion 5797838711 Moved to molang for pose conditions in charmander 2024-11-01 21:27:53 -04:00
Tyzillion e048e8a58d Updated particles for Status Effects, Stat buffs/debuffs, Protect, Sand Attack, Quick Attack, and Gastly.
Added the "top" universal locator.
2024-10-31 10:02:34 -04:00
Tyzillion 3656513255 Merge branch 'main' of https://gitlab.com/cable-mc/cobblemon into move-effects
# Conflicts:
#	common/src/main/resources/assets/cobblemon/sounds.json
2024-10-31 07:52:01 -04:00
Wi2tert 2734f1d00c Update Bulbasaur Ivysaur Venusaur Animation 2024-10-31 12:20:53 +08:00
tmetcalfe89 e66069b270 swapped smeargle colors right way around 2024-10-30 01:49:28 -07:00
tmetcalfe89 a661575451 de-dyed smeargle 2024-10-29 23:16:22 -07:00
Carmendar a23017cd1f Updated scaling of a handful of pokemon, gave pory line dummy sleep cries, fixed mantine antennae, and onix has math.mod now.
- Removed Herobrine.
2024-10-29 22:13:20 -05:00
tmetcalfe89 0df19ce18a integrated retro's changes
Fixed Bellsprout's GEO ("arns" to "arms", "foor" to "foot", etcetera).
Altered Weepinbell's Scale and Hitbox
Altered Victreebel's Walk Speed and Hitbox.
2024-10-29 15:22:53 -07:00
Wi2ter 5a751546ec Update Changelog 2024-10-29 18:38:25 +08:00
Carmendar ee9e1cabc1 remodeled Poliwhirl, Poliwrath, Riolu & Lucario. Added animations for Bagon line, Shellder line, Kecleon, Furret & Spinda. Updated changelog.
- Removed Herobrine.
2024-10-29 01:44:02 -05:00
Wi2ter d78b46155f Update Klink Line animation 2024-10-28 17:26:14 +08:00
Wi2ter 1afd61d517 Update Dreepy Drakloak Animation 2024-10-28 16:27:57 +08:00
Carmendar 97a5083ff5 Updated swim speeds for some water mons & merged main into implement. 2024-10-27 19:43:51 -05:00
Carmendar 0d31e74790 Merge branch 'main' into implement_pokemon 2024-10-27 17:42:35 -05:00
Carmendar 02214196f4 Merge remote-tracking branch 'origin/main' 2024-10-27 17:40:11 -05:00
Carmendar aae268cfc5 New water pokemon can actually water now. 2024-10-27 17:05:46 -05:00
Carmendar 20f37d8799 Third coming of Klawf. (fixed the cry for real this time. 2024-10-27 15:52:46 -05:00
Carmendar 0b825bcda3 The second coming of Klawf (its cry), animation updates for a handful of mons, Portrait/Picture & scale fixes for a handful of mons, added species feature for three-segment dudunsparce, added dummy animation file for sleep cries, and added cries for Magikarp & Gyarados.
- Removed Herobrine.
2024-10-27 15:48:29 -05:00
GenotypeXD-Dev aba3bd22c7 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-26 22:02:04 -06:00
GenotypeXD-Dev b1fc33f5a1 Added Klawf 2024-10-26 22:01:39 -06:00
tmetcalfe89 f2033f5e33 fix alakazam json poser 2024-10-25 12:51:57 -07:00
tmetcalfe89 6c600b7bdb alakazam - kt->json 2024-10-25 12:27:33 -07:00
Wi2ter e93bfb7f0f Update Kleavor Animation 2024-10-25 18:25:09 +08:00
Wi2ter 8976909742 Update Alomomola Animation 2024-10-25 18:23:06 +08:00
Wi2ter 30a9c2f53e Update Mantyke Mantine Animation 2024-10-25 18:18:58 +08:00
Wi2ter ea60790865 I forgot to change the poser! 😭 2024-10-25 11:36:38 +08:00
Wi2ter f906fac8f3 Update Buneary and Lopunny animation 2024-10-25 11:28:57 +08:00
Wi2ter 05b324a3cb Remodel Swinub Piloswine Mamoswine [big guy] 2024-10-25 09:40:37 +08:00
Carmendar 8ce1c7ccf5 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-24 19:06:09 -05:00
Carmendar a37f93241f Slowed Numel, and fixed shiny Staryu emissive texture. 2024-10-24 19:05:14 -05:00
Wi2ter 6689663ca9 remodel Snivy Servin Serperior 🌿 🐍 2024-10-24 19:10:37 +08:00
Carmendar 959b81a58f flashy new models for ✨ Dwebble & Crustle ✨ 2024-10-24 01:27:11 -05:00
Carmendar 62e607b44e Forgot to remove magby line & onix from the kotlin model repository. 2024-10-23 23:22:19 -05:00
Carmendar 407bb6b977 Merge remote-tracking branch 'origin/main' 2024-10-23 20:07:59 -05:00
Carmendar a9efd327b8 Magby line & Onix are now beautiful. 2024-10-23 19:58:34 -05:00
Carmendar 64cb4d2ff8 Removed Herobrine 2024-10-23 00:36:52 -05:00
FrankTheFarmer 54786fa82e I forgot the changelog again 😔 2024-10-23 15:06:56 +10:00
FrankTheFarmer ecab1b7825 Porygon line poser fixes 🖥🦆 2024-10-23 14:57:22 +10:00
FrankTheFarmer 75d7106f46 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-23 14:37:28 +10:00
Carmendar 6f82c09afa angry crying 😠😢 2024-10-22 23:21:40 -05:00
Carmendar 778e5e219c Everyone is crying 😢 so sad. 2024-10-22 22:05:42 -05:00
FrankTheFarmer f4682e0bd2 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-23 11:07:21 +10:00
Tyzillion 906d487ffc Added rootBone to all existing json posers. 2024-10-22 08:08:31 -04:00
Tyzillion 817b801bf7 Merge branch 'main' of https://gitlab.com/cable-mc/cobblemon into implement_pokemon
# Conflicts:
#	common/src/main/resources/assets/cobblemon/bedrock/pokemon/animations/0006_charizard/charizard.animation.json
#	common/src/main/resources/assets/cobblemon/bedrock/pokemon/posers/0595_joltik/joltik.json
2024-10-22 07:44:07 -04:00
Sterrezo e401b11ab9 Added a sound keyframe to absol.animation.json 2024-10-22 10:21:08 +02:00
Carmendar 165f70e01d Updated changelog 2024-10-22 02:05:50 -05:00
GenotypeXD-Dev fddfbfb4ed Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-21 20:03:46 -06:00
GenotypeXD-Dev 03e229c511 Implemented Absol and Veluza. Fixed Charizard sleep crash 2024-10-21 20:02:26 -06:00
Sterrezo 0b08372407 Pushed an updated cry checker script. Corrected cries for Smearlge, Ledyba, Ledian, Sunkern, Sunflora, Smeargle.
Thanks to Polymeta for saving the script
2024-10-21 00:43:33 +02:00
Carmendar 6d26b5de20 Joltik can now blink while walking without blowing up your game. 2024-10-20 02:16:00 -05:00
Carmendar ef179410f9 Joltik can now blink while walking without blowing up your game. 2024-10-20 02:08:30 -05:00
FrankTheFarmer 194f6e019a Bellsprout line remodeled and animated 2024-10-18 16:29:15 +10:00
FrankTheFarmer 1f933827b9 Merge branch 'main' into implement_pokemon 2024-10-18 16:08:20 +10:00
FrankTheFarmer 28765bb2ce Merge branch 'main' into implement_pokemon 2024-10-18 13:29:35 +10:00
FrankTheFarmer 136391db04 👨‍🌾🔫🐲 2024-10-18 13:27:26 +10:00
Wi2ter 0cc39e71fc revamp Klink Klang and Klingklang 2024-10-18 10:11:53 +08:00
FrankTheFarmer d65cc08793 Several data fixes for posers and hitboxes 2024-10-17 23:11:43 +10:00
GenotypeXD-Dev a1729a0266 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-17 01:43:17 -06:00
GenotypeXD-Dev 8505634df3 Implement Charmander, Charmeleon, And Charizard Remodels + Gyarados Poser Fixes 2024-10-17 01:42:40 -06:00
FrankTheFarmer 02047c1ec0 Like a bajillion data fixes for posers and hitboxes 2024-10-17 17:24:39 +10:00
FrankTheFarmer 068fa4b2ef Updated Firefox. Make sure to update yours too! 2024-10-17 09:48:45 +10:00
Carmendar bfd266a40e Updated Toxapex, revamped Porygon line, remodeled Gastly and Haunter, updated portraits & pictures for many pokemon. 2024-10-15 23:54:34 -05:00
FrankTheFarmer 6367d4e2aa Tweaked Regional Pokédex orders to allow for proper ordering of the National Pokédex. 2024-10-16 12:59:16 +10:00
FrankTheFarmer f8a680f381 :*: **:** *:*:* :: :***: :;: 2024-10-15 22:32:01 +10:00
GenotypeXD-Dev 81750e6eb9 Added Implemented tag to Finizen and Palafin 2024-10-14 02:17:18 -06:00
GenotypeXD-Dev 818cf682bf Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-14 02:15:11 -06:00
GenotypeXD-Dev 3112a0650f Implemented Finizen and Palafin (+Hero form) 2024-10-14 02:14:51 -06:00
FrankTheFarmer 747ef94f04 Fixed baltoy and claydol exploding the game when scanned. 2024-10-14 15:56:38 +10:00
FrankTheFarmer dbacada48c Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-14 15:16:12 +10:00
FrankTheFarmer 26db8a40cc Un deleted female oinkolognes. This will affect the oinkologne population. 2024-10-14 15:15:30 +10:00
GenotypeXD-Dev 6e5feda00e Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-13 23:12:07 -06:00
GenotypeXD-Dev f04330074b Added implemented tag to all currently implemented 1.6 pokemon 2024-10-13 23:11:46 -06:00
FrankTheFarmer 80d733d329 Merge branch 'main' into implement_pokemon 2024-10-14 14:18:08 +10:00
FrankTheFarmer 0099dcf5c5 Alolan Exeggutor will now appear in front of all pokemon in the dex no matter what lol 2024-10-14 14:16:42 +10:00
GenotypeXD-Dev 0a30551b7d Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-13 19:23:49 -06:00
GenotypeXD-Dev e4ee0227fd Reapply "Implement Magikarp and Gyarados Remodels + Jump Variants"
This reverts commit 4ec7168499.
2024-10-13 19:22:35 -06:00
GenotypeXD-Dev 4ec7168499 Revert "Implement Magikarp and Gyarados Remodels + Jump Variants"
This reverts commit 650647e94b.
2024-10-13 19:20:46 -06:00
GenotypeXD-Dev 650647e94b Implement Magikarp and Gyarados Remodels + Jump Variants 2024-10-13 19:19:46 -06:00
Carmendar a5371f4b5d Updated Tepig line & Baltoy line. 2024-10-13 16:03:10 -05:00
Wi2ter d47e7fb3c4 Implemented Corphish Crawdaunt 2024-10-13 12:32:27 +08:00
Carmendar ef983e17fe Implemented Palossand, updated Bulbasaur texture, Ivysaur model & texture, Mudkip model & texture. Fixed portraits, pictures & scales for many Pokemon. 2024-10-12 22:42:41 -05:00
GenotypeXD-Dev d78975be6e Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-12 01:15:01 -06:00
GenotypeXD-Dev 19a264870c Implemented Scraggy, Scrafty, Hatenna, Hattrem, Hatterene, Wattrel, Kilowattrel, Alola_bias cubone. Fixed Resolver typo from last Push 2024-10-12 01:14:11 -06:00
Carmendar ee1753de67 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-10-11 01:28:24 -05:00
Carmendar 742354b2cb Implemented Slakoth, Vigoroth, Slaking. Adjusted Larvitar scale. 2024-10-11 01:24:30 -05:00
GenotypeXD-Dev e2f6aaa4de Shelgon Basescale adjustment 2024-10-10 18:53:12 -06:00
GenotypeXD-Dev abc2911059 Implemented Bagon, Shelgon, Salamence, Pikipek, Trumbeak, Toucannon, Dondozo, Alolan Marowak 2024-10-10 17:46:09 -06:00
FrankTheFarmer d76caf7093 i forgot to write implemented 😩 2024-10-10 10:37:38 +10:00
FrankTheFarmer bf859f8435 Sand castle :) 2024-10-10 10:06:19 +10:00
FrankTheFarmer b31c10cc52 Took Venusaurs foot off the pedal (bone name changes) 2024-10-04 09:30:45 +10:00
FrankTheFarmer 89e3c7d8b0 Sealeo zfight fix 2024-10-04 08:52:20 +10:00
FrankTheFarmer 167b09f24f Fixed Diggersby using its walk animation in its battle portrait 2024-10-01 21:18:09 +10:00
FrankTheFarmer 39165266d5 🎬🔴👗 👠 2024-10-01 20:35:01 +10:00
FrankTheFarmer 7405f2de75 💍⚡🕶️⚡🧋 2024-10-01 20:34:20 +10:00
FrankTheFarmer 762fe87454 ✨🎡🧣 2024-10-01 20:33:41 +10:00
FrankTheFarmer ebbc81b605 💋🎙️🇫🇷 🎩 2024-10-01 20:33:01 +10:00
FrankTheFarmer 12d41aada1 👁️🍧👁️ 2024-10-01 20:32:20 +10:00
FrankTheFarmer 61fe9c23ce 💅 🪨 👜 🐩 2024-10-01 20:31:20 +10:00
FrankTheFarmer 945c9c60a9 Mmm monkey 2024-10-01 20:30:10 +10:00
FrankTheFarmer 8413b0392e Venusaur scaling stuff for Jazz 😈 2024-10-01 16:26:55 +10:00
FrankTheFarmer 868edcd392 Looped Walreins temp idle animation 2024-10-01 16:21:43 +10:00
FrankTheFarmer a3b2f9b6fc Rotom assets for future implementation 2024-10-01 16:07:26 +10:00
FrankTheFarmer 12b444bb41 Kecleon Assets for future implementation 2024-10-01 16:06:57 +10:00
FrankTheFarmer 0e814fd567 Added Flamigo 🔫🦩 2024-10-01 16:05:42 +10:00
FrankTheFarmer 7b083aa038 Added Walrein 🗡️ 🦭 2024-10-01 15:56:16 +10:00
FrankTheFarmer 4e0a4c84b5 Added Sealeo 🦭 2024-10-01 15:54:30 +10:00
FrankTheFarmer 2d9b47e645 Added Spheal 🪩 2024-10-01 15:53:38 +10:00
FrankTheFarmer 39a2182736 Added Toxapex ☂️ 2024-10-01 15:51:23 +10:00
FrankTheFarmer 5a996abbf3 Added Mareanie ☂️ 2024-10-01 15:50:31 +10:00
FrankTheFarmer a20def5161 Snail textures woops 2024-10-01 15:09:31 +10:00
FrankTheFarmer 030f370290 Added Gastrodon 🐌 2024-10-01 11:15:43 +10:00
FrankTheFarmer f3ade3cb82 Added Shellos 🐌 2024-10-01 11:14:14 +10:00
FrankTheFarmer 315cb6a1ac Added Lumineon 🐠 2024-10-01 10:48:35 +10:00
FrankTheFarmer 60615d32f5 Added Finneon 🐟 2024-10-01 10:48:18 +10:00
FrankTheFarmer 1d27d9cf5b Added Clawitzer 🔫🦞 2024-10-01 10:40:21 +10:00
FrankTheFarmer 2ba760d0f9 Added Clauncher 🦞 2024-10-01 10:38:35 +10:00
FrankTheFarmer c31ec3b418 Added Bruxish 🪥🐟🌈 2024-10-01 10:30:52 +10:00
FrankTheFarmer d0afab9604 Added Wugtrio 🪱🪱🪱 2024-10-01 10:16:39 +10:00
FrankTheFarmer 4e9f8fe1c0 Added Wiglett 🪱 2024-10-01 10:16:18 +10:00
FrankTheFarmer 803f93aa73 Added Corsola 🪸 2024-09-30 17:21:31 +10:00
FrankTheFarmer 853940d009 Added Pincurchin 🦔 2024-09-30 17:16:38 +10:00
FrankTheFarmer 6ddb746d49 Fired for not using indents of 2 again 2024-09-30 17:05:47 +10:00
FrankTheFarmer 2b86b15132 Added Liepard 🐆 2024-09-30 17:05:34 +10:00
FrankTheFarmer 5f0f5d0aa5 Added Purrloin 🐈 2024-09-30 17:02:17 +10:00
FrankTheFarmer 136aab872a Added Mantine 🌊🥞 2024-09-30 17:00:04 +10:00
FrankTheFarmer a1d4702af0 Added Mantyke 🥞 2024-09-30 16:59:33 +10:00
FrankTheFarmer b2777c13b8 Added Milotic 🐍 2024-09-30 16:55:33 +10:00
FrankTheFarmer 26cb473b9d Added Feebas 🎣 2024-09-30 16:55:09 +10:00
FrankTheFarmer 907c639e28 Added Octillery 🐙 2024-09-30 16:52:21 +10:00
FrankTheFarmer 80d2eafed7 Added Remoraid 🐟 2024-09-30 16:51:40 +10:00
FrankTheFarmer 519122e5be Little bit of Rhyhorn line resizing 2024-09-29 22:45:59 +10:00
FrankTheFarmer c211768d5c Forgor to remove Rhyhorn line kotlin posers 2024-09-29 22:45:35 +10:00
FrankTheFarmer 908f318eeb Carvanha remodel 2024-09-29 22:40:27 +10:00
FrankTheFarmer 0143f93577 Rhyperior remodel 🌤🦏 2024-09-29 22:31:46 +10:00
FrankTheFarmer f8615aeb82 Rhyhorn remodel 🦏 2024-09-29 22:26:06 +10:00
FrankTheFarmer b113448a9c Rhydon remodel 🦏 2024-09-29 22:23:56 +10:00
FrankTheFarmer 2930a11c75 Garchomp remodel ✈ 2024-09-29 22:13:00 +10:00
FrankTheFarmer 982de7f5c7 Gabite remodel 🦈 2024-09-29 22:12:08 +10:00
FrankTheFarmer bfdb5e9787 Gible remodel 🐟 2024-09-29 22:11:27 +10:00
FrankTheFarmer d5ea945c6b Krookodile remodel 2024-09-29 22:00:52 +10:00
FrankTheFarmer 5a18d038a2 Wigglytuff remodel 🍎 2024-09-29 21:51:56 +10:00
FrankTheFarmer d0389d6c9c Jigglypuff remodel 🎤 2024-09-29 21:51:32 +10:00
FrankTheFarmer c9bc6e24fe Igglybuff remodel 2024-09-29 21:50:39 +10:00
FrankTheFarmer 8b4a8e9534 oop. Tatsugiri resolver fix 2024-09-29 21:46:25 +10:00
FrankTheFarmer 5adfd00509 Tatsugiri model update 🍙🐟 2024-09-29 21:26:31 +10:00
FrankTheFarmer 4090e038ae Cloyster model update 2024-09-29 21:25:33 +10:00
FrankTheFarmer f3ab282fd1 Shellder model update 2024-09-29 21:25:16 +10:00
FrankTheFarmer 40b97d3c1e Merge branch 'main' into implement_pokemon 2024-09-29 21:17:27 +10:00
FrankTheFarmer 829b97270d Seaking model update 2024-09-29 21:16:49 +10:00
FrankTheFarmer 61111c8038 Goldeen model update 2024-09-29 21:16:34 +10:00
FrankTheFarmer 1f4fbaa177 oop. relicanth resolver update 2024-09-29 21:16:16 +10:00
FrankTheFarmer 9e8ef7e875 Relicanth remodel 2024-09-29 21:15:35 +10:00
FrankTheFarmer 190d90a966 Empoleon remodel 2024-09-29 20:56:38 +10:00
FrankTheFarmer 5a07c82a5d Prinplup remodel 2024-09-29 20:55:57 +10:00
FrankTheFarmer 9c2e56ee8b Cinderace remodel 2024-09-29 20:52:27 +10:00
FrankTheFarmer c83f194dc9 Scorbunny remodel 2024-09-29 20:52:06 +10:00
FrankTheFarmer b9bcb66d2a Swampert remodel 2024-09-29 20:47:43 +10:00
FrankTheFarmer b72050da1d Marshtomp remodel 2024-09-29 20:46:36 +10:00
FrankTheFarmer 82522ad6ab Mudkip remodel 💙 2024-09-29 20:46:02 +10:00
FrankTheFarmer d40e2e6103 Changelog for incoming implementation 2024-09-29 11:41:52 +10:00
FrankTheFarmer 96715770a7 Incineroar Remodel 🔥🧍‍♂️ 2024-09-29 11:41:09 +10:00
FrankTheFarmer 48fa67c2e4 Torracat Remodel 🔥🐆 2024-09-29 11:40:31 +10:00
FrankTheFarmer 9a6217f755 Litten Remodel 🔥🐈 2024-09-29 11:39:38 +10:00
FrankTheFarmer f1f035b5f9 Fired for not using double spaced (2)JSON indents 2024-09-29 11:31:44 +10:00
FrankTheFarmer 19aa53effc Horsea Remodel 2024-09-29 11:24:46 +10:00
FrankTheFarmer be7cb4583c Seadra Remodel 2024-09-29 11:24:36 +10:00
FrankTheFarmer 887891f74d Kingdra Remodel 2024-09-29 11:24:19 +10:00
FrankTheFarmer d83cd34bf4 Removed several pokemon from PokemonModelRepository as they have JSON posers now! 2024-09-28 20:08:54 +10:00
FrankTheFarmer bee41a90f9 Venusaur remodel 2024-09-28 19:59:28 +10:00
FrankTheFarmer 79afe9d812 Ivysaur remodel 2024-09-28 19:59:07 +10:00
FrankTheFarmer 9fe55c5692 Bulbasaur remodel 2024-09-28 19:58:44 +10:00
FrankTheFarmer feddce2575 Merge branch 'main' into implement_pokemon 2024-09-28 19:39:36 +10:00
FrankTheFarmer 4ddc5e3a93 Cetitan can now cry and walk/sleep at the same time! Unfortunately relatable! 2024-09-28 06:43:47 +10:00
FrankTheFarmer f63f1764ab Merge branch 'main' into implement_pokemon 2024-09-28 06:35:49 +10:00
FrankTheFarmer 7c694e9733 Corrected Dachsbun's resolver name. Was using Fidough 2024-09-25 21:19:58 +10:00
FrankTheFarmer 21b6977387 Merge branch 'main' into implement_pokemon 2024-09-25 21:09:08 +10:00
FrankTheFarmer 408735399c Merge branch 'main' into implement_pokemon 2024-09-24 21:13:15 +10:00
FrankTheFarmer f6c856d161 Merge branch 'main' into implement_pokemon 2024-09-24 08:23:07 +10:00
FrankTheFarmer 8173cf13a8 data updates for walking wake and iron leaves 2024-09-17 22:28:39 +10:00
FrankTheFarmer 7d0becf1bd Fixed that one elekid thing that was breaking the thingy™ 2024-09-17 09:45:15 +10:00
FrankTheFarmer 9b4a87ce68 Merge branch 'main' into implement_pokemon 2024-09-16 14:51:53 +10:00
Hiroku 464c4d349d Update CHANGELOG.md 2024-09-15 09:31:47 +00:00
Hiroku a35d3131f8 Update CHANGELOG.md 2024-09-15 09:30:28 +00:00
FrankTheFarmer 9d99d3c331 Merge branch 'main' into implement_pokemon 2024-09-14 19:49:29 +10:00
Paul b100516b24 Fixed JSON posed mons having _issues_ when evolved 2024-09-14 12:31:40 +10:00
FrankTheFarmer 8da5396443 Merge branch 'main' into implement_pokemon 2024-09-13 20:58:59 +10:00
FrankTheFarmer 5d2a727311 Chest Gimmighoul quirk fixes 2024-09-13 20:01:19 +10:00
FrankTheFarmer d7f03215e2 Merge branch 'main' into implement_pokemon 2024-09-13 15:18:46 +10:00
FrankTheFarmer d366471e71 Merge branch 'main' into implement_pokemon 2024-09-12 20:17:22 +10:00
FrankTheFarmer e5163f154a The "true".asExpressionLike fix for the bird wing visibility 2024-09-12 20:16:20 +10:00
FrankTheFarmer cfc497d8ed Consistency update for the first few json posers 2024-09-11 18:39:58 +10:00
FrankTheFarmer 35f8ab0257 Removed life ending comma 2024-09-11 17:35:25 +10:00
FrankTheFarmer e890743c86 Merge branch 'main' into implement_pokemon 2024-09-11 17:34:19 +10:00
FrankTheFarmer ffec6e307d Move over poser! 2024-09-11 16:16:01 +10:00
FrankTheFarmer 7c35db7eaa Temp horse data 2024-09-11 16:15:38 +10:00
FrankTheFarmer 9f0c2296bc Fixed the wing flap placeholder animation 2024-09-09 10:32:27 +10:00
FrankTheFarmer 6b0a06c64d I have restored the named animations. i think they got lost. 2024-09-08 15:18:12 +10:00
FrankTheFarmer 160186931f Merge branch 'main' into implement_pokemon 2024-09-08 14:23:54 +10:00
FrankTheFarmer 22c4a14fbe Changelog and maybe added fortnite 2024-09-08 14:22:14 +10:00
FrankTheFarmer 241a82764b Removal of Kingler kotlin poser. im too lazy to do krabby rn lol 2024-09-08 14:18:58 +10:00
FrankTheFarmer 6e4d48bb07 Cramorant remodel 🐟 2024-09-08 14:16:55 +10:00
FrankTheFarmer 7a383f419a 🦀🦀 Krabby & Kingler updates 🦀🦀 2024-09-08 13:30:16 +10:00
FrankTheFarmer 933b99d349 Wobbuffet! 💁‍♀️ 2024-09-08 11:03:30 +10:00
FrankTheFarmer 72d78084f6 Merge branch 'main' into implement_pokemon 2024-09-08 10:21:30 +10:00
FrankTheFarmer fcee4d2774 Merge branch 'main' into implement_pokemon 2024-09-08 07:47:04 +10:00
FrankTheFarmer 61c7f3bc13 sunkern line look animation fixes 2024-09-08 07:45:15 +10:00
FrankTheFarmer 3830637f3c Stupid ass dinosaur crying in his sleep 2024-09-08 07:45:14 +10:00
FrankTheFarmer 45f8049521 💖🌱Sunkern & Sunflora🌻✨ given Retro's placeholder assets and data 2024-09-06 16:47:43 +10:00
FrankTheFarmer 823774bcfe Merge branch 'main' into implement_pokemon 2024-09-06 10:48:03 +10:00
FrankTheFarmer 920e5211c0 Somebody forgot the changelog again 2024-09-06 10:47:02 +10:00
FrankTheFarmer 7da61e3d8d Fixed the look animations for the ledyba line 2024-09-06 10:41:34 +10:00
FrankTheFarmer 754b60b15c fixed Maushold faints not playing 2024-09-03 21:29:09 +10:00
FrankTheFarmer 839454bfd6 Fixed Slowking battle idle not playing properly 2024-09-03 20:31:41 +10:00
FrankTheFarmer 3b6a0667d6 Adjusted Grafaiai walk speed to reduce feet sliding 2024-09-03 20:05:56 +10:00
FrankTheFarmer f298adaea8 Vivillon will stop being naked when removing Vivillon addons 2024-09-03 09:36:53 +10:00
FrankTheFarmer 641206b811 Merge branch 'main' into implement_pokemon 2024-09-02 14:52:59 +10:00
Tyzillion 117f13b056 Added sounds to mud sport and water sport. 2024-08-10 14:54:26 -04:00
Tyzillion 93a94b4900 Updated model for Beedrill and Kingler.
Implement Cramorant.
2024-08-05 17:43:24 -04:00
Tyzillion 40363c2ea1 Merge remote-tracking branch 'origin/implement_pokemon' into implement_pokemon 2024-08-04 14:09:00 -04:00
Tyzillion 056252d2bb Implemented particles for psychic, mudsport, watersport, and updated confusion attack particles. 2024-08-04 13:58:04 -04:00
FrankTheFarmer 6f15d65d90 Unbiases your hisuian starter evolution methods 2024-07-15 16:37:53 +10:00
FrankTheFarmer 02f9b21cff Small changelog tweak. I didn't forget i promise. 2024-07-15 12:56:41 +10:00
FrankTheFarmer 79cf154304 What if we take bikini bottom and push it somewhere else?! 2024-07-15 12:19:29 +10:00
FrankTheFarmer a650683d45 Merge remote-tracking branch 'origin/main' into implement_pokemon 2024-07-15 10:54:23 +10:00
Apion 311dc3dc9c Merge branch 'json-poser-conversion' into 'implement_pokemon'
Json poser conversion

See merge request cable-mc/cobblemon!1081
2024-06-27 23:50:31 +00:00
FrankTheFarmer bda1f80ecc Corrected Zangoose's egg moves being in its leveled move list. 2024-06-26 14:28:03 +10:00
FrankTheFarmer 817796bf40 Corrected Klevin's stats to match current databases post S/V patch 2024-06-26 10:22:02 +10:00
FrankTheFarmer 8a48eeab8b Merge branch 'main' into implement_pokemon 2024-06-23 20:48:59 +10:00
FrankTheFarmer 0061104c0d I did not forget the changelog this time 2024-06-23 20:47:37 +10:00
FrankTheFarmer 5110a1be17 Removed Chikorita's ability to look due to some awkward pivots and head structure 2024-06-23 20:28:37 +10:00
FrankTheFarmer 4cbb998106 Adjusted Shroomish's Yaw range for looks. Yeehaw 2024-06-23 20:24:20 +10:00
FrankTheFarmer 17de3f496c Adjusted Bellossom shoulder pose to clip a lot less than before. 2024-06-23 20:08:22 +10:00
FrankTheFarmer b54181e93a Glimmet and Tatsugiri are now shoulder mountable 2024-06-23 20:05:21 +10:00
FrankTheFarmer eaf7edcd94 Fletchling, Skrelp, Klefki, Fomantis, Morelull and Shroodle are now shoulder mountable 2024-06-23 19:46:16 +10:00
FrankTheFarmer cdf1631e2b ZORUA 2 STOP FLOATING 2024-06-23 18:51:40 +10:00
FrankTheFarmer 841f49553e Pidove, Petilil, Hisui Bias Petilil, Zorua, Zorua 2 and Elgyem are now shoulder mountable 2024-06-23 18:51:22 +10:00
FrankTheFarmer 57d7d5a1b9 Minun, Beldum, Starly, Buneary, Combee and Pachirisu are now shoulder mountable 2024-06-23 17:46:41 +10:00
FrankTheFarmer b1f2ab2ed7 Merge branch 'main' into implement_pokemon 2024-06-23 17:26:01 +10:00
FrankTheFarmer f629d95844 Spearow, Murkrow, Mew, Larvitar, Taillow and Plusleare now shoulder mountable 2024-06-23 16:58:37 +10:00
FrankTheFarmer 30904fbdda Caterpie, Weedle, and Smoochum are now shoulder mountable 2024-06-23 16:00:14 +10:00
FrankTheFarmer 9a3be6a85a Roaming Gimmighoul is now shoulder mountable 2024-06-23 15:01:17 +10:00
FrankTheFarmer 88c91d9bdd Reverted Hisuian Zoroark stats to be different from base Zoroark 2024-06-23 09:50:05 +10:00
FrankTheFarmer 5d2efe3e6b Merge branch 'main' into implement_pokemon 2024-06-23 09:41:59 +10:00
FrankTheFarmer d6354d3d94 Fixed Duskull and Dusclops spawn data 2024-06-14 11:51:33 +10:00
FrankTheFarmer 4ddfdd828c Merge branch 'main' into implement_pokemon 2024-06-14 11:30:43 +10:00
FrankTheFarmer 06b70c6204 After nearly 2 years, the Magby line received their placeholder walks 2024-06-12 14:05:54 +10:00
FrankTheFarmer 2dc9d11f79 Merge branch 'main' into implement_pokemon 2024-06-12 14:00:10 +10:00
FrankTheFarmer fbb161c511 I FORGOT THE CHANGELOG 2024-06-04 14:36:35 +10:00
FrankTheFarmer f84bc62d61 Dreepy can now float on your shoulders 2024-06-04 14:17:39 +10:00
FrankTheFarmer 2e20554d1e Fixed Chimchar and Monferno sleeping T pose 2024-06-04 13:55:16 +10:00
apion bb9fcc64ed Started working on Aerodactyl JSON poser 2024-05-24 21:52:16 -04:00
apion 2d908468ea Fixed issue where singular conditions not met, abra is now completely working with a JSON poser 2024-05-24 11:21:01 -04:00
apion c9ae148d86 Moved Abra to JSON poser, pose conditions not properly working 2024-05-24 10:24:50 -04:00
2191 changed files with 23968 additions and 110617 deletions
+3
View File
@@ -0,0 +1,3 @@
### Additions
- Added the Poké Dex as a craftable item.
- Poké Dexes can be placed on lecterns.
+6
View File
@@ -0,0 +1,6 @@
### Additions
- Added `moves` option to PokemonProperties, allowing you to set the moves of a Pokémon in commands and spawn files.
- Added /spawnnpc and /spawnnpcat commands.
### Fixes
- Fixed sync issues with recently learned moves where their PP would not go down until you logout and in.
+24
View File
@@ -0,0 +1,24 @@
### Additions
- Pokémon are now animated when seen in any GUI that isn't the party GUI.
- Quirk animations can now occur for Pokémon that are shoulder mounted.
### Changes
- Improved the performance of display cases that contain Pokémon photos.
### Fixes
- Fixed some Pokémon photos in display cases flashing if the Pokémon has gender differences.
- Fixed Bidoof and Jigglypuff sleep animations stopping after some time, causing them to be 'asleep' while T-posing menacingly.
- Fixed entities not changing poses unless you're looking at them.
- Fixed cries not playing on send-out if the Pokémon is off-screen.
### Developer
- Rebuilt large swaths of the model animation code to simplify it.
- Renamed a bunch of things from %Poseable% to %Posable% because spelling.
- Renamed StatelessAnimation to PoseAnimation.
- Renamed StatefulAnimation to ActiveAnimation.
- Documented the animation system.
### Data Pack & Resource Pack Creators
- Added MoLang compatibility in the isVisible property for transformed parts.
- Added q.has_aspect('some_aspect') function to animations, posers, and entity particle effects.
- Added support for conditional pose animations.
+33 -53
View File
@@ -3,8 +3,6 @@
#### "Now that there's a fishing mechanic, the mod is actually good!"
### Additions
- Added the Poké Dex as a craftable item.
- Poké Dexes can be placed on lecterns.
- Added Pokémon (and item) fishing using modified fishing rods - Poké Rods! You'll need a Poké Rod smithing template, a fishing rod, and some type of Poké Ball. Each Poké Ball makes a differently themed rod. Why not?
- Added Lure Ball functionality, increasing the catch rate of Pokémon that were caught on a fishing rod.
- Added Repeat Ball functionality, increasing the catch rate of Pokémon that are already registered as caught in a player's Pokédex.
@@ -32,23 +30,12 @@
- New config setting `displayEntityNameLabel` and `displayEntityLabelsWhenCrouchingOnly` to control what and when is displayed for the pokemon label
- `/freezepokemon` command to pause a Pokémon's animation at a specific point in time.
- Added `no_ai` and `freeze_frame` options to the `/spawnpokemon` command.
- Added shiny Pokémon particles with sound effects.
- Added animation for trading.
- Added shiny Pokémon effects.
- Added effects for the burn status effect.
- Added effects for the moves: Psychic, Water Sport, and Mud Sport.
- Added a new universal locator called "top".
- Added `moves` option to Pokémon properties, allowing you to set the moves of a Pokémon in commands and spawn files using comma-separated move names.
- Added shiny Pokémon effects.
- Added effects for the burn status effect.
- Added effects for the moves: Seismic Toss, Withdraw, Bite, Crunch, Super Fang, Hyper Fang, Pursuit, Mist, Haze, Lick, Kinesis, Psychic, Water Sport, and Mud Sport.
- Added a new universal locator called `top`.
- Added shiny Pokémon particles with sound effects.
- Added animation for trading.
- Added icons for pending trade, team-up, and battle requests from other players.
- Added `/spawnnpc` and `/spawnnpcat` commands.
- Pokémon are now animated when seen in any GUI that isn't the party GUI.
- Quirk animations can now occur for Pokémon that are shoulder mounted.
- Added `fishing boat` structures that contain a map to a shipwreck cove and a pokerod smithing template.
- Added `submerged_shipwreck_cove` and `lush_shipwreck_cove` structures.
### Pokémon Added
#### Gen 1
@@ -67,6 +54,10 @@
- Octillery
- Mantine
- Smeargle
- Remoraid
- Octillery
- Mantine
- Corsola
#### Gen 3
- Slakoth
@@ -84,6 +75,18 @@
- Bagon
- Shelgon
- Salamence
#### Gen 4
- Shellos [East Sea form]
- Gastrodon [East Sea form]
- Finneon
- Lumineon
- Mantyke
- Feebas
- Milotic
- Spheal
- Sealeo
- Walrein
- Kecleon
#### Gen 4
@@ -119,6 +122,12 @@
- Hatenna
- Hattrem
- Hatterene
- Bruxish
- Mareanie
- Toxapex
#### Gen 8
- Cramorant
- Pincurchin
#### Gen 9
@@ -135,7 +144,6 @@
- Wiglett
- Wugtrio
- Flamigo
- Dondozo
#### Unique Forms
- Magikarp Jump Variants
@@ -181,7 +189,7 @@
- Hatenna, Hattrem, Hatterene
- Pincurchin
- Klawf
- Finizen, Palafin \[Zero\], Palafin \[Hero\]
- Finizen, Palafin [Zero], Palafin [Hero]
- Dondozo
### Added shoulder mounts for the following Pokémon
@@ -200,7 +208,6 @@
- Buneary
- Combee
- Pachirisu
- Tepig
- Pidove
- Petilil, Hisui Bias Petilil
- Zorua, Hisui Bias Zorua
@@ -208,46 +215,35 @@
- Fletchling
- Skrelp
- Klefki
- Litten
- Fomantis
- Morelull
- Dreepy
- Sprigatito
- Shroodle
- Tatsugiri
- Glimmet
- Gimmighoul \[Roaming\]
- Gimmighoul [Roaming]
### Animation updates for the following Pokémon
- Bellsprout, Weepinbell, Victreebel
- Bellsprout, Weepinbel, Victreebel
- Shellder, Cloyster
- Porygon, Porygon2, Porygon-Z
- Furret
- Swinub, Piloswine, Mamoswine
- Skarmory
- Tyrogue
- Spinda
- Torkoal
- Nincada, Ninjask
- Lunatone
- Solrock
- Buneary, Lopunny
- Magnezone
- Alomomola
- Tepig, Pignite, Emboar
- Flabebe, Floette, Florges
- Litten, Torracat, Incineroar
- Fomantis, Lurantis
- Dreepy, Drakloak
- Kleavor
- Scorbunny
- Gimmighoul \[Roaming\]
### Model updates for the following Pokémon
- Bulbasaur, Ivysaur, Venusaur
- Charmander, Charmeleon, Charizard
- Kakuna, Beedrill
- Lapras
- Porygon, Porygon2, Porygon-Z
- Igglybuff, Jigglypuff, Wigglytuff
- Poliwhirl, Poliwrath
@@ -324,12 +320,11 @@
- Updated particles for status effects: Paralysis, Poison, and Sleep.
- Updated particles on Gastly.
- Revamped stat buff and de-buff particles.
- Improved the performance of display cases that contain Pokémon photos.
### Fixes
- Scaled down Amaura's fetus model to avoid clipping through the tank while animating.
- Fixed Cubone's cry not having a sound.
- Fixed the sendout sound erroneously playing when a wild Pokémon breaks out of a Poké ball.
- Fixed the sendout sound erronously playing when a wild Pokémon breaks out of a Poké ball.
- Flamethrower is no longer missing sounds.
- Fixed the Seafloor spawning context not being a usable context.
- Fixed Pokemon spawning in non-full blocks like slabs.
@@ -337,6 +332,11 @@
- Fixed Pokémon losing their Hidden Ability through evolution if the middle stage did not have a Hidden Ability.
- Hidden Power no longer plays the water type action effect (It now plays the normal type action effect).
- Fixed Chimchar and Monferno T-posing whenever they sleep.
- Fixed the Magby line not having any placeholder walk animations.
- Fixed Duskull and Dusclops using skylight levels for their nether spawn data. There is no sun in the Nether!
- Fixed Hisuian Zoroark using base Zoroark stats.
- Fixed Bellossom clipping into the player head when shoulder mounted.
- Fixed Shroomish's look range to prevent it from looking higher than it should.
- Fixed Cetitan's cry breaking its walk and sleep animations.
- Fixed Crumbling Arch not blending in with the world.
- Fixed Energy Root applying being usable on a fainted Pokémon.
@@ -393,15 +393,6 @@
- Fixed the Ice Face ability activation being displayed incorrectly in a battle.
- Fixed edge case of F1 and R locking you in battle with no R functionality (requiring ESC to get out).
- Fixed Poké Ball render orientation in battle interface when capturing.
- Fixed sync issues with recently learned moves where their PP would not go down until you logout and in.
- Fixed some Pokémon photos in display cases flashing if the Pokémon has gender differences.
- Fixed Bidoof and Jigglypuff sleep animations stopping after some time, causing them to be 'asleep' while T-posing menacingly.
- Fixed entities not changing poses unless you're looking at them.
- Fixed cries not playing on send-out if the Pokémon is off-screen.
- Fixed text row selection highlight in battle log.
- Fixed top black border rendering in scroll interfaces in summary UI.
- Fixed aspect tracking for Advancements.
- Fixed illusion not copying aspects or caught ball.
### Developer
- `SpawnCause` is now an implementation of `SpawningInfluence`.
@@ -432,12 +423,6 @@
- Pokémon Heal (with context)
- Added HealingSource, an interface applied to all sources of healing from player actions, for easier tracking of healing sources.
- Move Change
- Shiny Chance Calculation Event (with player context)
- Rebuilt large swaths of the model animation code to simplify it.
- Renamed a bunch of things from %Poseable% to %Posable% because spelling.
- Renamed StatelessAnimation to PoseAnimation.
- Renamed StatefulAnimation to ActiveAnimation.
- Documented the animation system.
### Data Pack & Resource Pack Creators
- Added support for "shedders" similar to Shedinja's evolution logic.
@@ -454,11 +439,6 @@
- Sound events for all blocks now start with "block."
- Gimmighoul chest and item interaction sounds have been moved to where its cry is.
- Unused sound files and sound events have been removed.
- Added MoLang compatibility in the isVisible property for transformed parts.
- Added q.has_aspect('some_aspect') function to animations, posers, and entity particle effects.
- Added support for conditional pose animations.
- Added a new universal locator called "top".
- Added `eggs_collected` and `eggs_hatched` Advancement triggers.
### Localization
- Updated translations for:
@@ -8,7 +8,7 @@
package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.client.render.ClientPlayerIcon;
import com.cobblemon.mod.common.client.CobblemonClient;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.MultiBufferSource;
@@ -20,9 +20,11 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerRenderer.class)
public class PlayerRendererMixin {
@Inject(method = "render", at = @At(value = "TAIL"))
@Inject(
method = "render(Lnet/minecraft/client/player/AbstractClientPlayer;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V",
at = @At(value = "TAIL")
)
public void renderPlayer(AbstractClientPlayer player, float f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, CallbackInfo ci) {
ClientPlayerIcon.Companion.onRenderPlayer(player);
CobblemonClient.INSTANCE.getRequests().onRenderPlayer(player, g);
}
}
@@ -17,7 +17,6 @@ import com.cobblemon.mod.common.api.drop.DropEntry
import com.cobblemon.mod.common.api.drop.ItemDropEntry
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.CobblemonEvents.DATA_SYNCHRONIZED
import com.cobblemon.mod.common.api.interaction.RequestManager
import com.cobblemon.mod.common.api.permission.PermissionValidator
import com.cobblemon.mod.common.api.pokeball.catching.calculators.CaptureCalculator
import com.cobblemon.mod.common.api.pokeball.catching.calculators.CaptureCalculators
@@ -44,7 +43,6 @@ import com.cobblemon.mod.common.api.spawning.prospecting.SpawningProspector
import com.cobblemon.mod.common.api.starter.StarterHandler
import com.cobblemon.mod.common.api.storage.PokemonStoreManager
import com.cobblemon.mod.common.api.storage.adapter.conversions.ReforgedConversion
import com.cobblemon.mod.common.api.storage.adapter.database.MongoDBStoreAdapter
import com.cobblemon.mod.common.api.storage.adapter.flatfile.FileStoreAdapter
import com.cobblemon.mod.common.api.storage.adapter.flatfile.JSONStoreAdapter
import com.cobblemon.mod.common.api.storage.adapter.flatfile.NBTStoreAdapter
@@ -54,7 +52,8 @@ import com.cobblemon.mod.common.api.storage.pc.PCStore
import com.cobblemon.mod.common.api.storage.pc.link.PCLinkManager
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreManager
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreTypes
import com.cobblemon.mod.common.api.storage.player.adapter.*
import com.cobblemon.mod.common.api.storage.player.adapter.DexDataNbtBackend
import com.cobblemon.mod.common.api.storage.player.adapter.PlayerDataJsonBackend
import com.cobblemon.mod.common.api.storage.player.factory.CachedPlayerDataStoreFactory
import com.cobblemon.mod.common.api.tags.CobblemonEntityTypeTags
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
@@ -107,10 +106,7 @@ import com.cobblemon.mod.common.util.*
import com.cobblemon.mod.common.world.feature.CobblemonPlacedFeatures
import com.cobblemon.mod.common.world.feature.ore.CobblemonOrePlacedFeatures
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.client.MongoClient
import com.mongodb.client.MongoClients
import java.io.File
import java.io.FileReader
import java.io.FileWriter
@@ -214,7 +210,7 @@ object Cobblemon {
BattleRegistry.onPlayerDisconnect(it.player)
storage.onPlayerDisconnect(it.player)
playerDataManager.onPlayerDisconnect(it.player)
RequestManager.onLogoff(it.player)
TradeManager.onLogoff(it.player)
}
PlatformEvents.PLAYER_DEATH.subscribe {
PCLinkManager.removeLink(it.player.uuid)
@@ -286,8 +282,6 @@ object Cobblemon {
CustomPokemonProperty.register(FreezeFrameProperty)
CustomPokemonProperty.register(NoAIProperty)
CobblemonEvents.POKEMON_PROPERTY_INITIALISED.emit()
ifDedicatedServer {
isDedicatedServer = true
}
@@ -328,7 +322,9 @@ object Cobblemon {
}
}
/*
"mongodb" -> {
/*
try {
Class.forName("com.mongodb.client.MongoClient")
@@ -336,22 +332,18 @@ object Cobblemon {
.applyConnectionString(ConnectionString(config.mongoDBConnectionString))
.build()
mongoClient = MongoClients.create(mongoClientSettings)
val generalMongoFactory = CachedPlayerDataStoreFactory(PlayerDataMongoBackend(mongoClient, config.mongoDBDatabaseName, "PlayerDataCollection"))
generalMongoFactory.setup(server)
val pokedexMongoFactory = CachedPlayerDataStoreFactory(DexDataMongoBackend(mongoClient, config.mongoDBDatabaseName, "PokeDexCollection"))
pokedexMongoFactory.setup(server)
playerDataManager.setFactory(generalMongoFactory, PlayerInstancedDataStoreTypes.GENERAL)
playerDataManager.setFactory(pokedexMongoFactory, PlayerInstancedDataStoreTypes.POKEDEX)
val mongoFactory = MongoPlayerDataStoreFactory(mongoClient, config.mongoDBDatabaseName)
playerData.setFactory(mongoFactory, PlayerInstancedDataStoreType.GENERAL)
MongoDBStoreAdapter(mongoClient, config.mongoDBDatabaseName)
} catch (e: ClassNotFoundException) {
LOGGER.error("MongoDB driver not found.")
throw e
}
*/
}
*/
else -> throw IllegalArgumentException("Unsupported storageFormat: ${config.storageFormat}")
}
@@ -388,9 +380,6 @@ object Cobblemon {
}
registerEventHandlers()
CobblemonEvents.COBBLEMON_INITIALISED.emit()
}
fun registerEventHandlers() {
@@ -155,19 +155,19 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
val pokedexes = mutableListOf<PokedexItem>()
@JvmField
val POKEDEX_RED = pokedexItem(PokedexTypes.RED)
@JvmField
val POKEDEX_YELLOW = pokedexItem(PokedexTypes.YELLOW)
@JvmField
val POKEDEX_GREEN = pokedexItem(PokedexTypes.GREEN)
val POKEDEX_BLACK = pokedexItem(PokedexTypes.BLACK)
@JvmField
val POKEDEX_BLUE = pokedexItem(PokedexTypes.BLUE)
@JvmField
val POKEDEX_GREEN = pokedexItem(PokedexTypes.GREEN)
@JvmField
val POKEDEX_PINK = pokedexItem(PokedexTypes.PINK)
@JvmField
val POKEDEX_BLACK = pokedexItem(PokedexTypes.BLACK)
val POKEDEX_RED = pokedexItem(PokedexTypes.RED)
@JvmField
val POKEDEX_WHITE = pokedexItem(PokedexTypes.WHITE)
@JvmField
val POKEDEX_YELLOW = pokedexItem(PokedexTypes.YELLOW)
@JvmField
val VIVICHOKE = compostableItem("vivichoke")
@@ -98,6 +98,9 @@ import com.cobblemon.mod.common.net.messages.client.ui.InteractPokemonUIPacket
import com.cobblemon.mod.common.net.messages.client.ui.PokedexUIPacket
import com.cobblemon.mod.common.net.messages.client.ui.SummaryUIPacket
import com.cobblemon.mod.common.net.messages.server.*
import com.cobblemon.mod.common.net.messages.server.battle.BattleSelectActionsPacket
import com.cobblemon.mod.common.net.messages.server.battle.RemoveSpectatorPacket
import com.cobblemon.mod.common.net.messages.server.battle.SpectateBattlePacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectCancelledPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectedPacket
import com.cobblemon.mod.common.net.messages.server.callback.party.PartyPokemonSelectedPacket
@@ -126,6 +129,9 @@ import com.cobblemon.mod.common.net.messages.server.storage.pc.ReleasePCPokemonP
import com.cobblemon.mod.common.net.messages.server.storage.pc.SwapPCPokemonPacket
import com.cobblemon.mod.common.net.messages.server.storage.pc.UnlinkPlayerFromPCPacket
import com.cobblemon.mod.common.net.serverhandling.*
import com.cobblemon.mod.common.net.serverhandling.battle.BattleSelectActionsHandler
import com.cobblemon.mod.common.net.serverhandling.battle.RemoveSpectatorHandler
import com.cobblemon.mod.common.net.serverhandling.battle.SpectateBattleHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectCancelledHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectedHandler
import com.cobblemon.mod.common.net.serverhandling.callback.party.PartyPokemonSelectedHandler
@@ -156,13 +162,6 @@ import com.cobblemon.mod.common.net.serverhandling.storage.pc.MovePartyPokemonTo
import com.cobblemon.mod.common.net.serverhandling.storage.pc.ReleasePartyPokemonHandler
import com.cobblemon.mod.common.net.serverhandling.storage.pc.SwapPCPokemonHandler
import com.cobblemon.mod.common.net.serverhandling.storage.pc.UnlinkPlayerFromPCHandler
import com.cobblemon.mod.common.net.serverhandling.trade.AcceptTradeRequestHandler
import com.cobblemon.mod.common.net.serverhandling.trade.CancelTradeHandler
import com.cobblemon.mod.common.net.serverhandling.trade.ChangeTradeAcceptanceHandler
import com.cobblemon.mod.common.net.serverhandling.trade.OfferTradeHandler
import com.cobblemon.mod.common.net.serverhandling.trade.UpdateTradeOfferHandler
import com.cobblemon.mod.common.net.messages.server.battle.*
import com.cobblemon.mod.common.net.serverhandling.battle.*
import com.cobblemon.mod.common.net.messages.client.pokedex.ServerConfirmedRegisterPacket
import com.cobblemon.mod.common.net.messages.client.trade.*
import com.cobblemon.mod.common.net.messages.server.pokedex.scanner.FinishScanningPacket
@@ -278,6 +277,7 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(BattleChallengeExpiredPacket.ID, BattleChallengeExpiredPacket::decode, BattleChallengeExpiredHandler))
list.add(PacketRegisterInfo(BattleReplacePokemonPacket.ID, BattleReplacePokemonPacket::decode, BattleReplacePokemonHandler))
list.add(PacketRegisterInfo(BattleTransformPokemonPacket.ID, BattleTransformPokemonPacket::decode, BattleTransformPokemonHandler))
list.add(PacketRegisterInfo(BattleAppendTargetedEntityPacket.ID, BattleAppendTargetedEntityPacket::decode, BattleSetTargetedEntityHandler))
// MultiBattleTeam Packets
list.add(PacketRegisterInfo(TeamRequestNotificationPacket.ID, TeamRequestNotificationPacket::decode, TeamRequestNotificationHandler))
@@ -29,8 +29,6 @@ object CobblemonCriteria : PlatformRegistry<Registry<CriterionTrigger<*>>, Resou
val CATCH_SHINY_POKEMON = this.create("catch_shiny_pokemon", SimpleCriterionTrigger(CountableCriterion.CODEC))
val EGG_COLLECT = this.create("eggs_collected", SimpleCriterionTrigger(CountableCriterion.CODEC))
val EGG_HATCH = this.create("eggs_hatched", SimpleCriterionTrigger(CountableCriterion.CODEC))
val EVOLVE_POKEMON = this.create("pokemon_evolved", SimpleCriterionTrigger(EvolvePokemonCriterion.CODEC))
@@ -60,4 +58,4 @@ object CobblemonCriteria : PlatformRegistry<Registry<CriterionTrigger<*>>, Resou
override val registry = BuiltInRegistries.TRIGGER_TYPES
override val resourceKey = Registries.TRIGGER_TYPE
}
}
@@ -26,7 +26,7 @@ import net.minecraft.nbt.NbtOps
* @author Qu
* @since January 9th, 2022
*/
open class Ability internal constructor(var template: AbilityTemplate, forced: Boolean, priority: Priority) {
open class Ability internal constructor(var template: AbilityTemplate, forced: Boolean) {
val name: String
get() = template.name
@@ -57,7 +57,7 @@ open class Ability internal constructor(var template: AbilityTemplate, forced: B
*
* @see [Pokemon.updateAbility].
*/
var priority = priority
var priority = Priority.LOWEST
internal set
@Deprecated("Please use the Codec instead", ReplaceWith("Ability.CODEC"))
@@ -111,7 +111,7 @@ open class Ability internal constructor(var template: AbilityTemplate, forced: B
Codec.BOOL.optionalFieldOf(DataKeys.POKEMON_ABILITY_FORCED, false).forGetter(Ability::forced),
Codec.INT.optionalFieldOf(DataKeys.POKEMON_ABILITY_INDEX, -1).forGetter(Ability::index),
Priority.CODEC.optionalFieldOf(DataKeys.POKEMON_ABILITY_PRIORITY, Priority.LOWEST).forGetter(Ability::priority)
).apply(it) { template, forced, index, priority -> Ability(template, forced, priority).apply {
).apply(it) { template, forced, index, priority -> Ability(template, forced).apply {
this.index = index
this.priority = priority
} }
@@ -23,7 +23,7 @@ import com.cobblemon.mod.common.pokemon.Species
*/
open class AbilityPool : PrioritizedList<PotentialAbility>() {
fun select(species: Species, aspects: Set<String>): Pair<Ability, Priority> {
for (priority in Priority.entries) {
for (priority in Priority.values()) {
val potentialAbilities = priorityMap[priority]?.filter { it.isSatisfiedBy(aspects) } ?: continue
if (potentialAbilities.isNotEmpty()) {
return potentialAbilities.random().template.create() to priority
@@ -31,7 +31,7 @@ open class AbilityPool : PrioritizedList<PotentialAbility>() {
}
LOGGER.error("Unable to select an ability from the pool for $species and aspects: ${aspects.joinToString()}")
LOGGER.error("Please show this to the Cobblemon developers!")
LOGGER.error("Usually this happens when a client is doing logic it shouldn't. Please show this to the Cobblemon developers!")
Exception().printStackTrace()
return Abilities.first().create() to Priority.LOWEST
}
@@ -8,7 +8,6 @@
package com.cobblemon.mod.common.api.abilities
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.util.codec.CodecUtils
import com.google.gson.JsonObject
import com.mojang.serialization.Codec
@@ -22,14 +21,14 @@ import net.minecraft.nbt.CompoundTag
*/
class AbilityTemplate(
val name: String = "",
var builder: (AbilityTemplate, forced: Boolean, priority: Priority) -> Ability = { template, forced, priority -> Ability(template, forced, priority) },
var builder: (AbilityTemplate, forced: Boolean) -> Ability = { template, forced -> Ability(template, forced) },
val displayName: String = "cobblemon.ability.$name",
val description: String = "cobblemon.ability.$name.desc"
) {
/**
* Returns the Ability or if applicable the extension connected to this template
*/
fun create(forced: Boolean = false, priority: Priority = Priority.LOWEST) = builder(this, forced, priority)
fun create(forced: Boolean = false) = builder(this, forced)
/**
* Returns the Ability and loads the given NBT Tag into it.
@@ -1,19 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.battles.interpreter
import com.cobblemon.mod.common.battles.dispatch.InterpreterInstruction
/**
* An exception thrown when properties from a [BattleMessage] cannot be interpreted for an [InterpreterInstruction].
*
* @author Segfault Guy
* @since November 10th, 2024
*/
class InvalidInstructionException(battleMessage: BattleMessage) : Exception("Failed to interpret ${battleMessage.rawMessage}")
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.api.data
import com.cobblemon.mod.common.api.net.Decodable
import com.cobblemon.mod.common.api.net.Encodable
// TODO this is implemented in multiple places but unused. Can we scratch this?
/**
* Represents an object that will possibly be synchronized to the client during datapack synchronization.
*
@@ -11,12 +11,11 @@ package com.cobblemon.mod.common.api.drop
import com.cobblemon.mod.common.api.events.CobblemonEvents.LOOT_DROPPED
import com.cobblemon.mod.common.api.events.drops.LootDroppedEvent
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import kotlin.random.Random
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.phys.Vec3
import kotlin.random.Random
/**
* A table of drops that can produce a list of [DropEntry]. You can produce a drop list from [getDrops] to
@@ -97,14 +96,4 @@ class DropTable {
ifSucceeded = { it.drops.forEach { it.drop(entity, world, pos, player) } }
)
}
fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeInt(this.entries.size)
this.entries.filterIsInstance<ItemDropEntry>().forEach { it.encode(buffer) }
}
fun decode(buffer: RegistryFriendlyByteBuf) {
val entries = buffer.readInt()
repeat(entries) { this.entries.add(ItemDropEntry().decode(buffer)) }
}
}
@@ -17,10 +17,9 @@ import com.cobblemon.mod.common.util.toBlockPos
import net.minecraft.core.component.DataComponentMap
import net.minecraft.core.component.DataComponentPatch
import net.minecraft.core.registries.Registries
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.server.level.ServerPlayer
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
@@ -34,12 +33,12 @@ import net.minecraft.world.phys.Vec3
* @since July 24th, 2022
*/
open class ItemDropEntry : DropEntry {
override var percentage = 100F
override var quantity = 1
open var quantityRange: IntRange? = null
override var maxSelectableTimes = 1
override val percentage = 100F
override val quantity = 1
open val quantityRange: IntRange? = null
override val maxSelectableTimes = 1
open val dropMethod: ItemDropMethod? = null
open var item = ResourceLocation.parse("minecraft:fish")
open val item = ResourceLocation.parse("minecraft:fish")
open val components: DataComponentMap? = null
override fun drop(entity: LivingEntity?, world: ServerLevel, pos: Vec3, player: ServerPlayer?) {
@@ -77,19 +76,4 @@ open class ItemDropEntry : DropEntry {
world.addFreshEntity(ItemEntity(world, pos.x, pos.y, pos.z, stack))
}
}
fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeFloat(this.percentage)
buffer.writeVarInt(this.quantity)
buffer.writeResourceLocation(this.item)
buffer.writeNullable(this.quantityRange) { _, it -> buffer.writeVarInt(it.first); buffer.writeVarInt(it.last) }
}
fun decode(buffer: RegistryFriendlyByteBuf): ItemDropEntry {
this.percentage = buffer.readFloat()
this.quantity = buffer.readVarInt()
this.item = buffer.readResourceLocation()
this.quantityRange = buffer.readNullable { buffer.readVarInt()..buffer.readVarInt() }
return this
}
}
@@ -8,13 +8,11 @@
package com.cobblemon.mod.common.api.entity.pokemon
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.effects.IllusionEffect
import com.cobblemon.mod.common.entity.pokemon.effects.TransformEffect
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.pokemon.FormData
import com.cobblemon.mod.common.pokemon.Species
import com.cobblemon.mod.common.util.DataKeys
@@ -97,7 +95,4 @@ interface MocKEffect : PhysicalEffect {
get() = this.mock.form?.let {
formID -> this.exposedSpecies?.forms?.firstOrNull { it.formOnlyShowdownId().equals(formID, true) } }
?: this.exposedSpecies?.standardForm
val exposedBall: PokeBall?
get() = this.mock.pokeball?.let { PokeBalls.getPokeBall(it.asIdentifierDefaultingNamespace()) }
}
@@ -54,10 +54,6 @@ import net.minecraft.server.level.ServerPlayer
@Suppress("unused")
object CobblemonEvents {
@JvmField
val POKEMON_PROPERTY_INITIALISED = SimpleObservable<Unit>()
@JvmField
val COBBLEMON_INITIALISED = SimpleObservable<Unit>()
@JvmField
val DATA_SYNCHRONIZED = SimpleObservable<ServerPlayer>()
@JvmField
@@ -133,8 +129,6 @@ object CobblemonEvents {
val POKEMON_ENTITY_SAVE_TO_WORLD = CancelableObservable<PokemonEntitySaveToWorldEvent>()
@JvmField
val ENTITY_SPAWN = CancelableObservable<SpawnEvent<*>>()
@JvmField
val SHINY_CHANCE_CALCULATION = EventObservable<ShinyChanceCalculationEvent>()
@JvmField
val POKEMON_ENTITY_SPAWN = ENTITY_SPAWN
@@ -1,57 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.pokemon
import com.cobblemon.mod.common.pokemon.Pokemon
import net.minecraft.server.level.ServerPlayer
/**
* An event to modify the shiny chance of a Pokémon.
*/
class ShinyChanceCalculationEvent(
val baseChance: Float,
val pokemon: Pokemon
) {
val chance: Float = baseChance
var isShiny: Boolean = false
private val modifiers = mutableListOf<Float>()
private val modificationFunctions = mutableListOf<(Float, ServerPlayer?, Pokemon) -> Float>()
/**
* Adds a modifier to the shiny chance.
*/
fun addModifier(modifier: Float) {
modifiers.add(modifier)
}
/**
* Adds a function to modify the shiny chance.
*/
fun addModificationFunction(function: (Float, ServerPlayer?, Pokemon) -> Float) {
modificationFunctions.add(function)
}
/**
* Calculates the shiny chance of a Pokémon.
*/
fun calculate(player: ServerPlayer?): Float {
var result = baseChance
for (modifier in modifiers) {
result += modifier
}
for (function in modificationFunctions) {
result = function(result, player, pokemon)
}
return result
}
fun isShiny(player: ServerPlayer?): Boolean {
return calculate(player) >= chance || isShiny
}
}
@@ -16,7 +16,6 @@ import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.core.Registry
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import net.minecraft.nbt.StringTag
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.entity.Entity
import net.minecraft.world.item.Item
@@ -88,8 +87,7 @@ data class FishingBait(
val BITE_TIME = cobblemonResource("bite_time")
val GENDER_CHANCE = cobblemonResource("gender_chance")
val LEVEL_RAISE = cobblemonResource("level_raise")
val TYPING = cobblemonResource("typing")
val EGG_GROUP = cobblemonResource("egg_group")
val TERA = cobblemonResource("tera")
val SHINY_REROLL = cobblemonResource("shiny_reroll")
val HIDDEN_ABILITY_CHANCE = cobblemonResource("ha_chance")
val POKEMON_CHANCE = cobblemonResource("pokemon_chance")
@@ -110,6 +108,7 @@ data class FishingBait(
EFFECT_FUNCTIONS[SHINY_REROLL] = { entity, effect -> FishingSpawnCause.shinyReroll(entity, effect) }
EFFECT_FUNCTIONS[GENDER_CHANCE] = { entity, effect -> FishingSpawnCause.alterGenderAttempt(entity, effect) }
EFFECT_FUNCTIONS[LEVEL_RAISE] = { entity, effect -> FishingSpawnCause.alterLevelAttempt(entity, effect) }
EFFECT_FUNCTIONS[TERA] = { entity, effect -> FishingSpawnCause.alterTeraAttempt(entity, effect) }
EFFECT_FUNCTIONS[HIDDEN_ABILITY_CHANCE] = { entity, _ -> FishingSpawnCause.alterHAAttempt(entity) }
EFFECT_FUNCTIONS[FRIENDSHIP] = { entity, effect -> FishingSpawnCause.alterFriendshipAttempt(entity, effect) }
CobblemonEvents.BAIT_EFFECT_REGISTRATION.post(BaitEffectFunctionRegistryEvent()) { event ->
@@ -1,106 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.interaction
import com.cobblemon.mod.common.CobblemonNetwork
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.api.text.yellow
import com.cobblemon.mod.common.battles.TeamManager
import com.cobblemon.mod.common.util.lang
import net.minecraft.server.level.ServerPlayer
import java.util.UUID
/**
* Represents an interaction request between players.
*
* @author Segfault Guy
* @since September 3rd, 2024
*/
interface PlayerActionRequest {
/** The unique ID of this request. */
val requestID: UUID
/** The unique ID of the party that's initiating this request. */
val senderID: UUID
/** The amount of seconds this request is valid for. */
val expiryTime: Int
}
/**
* An outbound [PlayerActionRequest].
*
* @author Segfault Guy
* @since September 29th, 2024
*/
interface ServerPlayerActionRequest : PlayerActionRequest {
/** The subkey identifying lang entries associated with this request. */
val key: String
/** The player initiating this interaction request. */
val sender: ServerPlayer
/** The player that's the target of this interaction request. */
val receiver: ServerPlayer
/** The unique ID of the party that's the target of this request. */
val receiverID: UUID get() = receiver.uuid
override val senderID: UUID get() = sender.uuid
/** Sends [packet] to sending party of this request. */
fun sendToSender(packet: NetworkPacket<*>) = sender.sendPacket(packet)
/** Sends [packet] to receiving party of this request. */
fun sendToReceiver(packet: NetworkPacket<*>) = receiver.sendPacket(packet)
/** Notifies the sending party of this request about [langKey]. */
fun notifySender(error: Boolean, langKey: String, vararg params: Any) = notify(sender, error, "$key.$langKey", *params)
/** Notifies the receiving party of this request about [langKey]. */
fun notifyReceiver(error: Boolean, langKey: String, vararg params: Any) = notify(receiver, error, "$key.$langKey", *params)
/** System message to inform individual [player] about [langKey]. */
fun notify(player: ServerPlayer, error: Boolean, langKey: String, vararg params: Any) {
val lang = lang(langKey, *params).apply { if (error) red() else yellow() }
player.sendSystemMessage(lang, false)
}
}
/**
* An outbound [PlayerActionRequest] made on behalf of a team.
*
* @author Segfault Guy
* @since October 29th, 2024
*/
interface ServerTeamActionRequest : ServerPlayerActionRequest {
/** The team initiating this request. */
val senderTeam: TeamManager.MultiBattleTeam
/** The team that's the target of this request. */
val receiverTeam: TeamManager.MultiBattleTeam
override val senderID: UUID get() = senderTeam.teamID
override val receiverID: UUID get() = receiverTeam.teamID
override fun sendToSender(packet: NetworkPacket<*>) = CobblemonNetwork.sendPacketToPlayers(senderTeam.teamPlayers, packet)
override fun sendToReceiver(packet: NetworkPacket<*>) = CobblemonNetwork.sendPacketToPlayers(receiverTeam.teamPlayers, packet)
override fun notifySender(error: Boolean, langKey: String, vararg params: Any) =
senderTeam.teamPlayers.forEach { this.notify(it, error, "$key.$langKey", *params) }
override fun notifyReceiver(error: Boolean, langKey: String, vararg params: Any) =
receiverTeam.teamPlayers.forEach { this.notify(it, error, "$key.$langKey", *params) }
}
@@ -1,230 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.interaction
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.scheduling.afterOnServer
import com.cobblemon.mod.common.api.text.aqua
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.battles.TeamManager
import com.cobblemon.mod.common.util.*
import net.minecraft.server.level.ServerPlayer
import java.util.*
/**
* Defines a manager for organizing active interaction requests between parties. Responsible for dispatching requests to clients,
* notifying senders and receivers of requests, and handling their acceptance, expiration, or cancellation.
*
* Implementations can manage either PLAYER-to-PLAYER requests or TEAM-to-TEAM requests.
*
* @param T The type of interaction request this manager tracks.
*
* @author Segfault Guy
* @since October 26th, 2024
*/
abstract class RequestManager<T : ServerPlayerActionRequest> {
/**
* Tracking of the active [ServerPlayerActionRequest]s by their sender.
*
* NOTE: only 1 request can be sent by a sender at a time.
*/
private val outboundRequests = mutableMapOf<UUID, T>()
/**
* Tracking of the active [ServerPlayerActionRequest]s by their recipient.
*
* NOTE: a recipient can receive multiple requests from different senders at the same time.
*/
private val inboundRequests = mutableMapOf<UUID, MutableList<T>>()
// we use the term 'sender' because BattleChallenges can be sent TEAM-to-TEAM instead of PLAYER-to-PLAYER for multi battles
/** Queries the latest pending request that was sent by [senderID]. */
fun getOutboundRequest(senderID: UUID) = outboundRequests.get(senderID)
/** Queries the pending request of [requestID] that was sent by [senderID]. */
fun getOutboundRequest(senderID: UUID, requestID: UUID) = this.getOutboundRequest(senderID)?.takeIf { it.requestID == requestID }
/** Queries the pending request that was sent by [senderID] and received by [receiverID]. */
fun getOutboundRequestByRecipient(senderID: UUID, receiverID: UUID) = this.getOutboundRequest(senderID)?.takeIf { it.receiverID == receiverID }
/** Queries the pending request of [requestID] that was sent by [sender] or their team. */
fun getOutboundRequest(sender: ServerPlayer, requestID: UUID) = TeamManager.getTeam(sender)?.let { this.getOutboundRequest(it.teamID, requestID) }
?: this.getOutboundRequest(sender.uuid, requestID)
/** Queries all pending requests that were received by [receiverID]. */
fun getInboundRequests(receiverID: UUID) = inboundRequests.get(receiverID)
/** Queries the pending request of [requestID] that was received by [receiverID]. */
fun getInboundRequest(receiverID: UUID, requestID: UUID) = this.getInboundRequests(receiverID)?.find { it.requestID == requestID }
/** Queries the pending request that was sent by [senderID] and received by [receiverID]. */
fun getInboundRequestBySender(receiverID: UUID, senderID: UUID) = this.getInboundRequests(receiverID)?.find { it.senderID == senderID }
/** Queries the pending request of [requestID] that was received by [receiver] or their team. */
fun getInboundRequest(receiver: ServerPlayer, requestID: UUID) = TeamManager.getTeam(receiver)?.let { this.getInboundRequest(it.teamID, requestID) }
?: this.getInboundRequest(receiver.uuid, requestID)
/** Determines whether [player] can receive a [T]. */
open fun isBusy(player: ServerPlayer): Boolean = player.isInBattle() || player.isTrading()
/** Determines if the [target] is a valid interaction request target. */
abstract fun isValidInteraction(player: ServerPlayer, target: ServerPlayer): Boolean
/** Determines whether [request] response is valid and can be accepted. If invalid, notifies the sender and receiver of the request why. */
protected abstract fun canAccept(request: T): Boolean
/** Creates a packet for notifying a recipient about a received request. */
protected abstract fun notificationPacket(request: T): NetworkPacket<*>
/** Creates a packet for canceling received requests. */
protected abstract fun expirationPacket(request: T): NetworkPacket<*>
protected fun addRequest(request: T) {
outboundRequests.put(request.senderID, request)
inboundRequests.computeIfAbsent(request.receiverID) { mutableListOf() }.add(request)
request.sendToReceiver(this.notificationPacket(request))
}
protected fun removeRequest(request: T): Boolean {
val inbound = inboundRequests.get(request.receiverID)
val removeOutbound = outboundRequests.remove(request.senderID, request)
val removeInbound = inbound?.remove(request) == true
if (removeInbound && inbound?.size == 0) inboundRequests.remove(request.receiverID, inbound)
if (removeInbound != removeOutbound)
Cobblemon.LOGGER.error("RequestManager: PlayerActionRequest desync") // USE ADDREQUEST AND REMOVEREQUEST
val isRemoved = removeInbound && removeOutbound
if (isRemoved) request.sendToReceiver(this.expirationPacket(request))
return isRemoved
}
/** Notifies and removes an outbound request [T] sent by [ServerPlayerActionRequest.sender] to [ServerPlayerActionRequest.receiver]. */
open fun cancelRequest(request: T, expired: Boolean = false) {
if (!this.removeRequest(request)) return
// canceled by expiration
if (expired) {
request.notifySender(true, "expired.sender", request.receiver.name.copy().aqua())
request.notifyReceiver(true, "expired.receiver", request.sender.name.copy().aqua())
}
// canceled by sender
else {
request.notifySender(true, "canceled.sender", request.receiver.name.copy().aqua())
request.notifyReceiver(true, "canceled.receiver", request.sender.name.copy().aqua())
}
// receivers DECLINE, not cancel
}
/** Hook into [sendRequest] immediately after the [request] is sent and added to the manager. Default behavior is to notify parties. */
protected open fun onSend(request: T) {
request.notifySender(false, "sent", request.receiver.name.copy().aqua())
request.notifyReceiver(false, "received", request.sender.name.copy().aqua())
}
/** Sends an outbound request [T] from [ServerPlayerActionRequest.sender] to [ServerPlayerActionRequest.receiver]. */
fun sendRequest(request: T): Boolean {
val existingRequest = this.getOutboundRequest(request.senderID)
val pendingRequest = this.getInboundRequestBySender(request.senderID, request.receiverID)
// old request
if (existingRequest != null && existingRequest.receiverID != request.receiverID)
this.cancelRequest(existingRequest)
// if sender already has a request awaiting a response from the receiver they're trying to send to.
if (existingRequest != null && existingRequest.receiverID == request.receiverID)
request.notify(request.sender, true, "${request.key}.error.duplicate", request.receiver.name.copy().aqua())
// if sender already has a pending request from the receiver they're trying to send to.
else if (pendingRequest != null)
request.notify(request.sender, true, "${request.key}.error.pending", request.receiver.name.copy().aqua())
// verify sending player can interact with target player
else if (!this.isValidInteraction(request.sender, request.receiver))
request.notify(request.sender, true, "ui.interact.failed")
else if (this.isBusy(request.receiver)) // TODO call to isBusy when setting up the interaction packet
request.notify(request.sender, true, "ui.interact.unavailable")
// new request
else {
this.addRequest(request)
afterOnServer(seconds = request.expiryTime.toFloat()) { this.cancelRequest(request, true) }
this.onSend(request)
return true
}
return false
}
/** Hook into [acceptRequest] immediately after the [request] is accepted and removed from the manager. Default behavior is to notify parties. */
protected open fun onAccept(request: T) {
request.notifySender(false, "accept.sender", request.receiver.name.copy().aqua())
request.notifyReceiver(false, "accept.receiver", request.sender.name.copy().aqua())
}
/** Accepts a pending inbound [requestID] for [player]. */
fun acceptRequest(player: ServerPlayer, requestID: UUID, target: ServerPlayer? = null): Boolean {
var accepted = false
val request = this.getInboundRequest(player, requestID)
// verify request being responded to still valid
if (request == null)
player.sendSystemMessage(lang("ui.interact.request_already_expired").red(), false)
// verify accepting player can respond to sending player
else if (!this.isValidInteraction(player, target ?: request.sender)) // with teams anyone can accept
request.notify(player, true, "ui.interact.failed")
// if sending player is occupied, can't accept response
else if (this.isBusy(request.sender)) // TODO enhancement: allow retries - modify client so we don't remove request when sending acceptance
request.notify(player, true, "ui.interact.unavailable")
// if no condition is blocking acceptance, accept
else if (this.canAccept(request))
accepted = true
request?.let {
this.removeRequest(it)
if (accepted) this.onAccept(request) // order matters
}
return accepted
}
/** Hook into [declineRequest] immediately after the [request] is declined and removed from the manager. Default behavior is to notify parties. */
protected open fun onDecline(request: T) {
request.notifySender(true, "decline.sender", request.receiver.name.copy().aqua())
request.notifyReceiver(false, "decline.receiver", request.sender.name.copy().aqua())
}
/** Declines a pending [request]. */
fun declineRequest(request: T) {
this.removeRequest(request)
this.onDecline(request)
}
/** Declines an inbound request [requestID] for [receiver]. */
fun declineRequest(receiver: ServerPlayer, requestID: UUID) {
val request = this.getInboundRequest(receiver, requestID) ?: return
this.declineRequest(request)
}
/** Cancels pending outbound requests sent from, and pending inbound request sent to, [player]. */
protected open fun onLogoff(player: ServerPlayer) {
// ONLY regarding the player. see TeamManager for how team requests are canceled on team disband.
outboundRequests.get(player.uuid)?.let { request ->
this.cancelRequest(request)
}
inboundRequests.get(player.uuid)?.toMutableList()?.let { requests ->
requests.forEach { request ->
this.declineRequest(player, request.requestID)
}
}
}
companion object {
private val managers = mutableListOf<RequestManager<*>>()
fun register(manager: RequestManager<*>) = managers.add(manager)
fun onLogoff(player: ServerPlayer) = managers.forEach { it.onLogoff(player) }
}
}
@@ -252,8 +252,6 @@ object MoLangFunctions {
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
map.put("class") { StringValue(npc.npc.id.toString()) }
map.put("name") { StringValue(npc.name.string) }
map.put("level") { DoubleValue(npc.level) }
map.put("has_aspect") { params -> DoubleValue(npc.aspects.contains(params.getString(0))) }
map.put("face") { params -> ObjectValue(ReferenceDialogueFaceProvider(npc.id, params.getBooleanOrNull(0) != false)) }
map.put("in_battle") { DoubleValue(npc.isInBattle()) }
map.put("run_script_on_client") { params ->
@@ -299,7 +297,7 @@ object MoLangFunctions {
}
map.put("put_pokemon_in_healer") { params ->
val healer = npc.level().getBlockEntity(params.get<ArrayStruct>(0).asBlockPos(), CobblemonBlockEntities.HEALING_MACHINE).orElse(null) ?: return@put DoubleValue.ZERO
val party = npc.party ?: return@put DoubleValue.ZERO
val party = npc.staticParty ?: return@put DoubleValue.ZERO
if (healer.canHeal(party)) {
healer.activate(npc.uuid, party)
return@put DoubleValue.ONE
@@ -337,7 +335,7 @@ object MoLangFunctions {
val pokemonFunctions = mutableListOf<(Pokemon) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
{ pokemon ->
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
map.put("is_wild") { DoubleValue(pokemon.entity?.let { it.ownerUUID == null } == true) }
map.put("is_wild") { DoubleValue(pokemon.isWild()) }
map.put("is_shiny") { DoubleValue(pokemon.shiny) }
map.put("form") { StringValue(pokemon.form.name) }
map.put("weight") { DoubleValue(pokemon.species.weight.toDouble()) }
@@ -11,14 +11,12 @@ package com.cobblemon.mod.common.api.moves.animations.keyframes
import com.cobblemon.mod.common.api.molang.ExpressionLike
import com.cobblemon.mod.common.api.moves.animations.ActionEffectContext
import com.cobblemon.mod.common.api.moves.animations.EntityProvider
import com.cobblemon.mod.common.api.moves.animations.TargetsProvider
import com.cobblemon.mod.common.api.moves.animations.UsersProvider
import com.cobblemon.mod.common.api.scheduling.delayedFuture
import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.net.messages.client.effect.SpawnSnowstormEntityParticlePacket
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import net.minecraft.commands.arguments.EntityArgument.getPlayers
import java.util.concurrent.CompletableFuture
import net.minecraft.server.level.ServerLevel
@@ -31,8 +29,7 @@ import net.minecraft.server.level.ServerLevel
class EntityParticlesActionEffectKeyframe : ConditionalActionEffectKeyframe(), EntityConditionalActionEffectKeyframe {
override val entityCondition = "q.entity.is_user".asExpressionLike()
var effect: String? = null
var locators: List<String> = listOf("target")
var locator: String = "root"
val delay: ExpressionLike = "0".asExpressionLike()
val visibilityRange = 200
@@ -48,7 +45,7 @@ class EntityParticlesActionEffectKeyframe : ConditionalActionEffectKeyframe(), E
}?.asIdentifierDefaultingNamespace() ?: return skip()
entities.filter { it is PosableEntity }.forEach { entity ->
val packet = SpawnSnowstormEntityParticlePacket(effectIdentifier, entity.id, (locators).toList())
val packet = SpawnSnowstormEntityParticlePacket(effectIdentifier, entity.id, listOf(locator))
val players = (entity.level() as ServerLevel).getPlayers { it.distanceTo(entity) <= visibilityRange }
packet.sendToPlayers(players)
}
@@ -47,7 +47,6 @@ class NPCClass {
var variables = mutableMapOf<String, MoValue>() // Questionable whether this should be here.
var party: NPCPartyProvider? = null
var skill: Int = 0
var autoHealParty: Boolean = false
var battleTheme: ResourceLocation? = null
var ai: MutableList<BrainConfig> = mutableListOf()
@@ -78,7 +77,6 @@ class NPCClass {
buffer.writeString(v.defaultValue)
}
buffer.writeInt(skill)
buffer.writeBoolean(autoHealParty)
buffer.writeMapK(size = IntSize.U_BYTE, map = variables) { (key, value) ->
buffer.writeString(key)
buffer.writeString(value.asString())
@@ -118,7 +116,6 @@ class NPCClass {
NPCConfigVariable(variableName, displayName, description, type, defaultValue)
}.toMutableList()
skill = buffer.readInt()
autoHealParty = buffer.readBoolean()
buffer.readMapK(size = IntSize.U_BYTE, map = variables) {
val key = buffer.readString()
val value = buffer.readString()
@@ -8,11 +8,15 @@
package com.cobblemon.mod.common.api.npc
import com.cobblemon.mod.common.api.npc.partyproviders.PoolPartyProvider
import com.cobblemon.mod.common.api.npc.partyproviders.DynamicPartyProvider
import com.cobblemon.mod.common.api.npc.partyproviders.NPCParty
import com.cobblemon.mod.common.api.npc.partyproviders.SimplePartyProvider
import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.google.gson.JsonElement
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.server.level.ServerPlayer
/**
* A provider of a party for battling the NPC. Completely custom party providers will only display
@@ -25,13 +29,11 @@ interface NPCPartyProvider {
companion object {
val types = mutableMapOf<String, (String) -> NPCPartyProvider>(
SimplePartyProvider.TYPE to { SimplePartyProvider() },
PoolPartyProvider.TYPE to { PoolPartyProvider() }
DynamicPartyProvider.TYPE to { DynamicPartyProvider() }
)
}
val type: String
val isStatic: Boolean
fun provide(npc: NPCEntity, level: Int): NPCPartyStore
// Why did I opt for manual JSON loading??? I must have had a reason but I can't remember. Maybe for S2C? Use a codec doofus
fun provide(npc: NPCEntity, level: Int): NPCParty
fun loadFromJSON(json: JsonElement)
}
@@ -29,7 +29,6 @@ class NPCPreset {
var hitbox: EntityDimensions? = null
var ai: List<BrainConfig>? = null
var skill: Int? = null
var autoHealParty: Boolean? = null
var battleTheme: ResourceLocation? = null
fun applyTo(npcClass: NPCClass) {
@@ -48,7 +47,6 @@ class NPCPreset {
names?.let { npcClass.names.addAll(it) }
hitbox?.let { npcClass.hitbox = it }
skill?.let { npcClass.skill = it }
autoHealParty?.let { npcClass.autoHealParty = it }
battleTheme?.let { npcClass.battleTheme = it }
ai?.let { npcClass.ai.addAll(it) }
}
@@ -8,15 +8,15 @@
package com.cobblemon.mod.common.api.npc.configuration
import com.cobblemon.mod.common.api.npc.NPCPartyProvider
import com.cobblemon.mod.common.util.DataKeys
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.RegistryFriendlyByteBuf
class NPCBattleConfiguration {
var canChallenge = false
@Deprecated("This is not likely to get used")
var party: NPCPartyProvider? = null
var simultaneousBattles = false
@Deprecated("This is not likely to get used")
var healAfterwards = true
fun encode(buffer: RegistryFriendlyByteBuf) {
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.npc.partyproviders
import com.cobblemon.mod.common.api.npc.NPCPartyProvider
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.google.gson.JsonElement
import net.minecraft.resources.ResourceLocation
/**
* A provider of a party for battling the NPC. It generates a [StaticNPCParty] but using a more complex process
* that takes an input level and makes a randomized selection of Pokémon and movesets.
*
* @author Hiroku
* @since July 12th, 2024
*/
class DynamicPartyProvider : NPCPartyProvider {
companion object {
val TYPE = "dynamic"
}
class DynamicPool {
val id = ResourceLocation.parse("cobblemon:pool")
val pokemon: MutableList<DynamicPokemon> = mutableListOf()
}
class DynamicPokemon(
val pokemon: PokemonProperties,
val possibleLevels: IntRange,
val selectableTimes: IntRange,
val guaranteed: Boolean = false
)
override val type = "dynamic"
override fun loadFromJSON(json: JsonElement) {
TODO("Not yet implemented")
}
override fun provide(npc: NPCEntity, level: Int): NPCParty {
TODO("Not yet implemented")
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.npc.partyproviders
import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.net.IntSize
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.readSizedInt
import com.cobblemon.mod.common.util.writeSizedInt
import net.minecraft.core.RegistryAccess
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.server.level.ServerPlayer
/**
* Represents a party of Pokemon that an NPC can have. This isn't directly a party of Pokémon so that
* a dynamically generated party can exist where a party is generated at the time of a challenge.
*
* This interface is sealed. Implementations should be either [StaticNPCParty] or [DynamicNPCParty].
* If you want a custom type then you should implement [DynamicNPCParty] and register it in the
* [DynamicNPCParty.types] map.
*
* @author Hiroku
* @since July 12th, 2024
*/
sealed interface NPCParty {
fun getParty(player: ServerPlayer, npc: NPCEntity): PartyStore?
fun encode(buffer: RegistryFriendlyByteBuf)
fun decode(buffer: RegistryFriendlyByteBuf)
fun saveToNBT(nbt: CompoundTag, registryAccess: RegistryAccess)
fun loadFromNBT(nbt: CompoundTag, registryAccess: RegistryAccess)
}
/**
* A simple wrapping around a [NPCPartyStore]. This is a straightforward party that is always the same.
*
* @author Hiroku
* @since July 12th, 2024
*/
class StaticNPCParty(val party: NPCPartyStore) : NPCParty {
override fun getParty(player: ServerPlayer, npc: NPCEntity) = party
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeSizedInt(IntSize.U_BYTE, party.size())
for (pokemon in party) {
Pokemon.S2C_CODEC.encode(buffer, pokemon)
}
}
override fun decode(buffer: RegistryFriendlyByteBuf) {
repeat(times = buffer.readSizedInt(IntSize.U_BYTE)) {
party.add(Pokemon.S2C_CODEC.decode(buffer))
}
}
override fun saveToNBT(nbt: CompoundTag, registryAccess: RegistryAccess) {
for ((index, pokemon) in party.withIndex()) {
nbt.put(DataKeys.NPC_PARTY_POKEMON + index, pokemon.saveToNBT(registryAccess))
}
}
override fun loadFromNBT(nbt: CompoundTag, registryAccess: RegistryAccess) {
var index = 0
while (nbt.contains(DataKeys.NPC_PARTY_POKEMON + index)) {
this.party.add(Pokemon().loadFromNBT(registryAccess, nbt.getCompound(DataKeys.NPC_PARTY_POKEMON + index)))
index++
}
}
}
/**
* A dynamic party that is generated at the time of a challenge.
*
* @author Hiroku
* @since July 12th, 2024
*/
interface DynamicNPCParty : NPCParty {
companion object {
val types = mutableMapOf<String, Class<out NPCParty>>()
init {}
}
}
@@ -1,128 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.npc.partyproviders
import com.bedrockk.molang.Expression
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.npc.NPCPartyProvider
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.weightedSelection
import com.cobblemon.mod.common.util.withQueryValue
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
/**
* A provider of a party for battling the NPC. It generates a party using a more complex process
* that takes an input level and makes a randomized selection of Pokémon and movesets from a pool.
*
* The party can be static or dynamic based on [isStatic]. If it is dynamic, the pool will be used
* to generate a party whenever the NPC is challenged and AI that depends on a reliable party will
* not run.
*
* Not an actual pool party. That's for v2.0.
*
* @author Hiroku
* @since July 12th, 2024
*/
class PoolPartyProvider : NPCPartyProvider {
companion object {
const val TYPE = "pool"
}
@Transient
override val type = TYPE
override var isStatic: Boolean = false
var minPokemon: Expression = "1".asExpression()
var maxPokemon: Expression = "6".asExpression()
var pool = mutableListOf<DynamicPokemon>()
override fun loadFromJSON(json: JsonElement) {
json as JsonObject
this.minPokemon = json.getAsJsonPrimitive("minPokemon").asString?.asExpression() ?: "1".asExpression()
this.maxPokemon = json.getAsJsonPrimitive("maxPokemon").asString?.asExpression() ?: "6".asExpression()
this.pool = json.getAsJsonArray("pool").map {
if (it is JsonPrimitive) {
return@map DynamicPokemon(
PokemonProperties.parse(it.asString),
0..0,
0..100,
"1".asExpression(),
"1".asExpression()
)
}
it as JsonObject
DynamicPokemon(
PokemonProperties.parse(it.getAsJsonPrimitive("pokemon").asString),
it.getAsJsonPrimitive("levelVariation")?.asString?.split("-")?.let { it[0].toInt()..it[1].toInt() } ?: 0..0,
it.getAsJsonPrimitive("npcLevels")?.asString?.split("-")?.let { it[0].toInt()..it[1].toInt() } ?: 0..100,
it.getAsJsonPrimitive("selectableTimes")?.asString?.asExpression() ?: "1".asExpression(),
it.getAsJsonPrimitive("weight")?.asString?.asExpression() ?: "1".asExpression()
)
}.toMutableList()
isStatic = json.getAsJsonPrimitive("isStatic").asBoolean
}
class DynamicPokemon(
val pokemon: PokemonProperties,
val levelVariation: IntRange,
val npcLevels: IntRange,
val selectableTimes: Expression,
val weight: Expression = "1".asExpression()
) {
fun getWeight(runtime: MoLangRuntime): Float {
return runtime.resolveFloat(weight)
}
fun hasWeight(runtime: MoLangRuntime): Boolean {
return runtime.resolveFloat(weight) != 0F
}
}
fun formulateParty(npc: NPCEntity, level: Int, party: NPCPartyStore) {
val runtime = MoLangRuntime().setup().withQueryValue("npc", npc.struct)
val minPokemon = runtime.resolveInt(this.minPokemon)
val maxPokemon = runtime.resolveInt(this.maxPokemon)
var desiredPokemonCount = (minPokemon..maxPokemon).random()
val workingPool = pool.filter { level in it.npcLevels }.toMutableList()
val useCounts = mutableMapOf<DynamicPokemon, Int>()
while (desiredPokemonCount > 0 && workingPool.filter { it.hasWeight(runtime) }.isNotEmpty()) {
val selected = workingPool.filter { it.getWeight(runtime) == -1F }.randomOrNull()
?: workingPool.weightedSelection { it.getWeight(runtime) }
?: break
useCounts[selected] = useCounts.getOrDefault(selected, 0) + 1
val allowedSelections = runtime.resolveInt(selected.selectableTimes)
if (useCounts[selected]!! >= allowedSelections) {
workingPool.remove(selected)
}
desiredPokemonCount--
// If the Pokémon's props specifies a level then use that, otherwise choose a random level within the range
val randomLevel = (level + selected.levelVariation.random())
val instance = selected.pokemon.copy().also { it.level = it.level ?: randomLevel }.create()
party.add(instance)
}
}
override fun provide(npc: NPCEntity, level: Int): NPCPartyStore {
val party = NPCPartyStore(npc)
formulateParty(npc, level, party)
return party
}
}
@@ -16,7 +16,7 @@ import com.cobblemon.mod.common.util.toProperties
import com.google.gson.JsonElement
/**
* A basic party provider that just produces a [NPCPartyStore] based on a simple list of [PokemonProperties].
* A basic party provider that just produces a [StaticNPCParty] based on a list of [PokemonProperties].
*
* @author Hiroku
* @since August 19th, 2023
@@ -28,15 +28,10 @@ class SimplePartyProvider : NPCPartyProvider {
@Transient
override val type = TYPE
override var isStatic = true
val pokemon = mutableListOf<PokemonProperties>()
override fun loadFromJSON(json: JsonElement) {
val isStatic = json.asJsonObject.get("isStatic")?.asBoolean
if (isStatic != null) {
this.isStatic = isStatic
}
val pokemonList = json.asJsonObject.getAsJsonArray("pokemon")
pokemonList.forEach {
val pokemon = if (it.isJsonPrimitive) {
@@ -52,10 +47,10 @@ class SimplePartyProvider : NPCPartyProvider {
}
}
override fun provide(npc: NPCEntity, level: Int): NPCPartyStore {
override fun provide(npc: NPCEntity, level: Int): NPCParty {
val pokemon = pokemon.map { it.copy().also { it.level = it.level ?: level }.create() }
val party = NPCPartyStore(npc)
pokemon.forEach(party::add)
return party
return StaticNPCParty(party)
}
}
@@ -61,15 +61,11 @@ class FormDexRecord {
@Transient
lateinit var speciesDexRecord: SpeciesDexRecord
@Transient
lateinit var formName: String
@Transient
lateinit var struct: QueryStruct
fun initialize(speciesDexRecord: SpeciesDexRecord, formName: String) {
fun initialize(speciesDexRecord: SpeciesDexRecord) {
this.speciesDexRecord = speciesDexRecord
this.formName = formName
struct = QueryStruct(hashMapOf())
.addFunction("data") { data }
.addFunction("knowledge") { StringValue(knowledge.name) }
@@ -79,7 +79,7 @@ class SpeciesDexRecord {
fun initialize(pokedexManager: AbstractPokedexManager, id: ResourceLocation) {
this.id = id
this.pokedexManager = pokedexManager
this.formRecords.forEach { it.value.initialize(this, it.key) }
this.formRecords.forEach { it.value.initialize(this) }
}
fun onFormRecordUpdated(formDexRecord: FormDexRecord) {
@@ -106,7 +106,7 @@ class SpeciesDexRecord {
fun getOrCreateFormRecord(formName: String): FormDexRecord {
return formRecords.getOrPut(formName.lowercase()) {
val record = FormDexRecord()
record.initialize(this, formName)
record.initialize(this)
onFormRecordUpdated(record)
// Some more stuff eventually
record
@@ -14,8 +14,6 @@ import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.abilities.Abilities
import com.cobblemon.mod.common.api.abilities.Ability
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.pokemon.ShinyChanceCalculationEvent
import com.cobblemon.mod.common.api.moves.Moves
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.aspect.AspectProvider
@@ -58,8 +56,6 @@ import net.minecraft.nbt.Tag
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
@@ -577,24 +573,18 @@ open class PokemonProperties {
return true
}
@JvmOverloads
fun create(player: ServerPlayer? = null): Pokemon {
fun create(): Pokemon {
val pokemon = Pokemon()
apply(pokemon)
pokemon.initialize()
roll(pokemon, player)
roll(pokemon)
return pokemon
}
// TEST YOUR LUCK!
@JvmOverloads
fun roll(pokemon: Pokemon, player: ServerPlayer? = null) {
fun roll(pokemon: Pokemon) {
val baseTypes = pokemon.form.types.toList()
var shinyRate = Cobblemon.config.shinyRate
CobblemonEvents.SHINY_CHANCE_CALCULATION.post(ShinyChanceCalculationEvent(shinyRate, pokemon)) { event ->
shinyRate = event.calculate(player)
}
if (this.shiny == null) pokemon.shiny = shinyRate.checkRate()
if (this.shiny == null) pokemon.shiny = Cobblemon.config.shinyRate.checkRate()
if (this.teraType == null) pokemon.teraType =
if (Cobblemon.config.teraTypeRate.checkRate()) {
var picked = TeraTypes.random(true)
@@ -606,9 +596,8 @@ open class PokemonProperties {
else TeraTypes.forElementalType(baseTypes.random())
}
@JvmOverloads
fun createEntity(world: Level, player: ServerPlayer? = null): PokemonEntity {
return PokemonEntity(world, create(player)).also { applyCustomProperties(it) }
fun createEntity(world: Level): PokemonEntity {
return PokemonEntity(world, create()).also { applyCustomProperties(it) }
}
// TODO Codecs at some point
@@ -794,7 +783,7 @@ open class PokemonProperties {
}
// If the config value is at least 1, then do 1/x and use that as the property chance
private fun Float.checkRate(): Boolean = if (this >= 1) (Random.Default.nextFloat() < 1 / this) else Random.Default.nextFloat() < this
private fun Float.checkRate(): Boolean = this >= 1 && (Random.Default.nextFloat() < 1 / this)
/**
* Attempts to find an ability by ID and resolve if it should be forced or if it's legal for the given form.
@@ -53,7 +53,7 @@ fun interface PokemonPropertyExtractor {
val EVS = add { pokemon, properties -> properties.evs = pokemon.evs }
@JvmField
val ILLUSION = mutableListOf(SPECIES, FORM, ASPECTS, GENDER, NICKNAME, SHINY, POKEBALL)
val ILLUSION = mutableListOf(SPECIES, FORM, ASPECTS, GENDER, NICKNAME, SHINY)
@JvmField
val TRANSFORM = mutableListOf(SPECIES, FORM, ASPECTS, GENDER)
@@ -15,7 +15,7 @@ package com.cobblemon.mod.common.api.pokemon.egg
*
* @property showdownID used for data synchronization with Showdown data format.
*/
enum class EggGroup(val showdownID: String) {
enum class EggGroup(internal val showdownID: String) {
MONSTER("Monster"),
WATER_1("Water 1"),
@@ -31,16 +31,6 @@ enum class EggGroup(val showdownID: String) {
WATER_2("Water 2"),
DITTO("Ditto"),
DRAGON("Dragon"),
UNDISCOVERED("Undiscovered");
UNDISCOVERED("Undiscovered")
companion object {
private val identifierMap: Map<String, EggGroup> = entries.associateBy {
it.showdownID.lowercase().replace(" ", "_").replace("-", "_")
}
fun fromIdentifier(identifier: String): EggGroup? {
val key = identifier.lowercase().replace(" ", "_").replace("-", "_")
return identifierMap[key]
}
}
}
@@ -156,11 +156,12 @@ interface Evolution : EvolutionLike {
}
val preEvoName = pokemon.getDisplayName()
val evolveMessage = lang("ui.evolve.into", preEvoName, pokemon.species.translatedName)
val pokemonEntity = pokemon.entity
if (pokemonEntity == null || !useEvolutionEffect) {
pokemon.getOwnerPlayer()?.playNotifySound(CobblemonSounds.EVOLUTION_UI, SoundSource.PLAYERS, 1F, 1F)
evolutionMethod(pokemon)
pokemon.getOwnerPlayer()?.sendSystemMessage(lang("ui.evolve.into", preEvoName, pokemon.species.translatedName))
pokemon.getOwnerPlayer()?.sendSystemMessage(evolveMessage)
} else {
pokemonEntity.busyLocks.add("evolving")
pokemonEntity.navigation.stop()
@@ -173,7 +174,7 @@ interface Evolution : EvolutionLike {
pokemonEntity.after( seconds = 12F ) {
cryAnimation(pokemonEntity)
pokemonEntity.busyLocks.remove("evolving")
pokemon.getOwnerPlayer()?.sendSystemMessage(lang("ui.evolve.into", preEvoName, pokemon.species.translatedName))
pokemon.getOwnerPlayer()?.sendSystemMessage(evolveMessage)
}
}
}
@@ -10,8 +10,6 @@ package com.cobblemon.mod.common.api.scheduling
import java.util.concurrent.CompletableFuture
import com.cobblemon.mod.common.util.runOnServer
import net.minecraft.world.TickRateManager
import net.minecraft.world.level.Level
@Deprecated("Use afterOnServer or afterOnClient; ambiguous side is not good for your health")
@JvmOverloads
@@ -35,13 +33,9 @@ fun delayedFuture(ticks: Int = 0, seconds: Float = 0F, serverThread: Boolean = f
* being completed after the delay does things like entity removal or other thread-unsafe actions.
*/
@JvmOverloads
fun afterOnServer(seconds: Float, action: () -> Unit) = ServerTaskTracker.after(seconds, action)
fun afterOnServer(ticks: Int = 0, seconds: Float = 0F, action: () -> Unit) = ServerTaskTracker.after(seconds + ticks / 20F, action)
@JvmOverloads
fun afterOnServer(ticks: Int, level: Level, action: () -> Unit) = ServerTaskTracker.after(ticks / level.tickRateManager().tickrate(), action)
@JvmOverloads
fun afterOnClient(seconds: Float, action: () -> Unit) = ClientTaskTracker.after(seconds, action)
@JvmOverloads
fun afterOnClient(ticks: Int, level: Level, action: () -> Unit) = ClientTaskTracker.after(ticks / level.tickRateManager().tickrate(), action)
fun afterOnClient(ticks: Int = 0, seconds: Float, action: () -> Unit) = ClientTaskTracker.after(seconds + ticks / 20F, action)
@Deprecated("Use lerpOnServer or lerpOnClient, side-ambiguity causes problems now")
fun lerp(seconds: Float = 0F, serverThread: Boolean = false, action: (Float) -> Unit) = (if (serverThread) ServerTaskTracker else ClientTaskTracker).lerp(seconds, action = action)
@@ -15,8 +15,6 @@ import com.cobblemon.mod.common.api.spawning.context.SpawningContext
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.feature.SeasonFeatureHandler
import com.cobblemon.mod.common.util.weightedSelection
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.player.Player
/**
* A [SpawnAction] that will spawn a single [PokemonEntity].
@@ -46,8 +44,7 @@ class PokemonSpawnAction(
} else {
null
}?.createStack(ctx)
val sourcePlayer = ctx.cause.entity as? ServerPlayer
val entity = props.createEntity(ctx.world, sourcePlayer)
val entity = props.createEntity(ctx.world)
entity.spawnCause = ctx.cause
SeasonFeatureHandler.updateSeason(entity.pokemon, Cobblemon.seasonResolver(ctx.world, ctx.position))
if (heldItem != null) {
@@ -17,8 +17,6 @@ import com.cobblemon.mod.common.api.events.fishing.BobberSpawnPokemonEvent
import com.cobblemon.mod.common.api.fishing.FishingBait
import com.cobblemon.mod.common.api.pokemon.Natures
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.pokemon.egg.EggGroup
import com.cobblemon.mod.common.api.pokemon.stats.Stat
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.spawning.SpawnBucket
import com.cobblemon.mod.common.api.spawning.SpawnCause
@@ -26,7 +24,6 @@ import com.cobblemon.mod.common.api.spawning.context.SpawningContext
import com.cobblemon.mod.common.api.spawning.detail.PokemonSpawnDetail
import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.api.spawning.spawner.Spawner
import com.cobblemon.mod.common.api.types.ElementalTypes
import com.cobblemon.mod.common.api.types.tera.TeraTypes
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.item.interactive.PokerodItem
@@ -104,6 +101,13 @@ class FishingSpawnCause(
pokemonEntity.pokemon.level = level
}
fun alterTeraAttempt(pokemonEntity: PokemonEntity, effect: FishingBait.Effect) {
if (pokemonEntity.pokemon.teraType == effect.subcategory?.let { TeraTypes.get(it.path) } ||
TeraTypes.get(effect.subcategory!!.path) == null) return
pokemonEntity.pokemon.teraType = TeraTypes.get(effect.subcategory.path)!!
}
fun alterHAAttempt(pokemonEntity: PokemonEntity) {
//val species = pokemonEntity.pokemon.species.let { PokemonSpecies.getByName(it.name) } ?: return
//val ability = species.abilities.mapping[Priority.LOW]?.first()?.template?.name ?: return
@@ -118,7 +122,7 @@ class FishingSpawnCause(
.randomOrNull ()
?.let { ability ->
// No need to force, this is legal
pokemonEntity.pokemon.ability = ability.template.create(false, ability.priority)
pokemonEntity.pokemon.ability = ability.template.create(false)
return
}
}
@@ -175,49 +179,6 @@ class FishingSpawnCause(
}
}
}
// if bait exists and any effects are related to Typing
if (bait != null && bait.effects.any{ it.type == FishingBait.Effects.TYPING }){
if (detail is PokemonSpawnDetail) {
val detailSpecies = detail.pokemon.species?.let { PokemonSpecies.getByName(it) }
val baitEffect = bait.effects.firstOrNull { it.type == FishingBait.Effects.TYPING }
val baitTypingEffect = baitEffect?.subcategory?.path?.let { ElementalTypes.get(it) }
if (detailSpecies != null && baitTypingEffect != null) {
val isMatchingType = detailSpecies.types.contains(baitTypingEffect)
return when {
isMatchingType -> super.affectWeight(detail, ctx, weight * baitEffect.value.toFloat()) // multiply weight by multiplier of bait effect if typing is found
else -> super.affectWeight(detail, ctx, weight) // use base spawn weight if typing is not same as bait
}
}
}
}
// if bait exists and any effects are related to Egg Groups
if (bait != null && bait.effects.any { it.type == FishingBait.Effects.EGG_GROUP }) {
if (detail is PokemonSpawnDetail) {
val detailSpecies = detail.pokemon.species?.let { PokemonSpecies.getByName(it) }
if (detailSpecies != null) {
// Collect all the egg group effects
val eggGroupEffects = bait.effects.filter { it.type == FishingBait.Effects.EGG_GROUP }
// Check if any of the egg group effects match the species' egg groups
val matchingEffect = eggGroupEffects.firstOrNull { effect ->
val effectEggGroupKey = effect.subcategory?.path ?: return@firstOrNull false
val eggGroup = EggGroup.fromIdentifier(effectEggGroupKey)
if (eggGroup == null) {
LOGGER.warn("Unknown egg group identifier: $effectEggGroupKey")
return@firstOrNull false
}
detailSpecies.eggGroups.contains(eggGroup)
}
if (matchingEffect != null) {
val multiplier = matchingEffect.value
return super.affectWeight(detail, ctx, (weight * multiplier).toFloat())
}
}
}
}
return super.affectWeight(detail, ctx, weight)
}
@@ -166,9 +166,9 @@ open class PartyStore(override val uuid: UUID) : PokemonStore<PartyPosition>() {
}
override fun loadFromNBT(nbt: CompoundTag, registryAccess: RegistryAccess): PartyStore {
val slotCount = nbt.getInt(DataKeys.STORE_SLOT_COUNT).takeIf { it in 1..6 } ?: 6
while (slotCount < slots.size) { slots.removeLast() }
while (slotCount > slots.size) { slots.add(null) }
val slotCount = nbt.getInt(DataKeys.STORE_SLOT_COUNT)
while (slotCount > slots.size) { slots.removeLast() }
while (slotCount < slots.size) { slots.add(null) }
for (slot in slots.indices) {
val pokemonNBT = nbt.getCompound(DataKeys.STORE_SLOT + slot)
try {
@@ -8,6 +8,7 @@
package com.cobblemon.mod.common.api.storage.player
import com.cobblemon.mod.common.advancement.criterion.AspectCriterion
import com.cobblemon.mod.common.api.types.ElementalType
import com.cobblemon.mod.common.pokemon.Pokemon
import net.minecraft.server.level.ServerPlayer
@@ -17,8 +18,6 @@ class PlayerAdvancementData {
var totalCaptureCount: Int = 0
private set
var totalEggsCollected: Int = 0
private set
var totalEggsHatched: Int = 0
private set
var totalEvolvedCount: Int = 0
@@ -45,10 +44,6 @@ class PlayerAdvancementData {
totalCaptureCount++
}
fun updateTotalEggsCollected() {
totalEggsCollected++
}
fun updateTotalEggsHatched() {
totalEggsHatched++
}
@@ -107,8 +102,7 @@ class PlayerAdvancementData {
}
fun updateAspectsCollected(player: ServerPlayer, pokemon: Pokemon) {
//TODO: take another look at using the Advancement progress
/*val aspectConditions = player.advancements.progress.keys
val aspectConditions = player.advancements.progress.keys
.flatMap { it.value.criteria.values }
.mapNotNull { it.trigger }
.filterIsInstance<AspectCriterion>()
@@ -120,9 +114,6 @@ class PlayerAdvancementData {
if (trackedAspects.isNotEmpty()) {
val collectedAspects = aspectsCollected.getOrPut(pokemon.species.resourceIdentifier) { mutableSetOf() }
pokemon.aspects.filter(trackedAspects::contains).forEach(collectedAspects::add)
}*/
val collectedAspects = aspectsCollected.getOrPut(pokemon.species.resourceIdentifier) { mutableSetOf() }
pokemon.aspects.forEach(collectedAspects::add)
}
}
}
}
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.api.storage.player.adapter
import com.cobblemon.mod.common.api.pokedex.PokedexManager
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreType
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreTypes
import com.cobblemon.mod.common.util.adapters.CodecBackedAdapter
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
@@ -28,7 +27,7 @@ class DexDataJsonBackend: JsonBackedPlayerDataStoreBackend<PokedexManager>("poke
override val gson = GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.registerTypeAdapter(PokedexManager::class.java, CodecBackedAdapter(PokedexManager.CODEC))
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.create()
override val classToken = TypeToken.get(PokedexManager::class.java)
override val defaultData = defaultDataFunc
@@ -1,44 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.storage.player.adapter
import com.cobblemon.mod.common.api.pokedex.PokedexManager
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreTypes
import com.cobblemon.mod.common.util.adapters.CodecBackedAdapter
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.mongodb.client.MongoClient
import java.util.UUID
/**
* A [PlayerDataStoreBackend] for [PokedexManager]
*
* @author Pebbles
* @since October 26, 2024
*/
class DexDataMongoBackend(mongoClient: MongoClient, databaseName: String, collectionName: String) :
MongoBackedPlayerDataStoreBackend<PokedexManager>(mongoClient, databaseName, collectionName, PlayerInstancedDataStoreTypes.POKEDEX) {
override val gson = GsonBuilder()
.registerTypeAdapter(PokedexManager::class.java, CodecBackedAdapter(PokedexManager.CODEC))
.create()
override val classToken = TypeToken.get(PokedexManager::class.java)
override val defaultData = defaultDataFunc
override fun initialize(store: PokedexManager) {
store.initialize()
}
companion object {
val defaultDataFunc = { uuid: UUID ->
PokedexManager(uuid, mutableMapOf())
}
}
}
@@ -1,59 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.storage.player.adapter
import com.cobblemon.mod.common.api.storage.player.InstancedPlayerData
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreType
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mongodb.client.MongoClient
import com.mongodb.client.model.ReplaceOptions
import org.bson.Document
import java.io.BufferedReader
import java.io.FileReader
import java.io.PrintWriter
import java.util.UUID
import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.memberProperties
abstract class MongoBackedPlayerDataStoreBackend<T : InstancedPlayerData>(
mongoClient: MongoClient, databaseName: String, collectionName: String, type: PlayerInstancedDataStoreType
) : MongoBasedPlayerDataStoreBackend<T>(mongoClient, type, databaseName, collectionName) {
abstract val gson: Gson
//The class GSON needs to deserialize to
abstract val classToken: TypeToken<T>
override fun save(playerData: T) {
collection.replaceOne(
Document("uuid", playerData.uuid.toString()),
Document.parse(gson.toJson(playerData)),
ReplaceOptions().upsert(true)
)
}
override fun load(uuid: UUID): T {
val filter = Document("uuid", uuid.toString())
val document = collection.find(filter).first()
return if (document != null) {
val jsonStr = document.toJson()
gson.fromJson(jsonStr, classToken).also {
val newProps = it::class.memberProperties.filterIsInstance<KMutableProperty<*>>()
.filter { member -> member.getter.call(it) == null }
if (newProps.isNotEmpty()) {
val defaultData = defaultData(uuid)
newProps.forEach { member -> member.setter.call(it, member.getter.call(defaultData)) }
}
}
} else {
defaultData(uuid).also(::save)
}
}
}
@@ -1,36 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.storage.player.adapter
import com.cobblemon.mod.common.api.storage.player.InstancedPlayerData
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreType
import com.mongodb.client.MongoClient
import net.minecraft.server.MinecraftServer
import java.util.UUID
/**
* A [PlayerDataStoreBackend] that stores the [InstancedPlayerData] in a file.
*
* @author Pebbles
* @since October 27, 2024
*/
abstract class MongoBasedPlayerDataStoreBackend<T : InstancedPlayerData>(
val mongoClient: MongoClient, val type: PlayerInstancedDataStoreType, databaseName: String, collectionName: String
) : PlayerDataStoreBackend<T>(type) {
abstract val defaultData: (UUID) -> (T)
val collection by lazy {
mongoClient.getDatabase(databaseName).getCollection(collectionName)
}
override fun setup(server: MinecraftServer) {
// Ping the database to ensure it's connected
mongoClient.listDatabaseNames().first()
}
}
@@ -0,0 +1,67 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/*
package com.cobblemon.mod.common.api.storage.player.adapter
import com.cobblemon.mod.common.api.storage.player.PlayerData
import com.cobblemon.mod.common.api.storage.player.PlayerDataExtension
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.google.gson.GsonBuilder
import com.mongodb.client.MongoClient
import com.mongodb.client.model.ReplaceOptions
import net.minecraft.resources.ResourceLocation
import org.bson.Document
import java.util.UUID
import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.memberProperties
class MongoPlayerDataAdapter(
mongoClient: MongoClient,
databaseName: String
) : PlayerDataStoreAdapter {
companion object {
val gson = GsonBuilder()
.disableHtmlEscaping()
.registerTypeAdapter(PlayerDataExtension::class.java, PlayerDataExtensionAdapter)
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.create()
}
private val collection = mongoClient.getDatabase(databaseName).getCollection("PlayerDataCollection")
override fun load(uuid: UUID): PlayerData {
val filter = Document("uuid", uuid.toString())
val document = collection.find(filter).first()
return if (document != null) {
val jsonStr = document.toJson()
gson.fromJson(jsonStr, PlayerData::class.java).also {
val newProps = it::class.memberProperties.filterIsInstance<KMutableProperty<*>>().filter { member -> member.getter.call(it) == null }
if (newProps.isNotEmpty()) {
val defaultData = PlayerData.defaultData(uuid)
newProps.forEach { member -> member.setter.call(it, member.getter.call(defaultData)) }
}
}
} else {
PlayerData.defaultData(uuid).also(::save)
}
}
override fun save(playerData: PlayerData) {
val jsonStr = gson.toJson(playerData)
val document = Document.parse(jsonStr)
document.put("uuid", playerData.uuid.toString())
val filter = Document("uuid", playerData.uuid.toString())
collection.replaceOne(filter, document, ReplaceOptions().upsert(true))
}
}
*/
@@ -1,49 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.storage.player.adapter
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.storage.player.GeneralPlayerData
import com.cobblemon.mod.common.api.storage.player.PlayerDataExtension
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreTypes
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.mongodb.client.MongoClient
import net.minecraft.resources.ResourceLocation
import java.util.UUID
/**
* A [PlayerDataStoreBackend] for [GeneralPlayerData]
*
* @author Apion
* @since February 21, 2024
*/
class PlayerDataMongoBackend(mongoClient: MongoClient, databaseName: String, collectionName: String): MongoBackedPlayerDataStoreBackend<GeneralPlayerData>(
mongoClient, databaseName, collectionName, PlayerInstancedDataStoreTypes.GENERAL
){
override val defaultData = { forPlayer: UUID -> GeneralPlayerData(
uuid = forPlayer,
starterPrompted = false,
starterLocked = !Cobblemon.starterConfig.allowStarterOnJoin,
starterSelected = false,
starterUUID = null,
keyItems = mutableSetOf(),
extraData = mutableMapOf(),
battleTheme = CobblemonSounds.PVP_BATTLE.location
)}
override val gson = GsonBuilder()
.registerTypeAdapter(PlayerDataExtension::class.java, PlayerDataExtensionAdapter)
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.create()
override val classToken = TypeToken.get(GeneralPlayerData::class.java)
}
@@ -134,12 +134,12 @@ class Toast(
}
/**
* Invokes [expire] after the specified [seconds].
* Invokes [expire] after the specified [ticks].
*
* @param seconds The number of seconds before the lifecycle of this toast ends.
* @param ticks The number of ticks before the lifecycle of this toast ends.
*/
fun expireAfter(seconds: Float) {
afterOnServer(seconds = seconds) {
fun expireAfter(ticks: Int) {
afterOnServer(ticks = ticks) {
this.expire()
}
}
@@ -125,44 +125,42 @@ object BattleBuilder {
@JvmOverloads
fun pvp2v2(
players: List<ServerPlayer> = emptyList(),
leadingPokemon: List<UUID> = emptyList(),
battleFormat: BattleFormat = BattleFormat.GEN_9_MULTI,
cloneParties: Boolean = false,
healFirst: Boolean = false,
partyAccessor: (ServerPlayer) -> PartyStore = { it.party() }
players: List<ServerPlayer> = emptyList(),
leadingPokemon: List<UUID> = emptyList(),
battleFormat: BattleFormat = BattleFormat.GEN_9_MULTI,
cloneParties: Boolean = false,
healFirst: Boolean = false,
partyAccessor: (ServerPlayer) -> PartyStore = { it.party() }
): BattleStartResult {
val adjustLevel = battleFormat.adjustLevel
val teams = players.mapIndexed { index, it ->
partyAccessor(it).toBattleTeam(
clone = cloneParties || adjustLevel > 0,
clone = cloneParties,
healPokemon = healFirst,
leadingPokemon[index]
).sortedBy { it.health <= 0 }
}
val playerActors = teams.mapIndexed { index, team -> PlayerBattleActor(players[index].uuid, team)}.toMutableList()
val adjustLevel = battleFormat.adjustLevel
val battlePartyStores = mutableListOf<PlayerPartyStore>()
if (adjustLevel > 0) {
teams.forEachIndexed { playerIndex, battleTeam ->
val tempStore = PlayerPartyStore(players[playerIndex].uuid)
battleTeam.forEachIndexed { pokemonIndex, battlePokemon ->
teams.forEachIndexed { index, battleTeam ->
battleTeam.forEach { battlePokemon ->
battlePokemon.effectedPokemon.level = adjustLevel
battlePokemon.effectedPokemon.heal()
tempStore.set(pokemonIndex, battlePokemon.effectedPokemon)
val tempStore = PlayerPartyStore(players[index].uuid)
battlePartyStores.add(tempStore)
}
battlePartyStores.add(tempStore)
}
}
val errors = ErroredBattleStart()
if (players.size != TeamManager.MAX_TEAM_MEMBER_COUNT * 2) {
if (players.size != BattleRegistry.MAX_TEAM_MEMBER_COUNT * 2) {
playerActors.forEach {actor ->
errors.participantErrors[actor] += BattleStartError.incorrectActorCount(
requiredCount = TeamManager.MAX_TEAM_MEMBER_COUNT * 2,
requiredCount = BattleRegistry.MAX_TEAM_MEMBER_COUNT * 2,
hadCount = players.size
)
}
@@ -314,7 +312,7 @@ object BattleBuilder {
): BattleStartResult {
val playerTeam = party.toBattleTeam(clone = cloneParties, healPokemon = healFirst, leadingPokemon = leadingPokemon)
val playerActor = PlayerBattleActor(player.uuid, playerTeam)
val npcParty = npcEntity.getPartyForChallenge(player)
val npcParty = npcEntity.party?.getParty(player, npcEntity)
val errors = ErroredBattleStart()
if (playerActor.pokemonList.size < battleFormat.battleType.slotsPerActor) {
@@ -334,12 +332,12 @@ object BattleBuilder {
return errors
}
val npcActor = NPCBattleActor(npcEntity, npcParty, npcEntity.skill ?: npcEntity.npc.skill)
val npcActor = NPCBattleActor(npcEntity, npcParty, npcEntity.skill ?: 0)
// if (npcEntity.battleIds.get().isPresent) {
// errors.participantErrors[npcActor] += BattleStartError.alreadyInBattle(npcActor)
// }
if (npcActor.pokemonList.filter { it.health > 0 }.size < battleFormat.battleType.slotsPerActor) {
if (npcActor.pokemonList.size < battleFormat.battleType.slotsPerActor) {
errors.participantErrors[npcActor] += BattleStartError.insufficientPokemon(
actorEntity = npcEntity,
requiredCount = battleFormat.battleType.slotsPerActor,
@@ -497,10 +495,6 @@ open class ErroredBattleStart(
return this
}
fun sendTo(entities: Collection<Entity>, transformer: (MutableComponent) -> (MutableComponent) = { it }) {
entities.forEach { this.sendTo(it, transformer) }
}
fun sendTo(entity: Entity, transformer: (MutableComponent) -> (MutableComponent) = { it }) {
errors.forEach { entity.sendSystemMessage(transformer(it.getMessageFor(entity))) }
}
@@ -8,6 +8,8 @@
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.CobblemonNetwork
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.battles.BattleStartedPostEvent
@@ -17,26 +19,142 @@ import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.cobblemon.mod.common.net.messages.client.battle.BattleChallengeExpiredPacket
import com.cobblemon.mod.common.net.messages.client.battle.TeamMemberRemoveNotificationPacket
import com.cobblemon.mod.common.net.messages.client.battle.TeamRequestExpiredPacket
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.util.server
import com.cobblemon.mod.common.util.lang
import com.google.gson.GsonBuilder
import java.time.Instant
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import net.minecraft.server.level.ServerPlayer
object BattleRegistry {
const val MAX_TEAM_MEMBER_COUNT = 2
const val MAX_BATTLE_RADIUS = 15.0
class BattleChallenge(
val challengeId: UUID,
val challengedPlayerUUID: UUID,
val selectedPokemonId: UUID,
val battleFormat: BattleFormat,
var expiryTimeSeconds: Int = 60
) {
val challengedTime = Instant.now()
fun isExpired() = Instant.now().isAfter(challengedTime.plusSeconds(expiryTimeSeconds.toLong()))
}
class TeamRequest(
val requestID: UUID,
val requestedPlayerUUID: UUID,
var expiryTimeSeconds: Int = 60
) {
val challengedTime = Instant.now()
fun isExpired() = Instant.now().isAfter(challengedTime.plusSeconds(expiryTimeSeconds.toLong()))
}
class MultiBattleTeam(
val teamID: UUID,
val teamPlayersUUID: MutableList<UUID>,
)
val gson = GsonBuilder()
.disableHtmlEscaping()
.registerTypeAdapter(ShowdownMoveset::class.java, ShowdownMovesetAdapter)
.create()
private val battleMap = ConcurrentHashMap<UUID, PokemonBattle>()
// Challenger to challenge
val pvpChallenges = mutableMapOf<UUID, BattleChallenge>()
// Multi-battle teams
val playerToTeam = mutableMapOf<UUID, MultiBattleTeam>()
val multiBattleTeams = mutableMapOf<UUID, MultiBattleTeam>()
val multiBattleTeamRequests = mutableMapOf<UUID, TeamRequest>()
fun onServerStarted() {
battleMap.clear()
pvpChallenges.clear()
playerToTeam.clear()
}
fun removeChallenge(challengerId: UUID, challengeId: UUID? = null, isMultiBattleTeam: Boolean = false) {
val existing = pvpChallenges[challengerId] ?: return
if (existing.challengeId != challengeId) {
return
}
pvpChallenges.remove(challengerId)
if (isMultiBattleTeam) {
multiBattleTeams[existing.challengedPlayerUUID]?.teamPlayersUUID?.let {
CobblemonNetwork.sendPacketToPlayers(it.mapNotNull { serverPlayer -> serverPlayer.getPlayer() }, BattleChallengeExpiredPacket(existing.challengeId))
}
} else {
existing.challengedPlayerUUID.getPlayer()?.sendPacket(BattleChallengeExpiredPacket(existing.challengeId))
}
}
fun removeTeamUpRequest(requesterId: UUID, requestId: UUID? = null) {
val existing = multiBattleTeamRequests[requesterId] ?: return
if (existing.requestID != requestId) {
return
}
multiBattleTeamRequests.remove(requesterId)
existing.requestedPlayerUUID.getPlayer()?.sendPacket(TeamRequestExpiredPacket(existing.requestID))
}
fun onPlayerDisconnect(player: ServerPlayer) {
// Stop battles
getBattleByParticipatingPlayer(player)?.stop()
// Remove player from any teams they may be a part of
removeTeamMember(player)
}
fun removeTeamMember(player: ServerPlayer) {
val teamEntry = playerToTeam[player.uuid]
if (teamEntry != null) {
teamEntry.teamPlayersUUID.remove(player.uuid)
playerToTeam.remove(player.uuid)
val notificationPacket = TeamMemberRemoveNotificationPacket(player.uuid)
CobblemonNetwork.sendPacketToPlayer(player, notificationPacket)
// Notify remaining members that the player has left the group
server()?.let {
val teamServerPlayers = teamEntry.teamPlayersUUID.mapNotNull { uuid -> it.playerList.getPlayer(uuid) }
CobblemonNetwork.sendPacketToPlayers(teamServerPlayers, notificationPacket)
}
if (teamEntry.teamPlayersUUID.count() == 1) {
val remainingPlayerUUID = teamEntry.teamPlayersUUID.first()
// Remove any outstanding battle requests for the team
// TODO: Find a way to not do a reverse map look up
val battleChallengeEntry = pvpChallenges.entries.firstOrNull { it -> it.value.challengedPlayerUUID == teamEntry.teamID }
if (battleChallengeEntry != null) {
val battleChallenge = battleChallengeEntry.value
removeChallenge(battleChallengeEntry.key, battleChallenge.challengeId, true)
// Notify opposing team that the challenge was cancelled
val opposingTeam = multiBattleTeams[battleChallengeEntry.key]
opposingTeam?.teamPlayersUUID?.map { it.getPlayer() }?.forEach { serverPlayerEntity ->
serverPlayerEntity?.sendSystemMessage(lang("challenge.multi.decline.disband"))
}
}
// Disband the team
playerToTeam.remove(remainingPlayerUUID)
multiBattleTeams.remove(teamEntry.teamID)
// Notify remaining player that the team has been disbanded
server()?.let {
it.playerList.getPlayer(remainingPlayerUUID)?.let { serverPlayerEntity ->
CobblemonNetwork.sendPacketToPlayer(serverPlayerEntity, TeamMemberRemoveNotificationPacket(remainingPlayerUUID))
}
}
}
}
}
/**
@@ -40,7 +40,7 @@ class BattleSide(vararg val actors: BattleActor) {
activePokemon.forEach {
val entity = it.battlePokemon?.entity ?: return@forEach
entity.cry()
if(entity.pokemon.shiny && entity.pokemon.isWild()) {
if(entity.pokemon.shiny) {
SpawnSnowstormEntityParticlePacket(cobblemonResource("shiny_ring"), entity.id, listOf("shiny_particles", "middle"))
.sendToPlayersAround(entity.x, entity.y, entity.z, 64.0, entity.level().dimension())
}
@@ -1,194 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.interaction.RequestManager
import com.cobblemon.mod.common.api.interaction.ServerPlayerActionRequest
import com.cobblemon.mod.common.api.interaction.ServerTeamActionRequest
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.text.aqua
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.battles.TeamManager.MAX_TEAM_MEMBER_COUNT
import com.cobblemon.mod.common.battles.TeamManager.MultiBattleTeam
import com.cobblemon.mod.common.net.messages.client.battle.BattleChallengeExpiredPacket
import com.cobblemon.mod.common.net.messages.client.battle.BattleChallengeNotificationPacket
import com.cobblemon.mod.common.util.canInteractWith
import com.cobblemon.mod.common.util.getBattleTeam
import com.cobblemon.mod.common.util.party
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.phys.Vec3
import java.util.*
/**
* Responsible for managing [BattleChallenge]s and initiating PVP [PokemonBattle]s.
*
* @author Segfault Guy, JazzMcNade
* @since October 28th, 2024
*/
object ChallengeManager : RequestManager<ChallengeManager.BattleChallenge>() {
init {
register(this)
}
const val MAX_BATTLE_RADIUS = 15.0
/** Mapping of players to their lead Pokemon. */
private val selectedLead = mutableMapOf<UUID, UUID>()
/**
* Represents an interaction request between players or teams to start a battle.
*
* @param sender The player sending this request.
* @param receiver The player receiving this request.
* @param selectedPokemonId
* @param battleFormat
* @param expiryTime How long (in seconds) this request is active.
*/
abstract class BattleChallenge : ServerPlayerActionRequest {
abstract val selectedPokemonId: UUID
abstract val battleFormat: BattleFormat
override val requestID: UUID = UUID.randomUUID()
}
/** PLAYER-to-PLAYER BattleChallenge */
data class SinglesBattleChallenge(
override val sender: ServerPlayer,
override val receiver: ServerPlayer,
override val selectedPokemonId: UUID,
override val battleFormat: BattleFormat,
override val expiryTime: Int = 20
) : BattleChallenge() {
override val key: String = "challenge"
}
/** TEAM-to-TEAM BattleChallenge */
data class MultiBattleChallenge(
override val sender: ServerPlayer,
override val receiver: ServerPlayer,
override val selectedPokemonId: UUID,
override val battleFormat: BattleFormat, // TODO force this to be multi battletype
override val expiryTime: Int = 20
) : BattleChallenge(), ServerTeamActionRequest {
override val key: String = "challenge.multi"
override val senderTeam: MultiBattleTeam = sender.getBattleTeam() ?: throw IllegalArgumentException("Sending player is not part of a team!")
override val receiverTeam: MultiBattleTeam = receiver.getBattleTeam() ?: throw IllegalArgumentException("Target player is not part of a team!")
}
override fun expirationPacket(request: BattleChallenge): NetworkPacket<*> = BattleChallengeExpiredPacket(request)
override fun notificationPacket(request: BattleChallenge): NetworkPacket<*> = BattleChallengeNotificationPacket(request)
override fun onDecline(request: BattleChallenge) {
request.notifySender(true, "decline.sender", request.receiver.name.copy().aqua(), request.battleFormat.battleType.displayName)
request.notifyReceiver(false, "decline.receiver", request.sender.name.copy().aqua(), request.battleFormat.battleType.displayName)
}
override fun onSend(request: BattleChallenge) {
request.notifySender(false, "sent", request.receiver.name.copy().aqua(), request.battleFormat.battleType.displayName)
request.notifyReceiver(false, "received", request.sender.name.copy().aqua(), request.battleFormat.battleType.displayName)
}
override fun onAccept(request: BattleChallenge) {
if (request is MultiBattleChallenge) {
val players = request.receiverTeam.teamPlayers + request.senderTeam.teamPlayers
val leadPokemon = players.mapNotNull { it.party().first().uuid }
BattleBuilder.pvp2v2(
players,
leadPokemon,
request.battleFormat
).ifErrored {
erredStart -> erredStart.sendTo(players) { it.red() }
}
}
else {
BattleBuilder.pvp1v1(
request.receiver,
request.sender,
selectedLead.get(request.receiver.uuid),
selectedLead.get(request.sender.uuid),
request.battleFormat
).ifErrored {
it.sendTo(request.receiver) { it.red() }
it.sendTo(request.sender) { it.red() }
}
}
}
override fun isValidInteraction(player: ServerPlayer, target: ServerPlayer) = player.canInteractWith(target, Cobblemon.config.BattlePvPMaxDistance)
override fun canAccept(request: BattleChallenge): Boolean {
if (request is MultiBattleChallenge) {
val existingReceiverTeam = TeamManager.getTeam(request.receiverID)
val existingSenderTeam = TeamManager.getTeam(request.senderID)
// validate teams
if (existingReceiverTeam == null || existingSenderTeam == null) {
request.notifySender(true, "error.missing_team")
request.notifyReceiver(true, "error.missing_team")
return false;
}
val players = existingReceiverTeam.teamPlayers + existingSenderTeam.teamPlayers
val leads = players.mapNotNull { it.party().first().uuid }
val farAwayPlayer = this.validateProximity(players)
// validate team sizes
if (players.count() != MAX_TEAM_MEMBER_COUNT * 2) {
request.notifySender(true, "error.invalid_team_size", MAX_TEAM_MEMBER_COUNT)
request.notifyReceiver(true, "error.invalid_team_size", MAX_TEAM_MEMBER_COUNT)
}
// validate parties
else if (leads.count() != players.count()) {
request.notifySender(true, "error.insufficient_pokemon")
request.notifyReceiver(true, "error.insufficient_pokemon")
}
// validate dimension
else if (this.validateDimension(players)) {
request.notifySender(true, "error.player_different_dimension")
request.notifyReceiver(true, "error.player_different_dimension")
}
// validate proximity
else if (farAwayPlayer != null) {
request.notifySender(true, "error.player_distance", farAwayPlayer.name.copy().aqua())
request.notifyReceiver(true, "error.player_distance", farAwayPlayer.name.copy().aqua())
}
else return true
}
else {
// validate parties
if (request.receiver.party().none()) {
request.notifySender(true, "error.insufficient_pokemon.other", request.receiver.name.copy().aqua())
request.notifyReceiver(true, "error.insufficient_pokemon.self")
}
else if (request.sender.party().none()) {
request.notifySender(true, "error.insufficient_pokemon.self")
request.notifyReceiver(true, "error.insufficient_pokemon.other", request.sender.name.copy().aqua())
}
// TODO worth validating size and party health here? BattleBuilder already does it
else return true
}
return false
}
private fun validateDimension(players: Collection<ServerPlayer>): Boolean {
val dimension = players.first().level().dimension()
val playerInWrongDimension = players.firstOrNull { it.level().dimension() != dimension }
return playerInWrongDimension != null
}
private fun validateProximity(players: Collection<ServerPlayer>): ServerPlayer? {
// Check if all players are nearby
var averagePos = Vec3(0.0, 0.0, 0.0)
players.forEach { averagePos = averagePos.add(it.position().multiply(1.0 / players.count(), 0.0, 1.0 / players.count())) }
val farAwayPlayer = players.firstOrNull { it.position().subtract(0.0, it.position().y, 0.0).distanceToSqr(averagePos) > MAX_BATTLE_RADIUS * MAX_BATTLE_RADIUS }
return farAwayPlayer
}
fun setLead(player: ServerPlayer, lead: UUID) = this.selectedLead.put(player.uuid, lead)
}
@@ -35,12 +35,6 @@ interface Targetable {
}
}
fun getOppositeOpponent() : Targetable {
val digit = getDigit()
val sideSize = getFormat().battleType.pokemonPerSide
return getAllActivePokemon().first { pokemon -> !pokemon.isAllied(this) && (sideSize - pokemon.getDigit() + 1) - digit == 0 }
}
fun getAdjacentAllies() = getAdjacent().filter { it.isAllied(this) }
fun getAdjacentOpponents() = getAdjacent().filterNot { it.isAllied(this) }
@@ -403,7 +403,6 @@ class ShowdownPokemon {
lateinit var ability: String
var baseTypes = mutableListOf<String>()
var types = mutableListOf<String>()
var commanding: Boolean = false
var reviving: Boolean = false
val uuid: UUID by lazy { UUID.fromString(details.split(",")[1].trim()) }
@@ -413,7 +412,6 @@ class ShowdownPokemon {
buffer.writeString(condition)
buffer.writeBoolean(active)
buffer.writeBoolean(reviving)
buffer.writeBoolean(commanding)
buffer.writeSizedInt(IntSize.U_BYTE, moves.size)
moves.forEach(buffer::writeString)
buffer.writeString(baseAbility)
@@ -431,7 +429,6 @@ class ShowdownPokemon {
condition = buffer.readString()
active = buffer.readBoolean()
reviving = buffer.readBoolean()
commanding = buffer.readBoolean()
repeat(times = buffer.readSizedInt(IntSize.U_BYTE)) {
moves.add(buffer.readString())
}
@@ -9,11 +9,14 @@
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.api.battles.interpreter.*
import com.cobblemon.mod.common.api.battles.interpreter.BasicContext
import com.cobblemon.mod.common.api.battles.interpreter.BattleContext
import com.cobblemon.mod.common.api.battles.interpreter.BattleMessage
import com.cobblemon.mod.common.api.battles.interpreter.Effect
import com.cobblemon.mod.common.api.battles.interpreter.MissingContext
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.api.battles.model.actor.EntityBackedBattleActor
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.api.text.yellow
import com.cobblemon.mod.common.battles.dispatch.InstructionSet
import com.cobblemon.mod.common.battles.dispatch.InterpreterInstruction
@@ -60,12 +63,12 @@ object ShowdownInterpreter {
updateInstructionParser["-ability"] = { _, instructionSet, message, _ -> AbilityInstruction(instructionSet, message) }
updateInstructionParser["-activate"] = { _, instructionSet, message, _ -> ActivateInstruction(instructionSet, message) }
updateInstructionParser["bagitem"] = { _, _, message, _ -> BagItemInstruction(message) }
updateInstructionParser["-boost"] = { battle, _, message, _ -> BoostInstruction(battle, message, true) }
updateInstructionParser["-boost"] = { _, instructionSet, message, remainingLines -> BoostInstruction(instructionSet, message, remainingLines, true) }
updateInstructionParser["-block"] = { _, _, message, _ -> BlockInstruction(message) }
updateInstructionParser["cant"] = { _, _, message, _ -> CantInstruction(message) }
updateInstructionParser["-clearallboost"] = { _, _, message, _ -> ClearAllBoostInstruction(message) }
updateInstructionParser["-clearnegativeboost"] = { _, _, message, _ -> ClearNegativeBoostInstruction(message) }
updateInstructionParser["-clearboost"] = { _, _, message, _ -> ClearBoostInstruction(message) }
updateInstructionParser["-clearboost"] = { _, _, message, _ -> ClearBoostInstruction(message) }
updateInstructionParser["-copyboost"] = { _, _, message, _ -> CopyBoostInstruction(message) }
updateInstructionParser["-crit"] = { _, instructionSet, message, _ -> CritInstruction(message, instructionSet) }
updateInstructionParser["-curestatus"] = { _, _, message, _ -> CureStatusInstruction(message) }
@@ -105,7 +108,7 @@ object ShowdownInterpreter {
updateInstructionParser["-terastallize"] = { _, _, message, _ -> TerastallizeInstruction(message) }
updateInstructionParser["-transform"] = { battle, _, message, _ -> TransformInstruction(battle, message) }
updateInstructionParser["turn"] = { _, _, message, _ -> TurnInstruction(message) }
updateInstructionParser["-unboost"] = { battle, _, message, _ -> BoostInstruction(battle, message, false) }
updateInstructionParser["-unboost"] = { _, instructionSet, message, remainingLines -> BoostInstruction(instructionSet, message, remainingLines, false) }
updateInstructionParser["upkeep"] = { _, _, _, _ -> UpkeepInstruction() }
updateInstructionParser["-weather"] = { _, _, message, _ -> WeatherInstruction(message) }
updateInstructionParser["win"] = { _, _, message, _ -> WinInstruction(message) }
@@ -145,74 +148,59 @@ object ShowdownInterpreter {
*/
fun getSendoutPosition(battle: PokemonBattle, activePokemon: ActiveBattlePokemon, battleActor: BattleActor): Vec3? {
val pnx = activePokemon.getPNX()
val actorEntityPosList = battleActor.getSide().actors.mapNotNull { if (it is EntityBackedBattleActor<*>) it.initialPos else null }
val actorEntityPos = if (actorEntityPosList.size == 1)
actorEntityPosList[0]
else if (actorEntityPosList.size > 1)
actorEntityPosList.fold(Vec3(0.0, 0.0, 0.0)) { acc, vec3 -> acc.add(vec3.scale(1.0 / actorEntityPosList.size)) }
val entityPosList = battleActor.getSide().actors.mapNotNull { if (it is EntityBackedBattleActor<*>) it.initialPos else null }
var entityPos = if (entityPosList.size == 1)
entityPosList[0]
else if (entityPosList.size > 1)
entityPosList.fold(Vec3(0.0, 0.0, 0.0)) { acc, vec3 -> acc.add(vec3.scale(1.0 / entityPosList.size)) }
else
null
val opposingActorEntityList = battleActor.getSide().getOppositeSide().actors.mapNotNull { if (it is EntityBackedBattleActor<*>) it.initialPos else null }
val opposingEntityPos = if (opposingActorEntityList.size == 1)
opposingActorEntityList[0]
else if (opposingActorEntityList.size > 1) {
// If multiple actors per side, avg their position
opposingActorEntityList.fold(Vec3(0.0, 0.0, 0.0)) { acc, vec3 -> acc.add(vec3.scale(1.0 / opposingActorEntityList.size)) }
}
val opposingEntityList = battleActor.getSide().getOppositeSide().actors.mapNotNull { if (it is EntityBackedBattleActor<*>) it.initialPos else null }
val opposingEntityPos = if (opposingEntityList.size == 1)
opposingEntityList[0]
else if (opposingEntityList.size > 1)
opposingEntityList.fold(Vec3(0.0, 0.0, 0.0)) { acc, vec3 -> acc.add(vec3.scale(1.0 / opposingEntityList.size)) }
else null
var actorOffset = actorEntityPos?.let { opposingEntityPos?.subtract(it) }
var result = actorEntityPos
if (actorOffset != null) {
var widthSum = 4.0 // Leave a constant to allow double/triples alignment to be consistent
if (battle.format.battleType.pokemonPerSide == 1) {
activePokemon.battlePokemon?.let { battlePokemon ->
// sum of the hitbox widths of both pokemon
val opposingActivePokemon = (activePokemon.getOppositeOpponent() as ActiveBattlePokemon)
val pokemonWidth = battlePokemon.originalPokemon.form.hitbox.width * battlePokemon.originalPokemon.form.baseScale
val opposingPokemonWidth = opposingActivePokemon.battlePokemon?.let {
it.originalPokemon.form.hitbox.width * it.originalPokemon.form.baseScale
} ?: pokemonWidth
widthSum = (pokemonWidth + opposingPokemonWidth) / 2.0 // Only care about the front half of each hitbox
}
}
var baseOffset = entityPos?.let { opposingEntityPos?.subtract(it) }
val minDistance = 4.0 + widthSum
val actorDistance = actorOffset.length()
if (actorDistance < minDistance) {
val temp = actorOffset.scale(minDistance / actorDistance) ?: actorOffset
result = actorEntityPos?.subtract(temp.subtract(actorOffset))
actorOffset = temp
if (baseOffset != null) {
val minDistance = if (battle.isPvW) 8.0 else 5.0
val length = baseOffset.length()
if (length < minDistance) {
val temp = baseOffset.scale(minDistance / length) ?: baseOffset
entityPos = entityPos?.subtract(temp.subtract(baseOffset))
baseOffset = temp
}
var vector = Vec3(actorOffset.x, 0.0, actorOffset.z).normalize()
var vector = Vec3(baseOffset.x, 0.0, baseOffset.z).normalize()
vector = vector.cross(Vec3(0.0, 1.0, 0.0))
if (battle.format.battleType.pokemonPerSide == 1) { // Singles
result = result?.add(actorOffset.scale(if (battle.isPvW) 0.4 else 0.3))
entityPos = entityPos?.add(baseOffset.scale(if (battle.isPvW) 0.4 else 0.3))
activePokemon.battlePokemon?.let { battlePokemon ->
val hitbox = battlePokemon.originalPokemon.form.hitbox
val scale = battlePokemon.originalPokemon.form.baseScale
activePokemon.getAdjacentOpponents()
result = result?.add(vector.scale(-0.3 - hitbox.width * scale ))
if (hitbox.height * scale > 1.1) {
entityPos = entityPos?.add(vector.scale(-1.5 - hitbox.width * scale / 2))
}
}
} else if (battle.format.battleType.pokemonPerSide == 2) { // Doubles/Multi
} else if (battle.format.battleType.pokemonPerSide == 2) { // Doubles
if (battle.actors.first() !== battle.actors.last()) {
val offsetB = if (pnx[2] == 'a') vector.scale(-1.0) else vector
result = result?.add(actorOffset.scale(0.33))?.add(offsetB.scale(2.5))
entityPos = entityPos?.add(baseOffset.scale(0.33))?.add(offsetB.scale(2.5))
}
} else if (battle.format.battleType.pokemonPerSide == 3) { // Triples
if (battle.actors.first() !== battle.actors.last()) {
result = when (pnx[2]) {
'a' -> result?.add(actorOffset.scale(0.15))?.add(vector.scale(-3.5))
'b' -> result?.add(actorOffset.scale(0.3))
'c' -> result?.add(actorOffset.scale(0.15))?.add(vector.scale(3.5))
else -> result
entityPos = when (pnx[2]) {
'a' -> entityPos?.add(baseOffset.scale(0.15))?.add(vector.scale(-3.5))
'b' -> entityPos?.add(baseOffset.scale(0.3))
'c' -> entityPos?.add(baseOffset.scale(0.15))?.add(vector.scale(3.5))
else -> entityPos
}
}
}
}
return result
return entityPos
}
@@ -276,16 +264,8 @@ object ShowdownInterpreter {
}
instructionSet.execute(battle)
}
catch (e: InvalidInstructionException) {
e.message?.let {
battle.broadcastChatMessage(it.red())
LOGGER.error(it)
}
}
catch (e: Exception) {
battle.broadcastChatMessage("A fatal error occurred. Please report to developers.".red())
LOGGER.error("Caught exception interpreting battle instructions.", e)
LOGGER.error("Caught exception interpreting {}", e)
}
}
@@ -1,201 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork
import com.cobblemon.mod.common.api.interaction.RequestManager
import com.cobblemon.mod.common.api.interaction.ServerPlayerActionRequest
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.text.aqua
import com.cobblemon.mod.common.net.messages.client.battle.*
import com.cobblemon.mod.common.util.*
import net.minecraft.server.level.ServerPlayer
import java.util.*
/**
* Responsible for managing active [MultiBattleTeam]s and the respective [TeamRequest]s that form them.
*
* @author Segfault Guy, JazzMcNade
* @since October 26th, 2024
*/
object TeamManager : RequestManager<TeamManager.TeamRequest>() {
init {
register(this)
}
const val MAX_TEAM_MEMBER_COUNT = 2
/**
* Represents an interaction request between players to form a team.
*
* @param sender The player sending this request.
* @param receiver The player receiving this request.
* @param expiryTime How long (in seconds) this request is active.
*/
data class TeamRequest(
override val sender: ServerPlayer,
override val receiver: ServerPlayer,
override val expiryTime: Int = 60
) : ServerPlayerActionRequest
{
override val key: String = "team"
override val requestID: UUID = UUID.randomUUID()
}
// TODO right now team requests are sent PLAYER-to-PLAYER. May want to redesign once larger teams are implemented? Or have a 'team lead' who is responsible for inviting?
/**
* Represents a team for multi battles.
*
* @param teamPlayers The players that form this team.
*/
data class MultiBattleTeam(val teamPlayers: MutableList<ServerPlayer>)
{
constructor(vararg teamPlayers: ServerPlayer) : this(teamPlayers.toMutableList())
val teamID: UUID = UUID.randomUUID()
val teamPlayersUUID get() = this.teamPlayers.map { it.uuid }
}
// Multi-battle teams
private val playerToTeam = mutableMapOf<UUID, MultiBattleTeam>()
private val multiBattleTeams = mutableMapOf<UUID, MultiBattleTeam>()
fun getTeam(player: ServerPlayer) = playerToTeam.get(player.uuid)
fun getTeam(teamID: UUID) = multiBattleTeams.get(teamID)
override fun notificationPacket(request: TeamRequest): NetworkPacket<*> = TeamRequestNotificationPacket(request)
override fun expirationPacket(request: TeamRequest): NetworkPacket<*> = TeamRequestExpiredPacket(request)
/** Removes the [teamEntry]. */
fun disbandTeam(teamEntry: MultiBattleTeam) {
// Remove any outstanding team-up requests from the team members
val pendingTeamRequests = teamEntry.teamPlayersUUID.mapNotNull { member -> this.getOutboundRequest(member) } // team requests are by player
pendingTeamRequests.forEach { this.cancelRequest(it) }
// Decline any inbound requests for the team
ChallengeManager.getInboundRequests(teamEntry.teamID)?.forEach { ChallengeManager.declineRequest(it) } // multi challenges are by team
// Remove any outstanding multibattle challenges from the team
ChallengeManager.getOutboundRequest(teamEntry.teamID)?.let { ChallengeManager.cancelRequest(it) } // multi challenges are by team
// TODO have a way to get all types of requests targeting a team instead of just querying the ChallengeManger
// Notify remaining players that the team has been disbanded
teamEntry.teamPlayersUUID.forEach { member ->
playerToTeam.remove(member)
member.getPlayer()?.let { CobblemonNetwork.sendPacketToPlayer(it, TeamMemberRemoveNotificationPacket(it.uuid)) }
}
// Disband the team
multiBattleTeams.remove(teamEntry.teamID)
}
/** Removes a [player] from their [MultiBattleTeam]. Will disband the team if the last remaining member. */
fun removeTeamMember(player: ServerPlayer) {
val teamEntry = playerToTeam.get(player.uuid) ?: return
teamEntry.teamPlayers.remove(player)
playerToTeam.remove(player.uuid)
val notificationPacket = TeamMemberRemoveNotificationPacket(player.uuid)
CobblemonNetwork.sendPacketToPlayer(player, notificationPacket)
// Notify remaining members that the player has left the group
val teamServerPlayers = teamEntry.teamPlayersUUID.mapNotNull { it.getPlayer() }
CobblemonNetwork.sendPacketToPlayers(teamServerPlayers, notificationPacket)
if (teamEntry.teamPlayersUUID.count() == 1) this.disbandTeam(teamEntry)
}
/** Adds [player] as a member of existing [team]. */
fun joinTeam(player: ServerPlayer, team: MultiBattleTeam) {
// decline any other incoming requests to team up
this.getInboundRequests(player.uuid)?.forEach { this.cancelRequest(it) } // this is guaranteed to not contain the request currently being accepted
// notify the team
val teamNotifyPacket = TeamMemberAddNotificationPacket(
player.uuid,
player.name.copy()
)
CobblemonNetwork.sendPacketToPlayers(team.teamPlayers, teamNotifyPacket)
team.teamPlayers.add(player)
playerToTeam.put(player.uuid, team)
// notify the joiner
val joinerPacket = TeamJoinNotificationPacket(
team.teamPlayersUUID,
team.teamPlayers.mapNotNull { it.name.plainCopy() }
)
CobblemonNetwork.sendPacketToPlayer(player, joinerPacket)
}
/** Creates and registers a [MultiBattleTeam] from [players]. */
fun createTeam(vararg players: ServerPlayer): MultiBattleTeam {
// decline any other incoming requests to team up
players.forEach {
this.getInboundRequests(it.uuid)?.forEach { this.cancelRequest(it) } // this is guaranteed to not contain the request currently being accepted
}
val team = MultiBattleTeam(*players)
this.multiBattleTeams.put(team.teamID, team)
// Notify the team
val joinerPacket = TeamJoinNotificationPacket(
team.teamPlayersUUID,
players.mapNotNull { it.name.plainCopy() }
)
players.forEach {
this.playerToTeam.put(it.uuid, team)
CobblemonNetwork.sendPacketToPlayer(it, joinerPacket)
}
return team
}
override fun onAccept(request: TeamRequest) {
super.onAccept(request) // notification
val existingTeam = this.getTeam(request.sender)
if (existingTeam == null)
this.createTeam(request.receiver, request.sender)
else
this.joinTeam(request.receiver, existingTeam)
}
override fun canAccept(request: TeamRequest): Boolean {
val existingReceiverTeam = this.getTeam(request.receiverID)
val existingSenderTeam = this.getTeam(request.senderID)
if (request.sender.party().none()) {
request.notifySender(true, "error.no_pokemon")
request.notifyReceiver(true, "error.no_pokemon")
}
else if (existingReceiverTeam != null) {
request.notifySender(true, "error.existing_team.other", request.receiver.name.copy().aqua())
request.notifyReceiver(true, "error.existing_team.self")
}
else if (existingSenderTeam != null && existingSenderTeam.teamPlayersUUID.count() >= MAX_TEAM_MEMBER_COUNT) {
request.notifySender(true, "error.max_team_size.other", request.receiver.name.copy().aqua())
request.notifyReceiver(true, "error.max_team_size.self")
}
else {
return true
}
return false
}
override fun isValidInteraction(player: ServerPlayer, target: ServerPlayer): Boolean = player.canInteractWith(target, Cobblemon.config.tradeMaxDistance)
override fun onLogoff(sender: ServerPlayer) {
super.onLogoff(sender)
// Remove player from any teams they may be a part of
this.removeTeamMember(sender)
}
}
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.battles.interpreter.instructions
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.api.battles.interpreter.BattleContext
import com.cobblemon.mod.common.api.battles.interpreter.BattleMessage
import com.cobblemon.mod.common.api.battles.interpreter.InvalidInstructionException
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.moves.animations.ActionEffectContext
import com.cobblemon.mod.common.api.moves.animations.ActionEffects
@@ -20,6 +19,7 @@ import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.battles.ShowdownInterpreter
import com.cobblemon.mod.common.battles.dispatch.ActionEffectInstruction
import com.cobblemon.mod.common.battles.dispatch.GO
import com.cobblemon.mod.common.battles.dispatch.InstructionSet
import com.cobblemon.mod.common.battles.dispatch.UntilDispatch
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.cobblemonResource
@@ -33,25 +33,19 @@ import java.util.concurrent.CompletableFuture
* @author Hiroku
* @since August 20th, 2022
*/
class BoostInstruction(battle: PokemonBattle, val message: BattleMessage, val isBoost: Boolean = true): ActionEffectInstruction {
class BoostInstruction(val instructionSet: InstructionSet, val message: BattleMessage, val remainingLines: Iterator<BattleMessage>, val isBoost: Boolean = true): ActionEffectInstruction {
override var future: CompletableFuture<*> = CompletableFuture.completedFuture(Unit)
override var holds = mutableSetOf<String>()
override val id = cobblemonResource("boost")
val pokemon = message.battlePokemon(0, battle) ?: throw InvalidInstructionException(message)
val statKey = message.argumentAt(1) ?: throw InvalidInstructionException(message)
val stages = message.argumentAt(2)?.toInt() ?: throw InvalidInstructionException(message)
val stat = Stats.getStat(statKey).displayName
override fun preActionEffect(battle: PokemonBattle) {
}
override fun runActionEffect(battle: PokemonBattle, runtime: MoLangRuntime) {
if (stages == 0) return // only play effect if there was a stat change
battle.dispatch {
val actionEffect = if (isBoost) BOOST_EFFECT else UNBOOST_EFFECT
val providers = mutableListOf<Any>(battle)
val pokemon = message.battlePokemon(0, battle) ?: return@dispatch GO
pokemon.effectedPokemon.entity?.let { UsersProvider(it) }?.let(providers::add)
val context = ActionEffectContext(
actionEffect = actionEffect,
@@ -66,6 +60,10 @@ class BoostInstruction(battle: PokemonBattle, val message: BattleMessage, val is
}
override fun postActionEffect(battle: PokemonBattle) {
val pokemon = message.battlePokemon(0, battle) ?: return
val statKey = message.argumentAt(1) ?: return
val stages = message.argumentAt(2)?.toInt() ?: return
val stat = Stats.getStat(statKey).displayName
val severity = Stats.getSeverity(stages)
val rootKey = if (isBoost) "boost" else "unboost"
@@ -150,12 +150,12 @@ class DamageInstruction(
if (effect != null) {
val lang = when (effect.id) {
"blacksludge", "stickybarb", "jabocaberry", "rowapberry" -> battleLang("damage.item", pokemonName, effect.typelessData)
"blacksludge", "stickybarb" -> battleLang("damage.item", pokemonName, effect.typelessData)
"brn", "psn", "tox" -> {
val status = Statuses.getStatus(effect.id)?.name?.path ?: return@dispatch GO
lang("status.$status.hurt", pokemonName)
}
"aftermath", "innardsout" -> battleLang("damage.generic", pokemonName)
"aftermath" -> battleLang("damage.generic", pokemonName)
"chloroblast", "steelbeam" -> battleLang("damage.mindblown", pokemonName)
"jumpkick" -> battleLang("damage.highjumpkick", pokemonName)
else -> battleLang("damage.${effect.id}", pokemonName, source?.getName() ?: Component.literal("UNKOWN"))
@@ -209,7 +209,7 @@ class DamageInstruction(
} else if (causedFaint) {
GO
} else {
UntilDispatch { "effects" !in holds}
UntilDispatch {"effects" !in holds}
}
}
}
@@ -33,7 +33,7 @@ class FailInstruction(val message: BattleMessage): InterpreterInstruction {
val of = message.battlePokemonFromOptional(battle)
val lang = when (effectID) {
null, "burnup", "doubleshock", "allyswitch" -> battleLang("fail") // Moves that use default fail lang. (Null included for moves that fail with no effect, for example: Baton Pass.)
null, "burnup", "doubleshock" -> battleLang("fail") // Moves that use default fail lang. (Null included for moves that fail with no effect, for example: Baton Pass.)
"shedtail" -> battleLang("fail.substitute", pokemonName)
"hyperspacefury", "aurawheel" -> battleLang("fail.darkvoid", pokemonName) // Moves that can only be used by one species and fail when any others try
"corrosivegas" -> battleLang("fail.healblock", pokemonName)
@@ -9,11 +9,16 @@
package com.cobblemon.mod.common.battles.interpreter.instructions
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.battles.interpreter.BattleMessage
import com.cobblemon.mod.common.api.battles.interpreter.Effect
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addEntityFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addPokemonEntityFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addPokemonFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addStandardFunctions
import com.cobblemon.mod.common.api.moves.Moves
import com.cobblemon.mod.common.api.moves.animations.ActionEffectContext
@@ -26,9 +31,14 @@ import com.cobblemon.mod.common.battles.dispatch.InstructionSet
import com.cobblemon.mod.common.battles.dispatch.InterpreterInstruction
import com.cobblemon.mod.common.battles.dispatch.UntilDispatch
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.net.messages.client.battle.BattleAppendTargetedEntityPacket
import com.cobblemon.mod.common.pokemon.evolution.progress.UseMoveEvolutionProgress
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.ai.targeting.TargetingConditions
import net.minecraft.world.phys.AABB
import java.util.concurrent.CompletableFuture
/**
@@ -97,6 +107,13 @@ class MoveInstruction(
val runtime = MoLangRuntime().also {
battle.addQueryFunctions(it.environment.query).addStandardFunctions()
}
userPokemon.effectedPokemon.entity?.let {
val queryStruct = QueryStruct(hashMapOf())
queryStruct.addEntityFunctions(it)
queryStruct.addPokemonEntityFunctions(it)
queryStruct.addPokemonFunctions(it.pokemon)
runtime.environment.variable.setDirectly("user", queryStruct)
}
actionEffect ?: return@dispatch GO
val context = ActionEffectContext(
@@ -130,6 +147,17 @@ class MoveInstruction(
runtime.environment.query.addFunction("move") { move.struct }
runtime.environment.query.addFunction("instruction_id") { StringValue(cobblemonResource("move").toString()) }
if (userPokemon.entity != null && targetPokemon?.entity != null) {
//Not the most elegant solution, maybe we should just make the targeted entity a piece of SyncedData
val serverLevel = userPokemon.entity!!.level() as? ServerLevel
serverLevel?.getNearbyPlayers(
TargetingConditions.forNonCombat(),
userPokemon.entity!!,
AABB.ofSize(userPokemon.entity!!.position(), 128.0, 128.0, 128.0)
)?.mapNotNull { it as? ServerPlayer }?.forEach { it.sendPacket(BattleAppendTargetedEntityPacket(userPokemon.entity!!.id, targetPokemon.entity!!.id)) }
battle.sendUpdate(BattleAppendTargetedEntityPacket(userPokemon.entity!!.id, targetPokemon.entity!!.id))
}
this.future = actionEffect.run(context)
holds = context.holds // Reference so future things can check on this action effect's holds
future.thenApply { holds.clear() }
@@ -41,7 +41,6 @@ class StatusInstruction( val message: BattleMessage): InterpreterInstruction {
if (status is PersistentStatus) {
pokemon.effectedPokemon.applyStatus(status)
battle.sendUpdate(BattlePersistentStatusPacket(pnx, status))
pokemon.sendUpdate()
}
battle.broadcastChatMessage(status.applyMessage.asTranslated(pokemon.getName()))
@@ -164,7 +164,7 @@ class GildedChestBlock(settings: Properties, val type: Type = Type.RED) : BaseEn
world.addFreshEntity(entity)
world.removeBlock(pos, false)
afterOnServer(seconds = 0.1F) {
afterOnServer(ticks = 2) {
if (player !in player.level().players()) {
return@afterOnServer
}
@@ -137,7 +137,7 @@ class HealingMachineBlockEntity(
val npc = level
?.getEntities(null, AABB.ofSize(blockPos.toVec3d(), 10.0, 10.0, 10.0)) { it.uuid == currentUser && it is NPCEntity }
?.firstOrNull() as? NPCEntity
val party = npc?.party
val party = npc?.staticParty
if (party != null) {
party.heal()
npc.sendSystemMessage(lang("healingmachine.healed").green()) // An NPC can read text, right?
@@ -126,7 +126,7 @@ class FossilMultiblockStructure (
stack?.shrink(1)
}
val pokemon = this.resultingFossil?.result?.create(player)
val pokemon = this.resultingFossil?.result?.create()
if(pokemon != null) {
pokemon.caughtBall = ballType
@@ -0,0 +1,78 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client
import com.cobblemon.mod.common.client.battle.ClientBattleChallenge
import com.cobblemon.mod.common.client.particle.BedrockParticleOptionsRepository
import com.cobblemon.mod.common.client.particle.ParticleStorm
import com.cobblemon.mod.common.client.render.MatrixWrapper
import com.cobblemon.mod.common.client.trade.ClientTradeOffer
import com.cobblemon.mod.common.util.cobblemonResource
import java.util.UUID
import net.minecraft.client.Minecraft
import net.minecraft.world.entity.player.Player
import net.minecraft.world.phys.Vec3
class ClientPlayerActionRequests {
val battleChallenges = mutableListOf<ClientBattleChallenge>()
val multiBattleTeamRequests = mutableListOf<ClientBattleChallenge>()
val tradeOffers = mutableListOf<ClientTradeOffer>()
val trackedPlayers = mutableMapOf<UUID, MatrixWrapper>()
fun onMultiChallengeExpired(challengeId: UUID) {
val players = multiBattleTeamRequests.filter { it.challengeId == challengeId }.flatMap { it.challengerIds }
players.forEach(trackedPlayers::remove)
multiBattleTeamRequests.removeIf { it.challengeId == challengeId }
}
fun onChallengeExpired(challengeId: UUID) {
val players = battleChallenges.filter { it.challengeId == challengeId }.flatMap { it.challengerIds }
players.forEach(trackedPlayers::remove)
battleChallenges.removeIf { it.challengeId == challengeId }
}
fun onTradeOfferExpired(uuid: UUID) {
val tradeOffers = tradeOffers.filter { it.tradeOfferId == uuid }
val players = tradeOffers.map { it.traderId }
players.forEach(trackedPlayers::remove)
this.tradeOffers.removeAll(tradeOffers)
}
fun onRenderPlayer(player: Player, partialTicks: Float) {
val matrixWrapper = trackedPlayers[player.uuid] ?: return
val position = player.getEyePosition(partialTicks)
matrixWrapper.updatePosition(
Vec3(
position.x,
position.y + 1.1,
position.z
)
)
}
fun addParticleEffect(challenge: ClientBattleChallenge) {
challenge.challengerIds.forEach { playerId ->
val player = Minecraft.getInstance().level?.getPlayerByUUID(playerId) ?: return@forEach
val wrapper = trackedPlayers.getOrPut(player.uuid) { MatrixWrapper() }
wrapper.updatePosition(player.getEyePosition(0F).add(0.0, 1.1, 0.0))
val effect = BedrockParticleOptionsRepository.getEffect(cobblemonResource("particle_exclamation"))
if (effect != null) {
val particleStorm = ParticleStorm(
effect = effect,
matrixWrapper = wrapper,
sourceAlive = { !player.isRemoved && trackedPlayers.containsKey(playerId) },
world = Minecraft.getInstance().level ?: return,
entity = player,
)
particleStorm.spawn()
}
}
}
}
@@ -8,16 +8,12 @@
package com.cobblemon.mod.common.client
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import java.util.UUID
class ClientPlayerTeamData {
var multiBattleTeamMembers = mutableListOf<ClientMultiBattleTeamMember>()
}
class ClientMultiBattleTeamMember(val uuid: UUID, val name: MutableComponent) : ClientPlayerIcon(null) {
override val texture: ResourceLocation = cobblemonResource("textures/particle/request/icon_partner.png")
class ClientMultiBattleTeamMember(val uuid: UUID, val name: MutableComponent) {
}
@@ -19,8 +19,6 @@ import com.cobblemon.mod.common.client.battle.ClientBattle
import com.cobblemon.mod.common.client.gui.PartyOverlay
import com.cobblemon.mod.common.client.gui.battle.BattleOverlay
import com.cobblemon.mod.common.client.particle.BedrockParticleOptionsRepository
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.client.render.DeferredRenderer
import com.cobblemon.mod.common.client.render.block.*
import com.cobblemon.mod.common.client.render.boat.CobblemonBoatRenderer
import com.cobblemon.mod.common.client.render.entity.PokeBobberEntityRenderer
@@ -33,7 +31,6 @@ import com.cobblemon.mod.common.client.render.models.blockbench.repository.*
import com.cobblemon.mod.common.client.render.npc.NPCRenderer
import com.cobblemon.mod.common.client.render.pokeball.PokeBallRenderer
import com.cobblemon.mod.common.client.render.pokemon.PokemonRenderer
import com.cobblemon.mod.common.client.requests.ClientPlayerActionRequests
import com.cobblemon.mod.common.client.sound.BattleMusicController
import com.cobblemon.mod.common.client.sound.EntitySoundTracker
import com.cobblemon.mod.common.client.storage.ClientStorageManager
@@ -107,8 +104,6 @@ object CobblemonClient {
ClientTaskTracker.clear()
checkedStarterScreen = false
CobblemonDataProvider.canReload = true
DeferredRenderer.clearAll()
ClientPlayerIcon.clear()
}
fun initialize(implementation: CobblemonClientImplementation) {
@@ -161,7 +156,6 @@ object CobblemonClient {
it.delegate.spawnShinyParticle(player!!)
}
}
ClientPlayerIcon.onTick()
}
}
@@ -8,29 +8,11 @@
package com.cobblemon.mod.common.client.battle
import com.cobblemon.mod.common.api.interaction.PlayerActionRequest
import com.cobblemon.mod.common.battles.BattleFormat
import com.cobblemon.mod.common.client.requests.ClientPlayerActionRequest
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.resources.ResourceLocation
import java.util.*
import java.util.UUID
/**
* Clientside representation of a [PlayerActionRequest] for a battle.
*
* @param requestID The unique identifier of this challenge.
* @param senderID The unique identifier of the player (or team) that sent this challenge.
* @param expiryTime The amount of time (in seconds) this challenge is active.
* @param battleFormat The
*
* @author JazzMcNade
* @since July 22nd, 2024
*/
data class ClientBattleChallenge(
override val requestID: UUID,
override val senderID: UUID,
override val expiryTime: Int,
val battleFormat: BattleFormat
) : ClientPlayerActionRequest(expiryTime) {
override val texture: ResourceLocation = cobblemonResource("textures/particle/request/icon_challenge.png")
}
class ClientBattleChallenge(
val challengeId: UUID,
val challengerIds: List<UUID>,
val battleFormat: BattleFormat? = null
)
@@ -1,22 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.battle
import com.cobblemon.mod.common.client.requests.ClientPlayerActionRequest
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.resources.ResourceLocation
import java.util.*
data class ClientTeamRequest(
override val requestID: UUID,
override val senderID: UUID,
override val expiryTime: Int
) : ClientPlayerActionRequest(expiryTime) {
override val texture: ResourceLocation = cobblemonResource("textures/particle/request/icon_team.png")
}
@@ -14,8 +14,8 @@ import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.entity.PokemonSideDelegate
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addEntityFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addFunctions
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.scheduling.ScheduledTask
import com.cobblemon.mod.common.api.scheduling.SchedulingTracker
@@ -32,7 +32,10 @@ import com.cobblemon.mod.common.client.render.models.blockbench.repository.Pokem
import com.cobblemon.mod.common.client.render.pokemon.PokemonRenderer.Companion.ease
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.*
import com.cobblemon.mod.common.util.MovingSoundInstance
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.resolve
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
import net.minecraft.network.syncher.EntityDataAccessor
@@ -43,8 +46,6 @@ import net.minecraft.world.InteractionHand
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.player.Player
import net.minecraft.world.phys.Vec3
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
class PokemonClientDelegate : PosableState(), PokemonSideDelegate {
companion object {
@@ -92,6 +93,8 @@ class PokemonClientDelegate : PosableState(), PokemonSideDelegate {
private var scaleAnimTask: ScheduledTask? = null
private var cryAnimation: ActiveAnimation? = null
var targetedEntityId: Int? = null
override fun onSyncedDataUpdated(data: EntityDataAccessor<*>) {
super.onSyncedDataUpdated(data)
if (this::currentEntity.isInitialized) {
@@ -104,10 +107,6 @@ class PokemonClientDelegate : PosableState(), PokemonSideDelegate {
} else if (data == PokemonEntity.ASPECTS) {
currentAspects = currentEntity.entityData.get(PokemonEntity.ASPECTS)
currentEntity.pokemon.shiny = currentAspects.contains("shiny")
} else if (data == PokemonEntity.CAUGHT_BALL) {
PokeBalls.getPokeBall(currentEntity.entityData.get(PokemonEntity.CAUGHT_BALL).asIdentifierDefaultingNamespace())?.let {
currentEntity.pokemon.caughtBall = it
}
} else if (data == PokemonEntity.DYING_EFFECTS_STARTED) {
val isDying = currentEntity.entityData.get(PokemonEntity.DYING_EFFECTS_STARTED)
if (isDying) {
@@ -232,6 +231,13 @@ class PokemonClientDelegate : PosableState(), PokemonSideDelegate {
world
).spawn()
}
currentEntity.after(seconds = 0.1f) {
//This is only for when the player is sending out the Pokemon into the world and not a battle.
if (currentEntity.pokemon.shiny && !currentEntity.isBattling) {
playShinyEffect("cobblemon:shiny_ring")
lastShinyParticle = System.currentTimeMillis()
}
}
}
}
}
@@ -334,6 +340,7 @@ class PokemonClientDelegate : PosableState(), PokemonSideDelegate {
struct.addFunctions(functions.functions)
struct.addFunctions(ClientMoLangFunctions.clientFunctions)
runtime.environment.query = struct
addEnemyFunctions(struct)
}
override fun initialize(entity: PokemonEntity) {
@@ -158,7 +158,7 @@ class BattleGUI : Screen(battleLang("gui.title")) {
// Known quirk of Showdown. It'll ask for actions on fainted slots
// Also during a forced switch in doubles/triples it'll ask for actions on non-switching slots
val pokemon = request.side?.pokemon?.firstOrNull { it.uuid == request.activePokemon.battlePokemon?.uuid }
if (pokemon == null || pokemon.condition.contains("fnt") || pokemon.commanding || request.moveSet == null) {
if(pokemon == null || pokemon.condition.contains("fnt") || request.moveSet == null) {
this.selectAction(request, PassActionResponse)
null
} else {
@@ -28,8 +28,8 @@ class BattleMessagePane(
messageQueue: ClientBattleMessageQueue
): ObjectSelectionList<BattleMessagePane.BattleMessageLine>(
Minecraft.getInstance(),
FRAME_WIDTH, // width
FRAME_HEIGHT, // height
TEXT_BOX_WIDTH, // width
TEXT_BOX_HEIGHT, // height
1, // top
LINE_HEIGHT
) {
@@ -62,7 +62,7 @@ class BattleMessagePane(
companion object {
const val LINE_HEIGHT = 10
const val LINE_WIDTH = 146
const val LINE_WIDTH = 142
const val FRAME_WIDTH = 169
const val FRAME_HEIGHT = 55
const val FRAME_EXPANDED_HEIGHT = 101
@@ -72,7 +72,6 @@ class BattleMessagePane(
private val battleMessagePaneFrameResource = cobblemonResource("textures/gui/battle/battle_log.png")
private val battleMessagePaneFrameExpandedResource = cobblemonResource("textures/gui/battle/battle_log_expanded.png")
private val battleMessageHighlight = cobblemonResource("textures/gui/battle/battle_log_row_selected_color.png")
private var expanded = false
}
@@ -80,54 +79,8 @@ class BattleMessagePane(
return super.addEntry(entry)
}
override fun getRowLeft(): Int {
return super.getRowLeft() + 4
}
override fun renderSelection(guiGraphics: GuiGraphics, top: Int, width: Int, height: Int, outerColor: Int, innerColor: Int) {
blitk(
matrixStack = guiGraphics.pose(),
texture = battleMessageHighlight,
x = x + 6,
y = top - 2,
height = 10,
width = 1,
alpha = opacity
)
blitk(
matrixStack = guiGraphics.pose(),
texture = battleMessageHighlight,
x = x + 6,
y = top - 2,
height = 1,
width = LINE_WIDTH,
alpha = opacity
)
blitk(
matrixStack = guiGraphics.pose(),
texture = battleMessageHighlight,
x = x + 6,
y = top + 7,
height = 1,
width = LINE_WIDTH,
alpha = opacity
)
blitk(
matrixStack = guiGraphics.pose(),
texture = battleMessageHighlight,
x = x + 6 + LINE_WIDTH - 1,
y = top - 2,
height = 10,
width = 1,
alpha = opacity
)
}
override fun getRowWidth(): Int {
return LINE_WIDTH
return 80
}
override fun getScrollbarPosition(): Int {
@@ -209,7 +162,7 @@ class BattleMessagePane(
drawScaledText(
context,
line,
rowLeft,
rowLeft - 29,
rowTop - 2,
opacity = pane.opacity
)
@@ -8,21 +8,15 @@
package com.cobblemon.mod.common.client.gui.interact.battleRequest
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.gui.ColourLibrary
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.text.bold
import com.cobblemon.mod.common.battles.BattleFormat
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.client.battle.ClientBattleChallenge
import com.cobblemon.mod.common.client.battle.ClientTeamRequest
import com.cobblemon.mod.common.client.render.drawScaledText
import com.cobblemon.mod.common.net.messages.client.PlayerInteractOptionsPacket
import com.cobblemon.mod.common.net.messages.server.*
import com.cobblemon.mod.common.net.messages.server.battle.BattleTeamLeavePacket
import com.cobblemon.mod.common.net.messages.server.battle.BattleTeamRequestPacket
import com.cobblemon.mod.common.net.messages.server.battle.BattleTeamResponsePacket
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
@@ -31,13 +25,12 @@ import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import java.util.*
class BattleConfigureGUI(
private val packet: PlayerInteractOptionsPacket,
private val activeRequest: ClientBattleChallenge? = null,
private val activeTeamRequest: ClientTeamRequest? = null
) : Screen(lang("ui.challenge.challenge_title")) {
private val activeTeamRequest: ClientBattleChallenge? = null
) : Screen(lang("challenge.request_battle_title")) {
companion object {
const val SIZE = 113
private val backgroundResource = cobblemonResource("textures/gui/interact/request/battle_request.png")
@@ -54,11 +47,11 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_SINGLES,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_single.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_overlay.png"),
title = lang("ui.challenge.challenge_title").bold(),
title = lang("challenge.request_battle_title").bold(),
subTitle = lang("battle.types.singles").bold(),
buttonText = lang("ui.challenge.challenge").bold(),
buttonText = lang("challenge.challenge").bold(),
onRequest = { packet, battleFormat -> sendBattleRequest(battleFormat, packet) },
onResponse = { packet, requestID, accept -> sendBattleResponse(packet, requestID, accept) }
onResponse = { packet, accept -> sendBattleResponse(packet, accept) }
)
),
Pair(
@@ -68,11 +61,11 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_DOUBLES,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_double.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_overlay.png"),
title = lang("ui.challenge.challenge_title").bold(),
title = lang("challenge.request_battle_title").bold(),
subTitle = lang("battle.types.doubles").bold(),
buttonText = lang("ui.challenge.challenge").bold(),
buttonText = lang("challenge.challenge").bold(),
onRequest = { packet, battleFormat -> sendBattleRequest(battleFormat, packet) },
onResponse = { packet, requestID, accept -> sendBattleResponse(packet, requestID, accept) }
onResponse = { packet, accept -> sendBattleResponse(packet, accept) }
),
),
Pair(
@@ -82,11 +75,11 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_TRIPLES,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_triple.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_overlay.png"),
title = lang("ui.challenge.challenge_title").bold(),
title = lang("challenge.request_battle_title").bold(),
subTitle = lang("battle.types.triples").bold(),
buttonText = lang("ui.challenge.challenge").bold(),
buttonText = lang("challenge.challenge").bold(),
onRequest = { packet, battleFormat -> sendBattleRequest(battleFormat, packet) },
onResponse = { packet, requestID, accept -> sendBattleResponse(packet, requestID, accept) }
onResponse = { packet, accept -> sendBattleResponse(packet, accept) }
),
),
Pair(
@@ -96,12 +89,12 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_MULTI,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_multi.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_multi_overlay_partner.png"),
title = lang("ui.team.invite_title").bold(),
title = lang("challenge.request_team_join_title").bold(),
subTitle = lang("battle.types.multi").bold(),
buttonText = lang("ui.team.invite").bold(),
buttonText = lang("challenge.multi.invite").bold(),
color = ColourLibrary.SIDE_1_ALLY_BATTLE_COLOUR,
onRequest = { packet, battleFormat -> BattleTeamRequestPacket(packet.numericTargetId).sendToServer() },
onResponse = { packet, requestID, accept -> sendTeamResponse(packet, requestID, accept) }
onResponse = { packet, accept -> BattleTeamResponsePacket(packet.numericTargetId, accept).sendToServer() }
),
),
Pair(
@@ -111,12 +104,12 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_MULTI,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_multi.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_multi_overlay_partner_leave.png"),
title = lang("ui.team.leave_title").bold(),
title = lang("challenge.request_team_leave_title").bold(),
subTitle = lang("battle.types.multi").bold(),
buttonText = lang("ui.team.leave").bold(),
buttonText = lang("challenge.multi.leave").bold(),
color = ColourLibrary.SIDE_1_ALLY_BATTLE_COLOUR,
onRequest = { _, _ -> BattleTeamLeavePacket().sendToServer() },
onResponse = { _, _, _ -> Unit }
onResponse = { _, _ -> Unit }
),
),
Pair(
@@ -126,11 +119,11 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_MULTI,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_multi.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_multi_overlay_opponent.png"),
title = lang("ui.challenge.challenge_title").bold(),
title = lang("challenge.request_battle_title").bold(),
subTitle = lang("battle.types.multi").bold(),
buttonText = lang("ui.challenge.challenge").bold(),
buttonText = lang("challenge.challenge").bold(),
onRequest = { packet, battleFormat -> sendBattleRequest(battleFormat, packet) },
onResponse = { packet, requestID, accept -> sendBattleResponse(packet, requestID, accept) }
onResponse = { packet, accept -> sendBattleResponse(packet, accept) }
),
),
Pair(
@@ -140,41 +133,38 @@ class BattleConfigureGUI(
battleFormat = BattleFormat.GEN_9_ROYAL,
tileTexture = cobblemonResource("textures/gui/interact/request/battle_request_royal.png"),
overlayTexture = cobblemonResource("textures/gui/interact/request/battle_request_royal_overlay.png"),
title = lang("ui.challenge.challenge_title").bold(),
title = lang("challenge.request_battle_title").bold(),
subTitle = lang("battle.types.freeforall").bold(),
buttonText = lang("ui.challenge.challenge").bold(),
buttonText = lang("challenge.challenge").bold(),
onRequest = { packet, battleFormat -> sendBattleRequest(battleFormat, packet) },
onResponse = { packet, requestID, accept -> sendBattleResponse(packet, requestID, accept) }
onResponse = { packet, accept -> sendBattleResponse(packet, accept) }
),
),
)
val levelRulesetOption = mutableListOf(-1, 50, 100, 5)
private fun sendTeamResponse(packet: PlayerInteractOptionsPacket, requestID: UUID, accept: Boolean) {
BattleTeamResponsePacket(packet.numericTargetId, requestID, accept).sendToServer()
}
fun sendBattleRequest(battleFormat: BattleFormat, packet: PlayerInteractOptionsPacket) {
BattleChallengePacket(packet.numericTargetId, packet.selectedPokemonId, battleFormat).sendToServer()
}
private fun sendBattleResponse(packet: PlayerInteractOptionsPacket, requestID: UUID, accept: Boolean) {
BattleChallengeResponsePacket(packet.numericTargetId, requestID, packet.selectedPokemonId, accept).sendToServer()
private fun sendBattleResponse(packet: PlayerInteractOptionsPacket, accept: Boolean) {
BattleChallengeResponsePacket(packet.numericTargetId, packet.selectedPokemonId, accept).sendToServer()
}
private var options: List<PlayerInteractOptionsPacket.Options> = emptyList()
private val blinkRate = 35
}
class BattleTypeTile(
val option: PlayerInteractOptionsPacket.Options,
val battleFormat: BattleFormat,
val tileTexture: ResourceLocation?,
val overlayTexture: ResourceLocation?,
val title: MutableComponent,
val subTitle: MutableComponent,
val buttonText: MutableComponent,
val color: Int = ColourLibrary.SIDE_1_BATTLE_COLOUR,
val onRequest: (packet : PlayerInteractOptionsPacket, battleFormat: BattleFormat) -> Unit,
val onResponse: (packet: PlayerInteractOptionsPacket, requestID: UUID, accept: Boolean) -> Unit,
val option: PlayerInteractOptionsPacket.Options,
val battleFormat: BattleFormat,
val tileTexture: ResourceLocation?,
val overlayTexture: ResourceLocation?,
val title: MutableComponent,
val subTitle: MutableComponent,
val buttonText: MutableComponent,
val color: Int = ColourLibrary.SIDE_1_BATTLE_COLOUR,
val onRequest: (packet : PlayerInteractOptionsPacket, battleFormat: BattleFormat) -> Unit,
val onResponse: (packet: PlayerInteractOptionsPacket, accept: Boolean) -> Unit,
)
private var currentPage = 0
@@ -206,20 +196,23 @@ class BattleConfigureGUI(
override fun init() {
val challenge = activeRequest
targetName = Minecraft.getInstance().player?.level()?.getPlayerByUUID(packet.targetId)?.name?.plainCopy()?.bold() ?: targetName
val pendingRequest = activeTeamRequest ?: activeRequest
hasRequest = challenge != null || activeTeamRequest != null
if (activeTeamRequest != null) {
options = listOf(PlayerInteractOptionsPacket.Options.TEAM_REQUEST)
} else if (activeRequest != null) {
options = packet.options.keys.filter { packet.options[it] === PlayerInteractOptionsPacket.OptionStatus.AVAILABLE && battleRequestMap[it]?.battleFormat?.battleType?.name == activeRequest.battleFormat.battleType.name }
val level = activeRequest.battleFormat.adjustLevel
} else if (challenge != null) {
options = packet.options.keys.filter { packet.options[it] === PlayerInteractOptionsPacket.OptionStatus.AVAILABLE && battleRequestMap[it]?.battleFormat?.battleType?.name == challenge.battleFormat?.battleType?.name }
val level = challenge.battleFormat?.adjustLevel ?: -1
levelRulesetOptionIndex = maxOf(0, levelRulesetOption.indexOf(level))
} else {
options = packet.options.keys.filter { packet.options[it] === PlayerInteractOptionsPacket.OptionStatus.AVAILABLE && battleRequestMap.containsKey(it) }.toList()
}
val (x, y) = getDimensions()
if(pendingRequest != null) {
if(hasRequest) {
// Draw Accept/Decline buttons
this.addRenderableWidget(
BattleResponseButton(
@@ -227,7 +220,7 @@ class BattleConfigureGUI(
y + 99,
true
) {
battleRequestMap[options[currentPage]]?.onResponse?.let { it1 -> it1(packet, pendingRequest.requestID, true) }
battleRequestMap[options[currentPage]]?.onResponse?.let { it1 -> it1(packet, true) }
closeGUI()
}
)
@@ -238,18 +231,17 @@ class BattleConfigureGUI(
y + 99,
false
) {
battleRequestMap[options[currentPage]]?.onResponse?.let { it1 -> it1(packet, pendingRequest.requestID, false) }
battleRequestMap[options[currentPage]]?.onResponse?.let { it1 -> it1(packet, false) }
closeGUI()
}
)
}
else {
} else {
// Draw Challenge button
requestButton = BattleRequestButton(
x + 22,
y + 99,
lang("ui.challenge.challenge"),
lang("challenge.challenge"),
) {
//TODO: add additional battle rules, otherwise this call feels pretty silly
battleRequestMap[options[currentPage]]?.onRequest?.let { it1 ->
@@ -311,7 +303,7 @@ class BattleConfigureGUI(
fun updateRequestButtonText() {
requestButton.let {
if (it != null) {
it.text = battleRequestMap[options[currentPage]]?.buttonText ?: lang("ui.challenge.challenge")
it.text = battleRequestMap[options[currentPage]]?.buttonText ?: lang("challenge.challenge")
}
}
}
@@ -8,13 +8,11 @@
package com.cobblemon.mod.common.client.gui.interact.wheel
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.pokemon.interaction.PokemonInteractionGUICreationEvent
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.interact.battleRequest.BattleConfigureGUI
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.net.messages.client.PlayerInteractOptionsPacket
import com.cobblemon.mod.common.net.messages.server.battle.SpectateBattlePacket
import com.cobblemon.mod.common.net.messages.server.pokemon.interact.InteractPokemonPacket
@@ -59,24 +57,24 @@ fun createPokemonInteractGui(pokemonID: UUID, canMountShoulder: Boolean): Intera
fun createPlayerInteractGui(optionsPacket: PlayerInteractOptionsPacket): InteractWheelGUI {
val trade = InteractWheelOption(
iconResource = cobblemonResource("textures/gui/interact/icon_trade.png"),
secondaryIconResource = if (CobblemonClient.requests.tradeOffers[optionsPacket.targetId] != null)
secondaryIconResource = if (CobblemonClient.requests.tradeOffers.any { it.traderId == optionsPacket.targetId })
cobblemonResource("textures/gui/interact/icon_exclamation.png")
else null,
colour = { null },
tooltipText = "cobblemon.ui.interact.trade",
onPress = {
val tradeOffer = CobblemonClient.requests.tradeOffers[optionsPacket.targetId]
val tradeOffer = CobblemonClient.requests.tradeOffers.find { it.traderId == optionsPacket.targetId }
if (tradeOffer == null) {
CobblemonNetwork.sendToServer(OfferTradePacket(optionsPacket.targetId))
} else {
CobblemonClient.requests.tradeOffers.remove(optionsPacket.targetId)
CobblemonNetwork.sendToServer(AcceptTradeRequestPacket(tradeOffer.requestID))
CobblemonClient.requests.tradeOffers -= tradeOffer
CobblemonNetwork.sendToServer(AcceptTradeRequestPacket(tradeOffer.tradeOfferId))
}
closeGUI()
}
)
val activeBattleRequest = CobblemonClient.requests.battleChallenges[optionsPacket.targetId]
val activeTeamRequest = CobblemonClient.requests.multiBattleTeamRequests[optionsPacket.targetId]
val activeBattleRequest = CobblemonClient.requests.battleChallenges.firstOrNull { it.challengerIds.contains(optionsPacket.targetId) }
val activeTeamRequest = CobblemonClient.requests.multiBattleTeamRequests.firstOrNull { it.challengerIds.contains(optionsPacket.targetId) }
val battle = InteractWheelOption(
iconResource = cobblemonResource("textures/gui/interact/icon_battle.png"),
secondaryIconResource = if(activeBattleRequest != null|| activeTeamRequest != null)
@@ -91,7 +89,7 @@ fun createPlayerInteractGui(optionsPacket: PlayerInteractOptionsPacket): Interac
val spectate = InteractWheelOption(
iconResource = cobblemonResource("textures/gui/interact/icon_spectate_battle.png"),
colour = { if (CobblemonClient.requests.battleChallenges[optionsPacket.targetId] != null) Vector3f(0F, 0.6F, 0F) else null },
colour = { if (CobblemonClient.requests.battleChallenges.any { it.challengerIds.contains(optionsPacket.targetId) }) Vector3f(0F, 0.6F, 0F) else null },
onPress = {
SpectateBattlePacket(optionsPacket.targetId).sendToServer()
closeGUI()
@@ -100,8 +98,8 @@ fun createPlayerInteractGui(optionsPacket: PlayerInteractOptionsPacket): Interac
)
val options: Multimap<Orientation, InteractWheelOption> = ArrayListMultimap.create()
//TODO: hasChallenge and hasTeamRequest get calculated a bunch of times. Might consider having the server just passing it over.
val hasChallenge = CobblemonClient.requests.battleChallenges[optionsPacket.targetId] != null
val hasTeamRequest = CobblemonClient.requests.multiBattleTeamRequests[optionsPacket.targetId] != null
val hasChallenge = CobblemonClient.requests.battleChallenges.any { it.challengerIds.contains(optionsPacket.targetId) }
val hasTeamRequest = CobblemonClient.requests.multiBattleTeamRequests.any { it.challengerIds.contains(optionsPacket.targetId) }
//The way things are positioned should probably be more thought out if more options are added
var addBattleOption = false
optionsPacket.options.forEach {
@@ -348,10 +348,7 @@ class PokedexGUI private constructor(
if (entries.isNotEmpty()) {
if (init && initSpecies != null) {
var entry = entries.firstOrNull { it.speciesId == initSpecies }
if (entry == null) {
entry = entries.first()
}
val entry = entries.first { it.speciesId == initSpecies }
setSelectedEntry(entry)
scrollScreen.scrollAmount = (entries.indexOf(entry).toDouble() / entries.size.toDouble()) * scrollScreen.maxScroll
} else {
@@ -448,7 +445,7 @@ class PokedexGUI private constructor(
val form = species.forms.find { it.name.equals(formName, ignoreCase = true) } ?: species.standardForm
when (tabInfoIndex) {
TAB_DESCRIPTION -> {
textToShowInDescription.addAll(form.pokedex)
textToShowInDescription.addAll(species.pokedex)
(tabInfoElement as DescriptionWidget).showPlaceholder = false
}
TAB_ABILITIES -> {
@@ -174,7 +174,6 @@ class PokemonInfoWidget(val pX: Int, val pY: Int, val updateForm: (PokedexForm)
}
val possibleVariationButtonPositions = mutableListOf<Pair<Float, Float>>(
126F to 27F,
114F to 27F,
102F to 27F,
90F to 27F,
@@ -470,6 +469,7 @@ class PokemonInfoWidget(val pX: Int, val pY: Int, val updateForm: (PokedexForm)
)
}
// Cry
blitk(
matrixStack = matrices,
@@ -550,12 +550,6 @@ class PokemonInfoWidget(val pX: Int, val pY: Int, val updateForm: (PokedexForm)
variationButtons.forEach { removeWidget(it.getWidget()) }
variationButtons.clear()
val seenShinyStates = CobblemonClient.clientPokedexData.getSeenShinyStates(pokedexEntry, pokedexForm)
shiny = seenShinyStates.count() == 1 && seenShinyStates.first() == "shiny"
shinyButton.resource = if (shiny) buttonShiny else buttonNone
shinyButton.visible = shiny || seenShinyStates.size > 1
shinyButton.active = seenShinyStates.size > 1
val form = species.forms.find { it.name.equals(pokedexForm.displayForm, ignoreCase = true) } ?: species.standardForm
maleRatio = form.maleRatio
@@ -568,13 +562,12 @@ class PokemonInfoWidget(val pX: Int, val pY: Int, val updateForm: (PokedexForm)
genderButton.visible = true
genderButton.active = seenGenders.size > 1
}
genderButton.buttonX = pX + (if (shinyButton.visible) 114F else 126F)
if (CobblemonClient.clientPokedexData.getHighestKnowledgeFor(pokedexEntry) == PokedexEntryProgress.NONE) return
var startPosition = if (shinyButton.visible) 1 else 0
startPosition += if (genderButton.visible || (species.maleRatio == -1F)) 1 else 0
if (CobblemonClient.clientPokedexData.getHighestKnowledgeFor(pokedexEntry) == PokedexEntryProgress.NONE) {
return
}
val startPosition = if (species.maleRatio == -1F) 0 else 1
pokedexEntry.variations.forEachIndexed { index, variation ->
val pos = possibleVariationButtonPositions[index + startPosition]
val button = VariationButtonWrapper(this, pX + pos.first, pY + pos.second)
@@ -582,6 +575,11 @@ class PokemonInfoWidget(val pX: Int, val pY: Int, val updateForm: (PokedexForm)
addWidget(button.getWidget())
variationButtons.add(button)
}
val seenShinyStates = CobblemonClient.clientPokedexData.getSeenShinyStates(pokedexEntry, pokedexForm)
shiny = seenShinyStates.count() == 1 && seenShinyStates.first() == "shiny"
shinyButton.resource = if (shiny) buttonShiny else buttonNone
shinyButton.active = seenShinyStates.size > 1
}
private fun updateType(species: Species, form: FormData) {
@@ -366,7 +366,7 @@ class Summary private constructor(party: Collection<Pokemon?>, private val edita
if (movesWidget is MovesWidget) {
sideScreen = MoveSwapScreen(
x + 216,
y + 23,
y + 24,
movesWidget = movesWidget,
replacedMove = move
).also { switchPane ->
@@ -387,7 +387,7 @@ class Summary private constructor(party: Collection<Pokemon?>, private val edita
EVOLVE -> {
sideScreen = EvolutionSelectScreen(
x + 216,
y + 23,
y + 22,
pokemon = selectedPokemon
)
}
@@ -592,7 +592,6 @@ class Summary private constructor(party: Collection<Pokemon?>, private val edita
override fun mouseDragged(mouseX: Double, mouseY: Double, button: Int, deltaX: Double, deltaY: Double): Boolean {
if (sideScreenIndex == MOVE_SWAP || sideScreenIndex == EVOLVE) sideScreen.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
if (mainScreenIndex == MOVES) mainScreen.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
@@ -13,7 +13,6 @@ import com.cobblemon.mod.common.api.text.bold
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.client.render.drawScaledText
import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetNicknamePacket
import com.cobblemon.mod.common.net.serverhandling.pokemon.update.SetNicknameHandler.MAX_NAME_LENGTH
import com.cobblemon.mod.common.pokemon.Pokemon
import com.mojang.blaze3d.platform.InputConstants
import net.minecraft.client.Minecraft
@@ -29,6 +28,9 @@ class NicknameEntryWidget(
Minecraft.getInstance().font,
x, y, width, height, text
) {
companion object {
private const val MAX_NAME_LENGTH = 12
}
var pokemonName = ""
@@ -32,7 +32,7 @@ abstract class SummaryScrollList<T : ObjectSelectionList.Entry<T>>(
) {
companion object {
const val WIDTH = 108
const val HEIGHT = 112
const val HEIGHT = 111
const val SLOT_WIDTH = 91
private val backgroundResource = cobblemonResource("textures/gui/summary/summary_scroll_background.png")
@@ -71,7 +71,7 @@ abstract class SummaryScrollList<T : ObjectSelectionList.Entry<T>>(
)
context.enableScissor(
x,
y,
y - 1,
x + width,
y + height
)
@@ -25,6 +25,7 @@ import net.minecraft.client.gui.GuiGraphics
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
class InfoWidget(
pX: Int,
pY: Int,
@@ -21,11 +21,14 @@ class MoveDescriptionScrollList(
) : ObjectSelectionList<MoveDescriptionEntry>(
Minecraft.getInstance(),
60, // width
30, // height
28, // height
0, // top
slotHeight
) {
private var scrolling = false
companion object {
const val WIDTH = 108
const val HEIGHT = 111
}
init {
this.y = this.listY
@@ -41,7 +44,7 @@ class MoveDescriptionScrollList(
isHovered = pMouseX >= x && pMouseY >= y && pMouseX < x + width && pMouseY < y + height
context.enableScissor(
x,
y,
y - 1,
x + width,
y + height
)
@@ -49,33 +52,7 @@ class MoveDescriptionScrollList(
context.disableScissor()
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
updateScrollingState(mouseX, mouseY)
if (scrolling) isDragging = true
return isDragging
}
override fun mouseDragged(mouseX: Double, mouseY: Double, button: Int, deltaX: Double, deltaY: Double): Boolean {
if (scrolling) {
if (mouseY < y) {
scrollAmount = 0.0
} else if (mouseY > bottom) {
scrollAmount = maxScroll.toDouble()
} else {
scrollAmount += deltaY
}
}
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
override fun renderListBackground(guiGraphics: GuiGraphics) {}
private fun updateScrollingState(mouseX: Double, mouseY: Double) {
scrolling = mouseX >= getScrollbarPosition().toDouble()
&& mouseX < (getScrollbarPosition() + 3).toDouble()
&& mouseY >= y
&& mouseY < bottom
override fun renderListBackground(guiGraphics: GuiGraphics) {
}
fun setMoveDescription(moveDescription: MutableComponent) {
@@ -105,4 +82,4 @@ class MoveDescriptionScrollList(
addEntry(MoveDescriptionEntry(Component.literal(part)))
}
}
}
}
@@ -67,7 +67,7 @@ class MovesWidget(
private var descriptionScrollList = MoveDescriptionScrollList(
x + 69,
y + 113,
y + 114,
5
)
@@ -218,18 +218,10 @@ class MovesWidget(
descriptionScrollList.setMoveDescription(selectedMove?.description ?: "".text())
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
if (descriptionScrollList.isHovered) descriptionScrollList.mouseClicked(mouseX, mouseY, button)
return super.mouseClicked(mouseX, mouseY, button)
}
override fun mouseScrolled(mouseX: Double, mouseY: Double, horizontalAmount: Double, verticalAmount: Double): Boolean {
if (descriptionScrollList.isHovered) descriptionScrollList.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount)
if (descriptionScrollList.isHovered) {
descriptionScrollList.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount)
}
return super.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount)
}
override fun mouseDragged(mouseX: Double, mouseY: Double, button: Int, deltaX: Double, deltaY: Double): Boolean {
if (descriptionScrollList.isHovered) descriptionScrollList.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
}
@@ -10,7 +10,6 @@ package com.cobblemon.mod.common.client.keybind.keybinds
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork.sendToServer
import com.cobblemon.mod.common.battles.BattleFormat
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.battle.BattleGUI
import com.cobblemon.mod.common.client.keybind.CobblemonBlockingKeyBinding
@@ -78,12 +77,12 @@ object PartySendBinding : CobblemonBlockingKeyBinding(
if (CobblemonClient.storage.selectedSlot != -1 && Minecraft.getInstance().screen == null) {
val pokemon = CobblemonClient.storage.myParty.get(CobblemonClient.storage.selectedSlot)
if (pokemon != null) {
if (pokemon != null && pokemon.currentHealth > 0) {
val targetEntity = player.traceFirstEntityCollision(
entityClass = LivingEntity::class.java,
ignoreEntity = player,
maxDistance = Cobblemon.config.battleSpectateMaxDistance,
collideBlock = ClipContext.Fluid.NONE)
entityClass = LivingEntity::class.java,
ignoreEntity = player,
maxDistance = Cobblemon.config.battleSpectateMaxDistance,
collideBlock = ClipContext.Fluid.NONE)
if (targetEntity == null || (targetEntity is PokemonEntity && targetEntity.ownerUUID == player.uuid)) {
sendToServer(SendOutPokemonPacket(CobblemonClient.storage.selectedSlot))
}
@@ -103,7 +102,7 @@ object PartySendBinding : CobblemonBlockingKeyBinding(
}
is PokemonEntity -> {
if (!entity.canBattle(player) || entity.position().distanceToSqr(player.position()) > Cobblemon.config.battleWildMaxDistance.pow(2)) return
sendToServer(BattleChallengePacket(entity.id, pokemon.uuid, BattleFormat.GEN_9_SINGLES))
sendToServer(BattleChallengePacket(entity.id, pokemon.uuid))
}
}
}
@@ -10,20 +10,11 @@ package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.net.messages.client.battle.BattleChallengeExpiredPacket
import net.minecraft.client.Minecraft
object BattleChallengeExpiredHandler : ClientNetworkPacketHandler<BattleChallengeExpiredPacket> {
override fun handle(packet: BattleChallengeExpiredPacket, client: Minecraft) {
val iter = CobblemonClient.requests.battleChallenges.iterator()
while(iter.hasNext()) {
val entry = iter.next()
val player = entry.key
if (entry.value.requestID == packet.requestID) {
iter.remove()
ClientPlayerIcon.update(player)
}
}
CobblemonClient.requests.onChallengeExpired(packet.battleChallengeId)
}
}
@@ -9,18 +9,33 @@
package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.api.snowstorm.BedrockParticleOptions
import com.cobblemon.mod.common.api.text.yellow
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.battle.ClientBattleChallenge
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.client.particle.BedrockParticleOptionsRepository
import com.cobblemon.mod.common.client.particle.ParticleStorm
import com.cobblemon.mod.common.client.render.MatrixWrapper
import com.cobblemon.mod.common.net.messages.client.battle.BattleChallengeNotificationPacket
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.util.lang
import com.mojang.authlib.minecraft.client.MinecraftClient
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
import net.minecraft.client.multiplayer.ClientLevel
object BattleChallengeNotificationHandler : ClientNetworkPacketHandler<BattleChallengeNotificationPacket> {
override fun handle(packet: BattleChallengeNotificationPacket, client: Minecraft) {
val clientBattleChallenge = ClientBattleChallenge(packet.challengeID, packet.senderID, packet.expiryTime, packet.battleFormat)
packet.challengerIDs.forEach {
CobblemonClient.requests.battleChallenges[it] = clientBattleChallenge
ClientPlayerIcon.update(it)
}
val clientBattleChallenge = ClientBattleChallenge(packet.battleChallengeId, packet.challengerIds, packet.battleFormat)
CobblemonClient.requests.battleChallenges.add(clientBattleChallenge)
client.player?.sendSystemMessage(
lang(
"challenge.receiver",
packet.challengerNames.first(),
lang("battle.types.${packet.battleFormat.battleType.name}"),
).yellow()
)
CobblemonClient.requests.addParticleEffect(clientBattleChallenge)
}
}
@@ -0,0 +1,18 @@
package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.entity.PokemonClientDelegate
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.battle.BattleAppendTargetedEntityPacket
import net.minecraft.client.Minecraft
object BattleSetTargetedEntityHandler : ClientNetworkPacketHandler<BattleAppendTargetedEntityPacket> {
override fun handle(packet: BattleAppendTargetedEntityPacket, client: Minecraft) {
val sourceEntity = Minecraft.getInstance().level?.getEntity(packet.sourceEntityId)
val sourcePokemon = sourceEntity as? PokemonEntity
if (sourcePokemon != null) {
(sourcePokemon.delegate as PokemonClientDelegate).targetedEntityId = packet.targetedEntityId
}
}
}
@@ -11,13 +11,15 @@ package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.ClientMultiBattleTeamMember
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.net.messages.client.battle.TeamJoinNotificationPacket
import net.minecraft.client.Minecraft
object TeamJoinNotificationHandler : ClientNetworkPacketHandler<TeamJoinNotificationPacket> {
override fun handle(packet: TeamJoinNotificationPacket, client: Minecraft) {
CobblemonClient.teamData.multiBattleTeamMembers = packet.teamMemberUUIDs.mapIndexed { index, uuid -> ClientMultiBattleTeamMember(uuid, packet.teamMemberNames[index]) }.toMutableList()
packet.teamMemberUUIDs.forEach { ClientPlayerIcon.update(it) }
// TODO: print something to the client
}
}
@@ -9,11 +9,7 @@
package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.api.text.aqua
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.api.text.yellow
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.net.messages.client.battle.TeamMemberRemoveNotificationPacket
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
@@ -23,28 +19,27 @@ object TeamMemberRemoveNotificationHandler : ClientNetworkPacketHandler<TeamMemb
if(packet.teamMemberUUID == client.player?.uuid) {
// Client removes itself from its team
val members = CobblemonClient.teamData.multiBattleTeamMembers.map { it.uuid }
val memberCount = members.count()
val memberCount = CobblemonClient.teamData.multiBattleTeamMembers.count()
CobblemonClient.teamData.multiBattleTeamMembers.clear()
members.forEach { ClientPlayerIcon.update(it) }
val langKey = if(memberCount > 1) "team.left.self" else "team.disband"
val langKey = if(memberCount > 1) "challenge.multi.team_remove.sender" else "challenge.multi.team_disband"
client.player?.sendSystemMessage(
lang(
langKey,
).red()
)
)
} else {
// Client removes a member from the team
val memberToRemove = CobblemonClient.teamData.multiBattleTeamMembers.find { it.uuid == packet.teamMemberUUID } ?: return
val memberToRemove = CobblemonClient.teamData.multiBattleTeamMembers.find { it.uuid == packet.teamMemberUUID }
CobblemonClient.teamData.multiBattleTeamMembers.remove(memberToRemove)
ClientPlayerIcon.update(memberToRemove.uuid)
client.player?.sendSystemMessage(
lang(
"team.left.other",
memberToRemove.name.copy().aqua(),
).red()
)
if(memberToRemove != null) {
client.player?.sendSystemMessage(
lang(
"challenge.multi.team_remove.receiver",
memberToRemove.name,
)
)
}
}
}
}
@@ -10,13 +10,11 @@ package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.net.messages.client.battle.TeamRequestExpiredPacket
import net.minecraft.client.Minecraft
object TeamRequestExpiredHandler : ClientNetworkPacketHandler<TeamRequestExpiredPacket> {
override fun handle(packet: TeamRequestExpiredPacket, client: Minecraft) {
CobblemonClient.requests.multiBattleTeamRequests.remove(packet.senderID)
ClientPlayerIcon.update(packet.senderID)
CobblemonClient.requests.onMultiChallengeExpired(packet.teamRequestId)
}
}
@@ -10,14 +10,19 @@ package com.cobblemon.mod.common.client.net.battle
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.battle.ClientTeamRequest
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.client.battle.ClientBattleChallenge
import com.cobblemon.mod.common.net.messages.client.battle.TeamRequestNotificationPacket
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
object TeamRequestNotificationHandler : ClientNetworkPacketHandler<TeamRequestNotificationPacket> {
override fun handle(packet: TeamRequestNotificationPacket, client: Minecraft) {
CobblemonClient.requests.multiBattleTeamRequests[packet.senderID] = ClientTeamRequest(packet.requestID, packet.senderID, packet.expiryTime)
ClientPlayerIcon.update(packet.senderID)
CobblemonClient.requests.multiBattleTeamRequests.add(ClientBattleChallenge(packet.teamRequestId, listOf(packet.requesterId)))
client.player?.sendSystemMessage(
lang(
"challenge.multi.team_request.receiver",
packet.requesterName,
)
)
}
}
@@ -19,6 +19,7 @@ import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.net.messages.client.effect.SpawnSnowstormEntityParticlePacket
import net.minecraft.client.Minecraft
import net.minecraft.world.entity.Entity
import kotlin.math.pow
object SpawnSnowstormEntityParticleHandler : ClientNetworkPacketHandler<SpawnSnowstormEntityParticlePacket> {
override fun handle(packet: SpawnSnowstormEntityParticlePacket, client: Minecraft) {
@@ -27,24 +28,72 @@ object SpawnSnowstormEntityParticleHandler : ClientNetworkPacketHandler<SpawnSno
val entity = world.getEntity(packet.entityId) as? PosableEntity ?: return
entity as Entity
val state = entity.delegate as PosableState
val locators = packet.locator.firstNotNullOfOrNull { state.getMatchingLocators(it).takeIf { it.isNotEmpty() } } ?: return
val locator = packet.locator.firstOrNull() { state.locatorStates[it] != null } ?: return
val matrixWrapper = state.locatorStates[locator]!!
val matrixWrappers = locators.mapNotNull { state.locatorStates[it] }
matrixWrappers.forEach { matrixWrapper ->
val particleRuntime = MoLangRuntime().setup().setupClient()
particleRuntime.environment.query.addFunction("entity") { state.runtime.environment.query }
val storm = ParticleStorm(
effect = effect,
matrixWrapper = matrixWrapper,
world = world,
runtime = particleRuntime,
sourceVelocity = { entity.deltaMovement },
sourceAlive = { !entity.isRemoved },
sourceVisible = { !entity.isInvisible },
entity = entity
val particleRuntime = MoLangRuntime().setup().setupClient()
particleRuntime.environment.query.addFunction("entity") { state.runtime.environment.query }
particleRuntime.environment.query.addFunction("point_on_curve") {
//All this just finds a curve that goes through the given points + 0, 0
//And calcs where we are on it at t
val t = it.getDouble(0)
val x1 = it.getDouble(1)
val y1 = it.getDouble(2)
val x2 = it.getDouble(3)
val y2 = it.getDouble(4)
val a0 = 0.0
val a1 = x1.pow(2)
val a2 = x2.pow(2)
val b0 = 0.0
val b1 = x1
val b2 = x2
val c0 = 1.0
val c1 = 1.0
val c2 = 1.0
val d0 = 0.0
val d1 = y1
val d2 = y2
val matrix = arrayOf(
arrayOf(a2, b2, c2, d2),
arrayOf(a1, b1, c1, d1),
arrayOf(a0, b0, c0, d0)
)
storm.spawn()
for (i in 0 until 3) {
var pivot = matrix[i][i]
if (pivot != 0.0) {
for (j in 0 until 4) {
matrix[i][j] /= pivot
}
}
// Make other elements in the current column 0
for (k in 0 until 3) {
if (k != i) {
val factor = matrix[k][i]
for (j in 0 until 4) {
matrix[k][j] -= factor * matrix[i][j]
}
}
}
}
return@addFunction matrix[0][3] * t.pow(2) + matrix[1][3] * t + matrix[2][3]
}
val storm = ParticleStorm(
effect = effect,
matrixWrapper = matrixWrapper,
world = world,
runtime = particleRuntime,
sourceVelocity = { entity.deltaMovement },
sourceAlive = { !entity.isRemoved },
sourceVisible = { !entity.isInvisible },
entity = entity
)
storm.spawn()
}
}
@@ -10,13 +10,11 @@ package com.cobblemon.mod.common.client.net.trade
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.net.messages.client.trade.TradeOfferExpiredPacket
import net.minecraft.client.Minecraft
object TradeOfferExpiredHandler : ClientNetworkPacketHandler<TradeOfferExpiredPacket> {
override fun handle(packet: TradeOfferExpiredPacket, client: Minecraft) {
CobblemonClient.requests.tradeOffers.remove(packet.senderID)
ClientPlayerIcon.update(packet.senderID)
CobblemonClient.requests.onTradeOfferExpired(packet.tradeOfferId)
}
}
@@ -10,14 +10,19 @@ package com.cobblemon.mod.common.client.net.trade
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.client.trade.ClientTradeRequest
import com.cobblemon.mod.common.client.keybind.boundKey
import com.cobblemon.mod.common.client.keybind.keybinds.PartySendBinding
import com.cobblemon.mod.common.client.trade.ClientTradeOffer
import com.cobblemon.mod.common.net.messages.client.trade.TradeOfferNotificationPacket
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
object TradeOfferNotificationHandler : ClientNetworkPacketHandler<TradeOfferNotificationPacket> {
override fun handle(packet: TradeOfferNotificationPacket, client: Minecraft) {
CobblemonClient.requests.tradeOffers[packet.senderID] = ClientTradeRequest(packet.requestID, packet.senderID, packet.expiryTime)
ClientPlayerIcon.update(packet.senderID)
CobblemonClient.requests.tradeOffers.add(ClientTradeOffer(packet.tradeOfferId, packet.traderId))
client.player?.displayClientMessage(
lang("trade.offer", packet.traderName, PartySendBinding.boundKey().displayName),
true
)
}
}
@@ -8,11 +8,9 @@
package com.cobblemon.mod.common.client.net.trade
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.trade.TradeGUI
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.client.trade.ClientTrade
import com.cobblemon.mod.common.net.messages.client.trade.TradeStartedPacket
import com.cobblemon.mod.common.net.messages.client.trade.TradeStartedPacket.TradeablePokemon
@@ -20,7 +18,6 @@ import net.minecraft.client.Minecraft
object TradeStartedHandler : ClientNetworkPacketHandler<TradeStartedPacket> {
override fun handle(packet: TradeStartedPacket, client: Minecraft) {
Cobblemon.LOGGER.error("handle trade start from: " + packet.traderId)
val trade = ClientTrade()
CobblemonClient.trade = trade
Minecraft.getInstance().setScreen(
@@ -32,7 +29,5 @@ object TradeStartedHandler : ClientNetworkPacketHandler<TradeStartedPacket> {
CobblemonClient.storage.myParty.map { it?.let(::TradeablePokemon) }.toMutableList()
)
)
CobblemonClient.requests.tradeOffers.remove(packet.traderId)
ClientPlayerIcon.update(packet.traderId)
}
}
@@ -15,6 +15,7 @@ import com.cobblemon.mod.common.api.snowstorm.BedrockParticleOptions
import com.cobblemon.mod.common.api.snowstorm.ParticleEmitterAction
import com.cobblemon.mod.common.client.render.MatrixWrapper
import com.cobblemon.mod.common.client.render.SnowstormParticle
import com.cobblemon.mod.common.entity.AttackingEntity
import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.particle.SnowstormParticleOptions
@@ -62,6 +63,9 @@ class ParticleStorm(
}
if (entity is PosableEntity) {
runtime.environment.query.addFunction("entity") { entity.struct }
if (entity is AttackingEntity) {
addAttackingFunctions()
}
} else if (entity is Player) {
runtime.environment.query.addFunction("entity") { entity.asMoLangValue() }
}
@@ -76,6 +80,33 @@ class ParticleStorm(
Minecraft.getInstance().particleEngine.add(this)
}
fun addAttackingFunctions(attackingEntity: AttackingEntity) {
attackingEntity as Entity
runtime.environment.query.addFunction("target_deltax") {
val targetedEntity = getEntityById(attackingEntity.getAttackingEntityId())?: return@addFunction 1.0
matrixWrapper.transformWorldToParticle(attackingEntity.position()).x - matrixWrapper.transformWorldToParticle(targetedEntity.position()).x
}
runtime.environment.query.addFunction("target_deltay") {
val targetedEntity = getEntityById(attackingEntity.getAttackingEntityId())?: return@addFunction 1.0
matrixWrapper.transformWorldToParticle(attackingEntity.position()).y - matrixWrapper.transformWorldToParticle(targetedEntity.position()).y
}
runtime.environment.query.addFunction("target_deltaz") {
val targetedEntity = getEntityById(attackingEntity.getAttackingEntityId())?: return@addFunction 1.0
matrixWrapper.transformWorldToParticle(attackingEntity.position()).z - matrixWrapper.transformWorldToParticle(targetedEntity.position()).z
}
runtime.environment.query.addFunction("target_distance") {
val targetedEntity = getEntityById(attackingEntity.getAttackingEntityId())?: return@addFunction 2.0
targetedEntity.position().distanceTo(attackingEntity.position())
}
}
private fun getEntityById(entityId: Int?): Entity? {
if (entityId != null) {
Minecraft.getInstance().level?.getEntity(entityId)
}
return null
}
fun getX() = x
fun getY() = y
fun getZ() = z
@@ -1,164 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.render
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.requests.ClientPlayerActionRequest
import com.cobblemon.mod.common.client.ClientMultiBattleTeamMember
import com.cobblemon.mod.common.platform.events.RenderEvent
import com.cobblemon.mod.common.util.cobblemonResource
import com.mojang.blaze3d.systems.RenderSystem
import com.mojang.blaze3d.vertex.*
import com.mojang.math.Axis
import net.minecraft.client.Camera
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.GameRenderer
import net.minecraft.resources.ResourceLocation
import net.minecraft.util.Mth
import net.minecraft.world.entity.EntityAttachment
import net.minecraft.world.entity.player.Player
import org.joml.Matrix4f
import java.util.*
/**
* Visual notification rendered above a player's nametag for [ClientMultiBattleTeamMember]s and unanswered [ClientPlayerActionRequest]s.
*
* @param expiryTime The amount of time (in seconds) this icon is valid.
*
* @author Segfault Guy
* @since September 1st, 2024
*/
abstract class ClientPlayerIcon(expiryTime: Int? = null) {
/** The texture to use for the icon. */
open val texture: ResourceLocation = cobblemonResource("textures/particle/request/icon_exclamation.png")
/** The offset of the icon from the player's head. */
open val Y_OFFSET = 1.5F
open val SCALE = 0.75F
private val FADE_RATIO = 0.25F
private val tickCount get() = Minecraft.getInstance().player?.tickCount ?: 0 // icon is only ticked when tracked, so derive lifetime from player tick - startTick
private val startTick = Minecraft.getInstance().player?.tickCount ?: 0
private val tickRateManager = Minecraft.getInstance().level!!.tickRateManager()
/** The tick at which the icon begins fading. */
private val fadeTickStamp = expiryTime?.let { it * tickRateManager.tickrate() * (1 - FADE_RATIO) + startTick}?.toInt() ?: Int.MAX_VALUE // TODO is server expiration based on epoc going to cause a problem?
/** Duration (in ticks) of the fade transition. */
open val fadeDuration = 30
/** How long (in ticks) the icon has been fading. */
private var fadeCount = 0
private val fading get() = tickCount >= fadeTickStamp
private var fadeOut = true
set(value) {
fadeCount = 0
field = value
}
private val MAX_ALPHA = 1F
private val MIN_ALPHA = 0.15F // MC fragment shaders won't draw textures with < 0.1 alpha and the sudden cutoff from 0.1 to 0 and vice versa is jarring
private var alpha = 1F
private val startAlpha get() = if (fadeOut) MAX_ALPHA else MIN_ALPHA
private val finalAlpha get() = if (fadeOut) MIN_ALPHA else MAX_ALPHA
fun onTick() {
if (!fading) return else fadeCount++
if (fadeCount == fadeDuration) fadeOut = !fadeOut // toggle transition
// alpha changed outside of render deltaticks so fade does not freeze off screen
alpha = Mth.lerp(fadeCount.toFloat()/fadeDuration, startAlpha, finalAlpha)
}
fun render(player: Player) {
if (CobblemonClient.battle != null) return
DeferredRenderer.enqueue(RenderEvent.Stage.TRANSLUCENT) { event ->
val poseStack = event.poseStack
val partialTicks = event.tickCounter.getGameTimeDeltaPartialTick(!tickRateManager.isEntityFrozen(player))
val camera = event.camera
poseStack.pushPose()
positionTag(player, poseStack, camera, partialTicks)
drawTag(poseStack)
poseStack.popPose()
}
}
/** Offsets and billboards the quad above the player. */
protected open fun positionTag(player: Player, poseStack: PoseStack, camera: Camera, partialTicks: Float) {
// position
val vec3 = player.attachments.getNullable(EntityAttachment.NAME_TAG, 0, player.getViewYRot(partialTicks))
poseStack.translate(player.getPosition(partialTicks).x, player.getPosition(partialTicks).y, player.getPosition(partialTicks).z)
poseStack.translate(vec3!!.x, vec3.y + Y_OFFSET, vec3.z)
poseStack.translate(-camera.position.x, -camera.position.y, -camera.position.z) // event posestack does not have PlayerRenderer context
// billboard
val entityRenderDispatcher = Minecraft.getInstance().entityRenderDispatcher
poseStack.mulPose(Axis.YP.rotationDegrees((180f - entityRenderDispatcher.camera.yRot)))
poseStack.scale(SCALE, -SCALE, SCALE)
}
/** Constructs the vertices for the rendered quad. */
protected open fun buildTag(model: Matrix4f, vertices: VertexConsumer) {
vertices.addVertex(model, -0.5f, 0f, 0f).setUv(0f, 0f).setColor(1f, 1f, 1f, 1f)
vertices.addVertex(model, -0.5f, 1f, 0f).setUv(0f, 1f).setColor(1f, 1f, 1f, 1f)
vertices.addVertex(model, 0.5f, 1f, 0f).setUv(1f, 1f).setColor(1f, 1f, 1f, 1f)
vertices.addVertex(model, 0.5f, 0f, 0f).setUv(1f, 0f).setColor(1f, 1f, 1f, 1f)
}
/** Sets the shading and gl states of the quad then queues for drawing. */
private fun drawTag(poseStack: PoseStack) {
// texture
RenderSystem.setShader { GameRenderer.getPositionTexColorShader() }
RenderSystem.setShaderTexture(0, texture)
RenderSystem.setShaderColor(1f, 1f, 1f, alpha)
// gl states
RenderSystem.enableBlend()
RenderSystem.defaultBlendFunc()
RenderSystem.enableDepthTest()
// TODO worth making a custom rendertype and getting buffer from multiBufferSource?
val model = poseStack.last().pose()
val buffer = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR)
buildTag(model, buffer)
BufferUploader.drawWithShader(buffer.buildOrThrow())
// undo
RenderSystem.disableBlend()
RenderSystem.disableDepthTest()
RenderSystem.setShaderColor(1f, 1f, 1f, 1f)
}
companion object {
private val trackedIcons = mutableMapOf<UUID, ClientPlayerIcon>()
fun onTick() = trackedIcons.values.forEach { it.onTick() }
/** Updates the icon that is rendered above the player. */
fun update(player: UUID) {
val teamIcon = CobblemonClient.teamData.multiBattleTeamMembers.find { it.uuid == player }
val requests = CobblemonClient.requests.getRequestsFrom(player).filterIsInstance<ClientPlayerIcon>()
if (requests.isNotEmpty()) {
val icon = requests.minBy { it.fadeTickStamp } // icon that expires the soonest has priority
trackedIcons[player] = icon
}
else if (teamIcon != null) {
trackedIcons[player] = teamIcon
}
else {
trackedIcons.remove(player)
}
}
// TODO make some api so this is expandable? i cant be assed right now
fun clear() = trackedIcons.clear()
fun onRenderPlayer(player: Player) = trackedIcons[player.uuid]?.render(player)
}
}
@@ -1,44 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.render
import com.cobblemon.mod.common.platform.events.PlatformEvents
import com.cobblemon.mod.common.platform.events.RenderEvent
/**
* Maintains a queue of [RenderEventConsumer]s for renders that need to be deferred until the specified [RenderEvent.Stage]
* occurs in the level renderer.
*
* Useful for changing the order of a render.
*
* @author Segfault Guy
* @since September 11th, 2024
*/
object DeferredRenderer {
private val renderQueues = HashMap<RenderEvent.Stage, ArrayDeque<RenderEventConsumer>>()
fun enqueue(stage: RenderEvent.Stage, consumer: RenderEventConsumer) = renderQueues.computeIfAbsent(stage) { ArrayDeque() }.add(consumer)
fun clear(stage: RenderEvent.Stage) = renderQueues[stage]?.clear()
fun clearAll() = renderQueues.clear()
init {
PlatformEvents.RENDER.subscribe { event ->
val queue = renderQueues[event.stage] ?: return@subscribe
while (queue.isNotEmpty()) {
queue.first().invoke(event)
queue.removeFirst()
}
}
}
}
typealias RenderEventConsumer = (RenderEvent) -> Unit
@@ -33,4 +33,5 @@ class MatrixWrapper {
fun getOrigin() = position.add(matrix.getOrigin())
fun transformPosition(position: Vec3) = this.position.add(matrix.transformPosition(position))
fun transformWorldToParticle(position: Vec3) = Matrix4f(matrix).invertAffine().transformPosition(position.subtract(this.position))
}

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