Compare commits

..
Author SHA1 Message Date
MeAlam1 27344f3862 License 2026-12-03 11:45:38 +01:00
MeAlam1 d557648519 Entire Foundation of Poke Radar
Oops, Sorry for not commiting
2026-12-02 23:02:23 +01:00
MeAlam1 119a352c1e Merge branch 'main' into wheres-that-pokemon 2026-12-02 21:09:08 +01:00
Polymeta 0922d4a37b Merge branch 'implement_pokemon' into 'main'
locators added to smeargle

See merge request cable-mc/cobblemon!2524
2026-11-28 23:50:18 +00:00
Sterrezo 866f210baf Added stepsounds to Salamence 2026-11-29 00:30:42 +01:00
Sterrezo f2957756ce Added stepsounds to Tropius, updated Flygon stepsounds 2026-11-29 00:19:17 +01:00
Sterrezo 0f4bd480fa Added stepsounds to Altaria 2026-11-29 00:08:20 +01:00
Sterrezo 83fb781f65 Added stepsounds to Flygon 2026-11-29 00:00:53 +01:00
Sterrezo 0941d50aaf Added stepsounds to Camerupt 2026-11-28 23:04:38 +01:00
Sterrezo 63c43fc41a Added stepsounds to Slaking 2026-11-26 16:12:09 +01:00
Sterrezo 8450681b54 Added stepsounds to Skarmory 2026-11-26 16:05:21 +01:00
Sterrezo 003c3b39ab Added stepsounds to Mantine 2026-11-26 15:58:40 +01:00
Sterrezo f9c7e38db4 Update ursaring.animation.json 2026-11-26 15:43:16 +01:00
Sterrezo c5421bc92a Added stepsounds to Ursaring 2026-11-26 15:42:29 +01:00
Sterrezo 1533bf8e41 Added stepsounds to Heracross 2026-11-26 15:30:42 +01:00
Sterrezo a016188534 Added stepsounds to Girafarig, fixed doubled Dragonite stepsounds 2026-11-25 21:57:28 +01:00
Sterrezo a100a3adf1 Revoked stepsound privileges from Crobat 2026-11-25 21:42:52 +01:00
Sterrezo d847e9e23b Stepsound volume rebalancing 2026-11-25 21:38:01 +01:00
Sterrezo 45fdaf43ea Added stepsounds to Ariados 2026-11-25 21:29:24 +01:00
Sterrezo dea8c56226 Added stepsounds to Draognite 2026-11-25 17:05:19 +01:00
Sterrezo 98e4232239 Update aerodactyl.animation.json 2026-11-25 16:55:17 +01:00
Sterrezo 65559b86c8 Added stepsounds to Aerodactyl 2026-11-25 16:53:30 +01:00
Sterrezo fdb2957844 Added stepsounds to Lapras 2026-11-25 16:41:02 +01:00
Hiroku 99e72339db Remove rogue println, closes #2147 2026-11-08 10:32:42 +10:00
ewwww 396b31e530 locators added to smeargle 2026-11-07 13:30:33 -05:00
Hiroku 10c9931d2c Merge branch 'weight-tweak-tweak' into 'main'
add `spawnable_position` to weight rule component's "weight" expression

Closes #2145

See merge request cable-mc/cobblemon!2521
2026-11-07 08:20:09 +00:00
Hiroku 0e55165570 Merge branch 'main' into 'main'
Main - fixs #2142, unown name issue.

See merge request cable-mc/cobblemon!2523
2026-11-07 08:19:02 +00:00
Matthew Baerg b6b87621a5 Update file CHANGELOG.md 2026-11-07 04:42:37 +00:00
Matthew Baerg 71b01d562b Update file CHANGELOG.md 2026-11-07 04:39:00 +00:00
Matthew Baerg 21eb66e69b Update file unown.json 2026-11-07 03:31:36 +00:00
Matthew Baerg 8b04e57a1d Update file unown.json 2026-11-07 02:35:21 +00:00
Hiroku 1ff3b7ee96 Updated molang dep for some library fixes 2026-11-07 12:07:03 +10:00
spacky 8a2d6096e3 update changelog 2026-11-03 09:02:01 -08:00
spacky 2645b5e375 add spawnable_position to weight rule component's "weight" expression 2026-11-03 08:03:14 -08:00
Polymeta 99e0a26d7b Merge branch 'compat-improvements' into 'main'
teeny fixes to compat

See merge request cable-mc/cobblemon!2520
2026-11-02 09:17:39 +00:00
dhi_holo 71753df513 Leftovers
Also a slight fix to the order in changelog
2026-11-02 13:30:23 +10:00
dhi_holo 729f080f6e Merge branch 'main' into compat-improvements 2026-11-02 13:26:43 +10:00
dhi_holo 13eb57afb1 category fix
Fixing one recipe category I missed teehee
2026-11-02 13:23:42 +10:00
Jackson Bowes 72b6cb06ff Merge branch 'soon-to-be-implemented-steps' into 'main'
Implementing some steps

See merge request cable-mc/cobblemon!2519
2026-11-01 08:15:06 -06:00
Jackson Bowes 74a57eb972 Merge branch 'sterr/move-sound-implementation' into 'main'
Added sounds to Gigaton Hammer and Pyro Ball

See merge request cable-mc/cobblemon!2518
2026-11-01 08:14:14 -06:00
Sterrezo 7246c7f8e6 Update CHANGELOG.md 2026-11-01 13:22:32 +01:00
Sterrezo cd05f741ae Merge branch 'main' into soon-to-be-implemented-steps 2026-11-01 13:21:23 +01:00
Sterrezo 00222d929d Added sounds to Gigaton Hammer and Pyro Ball 2026-11-01 13:18:22 +01:00
Polymeta b8f4637cb3 Merge branch 'feat/power-ride-training' into 'main'
power bracer ride stat training

See merge request cable-mc/cobblemon!2503
2026-10-31 12:33:22 +00:00
Ronak Chavva 9f572250f5 fix(*): modularization 2026-10-31 06:59:37 -05:00
Ronak Chavva 0927d6fa43 fix(*): enum change, configurable item stat 2026-10-31 06:26:45 -05:00
Ronak Chavva a293b3d71f changelog additions 2026-10-31 05:09:36 -05:00
Ronak Chavva 162b1cc68f Merge branch 'main' of https://gitlab.com/ronakch8/cobblemon into feat/power-ride-training 2026-10-31 05:07:29 -05:00
Ronak Chavva 066a6b56f7 Merge branch 'main' of https://gitlab.com/ronakch8/cobblemon into feat/power-ride-training 2026-10-23 18:13:32 -05:00
Ronak Chavva 7687833add mapping rewrite 2026-10-22 21:35:48 -05:00
Ronak Chavva cb9ba82fcc holding power bracer while riding, 1 to all 5 stats 2026-10-22 03:11:14 -05:00
MeAlam1 674ade41b1 Cleanup 2026-10-14 22:04:59 +02:00
MeAlam1 0c5d228a11 Broken, but something 2026-10-14 19:07:04 +02:00
MeAlam1 5831cb30d3 Merge branch 'main' into wheres-that-pokemon 2026-10-14 12:46:41 +02:00
MeAlam1 5cb933f555 Empty GUI 2026-10-14 12:46:35 +02:00
Sterrezo 4221993f7d Added stepsounds to Mr. Mime 2026-10-03 14:39:21 +02:00
Sterrezo a616c25c8c Added stepsounds to Parasect 2026-09-30 14:45:00 +02:00
Sterrezo 6ce4bf5673 Added stepsounds to Rhyhorn 2026-09-30 14:34:07 +02:00
Sterrezo 1b652ba99f Added stepsounds to Rhydron 2026-09-30 14:01:50 +02:00
Sterrezo 11b59df386 Added stepsounds to Dewgong 2026-09-28 20:20:16 +02:00
MeAlam1 2505d51744 Added the Blank Items 2026-09-28 16:29:45 +02:00
Sterrezo ac2b068bf3 Added stepsounds to Blastoise 2026-09-28 14:06:42 +02:00
Sterrezo 8e8f346e52 Added stepsounds keyframes to Venusaur 2026-09-28 13:47:47 +02:00
421 changed files with 6349 additions and 4793 deletions

No files matched your search

+21 -21
View File
@@ -1,35 +1,35 @@
# Changelog
## [1.9.0 (MONTH xth, 2026)](#1-9-0)
## [1.8.5 (MONTH xth, 2026)](#1-8-5)
### Additions
- Trainer bags and packs got added
- You can craft and equip those to store additional items
- Added the `healersSetSpawn` gamerule. When enabled, using a healing machine will set your spawnpoint.
- A Pokémon holding a Power item now gains 1 point in the corresponding riding stat every two minutes while being ridden. The interval is configurable, and can be disabled with `-1`.
- Added sounds to Gigaton Hammer and Pyro Ball
- Certain Pokémon now have custom, animation-driven footstep sounds that change based on the surface! We're slowly working on adding them to all animated Pokémon, but for now we've covered most that are rideable.
- Added footstep sounds to Venusaur, Blastoise, Dewgong, Rhydon, Rhyhorn, Parasect, Mr. Mime, Lapras, Aerodactyl, Dragonite, Ariados, Girafarig, Heracross, Ursaring, Mantine, Skarmory, Slaking, Camerupt, Flygon, Altaria, Tropius and Salamence.
### Changes
- Trading has been overhauled to allow offering multiple Pokémon, up to the entire party, in a single trade
- Selected Pokémon are now highlighted in both parties with new party slot assets
- Hovering an offered Pokémon now shows its summary, and clicking the active Pokémon no longer exits the summary view
- The trade animation now moves the offered Pokémon towards the Poké Ball
- Parties are compacted after a trade so no empty slots are left between Pokémon
- Amethyst now grows from Typegem core blocks like typegems do
- Updated the recipe category for the Create compatibility EXP Candy recipe
- Added No Man's Lands' Honeyed Apple to the Leaves Leftovers tag
- Updated Unown's punctuation form names from `!` and `?` to `Exclamation` and `Question`, changing their visible form labels in tooltips and mod integrations.
- Pokémon that received footstep sounds this update no longer make the usual Minecraft footstep sounds. Footstep sounds have also been removed for Crobat. (Note, game event detection like with Sculk Sensors still functions as normal.)
### Fixes
- Fixed Ponigiri food values for AppleSkin integration
- Fixed errors emitted by typos in Parched Peat bog structure files
- Fixed Unown punctuation forms (? and !) resolving to duplicate Showdown IDs and colliding in form displays.
### Developer
- Trade network packets (`TradeUpdatedPacket`, `UpdateTradeOfferPacket`, and `TradeCompletedPacket`) now receive an array of Pokémon instead of a single Pokémon to execute trades
- `TradeEvent.Pre` and `TradeEvent.Post` now expose every Pokémon each participant receives (`tradeParticipant1Pokemon` and `tradeParticipant2Pokemon` are now lists), and their Molang context includes `trade_participant_1_pokemon_list` and `trade_participant_2_pokemon_list`
- Fixed JsonArray to MoValue conversion not working properly.
### Molang & Datapacks
- `bag_categories` got added which control what kind of tabs and capabilities the Trainerbags have
```json
{
"order": 1,
"icon": "cobblemon:textures/item/medicine/potion.png",
"whiteListTag": "cobblemon:bag/whitelist_consumables",
"blackListTag": "cobblemon:bag/blacklist_consumables",
"maxCount": 512
}
```
- Bunch of default tags as white/blacklist got added to control what can be inserted the corresponding bag categories
- `q.is_standing_on_blocks` now properly checks for non-full blocks like slabs, Mud or Soul Sand.
- Added Molang functions to play footstep sounds based on the corresponding surface. These are intended to be used by Pokémon animations.
- Pokémon can now have their Minecraft footstep sounds silenced in their poser. This doesn't affect emitting game events.
- Fixed the Molang coalescing operator not working the way you'd expect a coalesce operator to.
- Added `v.spawnable_position` to the weight spawn rule component's "weight" expression
- Pokémon can now have their Minecraft footstep sounds silenced in their species file. This doesn't affect emitting game events.
### Particles
@@ -1,16 +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.bag;
import com.cobblemon.mod.common.item.bag.CobblemonBagContainer;
public interface BagEntity {
CobblemonBagContainer cobblemon$getBagContainer();
void cobblemon$setBagContainer(CobblemonBagContainer bagContainer);
}
@@ -23,8 +23,6 @@ import com.cobblemon.mod.common.api.tags.CobblemonItemTags;
import com.cobblemon.mod.common.duck.PlayerDuck;
import com.cobblemon.mod.common.duck.RidePassenger;
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity;
import com.cobblemon.mod.common.bag.BagEntity;
import com.cobblemon.mod.common.item.bag.CobblemonBagContainer;
import com.cobblemon.mod.common.pokedex.scanner.PokedexEntityData;
import com.cobblemon.mod.common.pokedex.scanner.ScannableEntity;
import com.cobblemon.mod.common.pokemon.FormData;
@@ -58,7 +56,6 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import org.objectweb.asm.Opcodes;
@@ -76,7 +73,7 @@ import java.util.*;
import java.util.stream.Collectors;
@Mixin(Player.class)
public abstract class PlayerMixin extends LivingEntity implements ScannableEntity, OrientationControllable, PlayerDuck, RidePassenger, BagEntity {
public abstract class PlayerMixin extends LivingEntity implements ScannableEntity, OrientationControllable, PlayerDuck, RidePassenger {
@Unique
private Vector3f cobblemon$driverInput;
@@ -110,8 +107,6 @@ public abstract class PlayerMixin extends LivingEntity implements ScannableEntit
@Unique private Vec3 cobblemon$rideEyePos = Vec3.ZERO;
@Unique private CobblemonBagContainer cobblemon$cobblemonBagContainer = new CobblemonBagContainer();
protected PlayerMixin(EntityType<? extends LivingEntity> p_20966_, Level p_20967_) {
super(p_20966_, p_20967_);
}
@@ -409,37 +404,4 @@ public abstract class PlayerMixin extends LivingEntity implements ScannableEntit
original.call(target, strength, x, z);
}
@Override @NotNull
public CobblemonBagContainer cobblemon$getBagContainer() { return cobblemon$cobblemonBagContainer; }
@Override
public void cobblemon$setBagContainer(CobblemonBagContainer bagContainer) { cobblemon$cobblemonBagContainer = bagContainer; }
@Inject(
method = "readAdditionalSaveData(Lnet/minecraft/nbt/CompoundTag;)V",
at = @At("TAIL")
)
private void cobblemon$readAdditionalSaveData(CompoundTag compound, CallbackInfo ci) {
if (compound.contains("CobblemonBagData", 9)) {
this.cobblemon$cobblemonBagContainer.fromTag(compound.getList("CobblemonBagData", 10), this.registryAccess());
}
}
@Inject(
method = "addAdditionalSaveData(Lnet/minecraft/nbt/CompoundTag;)V",
at = @At("TAIL")
)
private void cobblemon$addAdditionalSaveData(CompoundTag compound, CallbackInfo ci) {
compound.put("CobblemonBagData", this.cobblemon$cobblemonBagContainer.createTag(this.registryAccess()));
}
@Inject(
method = "dropEquipment()V",
at = @At("TAIL")
)
private void cobblemon$dropCobblemonBag(CallbackInfo ci) {
if (level().getGameRules().getBoolean(CobblemonGameRules.BAG_DROP_ITEMS)) {
this.cobblemon$cobblemonBagContainer.dropAll((Player)(Object)this);
}
}
}
@@ -18,7 +18,6 @@ import com.cobblemon.mod.common.api.stats.CobblemonStats;
import com.cobblemon.mod.common.block.HealingMachineBlock;
import com.cobblemon.mod.common.duck.ServerLevelDuck;
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity;
import com.cobblemon.mod.common.bag.BagEntity;
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
@@ -164,12 +163,4 @@ public abstract class ServerPlayerMixin implements PlayerSpawnerAccessor {
cir.setReturnValue(HealingMachineBlock.Companion.findStandUpPosition(EntityType.PLAYER, level, pos).map((vec3) -> ServerPlayer.RespawnPosAngle.of(vec3, pos)));
}
}
@Inject(
method = "restoreFrom",
at = @At("TAIL")
)
private void cobblemon$restoreCobblemonBag(ServerPlayer that, boolean keepEverything, CallbackInfo ci) {
((BagEntity)(Object)this).cobblemon$setBagContainer(((BagEntity)that).cobblemon$getBagContainer());
}
}
@@ -115,6 +115,10 @@ import com.cobblemon.mod.common.pokemon.properties.NoAIProperty
import com.cobblemon.mod.common.pokemon.properties.UnaspectPropertyType
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
import com.cobblemon.mod.common.pokemon.stat.CobblemonStatProvider
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import com.cobblemon.mod.common.pokeradar.PokeRadarManager.REVEAL_CHECK_INTERVAL
import com.cobblemon.mod.common.pokeradar.PokeRadarManager.revealEncryptedNavpoints
import com.cobblemon.mod.common.pokeradar.PokeRadarTracker
import com.cobblemon.mod.common.starter.CobblemonStarterHandler
import com.cobblemon.mod.common.util.*
import com.cobblemon.mod.common.world.feature.CobblemonPlacedFeatures
@@ -252,8 +256,12 @@ object Cobblemon {
it.requestWallpapers()
sendServerSettingsPacketToPlayer(it)
}
PlatformEvents.SERVER_PLAYER_LOGIN.subscribe {
PokeRadarManager.sync(it.player)
}
PlatformEvents.SERVER_PLAYER_LOGOUT.subscribe {
PCLinkManager.removeLink(it.player.uuid)
PokeRadarTracker.forget(it.player.uuid)
BattleRegistry.onPlayerDisconnect(it.player)
storage.onPlayerDisconnect(it.player)
playerDataManager.onPlayerDisconnect(it.player)
@@ -265,6 +273,8 @@ object Cobblemon {
}
PlatformEvents.PLAYER_DEATH.subscribe {
PCLinkManager.removeLink(it.player.uuid)
PokeRadarManager.data(it.player).apply { chainSpecies = null; chainCount = 0 }
PokeRadarManager.sync(it.player)
battleRegistry.getBattleByParticipatingPlayer(it.player)?.stop()
}
@@ -287,6 +297,7 @@ object Cobblemon {
PlatformEvents.CHANGE_DIMENSION.subscribe {
it.player.party().forEach { pokemon -> pokemon.entity?.recallWithAnimation() }
PokeRadarTracker.stop(it.player)
}
// Lowest priority because this applies after luxury ball bonus as of gen 4
@@ -365,9 +376,13 @@ object Cobblemon {
isDedicatedServer = true
}
PlatformEvents.SERVER_TICK_POST.subscribe {
PlatformEvents.SERVER_TICK_POST.subscribe { event ->
ServerTaskTracker.update(1/20F)
ServerRealTimeTaskTracker.update()
PokeRadarTracker.tick(event.server)
if (event.server.tickCount % REVEAL_CHECK_INTERVAL == 0) {
event.server.playerList.players.forEach(::revealEncryptedNavpoints)
}
}
PlatformEvents.SERVER_TICK_PRE.subscribe {
ServerRealTimeTaskTracker.update()
@@ -463,6 +478,7 @@ object Cobblemon {
battleRegistry.onServerStarted()
}
PlatformEvents.SERVER_TICK_POST.subscribe { ServerTickHandler.onTick(it.server) }
PokeRadarManager.register()
BagItems.observable.subscribe {
LOGGER.info("Starting dummy Showdown battle to force it to pre-load data.")
@@ -10,7 +10,6 @@ package com.cobblemon.mod.common
import com.cobblemon.mod.common.api.apricorn.Apricorn
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.types.ElementalTypes
import com.cobblemon.mod.common.block.*
import com.cobblemon.mod.common.block.LecternBlock
import com.cobblemon.mod.common.block.MintBlock.MintType
@@ -29,7 +28,6 @@ import com.cobblemon.mod.common.block.sign.CobblemonWallHangingSignBlock
import com.cobblemon.mod.common.block.sign.CobblemonWallSignBlock
import com.cobblemon.mod.common.block.tmmachine.TMMachineBlock
import com.cobblemon.mod.common.block.general.MintLitterBlock
import com.cobblemon.mod.common.block.typeplate.TypePlateBlock
import com.cobblemon.mod.common.mixin.invoker.BlocksInvoker
import com.cobblemon.mod.common.mixin.invoker.DoorBlockInvoker
import com.cobblemon.mod.common.mixin.invoker.FireBlockInvoker
@@ -475,134 +473,6 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
@JvmField
val DUSK_STONE_BLOCK = this.create("dusk_stone_block", Block(BlockBehaviour.Properties.of().mapColor(MapColor.WARPED_HYPHAE).strength(1.0F).sound(CobblemonSounds.EVOLUTION_STONE_BLOCK_SOUNDS).requiresCorrectToolForDrops().instrument(NoteBlockInstrument.BIT)))
@JvmField
val BLANK_PLATE = this.create("blank_plate",
TypePlateBlock(
BlockBehaviour.Properties.of().strength(1.0F).sound(SoundType.METAL).requiresCorrectToolForDrops().noOcclusion()
.lightLevel { if (it.getValue(TypePlateBlock.ACTIVATED)) 6 else 0 },
ElementalTypes.NORMAL
)
)
@JvmField
val FLAME_PLATE = this.create("flame_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.FIRE
)
)
@JvmField
val SPLASH_PLATE = this.create("splash_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.WATER
)
)
@JvmField
val ZAP_PLATE = this.create("zap_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.ELECTRIC
)
)
@JvmField
val MEADOW_PLATE = this.create("meadow_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.GRASS
)
)
@JvmField
val ICICLE_PLATE = this.create("icicle_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.ICE
)
)
@JvmField
val FIST_PLATE = this.create("fist_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.FIGHTING
)
)
@JvmField
val TOXIC_PLATE = this.create("toxic_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.POISON
)
)
@JvmField
val EARTH_PLATE = this.create("earth_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.GROUND
)
)
@JvmField
val SKY_PLATE = this.create("sky_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.FLYING
)
)
@JvmField
val MIND_PLATE = this.create("mind_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.PSYCHIC
)
)
@JvmField
val INSECT_PLATE = this.create("insect_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.BUG
)
)
@JvmField
val STONE_PLATE = this.create("stone_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.ROCK
)
)
@JvmField
val SPOOKY_PLATE = this.create("spooky_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.GHOST
)
)
@JvmField
val DRACO_PLATE = this.create("draco_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.DRAGON
)
)
@JvmField
val DREAD_PLATE = this.create("dread_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.DARK
)
)
@JvmField
val IRON_PLATE = this.create("iron_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.STEEL
)
)
@JvmField
val PIXIE_PLATE = this.create("pixie_plate",
TypePlateBlock(
BlockBehaviour.Properties.ofFullCopy(BLANK_PLATE),
ElementalTypes.FAIRY
)
)
@JvmField
val BLACK_APRICORN = apricornBlock("black_apricorn", Apricorn.BLACK)
@JvmField
@@ -124,6 +124,8 @@ interface CobblemonImplementation {
*/
fun registerMobEffects()
fun registerLootItemFunctions()
/**
* Add a feature to the current platform implementation.
@@ -99,6 +99,12 @@ object CobblemonItemComponents : PlatformRegistry<Registry<DataComponentType<*>>
.networkSynchronized(ByteBufCodecs.BOOL)
.build())
@JvmField
val NAV_CHIP: DataComponentType<NavChipComponent> = create("nav_chip", DataComponentType.builder<NavChipComponent>()
.persistent(NavChipComponent.CODEC)
.networkSynchronized(NavChipComponent.PACKET_CODEC)
.build())
fun register() {
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:pokemon_item"), POKEMON_ITEM)
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:bait"), BAIT)
@@ -23,10 +23,10 @@ import com.cobblemon.mod.common.block.MintBlock
import com.cobblemon.mod.common.block.MintBlock.MintType
import com.cobblemon.mod.common.block.campfirepot.CampfirePotColor
import com.cobblemon.mod.common.client.pokedex.PokedexType
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.entity.boat.CobblemonBoatType
import com.cobblemon.mod.common.item.*
import com.cobblemon.mod.common.item.armor.CobblemonArmorTrims
import com.cobblemon.mod.common.item.bag.CobblemonBagItem
import com.cobblemon.mod.common.item.battle.DireHitItem
import com.cobblemon.mod.common.item.battle.GuardSpecItem
import com.cobblemon.mod.common.item.battle.XStatItem
@@ -189,6 +189,29 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
val POKEDEX_BLACK = pokedexItem(PokedexType.BLACK)
@JvmField
val POKEDEX_WHITE = pokedexItem(PokedexType.WHITE)
val pokeradars = mutableListOf<PokeRadarItem>()
@JvmField
val POKERADAR_RED = pokeradarItem(PokeRadarType.RED)
@JvmField
val POKERADAR_YELLOW = pokeradarItem(PokeRadarType.YELLOW)
@JvmField
val POKERADAR_GREEN = pokeradarItem(PokeRadarType.GREEN)
@JvmField
val POKERADAR_BLUE = pokeradarItem(PokeRadarType.BLUE)
@JvmField
val POKERADAR_PINK = pokeradarItem(PokeRadarType.PINK)
@JvmField
val POKERADAR_BLACK = pokeradarItem(PokeRadarType.BLACK)
@JvmField
val POKERADAR_WHITE = pokeradarItem(PokeRadarType.WHITE)
@JvmField
val BLANK_NAV_CHIP = create("blank_nav_chip", NavChipItem(encrypted = false))
@JvmField
val NAV_CHIP = create("nav_chip", NavChipItem(encrypted = false))
@JvmField
val ENCRYPTED_NAV_CHIP = create("encrypted_nav_chip", NavChipItem(encrypted = true))
val campfire_pots = mutableListOf<CampfirePotItem>()
@JvmField
@@ -1212,43 +1235,6 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
@JvmField
val BLACK_TUMBLESTONE_BLOCK = blockItem("black_tumblestone_block", CobblemonBlocks.BLACK_TUMBLESTONE_BLOCK)
@JvmField
val BLANK_PLATE = blockItem("blank_plate", CobblemonBlocks.BLANK_PLATE)
@JvmField
val FLAME_PLATE = blockItem("flame_plate", CobblemonBlocks.FLAME_PLATE)
@JvmField
val SPLASH_PLATE = blockItem("splash_plate", CobblemonBlocks.SPLASH_PLATE)
@JvmField
val ZAP_PLATE = blockItem("zap_plate", CobblemonBlocks.ZAP_PLATE)
@JvmField
val MEADOW_PLATE = blockItem("meadow_plate", CobblemonBlocks.MEADOW_PLATE)
@JvmField
val ICICLE_PLATE = blockItem("icicle_plate", CobblemonBlocks.ICICLE_PLATE)
@JvmField
val FIST_PLATE = blockItem("fist_plate", CobblemonBlocks.FIST_PLATE)
@JvmField
val TOXIC_PLATE = blockItem("toxic_plate", CobblemonBlocks.TOXIC_PLATE)
@JvmField
val EARTH_PLATE = blockItem("earth_plate", CobblemonBlocks.EARTH_PLATE)
@JvmField
val SKY_PLATE = blockItem("sky_plate", CobblemonBlocks.SKY_PLATE)
@JvmField
val MIND_PLATE = blockItem("mind_plate", CobblemonBlocks.MIND_PLATE)
@JvmField
val INSECT_PLATE = blockItem("insect_plate", CobblemonBlocks.INSECT_PLATE)
@JvmField
val STONE_PLATE = blockItem("stone_plate", CobblemonBlocks.STONE_PLATE)
@JvmField
val SPOOKY_PLATE = blockItem("spooky_plate", CobblemonBlocks.SPOOKY_PLATE)
@JvmField
val DRACO_PLATE = blockItem("draco_plate", CobblemonBlocks.DRACO_PLATE)
@JvmField
val DREAD_PLATE = blockItem("dread_plate", CobblemonBlocks.DREAD_PLATE)
@JvmField
val IRON_PLATE = blockItem("iron_plate", CobblemonBlocks.IRON_PLATE)
@JvmField
val PIXIE_PLATE = blockItem("pixie_plate", CobblemonBlocks.PIXIE_PLATE)
@JvmField
val TYPE_GEM_CORE = blockItem("deepslate_crystal_core", CobblemonBlocks.TYPE_GEM_CORE)
@@ -1615,12 +1601,6 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
@JvmField
val LUCIBELL = compostableBlockItem("lucibell", CobblemonBlocks.LUCIBELL, 0.85f)
//Bags
@JvmField
val TRAINER_BAG = this.create("trainer_bag", CobblemonBagItem())
@JvmField
val TRAINER_PACK = this.create("trainer_pack", CobblemonBagItem())
private fun blockItem(name: String, block: Block, rarity: Rarity = Rarity.COMMON): BlockItem = this.create(name, BlockItem(block, Item.Properties().rarity(rarity)))
private fun itemNameBlockItem(name: String, block: Block, rarity: Rarity = Rarity.COMMON): ItemNameBlockItem = this.create(name, ItemNameBlockItem(block, Item.Properties().rarity(rarity)))
@@ -1655,6 +1635,12 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
return item
}
private fun pokeradarItem(type: PokeRadarType): PokeRadarItem {
val item = create("poke_radar_${type.name.lowercase()}", PokeRadarItem(type))
pokeradars.add(item)
return item
}
private fun wearableItem(name: String, heldItemRemappedName: String? = null): CobblemonItem = create(
name,
WearableHatItem(name).also {
@@ -0,0 +1,25 @@
/*
* 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
import com.cobblemon.mod.common.loot.SetNavChipDestinationFunction
import com.cobblemon.mod.common.platform.PlatformRegistry
import net.minecraft.core.Registry
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.core.registries.Registries
import net.minecraft.resources.ResourceKey
import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType
object CobblemonLootItemFunctions : PlatformRegistry<Registry<LootItemFunctionType<*>>, ResourceKey<Registry<LootItemFunctionType<*>>>, LootItemFunctionType<*>>() {
override val registry: Registry<LootItemFunctionType<*>> = BuiltInRegistries.LOOT_FUNCTION_TYPE
override val resourceKey: ResourceKey<Registry<LootItemFunctionType<*>>> = Registries.LOOT_FUNCTION_TYPE
@JvmField
val SET_NAV_CHIP_DESTINATION = create("set_nav_chip_destination", SetNavChipDestinationFunction.TYPE)
}
@@ -10,7 +10,6 @@ package com.cobblemon.mod.common
import com.cobblemon.mod.common.block.campfirepot.CookingPotMenu
import com.cobblemon.mod.common.item.bag.CobblemonBagMenu
import com.cobblemon.mod.common.block.tmmachine.TMMachineMenu
import com.cobblemon.mod.common.platform.PlatformRegistry
import net.minecraft.core.Registry
@@ -21,9 +20,8 @@ import net.minecraft.world.inventory.MenuType
object CobblemonMenuType : PlatformRegistry<Registry<MenuType<*>>, ResourceKey<Registry<MenuType<*>>>, MenuType<*>>() {
val COOKING_POT = MenuType.register("cooking_pot", ::CookingPotMenu)
val COOKING_POT = MenuType.register("cooking_pot_menu", ::CookingPotMenu)
val TM_MACHINE = MenuType.register("tm_machine_menu", ::TMMachineMenu)
val COBBLEMON_BAG = MenuType.register("cobblemon_bag", ::CobblemonBagMenu)
override val registry: Registry<MenuType<*>>
get() = BuiltInRegistries.MENU
@@ -13,8 +13,6 @@ import com.cobblemon.mod.common.client.net.OpenBehaviourEditorHandler
import com.cobblemon.mod.common.client.net.PlayerInteractOptionsHandler
import com.cobblemon.mod.common.client.net.SetClientPlayerDataHandler
import com.cobblemon.mod.common.client.net.animation.PlayPosableAnimationHandler
import com.cobblemon.mod.common.client.net.bag.UpdateBagMenuDataHandler
import com.cobblemon.mod.common.client.net.bag.UseItemOnPokemonFromBagHandler
import com.cobblemon.mod.common.client.net.battle.*
import com.cobblemon.mod.common.client.net.callback.move.OpenMoveCallbackHandler
import com.cobblemon.mod.common.client.net.callback.party.OpenPartyCallbackHandler
@@ -51,6 +49,9 @@ import com.cobblemon.mod.common.client.net.pokedex.ServerConfirmedRegisterHandle
import com.cobblemon.mod.common.client.net.pokemon.update.ClientboundSeatAssignmentPacketHandler
import com.cobblemon.mod.common.client.net.pokemon.update.ClientboundUpdateRidingStateHandler
import com.cobblemon.mod.common.client.net.pokemon.update.PokemonUpdatePacketHandler
import com.cobblemon.mod.common.client.net.pokeradar.PokeRadarScanResultHandler
import com.cobblemon.mod.common.client.net.pokeradar.PokeRadarSyncHandler
import com.cobblemon.mod.common.client.net.pokeradar.PokeRadarTrackingStateHandler
import com.cobblemon.mod.common.client.net.riding.ClientboundUpdateDriverInputHandler
import com.cobblemon.mod.common.client.net.settings.OpenCobblemonConfigEditorHandler
import com.cobblemon.mod.common.client.net.settings.ServerSettingsPacketHandler
@@ -78,8 +79,6 @@ import com.cobblemon.mod.common.net.messages.client.OpenBehaviourEditorPacket
import com.cobblemon.mod.common.net.messages.client.PlayerInteractOptionsPacket
import com.cobblemon.mod.common.net.messages.client.SetClientPlayerDataPacket
import com.cobblemon.mod.common.net.messages.client.animation.PlayPosableAnimationPacket
import com.cobblemon.mod.common.net.messages.client.bag.UpdateBagMenuDataPacket
import com.cobblemon.mod.common.net.messages.client.bag.UseItemOnPokemonFromBagPacket
import com.cobblemon.mod.common.net.messages.client.battle.*
import com.cobblemon.mod.common.net.messages.client.callback.OpenMoveCallbackPacket
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyCallbackPacket
@@ -111,6 +110,9 @@ import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.Add
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.ClearEvolutionsPacket
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.ClientboundSeatAssignmentPacket
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.RemoveEvolutionPacket
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarScanResultPacket
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarSyncPacket
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarTrackingStatePacket
import com.cobblemon.mod.common.net.messages.client.settings.OpenCobblemonConfigScreenPacket
import com.cobblemon.mod.common.net.messages.client.settings.ServerSettingsPacket
import com.cobblemon.mod.common.net.messages.client.sound.UnvalidatedPlaySoundS2CPacket
@@ -198,6 +200,10 @@ import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetItemHidden
import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetMarkingsPacket
import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetNicknamePacket
import com.cobblemon.mod.common.net.messages.server.pokemon.update.evolution.AcceptEvolutionPacket
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarScanPacket
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarNavpointPacket
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarSettingsPacket
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarTrackingPacket
import com.cobblemon.mod.common.net.messages.server.riding.DismountPokemonPacket
import com.cobblemon.mod.common.net.messages.server.riding.ServerboundUpdateDriverInputPacket
import com.cobblemon.mod.common.net.messages.server.riding.ServerboundUpdatePassengerPositionPacket
@@ -256,6 +262,10 @@ import com.cobblemon.mod.common.net.serverhandling.pokemon.update.SetActiveMarkH
import com.cobblemon.mod.common.net.serverhandling.pokemon.update.SetItemHiddenHandler
import com.cobblemon.mod.common.net.serverhandling.pokemon.update.SetMarkingsHandler
import com.cobblemon.mod.common.net.serverhandling.pokemon.update.SetNicknameHandler
import com.cobblemon.mod.common.net.serverhandling.pokeradar.PokeRadarScanHandler
import com.cobblemon.mod.common.net.serverhandling.pokeradar.PokeRadarNavpointHandler
import com.cobblemon.mod.common.net.serverhandling.pokeradar.PokeRadarSettingsHandler
import com.cobblemon.mod.common.net.serverhandling.pokeradar.PokeRadarTrackingHandler
import com.cobblemon.mod.common.net.serverhandling.riding.DismountPokemonPacketHandler
import com.cobblemon.mod.common.net.serverhandling.riding.DriverInputPacketHandler
import com.cobblemon.mod.common.net.serverhandling.riding.ServerboundUpdatePassengerPositionHandler
@@ -448,7 +458,6 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(BehaviourSyncPacket.ID, BehaviourSyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(MarkRegistrySyncPacket.ID, MarkRegistrySyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(RideSettingsSyncPacket.ID, RideSettingsSyncPacket::decode, RideSettingsSyncHandler))
list.add(PacketRegisterInfo(BagCategoriesSyncPacket.ID, BagCategoriesSyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(TechnicalMachineRegistrySyncPacket.ID, TechnicalMachineRegistrySyncPacket::decode, DataRegistrySyncPacketHandler()))
// Effects
@@ -517,6 +526,11 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(ClientboundUpdateDriverInputPacket.ID, ClientboundUpdateDriverInputPacket::decode, ClientboundUpdateDriverInputHandler))
list.add(PacketRegisterInfo(ClientboundSeatAssignmentPacket.ID, ClientboundSeatAssignmentPacket::decode, ClientboundSeatAssignmentPacketHandler))
// Poke Radar
list.add(PacketRegisterInfo(PokeRadarScanResultPacket.ID, PokeRadarScanResultPacket::decode, PokeRadarScanResultHandler))
list.add(PacketRegisterInfo(PokeRadarSyncPacket.ID, PokeRadarSyncPacket::decode, PokeRadarSyncHandler))
list.add(PacketRegisterInfo(PokeRadarTrackingStatePacket.ID, PokeRadarTrackingStatePacket::decode, PokeRadarTrackingStateHandler))
// Habitat blocks
list.add(PacketRegisterInfo(OpenHabitatBlockEditorPacket.ID, OpenHabitatBlockEditorPacket::decode, OpenHabitatBlockEditorHandler))
@@ -645,10 +659,6 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(SetActiveTMPacket.ID, SetActiveTMPacket::decode, SetActiveTMPacketHandler))
list.add(PacketRegisterInfo(SetTMMachineContainerDataPacket.ID, SetTMMachineContainerDataPacket::decode, SetTMMachineContainerDataPacketHandler))
// Bag
list.add(PacketRegisterInfo(UpdateBagMenuDataPacket.ID, UpdateBagMenuDataPacket::decode, UpdateBagMenuDataHandler))
list.add(PacketRegisterInfo(UseItemOnPokemonFromBagPacket.ID, UseItemOnPokemonFromBagPacket::decode, UseItemOnPokemonFromBagHandler))
// Behaviour Packets
list.add(PacketRegisterInfo(SetEntityBehaviourPacket.ID, SetEntityBehaviourPacket::decode, SetEntityBehaviourHandler))
list.add(PacketRegisterInfo(DamageOnCollisionPacket.ID, DamageOnCollisionPacket::decode, DamageOnCollisionPacketHandler))
@@ -656,7 +666,13 @@ object CobblemonNetwork {
// Habitat blocks
list.add(PacketRegisterInfo(SaveHabitatBlockSettingsPacket.ID, SaveHabitatBlockSettingsPacket::decode, SaveHabitatBlockSettingsHandler))
// Debug
// Poke Radar
list.add(PacketRegisterInfo(PokeRadarScanPacket.ID, PokeRadarScanPacket::decode, PokeRadarScanHandler))
list.add(PacketRegisterInfo(PokeRadarSettingsPacket.ID, PokeRadarSettingsPacket::decode, PokeRadarSettingsHandler))
list.add(PacketRegisterInfo(PokeRadarTrackingPacket.ID, PokeRadarTrackingPacket::decode, PokeRadarTrackingHandler))
list.add(PacketRegisterInfo(PokeRadarNavpointPacket.ID, PokeRadarNavpointPacket::decode, PokeRadarNavpointHandler))
// Debug / cheats
list.add(PacketRegisterInfo(RequestOpenRidingStatsDebugGUIPacket.ID, RequestOpenRidingStatsDebugGUIPacket::decode, RequestOpenRidingStatsDebugGUIHandler))
@@ -71,6 +71,17 @@ object CobblemonSounds : PlatformRegistry<Registry<SoundEvent>, ResourceKey<Regi
@JvmField
val POKE_BALL_TRAIL = this.create("poke_ball.trail")
@JvmField
val POKE_RADAR_SCAN = this.create("item.poke_radar.scan")
@JvmField
val POKE_RADAR_LOCK_ON = this.create("item.poke_radar.lock_on")
@JvmField
val POKE_RADAR_POWER_DOWN = this.create("item.poke_radar.power_down")
@JvmField
val POKE_RADAR_NOTIFICATION = this.create("item.poke_radar.notification")
@JvmField
val POKE_RADAR_MUTE_TOGGLE = this.create("item.poke_radar.mute_toggle")
@JvmField
val POKEDEX_OPEN = this.create("item.pokedex.open")
@JvmField
@@ -321,19 +332,6 @@ object CobblemonSounds : PlatformRegistry<Registry<SoundEvent>, ResourceKey<Regi
@JvmField
val MEDICINAL_LEEK_PLACE = this.create("block.medicinal_leek.plant")
@JvmField
val ITEM_BAG_OPEN = this.create("item.bag.open")
@JvmField
val ITEM_BAG_CLOSE = this.create("item.bag.close")
@JvmField
val ITEM_BAG_CLICK = this.create("item.bag.click")
@JvmField
val ITEM_BAG_ITEM_IN = this.create("item.bag.item_in")
@JvmField
val ITEM_BAG_ITEM_OUT = this.create("item.bag.item_out")
@JvmField
val ITEM_BAG_EQUIP = this.create("item.bag.equip")
@JvmField
val GILDED_CHEST_OPEN = this.create("block.gilded_chest.open")
@JvmField
@@ -1,66 +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.bag
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.data.JsonDataRegistry
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.net.messages.client.data.BagCategoriesSyncPacket
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.cobblemon.mod.common.util.adapters.TagKeyAdapter
import com.cobblemon.mod.common.util.cobblemonResource
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import net.minecraft.core.registries.Registries
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.server.packs.PackType
import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item
object BagCategories: JsonDataRegistry<BagCategory> {
override val id: ResourceLocation = cobblemonResource("bag_categories")
override val type: PackType = PackType.SERVER_DATA
override val observable = SimpleObservable<BagCategories>()
override val gson = GsonBuilder()
.disableHtmlEscaping()
.setPrettyPrinting()
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.registerTypeAdapter(TypeToken.getParameterized(TagKey::class.java, Item::class.java).type, TagKeyAdapter(Registries.ITEM))
.create()
override val typeToken: TypeToken<BagCategory> = TypeToken.get(BagCategory::class.java)
override val resourcePath = "bag_categories"
private val bagCategories = hashMapOf<ResourceLocation, BagCategory>()
override fun reload(data: Map<ResourceLocation, BagCategory>) {
bagCategories.clear()
data.forEach { identifier, category ->
try {
category.identifier = identifier
bagCategories[identifier] = category
} catch (e: Exception) {
Cobblemon.LOGGER.error("Skipped loading the {} category", identifier, e)
}
}
Cobblemon.LOGGER.info("Loaded {} bag categories", bagCategories.size)
this.observable.emit(this)
}
override fun sync(player: ServerPlayer) {
BagCategoriesSyncPacket(bagCategories.values.toList())
}
fun getOrderedCategoriesList(): List<BagCategory> {
return bagCategories.values.toList().sortedBy { it.order }
}
}
@@ -1,66 +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.bag
import com.cobblemon.mod.common.util.readIdentifier
import com.cobblemon.mod.common.util.writeIdentifier
import net.minecraft.core.registries.Registries
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.TagKey
import net.minecraft.util.StringRepresentable
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
class BagCategory(
identifier: ResourceLocation,
val order: Int,
val icon: ResourceLocation,
val whiteListTag: TagKey<Item>,
val blackListTag: TagKey<Item>,
val maxCount: Int
): StringRepresentable {
@Transient
var identifier: ResourceLocation = identifier
internal set
override fun getSerializedName(): String = identifier.toString()
fun getName(): MutableComponent = Component.translatable("${identifier.namespace}.bag_category.${identifier.path}")
fun itemIsValid(itemStack: ItemStack): Boolean {
if (itemStack.`is`(blackListTag)) return false
if (itemStack.`is`(whiteListTag)) return true
return false
}
fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeIdentifier(identifier)
buffer.writeInt(order)
buffer.writeIdentifier(icon)
buffer.writeIdentifier(whiteListTag.location)
buffer.writeIdentifier(blackListTag.location)
buffer.writeInt(maxCount)
}
companion object {
internal fun decode(buffer: RegistryFriendlyByteBuf): BagCategory {
return BagCategory(
buffer.readIdentifier(),
buffer.readInt(),
buffer.readIdentifier(),
TagKey.create(Registries.ITEM, buffer.readIdentifier()),
TagKey.create(Registries.ITEM, buffer.readIdentifier()),
buffer.readInt()
)
}
}
}
@@ -9,14 +9,12 @@
package com.cobblemon.mod.common.api.events.pokemon
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.MoValue
import com.cobblemon.mod.common.api.events.Cancelable
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.moLangFunctionMap
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.trade.TradeParticipant
import com.cobblemon.mod.common.util.asArrayValue
import com.cobblemon.mod.common.util.getPlayer
/**
@@ -33,9 +31,9 @@ interface TradeEvent {
val tradeParticipant1: TradeParticipant
/**
* All the [Pokemon] the first participant receives in the trade.
* The [Pokemon] being traded by the first participant.
*/
val tradeParticipant1Pokemon: List<Pokemon>
val tradeParticipant1Pokemon: Pokemon
/**
* The second [TradeParticipant].
@@ -43,19 +41,9 @@ interface TradeEvent {
val tradeParticipant2: TradeParticipant
/**
* All the [Pokemon] the second participant receives in the trade.
* The [Pokemon] being traded by the second participant.
*/
val tradeParticipant2Pokemon: List<Pokemon>
fun createContext(): MutableMap<String, MoValue> = mutableMapOf(
"trade_participant_1" to (tradeParticipant1.uuid.getPlayer()?.asMoLangValue() ?: DoubleValue.ZERO),
"trade_participant_2" to (tradeParticipant2.uuid.getPlayer()?.asMoLangValue() ?: DoubleValue.ZERO),
// Kept for backwards compatibility, this is the first Pokémon of each side.
"trade_participant_1_pokemon" to tradeParticipant1Pokemon.first().struct,
"trade_participant_2_pokemon" to tradeParticipant2Pokemon.first().struct,
"trade_participant_1_pokemon_list" to tradeParticipant1Pokemon.asArrayValue { it.struct },
"trade_participant_2_pokemon_list" to tradeParticipant2Pokemon.asArrayValue { it.struct }
)
val tradeParticipant2Pokemon: Pokemon
/**
* Event fired when a trade is about to happen. Cancelling this event prevents the trade from occurring.
@@ -65,11 +53,16 @@ interface TradeEvent {
*/
data class Pre(
override val tradeParticipant1: TradeParticipant,
override val tradeParticipant1Pokemon: List<Pokemon>,
override val tradeParticipant1Pokemon: Pokemon,
override val tradeParticipant2: TradeParticipant,
override val tradeParticipant2Pokemon: List<Pokemon>
override val tradeParticipant2Pokemon: Pokemon
) : TradeEvent, Cancelable() {
val context = createContext()
val context = mutableMapOf(
"trade_participant_1" to (tradeParticipant1.uuid.getPlayer()?.asMoLangValue() ?: DoubleValue.ZERO),
"trade_participant_2" to (tradeParticipant2.uuid.getPlayer()?.asMoLangValue() ?: DoubleValue.ZERO),
"trade_participant_1_pokemon" to tradeParticipant1Pokemon.struct,
"trade_participant_2_pokemon" to tradeParticipant2Pokemon.struct
)
val functions = moLangFunctionMap(
cancelFunc
@@ -84,10 +77,15 @@ interface TradeEvent {
*/
data class Post(
override val tradeParticipant1: TradeParticipant,
override val tradeParticipant1Pokemon: List<Pokemon>,
override val tradeParticipant1Pokemon: Pokemon,
override val tradeParticipant2: TradeParticipant,
override val tradeParticipant2Pokemon: List<Pokemon>
override val tradeParticipant2Pokemon: Pokemon
) : TradeEvent {
val context = createContext()
val context = mutableMapOf(
"trade_participant_1" to (tradeParticipant1.uuid.getPlayer()?.asMoLangValue() ?: DoubleValue.ZERO),
"trade_participant_2" to (tradeParticipant2.uuid.getPlayer()?.asMoLangValue() ?: DoubleValue.ZERO),
"trade_participant_1_pokemon" to tradeParticipant1Pokemon.struct,
"trade_participant_2_pokemon" to tradeParticipant2Pokemon.struct
)
}
}
@@ -35,6 +35,7 @@ import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.RenderablePokemon
import com.cobblemon.mod.common.pokemon.stat.CobblemonStatProvider
import com.cobblemon.mod.common.pokemon.status.PersistentStatus
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.isDouble
@@ -650,11 +651,14 @@ open class PokemonProperties {
// TEST YOUR LUCK!
@JvmOverloads
fun roll(pokemon: Pokemon, player: ServerPlayer? = null) {
val baseTypes = pokemon.form.types.toList()
var shinyRate = config.shinyRate
CobblemonEvents.SHINY_CHANCE_CALCULATION.post(ShinyChanceCalculationEvent(shinyRate, pokemon)) { event ->
shinyRate = event.calculate(player)
}
val baseTypes = pokemon.form.types.toList()
var shinyRate = config.shinyRate
if (player != null) {
shinyRate /= PokeRadarManager.shinyChainMultiplier(player, pokemon)
}
CobblemonEvents.SHINY_CHANCE_CALCULATION.post(ShinyChanceCalculationEvent(shinyRate, pokemon)) { event ->
shinyRate = event.calculate(player)
}
if (this.shiny == null) pokemon.shiny = shinyRate.checkRate()
if (this.teraType == null) pokemon.teraType =
if (config.teraTypeRate.checkRate()) {
@@ -9,9 +9,12 @@
package com.cobblemon.mod.common.api.riding.stats
import com.cobblemon.mod.common.api.cooking.Flavour
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.util.lang
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item
/**
* A stat that is used for riding Pokémon. The exact implementation of each of these depends on the [com.cobblemon.mod.common.api.riding.controller.RideController].
@@ -20,13 +23,14 @@ import net.minecraft.network.chat.MutableComponent
* @since February 17th, 2025
*/
enum class RidingStat(
val flavour: Flavour
val flavour: Flavour,
val powerItem: TagKey<Item>
) {
ACCELERATION(Flavour.SPICY),
SKILL(Flavour.DRY),
SPEED(Flavour.SWEET),
STAMINA(Flavour.SOUR),
JUMP(Flavour.BITTER);
ACCELERATION(Flavour.SPICY, CobblemonItemTags.POWER_BRACER),
SKILL(Flavour.DRY, CobblemonItemTags.POWER_BELT),
SPEED(Flavour.SWEET, CobblemonItemTags.POWER_ANKLET),
STAMINA(Flavour.SOUR, CobblemonItemTags.POWER_WEIGHT),
JUMP(Flavour.BITTER, CobblemonItemTags.POWER_BAND);
companion object {
fun getByName(name: String) = RidingStat.entries.firstOrNull { it.name.equals(name, ignoreCase = true) }
@@ -41,6 +41,7 @@ class WeightTweakRuleComponent : SpawnRuleComponent {
return if (spawnDetailSelector.selects(detail) && spawnablePositionSelector.selects(spawnablePosition)) {
runtime.environment.setSimpleVariable("spawn", detail.struct)
runtime.environment.setSimpleVariable("spawn_detail", detail.struct)
runtime.environment.setSimpleVariable("spawnable_position", spawnablePosition.getOrSetupStruct())
runtime.environment.setSimpleVariable("weight", DoubleValue(weight.toDouble()))
runtime.resolveFloat(this.weight)
} else {
@@ -140,20 +140,6 @@ object CobblemonItemTags {
@JvmField val WEARABLE_HAT_ITEMS = create("held/visibility/hat")
@JvmField val HIDDEN_ITEMS = create("held/visibility/hidden")
//Bag Categories Tags
@JvmField val BAG_WHITELIST_POKE_BALLS = create("bag/whitelist_poke_balls")
@JvmField val BAG_BLACKLIST_POKE_BALLS = create("bag/blacklist_poke_balls")
@JvmField val BAG_WHITELIST_CONSUMABLES = create("bag/whitelist_consumables")
@JvmField val BAG_BLACKLIST_CONSUMABLES = create("bag/blacklist_consumables")
@JvmField val BAG_WHITELIST_BERRIES = create("bag/whitelist_berries")
@JvmField val BAG_BLACKLIST_BERRIES = create("bag/blacklist_berries")
@JvmField val BAG_WHITELIST_HELD_EVO = create("bag/whitelist_held_evo")
@JvmField val BAG_BLACKLIST_HELD_EVO = create("bag/blacklist_held_evo")
@JvmField val BAG_WHITELIST_CURRENCY = create("bag/whitelist_currency")
@JvmField val BAG_BLACKLIST_CURRENCY = create("bag/blacklist_currency")
@JvmField val BAG_WHITELIST_TMS = create("bag/whitelist_tms")
@JvmField val BAG_BLACKLIST_TMS = create("bag/blacklist_tms")
//Empty Tag
@JvmField val EMPTY = create("empty")
@@ -11,6 +11,7 @@ package com.cobblemon.mod.common.battles.interpreter.instructions
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.model.PokemonBattle
import com.cobblemon.mod.common.api.battles.model.actor.ActorType
import com.cobblemon.mod.common.api.battles.model.actor.EntityBackedBattleActor
import com.cobblemon.mod.common.api.entity.PokemonSender
import com.cobblemon.mod.common.api.events.CobblemonEvents
@@ -20,7 +21,9 @@ import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.battles.ShowdownInterpreter
import com.cobblemon.mod.common.battles.dispatch.InterpreterInstruction
import com.cobblemon.mod.common.net.messages.client.battle.BattleFaintPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarManager.addToChain
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.getPlayer
import java.util.concurrent.CompletableFuture
/**
@@ -54,6 +57,16 @@ class FaintInstruction(battle: PokemonBattle, val message: BattleMessage) : Inte
faintingPokemon.effectedPokemon.currentHealth = 0
faintingPokemon.faintedAt = battle.faintCounter++
faintingPokemon.sendUpdate()
if (faintingPokemon.actor.type == ActorType.WILD) {
val species = faintingPokemon.originalPokemon.species.resourceIdentifier.toString()
battle.actors
.filter { it.type == ActorType.PLAYER }
.flatMap { it.getPlayerUUIDs() }
.mapNotNull { it.getPlayer() }
.forEach { addToChain(it, species) }
}
CobblemonEvents.BATTLE_FAINTED.post(BattleFaintedEvent(battle, pokemon, context, pnx))
battle.getActorAndActiveSlotFromPNX(pnx).second.battlePokemon = null
faintingPokemon.contextManager.add(context)
@@ -169,7 +169,6 @@ class TypeGemCoreBlock(properties: Properties) : Block(properties) {
if (fullClusterCount == 0) {
if (gemCount < Cobblemon.config.typeGemMinGrowth && clusters.isNotEmpty()) {
println("Force set a cluster to FULL at size $gemCount")
val randomCluster = clusters.random()
level.setBlockAndUpdate(randomCluster.second, randomCluster.first.setValue(GROWTH_TYPE, GrowthType.FULL))
}
@@ -1,203 +0,0 @@
package com.cobblemon.mod.common.block.typeplate
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.api.types.ElementalType
import com.cobblemon.mod.common.api.types.ElementalTypes
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.server.level.ServerLevel
import net.minecraft.util.RandomSource
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
import net.minecraft.world.level.LevelAccessor
import net.minecraft.world.level.LevelReader
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.DirectionalBlock
import net.minecraft.world.level.block.RenderShape
import net.minecraft.world.level.block.SimpleWaterloggedBlock
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.level.block.state.properties.BlockStateProperties.WATERLOGGED
import net.minecraft.world.level.block.state.properties.BooleanProperty
import net.minecraft.world.level.block.state.properties.IntegerProperty
import net.minecraft.world.level.material.FluidState
import net.minecraft.world.level.material.Fluids
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.Shapes
import net.minecraft.world.phys.shapes.VoxelShape
/**
* A type plate block (wow)
* Logic should be diverted to a [TypePlateMechanic] class whenever possible.
*
* @author whatsy
* @since December 2nd, 2026
*/
class TypePlateBlock(properties: Properties, val type: ElementalType) : DirectionalBlock(properties), SimpleWaterloggedBlock {
companion object {
val CODEC: MapCodec<TypePlateBlock> = RecordCodecBuilder.mapCodec { instance ->
instance.group(
propertiesCodec(),
ElementalType.BY_STRING_CODEC.fieldOf("type").forGetter(TypePlateBlock::type)
).apply(instance, ::TypePlateBlock)
}
val ACTIVATED = BooleanProperty.create("activated")
val ROTATION = IntegerProperty.create("rotation", 0, 3)
val FACING = DirectionalBlock.FACING
private val SHAPES = mapOf(
Direction.UP to Shapes.box(3.0 / 16.0, 0.0, 2.0 / 16.0, 13.0 / 16.0, 3.0 / 16.0, 14.0 / 16.0),
Direction.DOWN to Shapes.box(3.0 / 16.0, 13.0 / 16.0, 2.0 / 16.0, 13.0 / 16.0, 1.0, 14.0 / 16.0),
Direction.NORTH to Shapes.box(3.0 / 16.0, 2.0 / 16.0, 13.0 / 16.0, 13.0 / 16.0, 14.0 / 16.0, 1.0),
Direction.SOUTH to Shapes.box(3.0 / 16.0, 2.0 / 16.0, 0.0, 13.0 / 16.0, 14.0 / 16.0, 3.0 / 16.0),
Direction.EAST to Shapes.box(0.0, 2.0 / 16.0, 3.0 / 16.0, 3.0 / 16.0, 14.0 / 16.0, 13.0 / 16.0),
Direction.WEST to Shapes.box(13.0 / 16.0, 2.0 / 16.0, 3.0 / 16.0, 1.0, 14.0 / 16.0, 13.0 / 16.0)
)
private val typeToBlockMap: Map<Block, ElementalType> by lazy {
mapOf(
CobblemonBlocks.BLANK_PLATE to ElementalTypes.NORMAL,
CobblemonBlocks.FLAME_PLATE to ElementalTypes.FIRE,
CobblemonBlocks.SPLASH_PLATE to ElementalTypes.WATER,
CobblemonBlocks.ZAP_PLATE to ElementalTypes.ELECTRIC,
CobblemonBlocks.MEADOW_PLATE to ElementalTypes.GRASS,
CobblemonBlocks.ICICLE_PLATE to ElementalTypes.ICE,
CobblemonBlocks.FIST_PLATE to ElementalTypes.FIGHTING,
CobblemonBlocks.TOXIC_PLATE to ElementalTypes.POISON,
CobblemonBlocks.EARTH_PLATE to ElementalTypes.GROUND,
CobblemonBlocks.SKY_PLATE to ElementalTypes.FLYING,
CobblemonBlocks.MIND_PLATE to ElementalTypes.PSYCHIC,
CobblemonBlocks.INSECT_PLATE to ElementalTypes.BUG,
CobblemonBlocks.STONE_PLATE to ElementalTypes.ROCK,
CobblemonBlocks.SPOOKY_PLATE to ElementalTypes.GHOST,
CobblemonBlocks.DRACO_PLATE to ElementalTypes.DRAGON,
CobblemonBlocks.DREAD_PLATE to ElementalTypes.DARK,
CobblemonBlocks.IRON_PLATE to ElementalTypes.STEEL,
CobblemonBlocks.PIXIE_PLATE to ElementalTypes.FAIRY
)
}
private val typeToMechanicMap: Map<ElementalType, TypePlateMechanic> by lazy {
mapOf(
ElementalTypes.WATER to WaterPlateMechanic()
)
}
/**
* Get the [TypePlateMechanic] for the given [ElementalType]
*
* @param type The [ElementalType] to check.
* @return The [TypePlateMechanic], if existing.
*/
fun getPlateMechanic(type: ElementalType): TypePlateMechanic? {
return typeToMechanicMap[type]
}
fun getPlateType(block: Block): ElementalType? {
return typeToBlockMap[block]
}
fun getTypePlate(type: ElementalType): Block? {
return typeToBlockMap.entries.firstOrNull { it.value == type }?.key
}
}
init {
registerDefaultState(stateDefinition.any()
.setValue(FACING, Direction.UP)
.setValue(ROTATION, 0)
.setValue(ACTIVATED, false)
.setValue(WATERLOGGED, false)
)
}
override fun getStateForPlacement(context: BlockPlaceContext): BlockState {
val rotation = when (context.horizontalDirection.opposite) {
Direction.EAST -> 1
Direction.SOUTH -> 2
Direction.WEST -> 3
else -> 0
}
return defaultBlockState()
.setValue(FACING, context.clickedFace)
.setValue(ROTATION, rotation)
.setValue(BlockStateProperties.WATERLOGGED, context.level.isWaterAt(context.clickedPos))
}
override fun onPlace(state: BlockState, level: Level, pos: BlockPos, oldState: BlockState, movedByPiston: Boolean) {
getPlateMechanic(type)?.onPlace(state, level, pos, oldState, movedByPiston, this)
super.onPlace(state, level, pos, oldState, movedByPiston)
}
override fun tick(state: BlockState, level: ServerLevel, pos: BlockPos, random: RandomSource) {
getPlateMechanic(type)?.tick(state, level, pos, random, this)
super.tick(state, level, pos, random)
}
override fun getShape(state: BlockState, level: BlockGetter, pos: BlockPos, context: CollisionContext): VoxelShape {
val facing = state.getValue(FACING)
if (facing.axis == Direction.Axis.Y && state.getValue(ROTATION) % 2 == 1) {
return if (facing == Direction.UP) {
Shapes.box(2.0 / 16.0, 0.0, 3.0 / 16.0, 14.0 / 16.0, 3.0 / 16.0, 13.0 / 16.0)
} else {
Shapes.box(2.0 / 16.0, 13.0 / 16.0, 3.0 / 16.0, 14.0 / 16.0, 1.0, 13.0 / 16.0)
}
}
return SHAPES.getValue(facing)
}
override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block?, BlockState?>) {
builder.add(FACING, ROTATION, ACTIVATED, BlockStateProperties.WATERLOGGED)
}
override fun getFluidState(state: BlockState): FluidState {
return if (state.getValue(BlockStateProperties.WATERLOGGED)) Fluids.WATER.getSource(false) else super.getFluidState(state)
}
override fun getLightBlock(state: BlockState, level: BlockGetter, pos: BlockPos): Int {
return 0
}
override fun onRemove(
state: BlockState,
level: Level,
pos: BlockPos,
newState: BlockState,
movedByPiston: Boolean
) {
getPlateMechanic(type)?.onRemove(state, level, pos, newState, movedByPiston, this)
super.onRemove(state, level, pos, newState, movedByPiston)
}
override fun codec(): MapCodec<out TypePlateBlock> = CODEC
override fun updateShape(
state: BlockState,
direction: Direction,
neighborState: BlockState,
level: LevelAccessor,
pos: BlockPos,
neighborPos: BlockPos
): BlockState? {
if (state.getValue(WATERLOGGED)) {
level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level))
}
return if (!state.canSurvive(level, pos)) {
Blocks.AIR.defaultBlockState()
} else super.updateShape(state, direction, neighborState, level, pos, neighborPos)
}
override fun getRenderShape(state: BlockState) = RenderShape.MODEL
override fun canSurvive(state: BlockState, level: LevelReader, pos: BlockPos): Boolean {
getPlateMechanic(type)?.canSurvive(state, level, pos, this)?.let { return it }
return level.getBlockState(pos.relative(state.getValue(FACING).opposite)).isSolid
}
}
@@ -1,24 +0,0 @@
package com.cobblemon.mod.common.block.typeplate
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.util.RandomSource
import net.minecraft.world.level.Level
import net.minecraft.world.level.LevelReader
import net.minecraft.world.level.block.state.BlockState
/**
* Represents a mechanic tied to a specific type plate. Used to keep [TypePlateBlock] from turning into spaghetti.
* Methods are automatically called from the base class.
* Add new mechanics to [TypePlateBlock.typeToMechanicMap]
* Add more methods as necessary.
*
* @author whatsy
* @since December 2nd, 2026
*/
interface TypePlateMechanic {
fun onPlace(state: BlockState, level: Level, pos: BlockPos, oldState: BlockState, movedByPiston: Boolean, block: TypePlateBlock) {}
fun tick(state: BlockState, level: ServerLevel, pos: BlockPos, random: RandomSource, block: TypePlateBlock) {}
fun onRemove(state: BlockState, level: Level, pos: BlockPos, newState: BlockState, movedByPiston: Boolean, block: TypePlateBlock) {}
fun canSurvive(state: BlockState, level: LevelReader, pos: BlockPos, block: TypePlateBlock): Boolean? { return null }
}
@@ -1,35 +0,0 @@
package com.cobblemon.mod.common.block.typeplate
import com.cobblemon.mod.common.CobblemonBlocks
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.server.level.ServerLevel
import net.minecraft.sounds.SoundEvents
import net.minecraft.sounds.SoundSource
import net.minecraft.util.RandomSource
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.DirectionalBlock
import net.minecraft.world.level.block.entity.ConduitBlockEntity
import net.minecraft.world.level.block.state.BlockState
/**
* Handles spawning Manaphy.
*
* @author whatsy
* @since December 2nd, 2026
*/
class WaterPlateMechanic : TypePlateMechanic {
override fun onPlace(
state: BlockState,
level: Level,
pos: BlockPos,
oldState: BlockState,
movedByPiston: Boolean,
block: TypePlateBlock
) {
if (level.isClientSide) return
// TODO action effect
}
}
@@ -9,13 +9,10 @@
package com.cobblemon.mod.common.client
import com.cobblemon.mod.common.BakingOverride
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.item.bag.CobblemonBagItem
import com.cobblemon.mod.common.util.cobblemonModel
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.client.resources.model.ModelResourceLocation
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.Item
/**
* The purpose of this class is to hold models that we want baked, but aren't associated with
@@ -106,33 +103,9 @@ object CobblemonBakingOverrides {
cobblemonModel("surprise_mulch", "none")
)
// Bag
val bagModels = mutableMapOf<CobblemonBagItem, BakingOverride>()
val TRAINER_PACK = registerBagOverride(
CobblemonItems.TRAINER_PACK,
cobblemonResource("item/bag/trainer_pack"),
cobblemonModel("trainer_pack", "none")
)
val TRAINER_BAG = registerBagOverride(
CobblemonItems.TRAINER_BAG,
cobblemonResource("item/bag/trainer_bag"),
cobblemonModel("trainer_bag", "none")
)
/*val BAG_PENNY = registerBagOverride(
CobblemonItems.TRAINER_PACK,
cobblemonResource("item/bag/bag_penny"),
cobblemonModel("bag_penny", "penny")
)*/
fun registerOverride(modelLocation: ResourceLocation, modelIdentifier: ModelResourceLocation): BakingOverride {
val result = BakingOverride(modelLocation, modelIdentifier)
models.add(result)
return result
}
fun registerBagOverride(associatedItem: CobblemonBagItem, modelLocation: ResourceLocation, modelIdentifier: ModelResourceLocation): BakingOverride {
val result = registerOverride(modelLocation, modelIdentifier)
bagModels[associatedItem] = result
return result
}
}
@@ -8,6 +8,9 @@
package com.cobblemon.mod.common.client
import net.minecraft.world.item.DyeColor
import net.minecraft.util.FastColor
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.CobblemonBlockEntities
import com.cobblemon.mod.common.CobblemonBlocks
@@ -27,12 +30,12 @@ import com.cobblemon.mod.common.client.battle.ClientBattle
import com.cobblemon.mod.common.client.gui.PartyOverlay
import com.cobblemon.mod.common.client.gui.PartyOverlayDataControl
import com.cobblemon.mod.common.client.gui.RideControlsOverlay
import com.cobblemon.mod.common.client.gui.bag.CobblemonBagScreen
import com.cobblemon.mod.common.client.gui.battle.BattleOverlay
import com.cobblemon.mod.common.client.gui.cookingpot.CookingPotScreen
import com.cobblemon.mod.common.client.gui.party.PartyTutorialToasts
import com.cobblemon.mod.common.client.gui.tmmachine.TMMachineScreen
import com.cobblemon.mod.common.client.particle.BedrockParticleOptionsRepository
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.client.render.ClientPlayerIcon
import com.cobblemon.mod.common.client.render.DeferredRenderer
import com.cobblemon.mod.common.client.render.block.*
@@ -47,7 +50,6 @@ import com.cobblemon.mod.common.client.render.generic.GenericBedrockRenderer
import com.cobblemon.mod.common.client.render.item.CobblemonBuiltinItemRendererRegistry
import com.cobblemon.mod.common.client.render.item.PokemonItemRenderer
import com.cobblemon.mod.common.client.render.layer.PlayerRecallBallRenderer
import com.cobblemon.mod.common.client.render.layer.CobblemonBagRenderer
import com.cobblemon.mod.common.client.render.layer.PokemonOnShoulderRenderer
import com.cobblemon.mod.common.client.render.models.blockbench.bedrock.animation.BedrockAnimationRepository
import com.cobblemon.mod.common.client.render.models.blockbench.repository.BerryModelRepository
@@ -135,6 +137,7 @@ object CobblemonClient {
// CobblemonDataProvider.canReload = true
DeferredRenderer.clearAll()
ClientPlayerIcon.clear()
ClientPokeRadar.reset()
}
fun initialize(implementation: CobblemonClientImplementation) {
@@ -421,7 +424,7 @@ object CobblemonClient {
CobblemonBlocks.MOOMOO_MILK,
CobblemonBlocks.MEDICINAL_BREW,
CobblemonBlocks.TERRAIN_EXTENDER,
CobblemonBlocks.RED_MINT_LEAF_LITTER,
CobblemonBlocks.POTTED_RED_MINT,
CobblemonBlocks.BLUE_MINT_LEAF_LITTER,
@@ -541,17 +544,14 @@ object CobblemonClient {
skinMap?.get(PlayerSkin.Model.WIDE) as LivingEntityRenderer<Player, PlayerModel<Player>>
renderer?.addLayer(PokemonOnShoulderRenderer(renderer))
renderer?.addLayer(PlayerRecallBallRenderer(renderer))
renderer?.addLayer(CobblemonBagRenderer(renderer))
renderer = skinMap[PlayerSkin.Model.SLIM] as LivingEntityRenderer<Player, PlayerModel<Player>>?
renderer?.addLayer(PokemonOnShoulderRenderer(renderer))
renderer?.addLayer(PlayerRecallBallRenderer(renderer))
renderer?.addLayer(CobblemonBagRenderer(renderer))
}
private fun registerMenuScreens() {
MenuScreens.register(CobblemonMenuType.COOKING_POT, ::CookingPotScreen)
MenuScreens.register(CobblemonMenuType.TM_MACHINE, ::TMMachineScreen)
MenuScreens.register(CobblemonMenuType.COBBLEMON_BAG, ::CobblemonBagScreen)
}
private fun registerBlockEntityRenderers() {
@@ -604,6 +604,11 @@ object CobblemonClient {
implementation.registerItemColors(PokeBaitItemColorProvider, CobblemonItems.POKE_BAIT)
implementation.registerItemColors(PonigiriItemColorProvider, CobblemonItems.PONIGIRI)
implementation.registerItemColors(SinisterTeaItemColorProvider, CobblemonItems.SINISTER_TEA)
// TODO: Placeholder atm
implementation.registerItemColors({ stack, layer ->
val chip = stack.get(CobblemonItemComponents.NAV_CHIP)
if (layer == 1 && chip != null) FastColor.ARGB32.opaque(DyeColor.byId(chip.color).textureDiffuseColor) else -1
}, CobblemonItems.NAV_CHIP, CobblemonItems.ENCRYPTED_NAV_CHIP)
}
fun reloadCodedAssets(resourceManager: ResourceManager) {
@@ -1,88 +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.gui.bag
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
import com.cobblemon.mod.common.client.render.getDepletableRedGreen
import com.cobblemon.mod.common.util.asTranslated
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.sounds.SoundManager
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
class BagCategoryButton(
x: Int,
y: Int,
val parent: CobblemonBagScreen,
val category: Int,
val action: OnPress
): Button(x, y, WIDTH, HEIGHT, Component.empty(), action, DEFAULT_NARRATION), CobblemonRenderable {
companion object {
private const val WIDTH = 32
private const val HEIGHT = 31
private val CATEGORY_SLOT = cobblemonResource("textures/gui/bag/bag_tab.png")
private val VOLUME_BAR = cobblemonResource("textures/gui/bag/bag_tab_volume_bar.png")
}
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
val orderedCategories = BagCategories.getOrderedCategoriesList()
blitk(
matrixStack = context.pose(),
texture = CATEGORY_SLOT,
x = x, y = y,
width = WIDTH, height = HEIGHT,
textureHeight = 64,
vOffset = if (parent.menu.currentlySelectedCategory == category) 32 else 0
)
blitk(
matrixStack = context.pose(),
texture = if (category == -1) ResourceLocation("minecraft", "textures/item/bundle.png") else orderedCategories[category].icon,
x = x + 8, y = y + 9,
width = 16, height = 16
)
//The Bar
if (category != -1) {
blitk(
matrixStack = context.pose(),
texture = VOLUME_BAR,
x = x + 8, y = y + 25,
width = 16, height = 3
)
val itemRatio = (parent.menu.categoryItemCounts[category].toFloat() / orderedCategories[category].maxCount).coerceIn(0F, 1F)
val barWidth = itemRatio * 14
val (red, green) = getDepletableRedGreen(1 - itemRatio)
blitk(
matrixStack = context.pose(),
texture = CobblemonResources.WHITE,
x = x + 9, y = y + 26,
width = barWidth, height = 1,
red = red * 0.8F, green = green * 0.8F, blue = 0.27F
)
}
if (isHovered) {
context.renderTooltip(Minecraft.getInstance().font, if (category == -1) lang("bag_categories.all_items") else orderedCategories[category].getName(), mouseX, mouseY)
}
}
override fun playDownSound(handler: SoundManager) {}
}
@@ -1,50 +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.gui.bag
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.sounds.SoundManager
import net.minecraft.network.chat.Component
class BagCategoryPageButton(
x: Int,
y: Int,
val parent: CobblemonBagScreen,
val leftButton: Boolean,
val action: OnPress
): Button(x, y, WIDTH, HEIGHT, Component.empty(), action, DEFAULT_NARRATION), CobblemonRenderable {
companion object {
private const val WIDTH = 12
private const val HEIGHT = 10
private val LEFT_BUTTON = cobblemonResource("textures/gui/bag/button_left.png")
private val RIGHT_BUTTON = cobblemonResource("textures/gui/bag/button_right.png")
}
var enabled = true
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
blitk(
matrixStack = context.pose(),
texture = if (leftButton) LEFT_BUTTON else RIGHT_BUTTON,
x = x / 0.5F, y = y / 0.5F,
width = WIDTH * 2, height = HEIGHT * 2,
textureHeight = 40,
vOffset = if (enabled) 20 else 0,
scale = 0.5f
)
}
override fun playDownSound(handler: SoundManager) {}
}
@@ -1,416 +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.gui.bag
import com.cobblemon.mod.common.CobblemonNetwork.sendToServer
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.client.gui.drawProfilePokemon
import com.cobblemon.mod.common.client.render.drawScaledText
import com.cobblemon.mod.common.client.render.drawScaledTextJustifiedRight
import com.cobblemon.mod.common.client.render.getDepletableRedGreen
import com.cobblemon.mod.common.client.render.models.blockbench.FloatingState
import com.cobblemon.mod.common.item.bag.CobblemonBagMenu
import com.cobblemon.mod.common.item.battle.BagItem
import com.cobblemon.mod.common.net.messages.client.bag.UpdateBagMenuDataPacket
import com.cobblemon.mod.common.net.messages.client.bag.UseItemOnPokemonFromBagPacket
import com.cobblemon.mod.common.pokemon.Gender
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.math.fromEulerXYZDegrees
import juuxel.adorn.util.Colors
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen
import net.minecraft.client.resources.sounds.SimpleSoundInstance
import net.minecraft.network.chat.Component
import net.minecraft.sounds.SoundEvent
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.inventory.ClickType
import net.minecraft.world.inventory.Slot
import org.joml.Quaternionf
import org.joml.Vector3f
import kotlin.math.min
import kotlin.math.roundToInt
@Environment(EnvType.CLIENT)
class CobblemonBagScreen(
menu: CobblemonBagMenu,
playerInventory: Inventory,
title: Component
): AbstractContainerScreen<CobblemonBagMenu>(
menu,
playerInventory,
Component.translatable("cobblemon.container.bag")
) {
companion object {
private const val BACKGROUND_HEIGHT = 197
private const val BACKGROUND_WIDTH = 184
private val BACKGROUND = cobblemonResource("textures/gui/bag/bag_base.png")
private val SCROLL_TRACK = cobblemonResource("textures/gui/bag/scrollbar_track.png")
private val SCROLL_SLIDE = cobblemonResource("textures/gui/bag/scrollbar_slide.png")
private val PARTY_SLOT_BASE = cobblemonResource("textures/gui/bag/party_slot_base.png")
private val PARTY_SLOT_COLLAPSED = cobblemonResource("textures/gui/bag/party_slot_collapsed.png")
private val PARTY_SLOT = cobblemonResource("textures/gui/bag/party_slot.png")
private val PARTY_SLOT_FAINTED = cobblemonResource("textures/gui/bag/party_slot_fainted.png")
private val GENDER_ICON_MALE = cobblemonResource("textures/gui/party/party_gender_male.png")
private val GENDER_ICON_FEMALE = cobblemonResource("textures/gui/party/party_gender_female.png")
}
val categoriesWidgets = mutableListOf<BagCategoryButton>()
lateinit var allItemsCategoryWidget: BagCategoryButton
lateinit var leftCategoryPageButton: BagCategoryPageButton
lateinit var rightCategoryPageButton: BagCategoryPageButton
var currentCategoryPage = 0
var lastCategory = menu.currentlySelectedCategory
var lastScroll = menu.scroll
var scrolling = false
init {
this.imageWidth = BACKGROUND_WIDTH + 69
this.imageHeight = BACKGROUND_HEIGHT + 27
}
override fun init() {
super.init()
this.leftPos -= 34
for (i in 0..3) {
if (i < BagCategories.getOrderedCategoriesList().size) {
categoriesWidgets.add(
BagCategoryButton(leftPos + 76 + i * 33, topPos, this, i) {
if (menu.currentlySelectedCategory != i) {
menu.changeCategory(i)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
)
} else break
}
allItemsCategoryWidget = BagCategoryButton(leftPos + 214, topPos, this, -1) {
if (menu.currentlySelectedCategory != -1) {
menu.changeCategory(-1)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
leftCategoryPageButton = BagCategoryPageButton(leftPos + 218, topPos + 32, this, true) {
if (leftCategoryPageButton.enabled) {
cycleCategoryPage(false)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
rightCategoryPageButton = BagCategoryPageButton(leftPos + 229, topPos + 32, this, false) {
if (rightCategoryPageButton.enabled) {
cycleCategoryPage(true)
playSound(CobblemonSounds.ITEM_BAG_CLICK)
}
}.also { addRenderableWidget(it) }
playSound(CobblemonSounds.ITEM_BAG_OPEN)
}
override fun renderBg(context: GuiGraphics, partialTick: Float, mouseX: Int, mouseY: Int) {}
override fun renderBackground(guiGraphics: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {}
override fun renderLabels(guiGraphics: GuiGraphics, mouseX: Int, mouseY: Int) {}
override fun render(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
renderTransparentBackground(context)
val matrices = context.pose()
// Background
blitk(
matrixStack = matrices,
texture = BACKGROUND,
x = leftPos + 69, y = topPos + 27,
width = BACKGROUND_WIDTH, height = BACKGROUND_HEIGHT
)
//Scroll
val scrollYOffset = if (menu.maxScroll == 0) {
if (menu.scroll == 0) 0 else 53
} else ((min(menu.scroll, menu.maxScroll).toFloat() / menu.maxScroll) * 53).toInt()
val trackHeight = 71 - scrollYOffset - 13
if (trackHeight > 0) {
blitk(
matrixStack = matrices,
texture = SCROLL_TRACK,
x = leftPos + 230, y = topPos + 49 + (71 - trackHeight),
width = 9, height = trackHeight,
textureHeight = 71,
vOffset = 71 - trackHeight
)
}
blitk(
matrixStack = matrices,
texture = SCROLL_SLIDE,
x = leftPos + 230, y = topPos + 49 + scrollYOffset,
width = 9, height = 17
)
// Pokemon
val party = CobblemonClient.storage.party
for (i in 0..5) {
val pokemon = party.get(i)
val slotYPosition = topPos + i * 33 + 27
if (pokemon != null) {
blitk(
matrixStack = matrices,
texture = PARTY_SLOT_BASE,
x = leftPos, y = slotYPosition,
width = 67, height = 31
)
val slotWidth = 32
val slotLeft = leftPos + 11
blitk(
matrixStack = matrices,
texture = if (pokemon.isFainted()) PARTY_SLOT_FAINTED else PARTY_SLOT,
x = slotLeft, y = slotYPosition,
width = slotWidth, height = 26,
textureHeight = 52,
vOffset = if (!menu.carried.isEmpty && menu.carried.item is BagItem && partySlotHovered(i, mouseX, mouseY)) 26 else 0
)
val expForThisLevel = pokemon.experience - pokemon.experienceGroup.getExperience(pokemon.level)
val expToNextLevel = pokemon.experienceGroup.getExperience(pokemon.level + 1) - pokemon.experienceGroup.getExperience(pokemon.level)
val expRatio = expForThisLevel.toFloat() / expToNextLevel
val expBarHeight = expRatio * 20
if (expBarHeight > 0) {
blitk(
matrixStack = matrices,
texture = CobblemonResources.WHITE,
x = leftPos + 6, y = slotYPosition + 24 - expBarHeight,
width = 1, height = expBarHeight,
red = 0.2, green = 0.65, blue = 0.84
)
}
val hpRatio = pokemon.currentHealth.toFloat() / pokemon.maxHealth
val hpBarHeight = hpRatio * 20
val (red, green) = getDepletableRedGreen(hpRatio)
if (hpBarHeight > 0) {
blitk(
matrixStack = matrices,
texture = CobblemonResources.WHITE,
x = leftPos + 8, y = slotYPosition + 24 - hpBarHeight,
width = 2, height = hpBarHeight,
red = red * 0.8F, green = green * 0.8F, blue = 0.27F
)
}
// Ball Icon
val ballIcon = cobblemonResource("textures/gui/ball/" + pokemon.caughtBall.name.path + ".png")
blitk(
matrixStack = matrices,
texture = ballIcon,
x = (leftPos + 3.5F) / 0.5F, y = (slotYPosition + 23) / 0.5F,
width = 18, height = 22,
textureHeight = 44,
scale = 0.5F
)
//Gender
if (pokemon.gender != Gender.GENDERLESS) {
blitk(
matrixStack = matrices,
texture = if (pokemon.gender == Gender.MALE) GENDER_ICON_MALE else GENDER_ICON_FEMALE,
x = (leftPos + 62) / 0.5F, y = (slotYPosition + 26) / 0.5F,
width = 5, height = 7,
scale = 0.5F
)
}
//Status
val status = pokemon.status?.status
if (!pokemon.isFainted() && status != null) {
blitk(
matrixStack = matrices,
texture = cobblemonResource("textures/gui/bag/status_${status.showdownName}.png"),
x = leftPos + 1, y = slotYPosition + 9,
width = 4, height = 14
)
}
matrices.pushPose()
matrices.translate(slotLeft + ((slotWidth - 8) / 2.0), slotYPosition.toDouble() - 6, 0.0)
matrices.scale(3.5F, 3.5F, 1F)
val state = FloatingState()
state.currentAspects = pokemon.aspects
drawProfilePokemon(
species = pokemon.species.resourceIdentifier,
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = state,
scale = 4.5F,
partialTicks = 0F
)
matrices.popPose()
matrices.pushPose()
matrices.translate(0.0, 0.0, 100.0)
// Level and Name and Gender
drawScaledText(
context = context,
text = pokemon.getDisplayName(),
x = leftPos + 14, y = slotYPosition + 26,
scale = 0.5F
)
drawScaledTextJustifiedRight(
context = context,
text = lang("ui.lv"),
x = leftPos + 40, y = slotYPosition + 14,
shadow = true,
scale = 0.5F
)
drawScaledTextJustifiedRight(
context = context,
text = pokemon.level.toString().text(),
x = leftPos + 40, y = slotYPosition + 19,
shadow = true,
scale = 0.5F
)
matrices.popPose()
} else {
blitk(
matrixStack = matrices,
texture = PARTY_SLOT_COLLAPSED,
x = leftPos + 64, y = slotYPosition,
width = 5, height = 31
)
}
}
//Titles
context.drawString(font, title, leftPos + 80, topPos + 33, Colors.WHITE, false)
context.drawString(font, playerInventoryTitle, leftPos + 80, topPos + 129, 4210752, false)
super.render(context, mouseX, mouseY, partialTick)
renderTooltip(context, mouseX, mouseY)
}
fun partySlotHovered(index: Int, mouseX: Int, mouseY: Int): Boolean {
val left = leftPos + 11
val top = topPos + index * 33 + 27
return mouseX in left..(left + 32) && mouseY in top..(top + 26)
}
fun cycleCategoryPage(next: Boolean) {
val orderedCategories = BagCategories.getOrderedCategoriesList()
currentCategoryPage = (currentCategoryPage + if (next) 1 else -1).coerceIn(0, (orderedCategories.size - 1) / 4)
categoriesWidgets.forEach {
removeWidget(it)
}
categoriesWidgets.clear()
for (i in 0..3) {
val adjustedIndex = i + 4 * currentCategoryPage
if (adjustedIndex < orderedCategories.size) {
categoriesWidgets.add(
BagCategoryButton(leftPos + 76 + i * 33, topPos, this, adjustedIndex) {
playSound(CobblemonSounds.ITEM_BAG_CLICK)
menu.changeCategory(adjustedIndex)
}.also { addRenderableWidget(it) }
)
} else break
}
leftCategoryPageButton.enabled = currentCategoryPage > 0
rightCategoryPageButton.enabled = currentCategoryPage < (orderedCategories.size - 1) / 4
}
fun updateScrollValue(mouseY: Double) {
val adjustedMouseY = mouseY - topPos - 49.0
if (adjustedMouseY < 0) {
menu.scroll = 0
} else if (adjustedMouseY > 71) {
menu.scroll = menu.maxScroll
} else {
menu.scroll = ((adjustedMouseY / 71.0) * (menu.maxScroll)).roundToInt()
}
menu.setupSlotsBasedOnContent()
}
override fun slotClicked(slot: Slot?, slotId: Int, mouseButton: Int, type: ClickType) {
if (slotId in CobblemonBagMenu.BAG_SLOTS && (lastCategory != menu.currentlySelectedCategory || lastScroll != menu.scroll)) {
lastCategory = menu.currentlySelectedCategory
lastScroll = menu.scroll
sendToServer(UpdateBagMenuDataPacket(menu.currentlySelectedCategory, menu.scroll)) // Synchronize this data
}
super.slotClicked(slot, slotId, mouseButton, type)
}
override fun mouseScrolled(mouseX: Double, mouseY: Double, scrollX: Double, scrollY: Double): Boolean {
if (scrollY < 0 && menu.scroll < menu.maxScroll) {
menu.scroll += 1
} else if (scrollY > 0 && menu.scroll > 0) {
menu.scroll -= 1
}
menu.setupSlotsBasedOnContent()
return true
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
if (mouseX in (leftPos + 229.0)..(leftPos + 240.0) && mouseY in (topPos + 49.0)..(topPos + 120.0)) {
scrolling = true
updateScrollValue(mouseY)
return true
}
val party = CobblemonClient.storage.party
if (!menu.carried.isEmpty && menu.carried.item is BagItem) {
for (i in 0..5) {
if (party.get(i) != null && partySlotHovered(i, mouseX.toInt(), mouseY.toInt())) {
playSound(CobblemonSounds.GUI_CLICK)
sendToServer(UseItemOnPokemonFromBagPacket(i))
return true
}
}
}
return super.mouseClicked(mouseX, mouseY, button)
}
override fun mouseReleased(mouseX: Double, mouseY: Double, button: Int): Boolean {
scrolling = false
return super.mouseReleased(mouseX, mouseY, button)
}
override fun mouseDragged(mouseX: Double, mouseY: Double, button: Int, dragX: Double, dragY: Double): Boolean {
if (scrolling) {
updateScrollValue(mouseY)
return true
}
return super.mouseDragged(mouseX, mouseY, button, dragX, dragY)
}
fun playSound(soundEvent: SoundEvent) {
Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(soundEvent, 1.0F))
}
override fun onClose() {
Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(CobblemonSounds.ITEM_BAG_CLOSE, 1.0F))
super.onClose()
}
}
@@ -0,0 +1,131 @@
/*
* 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.gui.pokeradar
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarNavpointPacket
import com.cobblemon.mod.common.pokeradar.Navpoint
import com.cobblemon.mod.common.pokeradar.PokeRadarPage
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.gui.components.EditBox
import net.minecraft.network.chat.Component
import net.minecraft.world.item.DyeColor
import net.minecraft.world.level.Level
import kotlin.math.abs
class NavEditGUI(
override val type: PokeRadarType,
private val navpoint: Navpoint
) : PokeRadarGUI(type, PokeRadarPage.NAV) {
companion object {
const val SWATCH = 16
private val COORDINATE = Regex("-?\\d{0,8}")
}
private var title = navpoint.title
private var xText = navpoint.x.toString()
private var zText = navpoint.z.toString()
private lateinit var saveButton: Button
private val swatchX get() = left + 8
private val swatchY get() = top + 82
private fun parse(text: String) = text.toIntOrNull()?.takeIf { abs(it) <= Level.MAX_LEVEL_SIZE }
override fun initPage() {
addRenderableWidget(EditBox(font, left + 8, top + 50, 200, 16, lang("ui.poke_radar.nav.name"))).apply {
setMaxLength(Navpoint.MAX_TITLE_LENGTH)
value = title
setResponder { title = it }
}
coordinateBox(left + 28, xText) { xText = it }
coordinateBox(left + 128, zText) { zText = it }
button(lang("ui.poke_radar.nav.here"), left + 220, top + 140, 112) {
val player = minecraft!!.player!!
xText = player.blockX.toString()
zText = player.blockZ.toString()
rebuildWidgets()
}
saveButton = button(lang("ui.poke_radar.nav.save"), left + WIDTH - 104, top + HEIGHT - 22, 100) {
val x = parse(xText) ?: return@button
val z = parse(zText) ?: return@button
PokeRadarNavpointPacket(
PokeRadarNavpointPacket.Action.SAVE,
navpoint.copy(title = title, x = x, z = z)
).sendToServer()
minecraft!!.setScreen(NavGUI(type))
}
button(lang("ui.poke_radar.nav.cancel"), left + WIDTH - 208, top + HEIGHT - 22, 100) {
minecraft!!.setScreen(NavGUI(type))
}
}
private fun coordinateBox(x: Int, value: String, onChange: (String) -> Unit) {
addRenderableWidget(EditBox(font, x, top + 140, 80, 16, lang("ui.poke_radar.nav.coordinate"))).apply {
setFilter { COORDINATE.matches(it) }
this.value = value
setResponder { onChange(it); setTextColor(if (parse(it) == null) 0xFF5555 else 0xE0E0E0) }
}
}
override fun onDataChanged() {}
override fun renderPage(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
saveButton.active = parse(xText) != null && parse(zText) != null
context.drawString(
font,
lang(if (navpoint.id.isEmpty()) "ui.poke_radar.nav.add" else "ui.poke_radar.nav.edit"),
left + 8,
top + 28,
0xFFFFFF
)
context.drawString(font, lang("ui.poke_radar.nav.name"), left + 8, top + 40, 0xAAAAAA)
context.drawString(font, lang("ui.poke_radar.nav.color"), left + 8, top + 72, 0xAAAAAA)
context.drawString(font, "X", left + 16, top + 144, 0xAAAAAA)
context.drawString(font, "Z", left + 116, top + 144, 0xAAAAAA)
DyeColor.entries.forEach { color ->
val x = swatchX + (color.id % 8) * (SWATCH + 4)
val y = swatchY + (color.id / 8) * (SWATCH + 4)
context.fill(x, y, x + SWATCH, y + SWATCH, (0xFF000000 or color.textureDiffuseColor.toLong()).toInt())
if (color.id == navpoint.color) context.renderOutline(
x - 2,
y - 2,
SWATCH + 4,
SWATCH + 4,
0xFFFFFFFF.toInt()
)
if (isIn(
mouseX,
mouseY,
x,
y,
SWATCH,
SWATCH
)
) showTooltip(listOf(Component.translatable("color.minecraft.${color.getName()}")))
}
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
if (super.mouseClicked(mouseX, mouseY, button)) return true
DyeColor.entries.forEach { color ->
val x = swatchX + (color.id % 8) * (SWATCH + 4)
val y = swatchY + (color.id / 8) * (SWATCH + 4)
if (isIn(mouseX, mouseY, x, y, SWATCH, SWATCH)) {
navpoint.color = color.id
return true
}
}
return false
}
}
@@ -0,0 +1,211 @@
/*
* 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.gui.pokeradar
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.item.PokeRadarItem
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarNavpointPacket
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarTrackingPacket
import com.cobblemon.mod.common.pokeradar.Navpoint
import com.cobblemon.mod.common.pokeradar.PokeRadarPage
import com.cobblemon.mod.common.pokeradar.TrackingMode
import com.cobblemon.mod.common.pokeradar.TrackingQuery
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.EditBox
import net.minecraft.client.gui.screens.ConfirmScreen
import net.minecraft.network.chat.Component
import net.minecraft.util.Mth
import net.minecraft.world.item.DyeColor
import net.minecraft.world.item.ItemStack
class NavGUI(override val type: PokeRadarType) : PokeRadarGUI(type, PokeRadarPage.NAV) {
companion object {
const val ROW_H = 16
const val ROWS = 9
private var search = ""
private var colorFilter: DyeColor? = null
}
private var scrollRow = 0
private var selectedId: String? = null
private val listX get() = left + 4
private val listY get() = top + 58
private val listW = WIDTH - 8
private val visible: List<Navpoint>
get() = ClientPokeRadar.state.navpoints
.sortedByDescending { it.created }
.filter { colorFilter == null || it.color == colorFilter!!.id }
.filter { search.isBlank() || displayTitle(it).contains(search, ignoreCase = true) }
private val selected get() = ClientPokeRadar.state.navpoints.find { it.id == selectedId }
private fun displayTitle(navpoint: Navpoint) = if (navpoint.locked) Navpoint.HIDDEN_TITLE else navpoint.title
private fun isTracked(navpoint: Navpoint) = ClientPokeRadar.trackingActive &&
ClientPokeRadar.state.query?.let { it.mode == TrackingMode.NAVPOINT && it.navpointId == navpoint.id } == true
override fun initPage() {
addRenderableWidget(EditBox(font, left + 4, top + 24, 136, 16, lang("ui.poke_radar.search"))).apply {
setHint(lang("ui.poke_radar.search"))
value = search
setResponder { search = it; scrollRow = 0 }
}
button(Component.literal("x"), left + 142, top + 24, 14, 16, tooltip = lang("ui.poke_radar.search.clear")) {
search = ""
rebuildWidgets()
}
val filterLabel =
colorFilter?.let { Component.translatable("color.minecraft.${it.getName()}") } ?: lang("ui.poke_radar.any")
button(
lang("ui.poke_radar.nav.color_filter", filterLabel),
left + 160,
top + 24,
120,
16,
tooltip = lang("ui.poke_radar.nav.color_filter.tooltip")
) {
colorFilter = colorFilter.let { current ->
if (current == null) DyeColor.byId(0) else DyeColor.entries.getOrNull(current.id + 1)
}
scrollRow = 0
rebuildWidgets()
}
button(Component.literal("+"), left + WIDTH - 24, top + 24, 20, 16, tooltip = lang("ui.poke_radar.nav.add")) {
val player = minecraft!!.player!!
minecraft!!.setScreen(NavEditGUI(type, Navpoint(id = "", x = player.blockX, z = player.blockZ)))
}
val navpoint = selected ?: return
val y = top + HEIGHT - 22
val w = (WIDTH - 8 - 6) / 4
val locked = navpoint.locked
button(lang("ui.poke_radar.nav.edit"), left + 4, y, w) {
minecraft!!.setScreen(NavEditGUI(type, navpoint.copy()))
}.active = !locked
button(lang("ui.poke_radar.nav.delete"), left + 6 + w, y, w) {
minecraft!!.setScreen(
ConfirmScreen(
{ confirmed ->
if (confirmed) {
PokeRadarNavpointPacket(PokeRadarNavpointPacket.Action.DELETE, navpoint).sendToServer()
selectedId = null
}
minecraft!!.setScreen(this)
},
lang("ui.poke_radar.nav.delete.title"),
lang("ui.poke_radar.nav.delete.message", displayTitle(navpoint))
)
)
}
val tracked = isTracked(navpoint)
button(
lang(if (tracked) "ui.poke_radar.tracking.stop" else "ui.poke_radar.nav.track"),
left + 8 + w * 2,
y,
w
) {
PokeRadarTrackingPacket(
if (tracked) null else TrackingQuery(
mode = TrackingMode.NAVPOINT,
navpointId = navpoint.id
)
).sendToServer()
}.active = !locked
button(
lang("ui.poke_radar.nav.upload"),
left + 10 + w * 3,
y,
w,
tooltip = lang("ui.poke_radar.nav.upload.tooltip")
) {
PokeRadarNavpointPacket(PokeRadarNavpointPacket.Action.UPLOAD, navpoint).sendToServer()
}.active = !navpoint.encrypted && !chip().isEmpty
}
private fun chip() =
minecraft?.player?.let(PokeRadarItem::heldRadar)?.let(PokeRadarItem::getChip) ?: ItemStack.EMPTY
override fun renderPage(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
val chip = chip()
val chipText = when {
chip.isEmpty -> lang("ui.poke_radar.nav.chip.none")
chip.`is`(CobblemonItems.BLANK_NAV_CHIP) -> lang("ui.poke_radar.nav.chip.blank")
else -> lang("ui.poke_radar.nav.chip.written", chip.hoverName)
}
context.drawString(font, chipText, left + 6, top + 46, 0xAAAAAA)
val list = visible
if (list.isEmpty()) {
context.drawCenteredString(
font,
lang("ui.poke_radar.empty.no_navpoints"),
left + WIDTH / 2,
listY + 50,
0xAAAAAA
)
return
}
scrollRow = Mth.clamp(scrollRow, 0, maxScroll(list.size))
list.drop(scrollRow).take(ROWS).forEachIndexed { index, navpoint ->
val y = listY + index * ROW_H
val hovered = isIn(mouseX, mouseY, listX, y, listW, ROW_H - 2)
context.fill(
listX, y, listX + listW, y + ROW_H - 2,
if (navpoint.id == selectedId) CELL_SELECTED else if (hovered) CELL_HOVER else CELL
)
context.fill(
listX + 3,
y + 2,
listX + 13,
y + 12,
(0xFF000000 or navpoint.dyeColor().textureDiffuseColor.toLong()).toInt()
)
context.drawString(font, displayTitle(navpoint), listX + 18, y + 3, 0xFFFFFF)
val right = if (navpoint.locked) "X: ? Z: ?" else "X: ${navpoint.x} Z: ${navpoint.z}"
context.drawString(font, right, listX + listW - font.width(right) - 4, y + 3, 0xAAAAAA)
if (isTracked(navpoint)) context.drawString(
font,
"◎",
listX + listW - font.width(right) - 16,
y + 3,
0x55FF55
)
if (hovered) {
showTooltip(
listOfNotNull(
Component.literal(displayTitle(navpoint)),
Component.translatable("color.minecraft.${navpoint.dyeColor().getName()}"),
if (navpoint.locked) lang("ui.poke_radar.nav.encrypted") else null
)
)
}
}
}
private fun maxScroll(count: Int) = (count - ROWS).coerceAtLeast(0)
override fun mouseScrolled(mouseX: Double, mouseY: Double, scrollX: Double, scrollY: Double): Boolean {
scrollRow = Mth.clamp(scrollRow - Mth.sign(scrollY), 0, maxScroll(visible.size))
return true
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
if (super.mouseClicked(mouseX, mouseY, button)) return true
if (!isIn(mouseX, mouseY, listX, listY, listW, ROWS * ROW_H)) return false
val navpoint = visible.getOrNull(scrollRow + ((mouseY - listY) / ROW_H).toInt()) ?: return false
selectedId = if (selectedId == navpoint.id) null else navpoint.id
rebuildWidgets()
return true
}
}
@@ -0,0 +1,184 @@
/*
* 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.gui.pokeradar
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.pokedex.PokedexEntryProgress
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
import com.cobblemon.mod.common.client.gui.drawProfilePokemon
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.client.render.models.blockbench.FloatingState
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarSettingsPacket
import com.cobblemon.mod.common.pokemon.RenderablePokemon
import com.cobblemon.mod.common.pokeradar.PokeRadarPage
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.math.fromEulerXYZDegrees
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.gui.components.Tooltip
import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import org.joml.Quaternionf
import org.joml.Vector3f
/**
* Base for every Poké Radar page
*/
abstract class PokeRadarGUI(
open val type: PokeRadarType,
val page: PokeRadarPage
) : Screen(Component.translatable("cobblemon.ui.poke_radar.title")), CobblemonRenderable {
companion object {
const val WIDTH = 340
const val HEIGHT = 232
const val BACKGROUND = 0xE0101820.toInt()
const val BORDER = 0xFF5A6E8C.toInt()
const val CELL = 0x40FFFFFF
const val CELL_HOVER = 0x80FFFFFF.toInt()
const val CELL_SELECTED = 0x8055AAFF.toInt()
val CAUGHT_ICON = cobblemonResource("textures/gui/poke_radar/caught.png")
val UNKNOWN_ICON = cobblemonResource("textures/gui/poke_radar/unknown.png")
val SELECTED_ICON = cobblemonResource("textures/gui/poke_radar/selected.png")
fun open(type: PokeRadarType) {
Minecraft.getInstance().setScreen(create(type, ClientPokeRadar.state.lastPage))
ClientPokeRadar.playUiSound(CobblemonSounds.POKEDEX_OPEN)
}
fun create(
type: PokeRadarType,
page: PokeRadarPage,
preselect: List<ResourceLocation> = emptyList()
): PokeRadarGUI = when (page) {
PokeRadarPage.RADAR -> RadarGUI(type)
PokeRadarPage.TRACKING -> TrackingGUI(type, preselect)
PokeRadarPage.NAV -> NavGUI(type)
}
fun knowledge(species: ResourceLocation): PokedexEntryProgress =
CobblemonClient.clientPokedexData.getHighestKnowledgeForSpecies(species)
fun seen(species: ResourceLocation) = knowledge(species) != PokedexEntryProgress.UNREGISTERED
fun toggleLabel(selected: Boolean, label: Component): Component =
Component.literal(if (selected) "§a✔ §r" else "").append(label)
}
protected val left get() = (width - WIDTH) / 2
protected val top get() = (height - HEIGHT) / 2
private val pendingTooltip = mutableListOf<Component>()
override fun init() {
PokeRadarPage.entries.forEachIndexed { index, target ->
addRenderableWidget(
Button.builder(lang("ui.poke_radar.page.${target.name.lowercase()}")) { switchPage(target) }
.bounds(left + 4 + index * 66, top + 4, 64, 16)
.build()
).active = target != page
}
initPage()
}
protected abstract fun initPage()
protected abstract fun renderPage(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float)
open fun onDataChanged() = rebuildWidgets()
fun switchPage(target: PokeRadarPage, preselect: List<ResourceLocation> = emptyList()) {
ClientPokeRadar.state.lastPage = target
PokeRadarSettingsPacket(target, ClientPokeRadar.state.muted).sendToServer()
minecraft?.setScreen(create(type, target, preselect))
}
protected fun showTooltip(lines: List<Component>) {
pendingTooltip.clear()
pendingTooltip.addAll(lines)
}
protected fun button(
label: Component,
x: Int,
y: Int,
w: Int,
h: Int = 18,
tooltip: Component? = null,
onPress: () -> Unit
): Button =
addRenderableWidget(Button.builder(label) { onPress() }.bounds(x, y, w, h).build().also { b ->
tooltip?.let {
b.tooltip =
Tooltip.create(it)
}
})
override fun renderBackground(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
super.renderBackground(context, mouseX, mouseY, partialTick)
context.fill(left, top, left + WIDTH, top + HEIGHT, BACKGROUND)
context.renderOutline(left, top, WIDTH, HEIGHT, BORDER)
}
override fun render(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
super.render(context, mouseX, mouseY, partialTick)
renderPage(context, mouseX, mouseY, partialTick)
if (pendingTooltip.isNotEmpty()) {
context.renderComponentTooltip(font, pendingTooltip, mouseX, mouseY)
pendingTooltip.clear()
}
}
protected fun isIn(mouseX: Number, mouseY: Number, x: Int, y: Int, w: Int, h: Int) =
mouseX.toDouble() in x.toDouble()..(x + w).toDouble() && mouseY.toDouble() in y.toDouble()..(y + h).toDouble()
protected fun drawPokemon(
context: GuiGraphics,
pokemon: RenderablePokemon,
x: Int,
y: Int,
w: Int,
h: Int,
scale: Float
) {
context.enableScissor(x, y, x + w, y + h)
val matrices = context.pose()
matrices.pushPose()
matrices.translate(x + w / 2.0, y + h * 0.1, 0.0)
val state = FloatingState()
state.currentAspects = pokemon.aspects
drawProfilePokemon(
renderablePokemon = pokemon,
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = state,
partialTicks = 0F,
scale = scale
)
matrices.popPose()
context.disableScissor()
}
protected fun drawUnknown(context: GuiGraphics, x: Int, y: Int, w: Int, h: Int) =
context.blit(UNKNOWN_ICON, x + (w - 8) / 2, y + (h - 10) / 2, 0F, 0F, 8, 10, 8, 10)
protected fun drawCaught(context: GuiGraphics, rightX: Int, y: Int) {
context.pose().pushPose()
context.pose().translate(0.0, 0.0, 200.0)
context.blit(CAUGHT_ICON, rightX - 11, y, 0F, 0F, 11, 11, 11, 11)
context.pose().popPose()
}
override fun isPauseScreen() = false
}
@@ -0,0 +1,217 @@
/*
* 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.gui.pokeradar
import com.cobblemon.mod.common.api.pokedex.PokedexEntryProgress
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.text.gray
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarScanPacket
import com.cobblemon.mod.common.pokemon.RenderablePokemon
import com.cobblemon.mod.common.pokeradar.PokeRadarConstants
import com.cobblemon.mod.common.pokeradar.PokeRadarPage
import com.cobblemon.mod.common.pokeradar.RadarEntry
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.weightedSelection
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.network.chat.Component
import net.minecraft.util.Mth
class RadarGUI(override val type: PokeRadarType) : PokeRadarGUI(type, PokeRadarPage.RADAR) {
companion object {
const val CELL_W = 46
const val CELL_H = 58
const val COLUMNS = 7
const val ROWS = 3
const val HERD_PICKS = 3
}
private var scrollRow = 0
private lateinit var scanButton: Button
private var awaitingScan = false
private val herdPicks = mutableMapOf<String, List<RadarEntry.Member>>()
private val renderables = mutableMapOf<String, RenderablePokemon?>()
private val gridX get() = left + (WIDTH - COLUMNS * CELL_W) / 2
private val gridY get() = top + 46
private val entries: List<RadarEntry>?
get() = ClientPokeRadar.results[ClientPokeRadar.fishing]?.let { list ->
if (ClientPokeRadar.sortAscending) list.sortedBy { it.percentage } else list.sortedByDescending { it.percentage }
}
override fun initPage() {
val fishing = ClientPokeRadar.fishing
button(
lang(if (fishing) "ui.poke_radar.mode.fishing" else "ui.poke_radar.mode.normal"), left + 4, top + 24, 72,
tooltip = lang("ui.poke_radar.mode.tooltip")
) {
ClientPokeRadar.fishing = !ClientPokeRadar.fishing
scrollRow = 0
rebuildWidgets()
}
button(
lang(if (ClientPokeRadar.sortAscending) "ui.poke_radar.sort.least" else "ui.poke_radar.sort.most"),
left + 80,
top + 24,
78,
tooltip = lang("ui.poke_radar.sort.tooltip")
) {
ClientPokeRadar.sortAscending = !ClientPokeRadar.sortAscending
rebuildWidgets()
}
if (fishing) {
(0..3).forEach { level ->
button(
Component.literal("$level"),
left + 164 + level * 20,
top + 24,
18,
tooltip = lang("ui.poke_radar.lure_level", level)
) {
ClientPokeRadar.lureLevel = level
rebuildWidgets()
}.active = ClientPokeRadar.lureLevel != level
}
}
awaitingScan = false
scanButton = button(
lang("ui.poke_radar.scan"),
left + WIDTH - 84,
top + 24,
80,
tooltip = lang("ui.poke_radar.scan.tooltip")
) {
PokeRadarScanPacket(ClientPokeRadar.fishing, ClientPokeRadar.lureLevel).sendToServer()
awaitingScan = true
}
updateScanButton()
}
private fun updateScanButton() {
val seconds = ClientPokeRadar.cooldownSeconds
scanButton.message =
if (seconds > 0) lang("ui.poke_radar.scan.cooldown", seconds) else lang("ui.poke_radar.scan")
scanButton.active = seconds == 0 && !awaitingScan
}
override fun tick() {
super.tick()
updateScanButton()
}
private fun pickModels(entry: RadarEntry): List<RadarEntry.Member> = if (!entry.isHerd) entry.members else
herdPicks.getOrPut(entry.id) {
List(HERD_PICKS) {
entry.members.weightedSelection { it.weight } ?: entry.members.first()
}
}
private fun renderable(member: RadarEntry.Member) = renderables.getOrPut(member.properties) {
runCatching { PokemonProperties.parse(member.properties).asRenderablePokemon() }.getOrNull()
}
private fun caught(entry: RadarEntry) =
entry.members.map { it.species }.distinct().all { knowledge(it) == PokedexEntryProgress.OWNED }
override fun renderPage(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
val list = entries
if (list.isNullOrEmpty()) {
val key = if (list == null) "ui.poke_radar.empty.not_scanned" else "ui.poke_radar.empty.nothing"
context.drawCenteredString(font, lang(key), left + WIDTH / 2, top + HEIGHT / 2, 0xAAAAAA)
return
}
scrollRow = Mth.clamp(scrollRow, 0, maxScroll(list.size))
val first = scrollRow * COLUMNS
list.drop(first).take(COLUMNS * ROWS).forEachIndexed { i, entry ->
val x = gridX + (i % COLUMNS) * CELL_W
val y = gridY + (i / COLUMNS) * CELL_H
val hovered = isIn(mouseX, mouseY, x, y, CELL_W - 2, CELL_H - 2)
renderEntry(context, entry, x, y, hovered)
if (hovered) showTooltip(tooltipFor(entry))
}
if (list.size > COLUMNS * ROWS) {
context.drawString(
font,
"${scrollRow + 1}/${maxScroll(list.size) + 1}",
left + WIDTH - 30,
top + HEIGHT - 10,
0x888888
)
}
}
private fun renderEntry(context: GuiGraphics, entry: RadarEntry, x: Int, y: Int, hovered: Boolean) {
val w = CELL_W - 2
val modelH = CELL_H - 14
context.fill(x, y, x + w, y + CELL_H - 2, if (hovered) CELL_HOVER else CELL)
if (ClientPokeRadar.fishing) {
// TODO: Fishing Background
context.fill(x + 2, y + modelH - 8, x + w - 2, y + modelH, 0x803366CC.toInt())
}
val picks = pickModels(entry)
val slotW = w / picks.size
picks.forEachIndexed { index, member ->
val pokemon = renderable(member)
val slotX = x + index * slotW
if (pokemon != null && seen(member.species)) {
drawPokemon(context, pokemon, slotX, y + 1, slotW, modelH, if (picks.size > 1) 7F else 11F)
} else {
drawUnknown(context, slotX, y, slotW, modelH)
}
}
context.pose().pushPose()
context.pose().translate(0.0, 0.0, 200.0)
context.drawCenteredString(font, formatPercent(entry.percentage), x + w / 2, y + CELL_H - 12, 0xFFFFFF)
context.pose().popPose()
if (caught(entry)) drawCaught(context, x + w - 1, y + 1)
}
private fun formatPercent(percent: Float) = if (percent < 0.01F) "<0.01%" else "%.2f%%".format(percent)
private fun tooltipFor(entry: RadarEntry): List<Component> {
val names = entry.members.map { it.species }.distinct().map { id ->
if (seen(id)) PokemonSpecies.getByIdentifier(id)?.translatedName
?: Component.literal(id.path) else Component.literal("???")
}
return names + listOf(
Component.literal(entry.id).gray(),
lang("ui.poke_radar.chance", formatPercent(entry.percentage)).gray()
)
}
private fun maxScroll(count: Int) = ((count + COLUMNS - 1) / COLUMNS - ROWS).coerceAtLeast(0)
override fun mouseScrolled(mouseX: Double, mouseY: Double, scrollX: Double, scrollY: Double): Boolean {
scrollRow = Mth.clamp(scrollRow - Mth.sign(scrollY), 0, maxScroll(entries?.size ?: 0))
return true
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
if (super.mouseClicked(mouseX, mouseY, button)) return true
val list = entries ?: return false
val col = ((mouseX - gridX) / CELL_W).toInt()
val row = ((mouseY - gridY) / CELL_H).toInt()
if (mouseX < gridX || mouseY < gridY || col !in 0 until COLUMNS || row !in 0 until ROWS) return false
val entry = list.getOrNull((scrollRow + row) * COLUMNS + col) ?: return false
val species =
entry.members.map { it.species }.distinct().filter(::seen).take(PokeRadarConstants.MAX_TRACKED_SPECIES)
if (species.isEmpty()) return false
switchPage(PokeRadarPage.TRACKING, species)
return true
}
}
@@ -0,0 +1,358 @@
/*
* 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.gui.pokeradar
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.pokedex.PokedexEntryProgress
import com.cobblemon.mod.common.api.pokemon.Natures
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarSettingsPacket
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarTrackingPacket
import com.cobblemon.mod.common.pokemon.Gender
import com.cobblemon.mod.common.pokemon.PokemonSizeCategory
import com.cobblemon.mod.common.pokemon.RenderablePokemon
import com.cobblemon.mod.common.pokemon.Species
import com.cobblemon.mod.common.pokeradar.*
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.lang
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.EditBox
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import net.minecraft.util.Mth
class TrackingGUI(
override val type: PokeRadarType,
preselect: List<ResourceLocation> = emptyList()
) : PokeRadarGUI(type, PokeRadarPage.TRACKING) {
companion object {
const val SLOT = 30
const val COLUMNS = 6
const val ROWS = 4
}
private val query: TrackingQuery = ClientPokeRadar.draft
?: ClientPokeRadar.state.query?.takeIf { it.mode != TrackingMode.NAVPOINT }?.copyDeep()
?: TrackingQuery()
private var search = ""
private var scrollRow = 0
private val gridX get() = left + 4
private val gridY get() = top + 66
private val previewX get() = left + 196
private val previewY get() = top + 46
private val previewW = 140
init {
if (preselect.isNotEmpty()) {
query.mode = TrackingMode.POKEMON
query.species = preselect.map { it.toString() }.toMutableList()
clearSpeciesAttributes()
selectionChanged()
}
ClientPokeRadar.draft = query
}
private val selectedSpecies: List<Species>
get() = query.species.mapNotNull { PokemonSpecies.getByIdentifier(it.asIdentifierDefaultingNamespace()) }
private val visibleSpecies: List<Species>
get() = PokemonSpecies.implemented.sortedBy { it.nationalPokedexNumber }.filter {
search.isBlank() || (seen(it.resourceIdentifier) && it.translatedName.string.contains(
search,
ignoreCase = true
))
}
override fun initPage() {
val pokemonMode = query.mode == TrackingMode.POKEMON
button(lang("ui.poke_radar.tracking.general"), left + 4, top + 24, 72) {
query.mode = TrackingMode.GENERAL; rebuildWidgets()
}
.active = pokemonMode
button(lang("ui.poke_radar.tracking.pokemon"), left + 80, top + 24, 72) {
query.mode = TrackingMode.POKEMON; rebuildWidgets()
}
.active = !pokemonMode
button(
lang(if (ClientPokeRadar.state.muted) "ui.poke_radar.sound.off" else "ui.poke_radar.sound.on"),
left + WIDTH - 54, top + 24, 50,
tooltip = lang("ui.poke_radar.sound.tooltip")
) {
ClientPokeRadar.state.muted = !ClientPokeRadar.state.muted
ClientPokeRadar.playUiSound(CobblemonSounds.POKE_RADAR_MUTE_TOGGLE)
PokeRadarSettingsPacket(page, ClientPokeRadar.state.muted).sendToServer()
rebuildWidgets()
}
if (pokemonMode) initPokemon() else initGeneral()
val tracking = ClientPokeRadar.trackingActive
button(
lang(if (tracking) "ui.poke_radar.tracking.stop" else "ui.poke_radar.tracking.start"),
left + WIDTH - 104,
top + HEIGHT - 22,
100
) {
PokeRadarTrackingPacket(if (tracking) null else query.copyDeep()).sendToServer()
}.active = tracking || canStart()
}
private fun canStart() = when (query.mode) {
TrackingMode.GENERAL -> query.general.isNotEmpty()
else -> query.species.isNotEmpty()
}
private fun initGeneral() {
GeneralAttribute.entries.forEachIndexed { index, attribute ->
val selected = attribute in query.general
button(
toggleLabel(selected, lang("ui.poke_radar.attribute.${attribute.name.lowercase()}")),
left + 8 + (index % 2) * 164, top + 48 + (index / 2) * 22, 160,
tooltip = lang("ui.poke_radar.attribute.${attribute.name.lowercase()}.tooltip")
) {
if (!query.general.add(attribute)) query.general.remove(attribute)
selectionChanged()
}
}
}
private fun initPokemon() {
addRenderableWidget(EditBox(font, gridX, previewY, COLUMNS * SLOT, 16, lang("ui.poke_radar.search"))).apply {
setHint(lang("ui.poke_radar.search"))
value = search
setResponder { search = it; scrollRow = 0 }
}
button(
Component.literal("x"),
gridX + COLUMNS * SLOT + 2,
previewY,
14,
16,
tooltip = lang("ui.poke_radar.search.clear")
) {
search = ""
rebuildWidgets()
}
val species = selectedSpecies.singleOrNull() ?: return
val x = previewX
var y = previewY + 58
listOf(
"shiny" to query::shiny,
"alpha" to query::alpha,
"max_iv" to query::maxIv
).forEachIndexed { index, (key, property) ->
button(
toggleLabel(property.get(), lang("ui.poke_radar.attribute.$key")), x + index * 47, y, 45,
tooltip = lang("ui.poke_radar.attribute.$key.tooltip")
) {
property.set(!property.get())
selectionChanged()
}
}
y += 20
val abilities = species.abilities.map { it.template }.distinctBy { it.name }
val ability = abilities.find { it.name == query.ability }
button(
lang(
"ui.poke_radar.ability",
ability?.let { Component.translatable(it.displayName) } ?: lang("ui.poke_radar.any")), x, y, previewW) {
query.ability = cycle(abilities.map { it.name }, query.ability)
selectionChanged()
}
y += 20
val natures = Natures.all().sortedBy { it.name.path }
val nature = natures.find { it.name.toString() == query.nature }
button(
lang(
"ui.poke_radar.nature",
nature?.let { Component.translatable(it.displayName) } ?: lang("ui.poke_radar.any")), x, y, previewW) {
query.nature = cycle(natures.map { it.name.toString() }, query.nature)
selectionChanged()
}
y += 20
val genders = when {
species.maleRatio < 0 -> emptyList()
species.maleRatio == 0F -> listOf(Gender.FEMALE)
species.maleRatio == 1F -> listOf(Gender.MALE)
else -> listOf(Gender.MALE, Gender.FEMALE)
}
genders.forEachIndexed { index, gender ->
button(
toggleLabel(gender.name in query.genders, lang("gender.${gender.name.lowercase()}")),
x + index * 70,
y,
68
) {
if (!query.genders.add(gender.name)) query.genders.remove(gender.name)
selectionChanged()
}
}
y += 20
PokemonSizeCategory.entries.forEachIndexed { index, size ->
button(
toggleLabel(size.name in query.sizes, Component.literal(size.name)), x + index * 28, y, 27,
tooltip = lang("ui.poke_radar.size.tooltip")
) {
if (!query.sizes.add(size.name)) query.sizes.remove(size.name)
selectionChanged()
}
}
}
private fun cycle(options: List<String>, current: String?): String? {
val index = options.indexOf(current)
return options.getOrNull(index + 1)
}
private fun clearSpeciesAttributes() {
query.shiny = false
query.alpha = false
query.maxIv = false
query.ability = null
query.nature = null
query.genders.clear()
query.sizes.clear()
}
private fun selectionChanged() {
if (ClientPokeRadar.trackingActive) PokeRadarTrackingPacket(null).sendToServer()
if (minecraft != null) rebuildWidgets()
}
override fun renderPage(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTick: Float) {
val chainSpecies =
ClientPokeRadar.state.chainSpecies?.let { PokemonSpecies.getByIdentifier(it.asIdentifierDefaultingNamespace()) }
val chainText = lang("ui.poke_radar.chain", ClientPokeRadar.state.chainCount)
chainSpecies?.let { chainText.append(" (").append(it.translatedName).append(")") }
context.drawString(font, chainText, left + 158, top + 29, 0xFFFFFF)
val status = when {
ClientPokeRadar.targetFound -> lang("ui.poke_radar.tracking.locked")
ClientPokeRadar.trackingActive -> lang("ui.poke_radar.tracking.searching")
else -> null
}
status?.let { context.drawString(font, it, left + 8, top + HEIGHT - 17, 0x55FF55) }
if (query.mode == TrackingMode.POKEMON) renderPokemonPage(context, mouseX, mouseY)
}
private fun renderPokemonPage(context: GuiGraphics, mouseX: Int, mouseY: Int) {
val list = visibleSpecies
scrollRow = Mth.clamp(scrollRow, 0, maxScroll(list.size))
if (list.isEmpty()) {
context.drawCenteredString(
font,
lang("ui.poke_radar.empty.no_pokemon"),
gridX + COLUMNS * SLOT / 2,
gridY + 40,
0xAAAAAA
)
}
list.drop(scrollRow * COLUMNS).take(COLUMNS * ROWS).forEachIndexed { index, species ->
val x = gridX + (index % COLUMNS) * SLOT
val y = gridY + (index / COLUMNS) * SLOT
val id = species.resourceIdentifier
val selected = id.toString() in query.species
val hovered = isIn(mouseX, mouseY, x, y, SLOT - 2, SLOT - 2)
context.fill(
x,
y,
x + SLOT - 2,
y + SLOT - 2,
if (selected) CELL_SELECTED else if (hovered) CELL_HOVER else CELL
)
val knowledge = knowledge(id)
if (knowledge == PokedexEntryProgress.UNREGISTERED) drawUnknown(context, x, y, SLOT - 2, SLOT - 2)
else drawPokemon(
context,
RenderablePokemon(species, species.standardForm.aspects.toSet()),
x,
y,
SLOT - 2,
SLOT - 2,
6F
)
if (knowledge == PokedexEntryProgress.OWNED) drawCaught(context, x + SLOT - 2, y)
if (hovered) showTooltip(listOf(if (knowledge == PokedexEntryProgress.UNREGISTERED) Component.literal("???") else species.translatedName))
}
val selected = selectedSpecies
context.fill(previewX, previewY, previewX + previewW, previewY + 56, CELL)
when (selected.size) {
0 -> context.drawCenteredString(
font,
lang("ui.poke_radar.tracking.select_hint"),
previewX + previewW / 2,
previewY + 24,
0xAAAAAA
)
1 -> {
val species = selected.single()
drawPokemon(
context,
RenderablePokemon(species, species.standardForm.aspects.toSet()),
previewX,
previewY,
previewW,
56,
16F
)
context.blit(SELECTED_ICON, previewX + 2, previewY + 2, 0F, 0F, 14, 14, 14, 14)
context.drawString(font, species.translatedName, previewX + 18, previewY + 5, 0xFFFFFF)
}
else -> {
val slotW = previewW / 3
selected.forEachIndexed { index, species ->
drawPokemon(
context, RenderablePokemon(species, species.standardForm.aspects.toSet()),
previewX + (index % 3) * slotW, previewY + (index / 3) * 28, slotW, 28, 6F
)
}
context.drawString(font, lang("ui.poke_radar.tracking.multi_hint"), previewX, previewY + 62, 0xAAAAAA)
}
}
}
private fun maxScroll(count: Int) = ((count + COLUMNS - 1) / COLUMNS - ROWS).coerceAtLeast(0)
override fun mouseScrolled(mouseX: Double, mouseY: Double, scrollX: Double, scrollY: Double): Boolean {
scrollRow = Mth.clamp(scrollRow - Mth.sign(scrollY), 0, maxScroll(visibleSpecies.size))
return true
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
if (super.mouseClicked(mouseX, mouseY, button)) return true
if (query.mode != TrackingMode.POKEMON) return false
val col = ((mouseX - gridX) / SLOT).toInt()
val row = ((mouseY - gridY) / SLOT).toInt()
if (mouseX < gridX || mouseY < gridY || col !in 0 until COLUMNS || row !in 0 until ROWS) return false
val species = visibleSpecies.getOrNull((scrollRow + row) * COLUMNS + col) ?: return false
val id = species.resourceIdentifier.toString()
when {
id in query.species -> query.species.remove(id)
!seen(species.resourceIdentifier) -> return false
query.species.size >= PokeRadarConstants.MAX_TRACKED_SPECIES -> return false
else -> query.species.add(id)
}
clearSpeciesAttributes()
selectionChanged()
return true
}
}
@@ -28,9 +28,9 @@ import org.joml.Vector3f
open class PartySlot(
x: Int, y: Int,
val pokemon: TradeStartedPacket.TradeablePokemon?,
private val pokemon: TradeStartedPacket.TradeablePokemon?,
private val parent: TradeGUI,
val isOpposing: Boolean = false,
private val isOpposing: Boolean = false,
onPress: OnPress
) : Button(x, y, SIZE, SIZE, Component.literal("PartySlot"), onPress, DEFAULT_NARRATION), CobblemonRenderable {
val state = FloatingState()
@@ -42,8 +42,6 @@ open class PartySlot(
private val genderIconFemale = cobblemonResource("textures/gui/pc/gender_icon_female.png")
private val selectPointerResource = cobblemonResource("textures/gui/pc/pc_pointer.png")
private val untradeableResource = cobblemonResource("textures/gui/trade/trade_slot_icon_locked.png")
private val tradePartySlotSelectedResource = cobblemonResource("textures/gui/trade/trade_party_slot_selected.png")
private val tradePartySlotSelectedOpposingResource = cobblemonResource("textures/gui/trade/trade_party_slot_selected_opposing.png")
}
override fun playDownSound(soundManager: SoundManager) {
@@ -62,17 +60,6 @@ open class PartySlot(
)
}
if (hasSelected()) {
blitk(
matrixStack = matrices,
texture = if (isOpposing) tradePartySlotSelectedOpposingResource else tradePartySlotSelectedResource,
x = x - 2,
y = y - 2,
width = 29,
height = 29
)
}
if (pokemon != null) {
// context.enableScissor(x - 2, y + 2, x + SIZE + 4, y + SIZE + 4)
// Render Pokémon
@@ -131,16 +118,7 @@ open class PartySlot(
}
matrices.popPose()
val isViewed = if (isOpposing) {
parent.opposingOfferedPokemon?.uuid == pokemon.pokemonId
} else {
parent.offeredPokemon?.uuid == pokemon.pokemonId
}
if (isViewed && pokemon.tradeable) {
matrices.pushPose()
matrices.translate(0.0, 0.0, 200.0)
if (hasSelected()) {
blitk(
matrixStack = matrices,
texture = selectPointerResource,
@@ -150,7 +128,6 @@ open class PartySlot(
height = 8,
scale = TradeGUI.SCALE
)
matrices.popPose()
}
// Held Item
@@ -168,9 +145,8 @@ open class PartySlot(
}
open fun hasSelected(): Boolean {
if (pokemon == null) return false
val offeredPokemons = if (isOpposing) parent.trade.oppositeOffer.get() else parent.trade.myOffer.get()
return offeredPokemons.any { it.uuid == pokemon.pokemonId }
val offeredPokemon = if (isOpposing) parent.trade.oppositeOffer.get() else parent.trade.myOffer.get()
return pokemon?.pokemonId == offeredPokemon?.uuid && pokemon != null
}
fun isHovered(mouseX: Int, mouseY: Int) = pokemon?.tradeable != false && mouseX.toFloat() in (x.toFloat()..(x.toFloat() + SIZE)) && mouseY.toFloat() in (y.toFloat()..(y.toFloat() + SIZE))
@@ -25,7 +25,6 @@ import com.cobblemon.mod.common.client.gui.summary.widgets.common.reformatNature
import com.cobblemon.mod.common.client.render.drawScaledText
import com.cobblemon.mod.common.client.render.drawScaledTextJustifiedRight
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
import com.cobblemon.mod.common.net.messages.server.trade.*
import com.cobblemon.mod.common.pokemon.Gender
@@ -99,23 +98,15 @@ class TradeGUI(
private val tradeAnimationArrowsResource = cobblemonResource("textures/gui/trade/trade_animation_arrows.png")
}
private var offeredPokemonModels: MutableList<ModelWidget> = mutableListOf()
private var opposingOfferedPokemonModels: MutableList<ModelWidget> = mutableListOf()
private var offeredPokemonModel: ModelWidget? = null
private var opposingOfferedPokemonModel: ModelWidget? = null
private lateinit var offeredPokemonMarkings: MarkingsWidget
private lateinit var opposingOfferedPokemonMarkings: MarkingsWidget
var selectedPartyIndices = mutableListOf<Int>()
var offeredPokemons: MutableList<Pokemon> = mutableListOf()
var opposingPokemons: MutableList<Pokemon> = mutableListOf()
// For backwards compatibility where single is referenced in rendering text info
var offeredPokemon: Pokemon? = null
var opposingOfferedPokemon: Pokemon? = null
var myGridMode = true
var opposingGridMode = true
var ticksElapsed = 0
var protectiveTicks = 0
var selectPointerOffsetY = 0
@@ -134,67 +125,30 @@ class TradeGUI(
}
trade.completedEmitter.subscribe {
val (pokemonIds1, pokemonIds2) = it
val myTradedPokemons = pokemonIds1.mapNotNull { id -> party.find { it?.pokemonId == id } }
val theirTradedPokemons = pokemonIds2.mapNotNull { id -> traderParty.find { it?.pokemonId == id } }
if (myTradedPokemons.isEmpty() || theirTradedPokemons.isEmpty()) {
val (pokemonId1, pokemonId2) = it
val myTradedPokemon = party.find { it?.pokemonId == pokemonId1 }
val theirTradedPokemon = traderParty.find { it?.pokemonId == pokemonId2 }
if (myTradedPokemon == null || theirTradedPokemon == null) {
CobblemonNetwork.sendToServer(CancelTradePacket())
return@subscribe onClose()
}
myTradedPokemons.forEach { pk ->
val idx = party.indexOf(pk)
if (idx != -1) party[idx] = null
}
theirTradedPokemons.forEach { pk ->
val idx = traderParty.indexOf(pk)
if (idx != -1) traderParty[idx] = null
}
val newSelectedIndices = mutableListOf<Int>()
theirTradedPokemons.forEach { pk ->
val emptyIdx = party.indexOf(null)
if (emptyIdx != -1) {
party[emptyIdx] = pk
}
}
myTradedPokemons.forEach { pk ->
val emptyIdx = traderParty.indexOf(null)
if (emptyIdx != -1) traderParty[emptyIdx] = pk
}
val compactUI = { list: MutableList<TradeStartedPacket.TradeablePokemon?> ->
val nonNulls = list.filterNotNull()
list.clear()
list.addAll(nonNulls)
while (list.size < 6) list.add(null)
}
compactUI(party)
compactUI(traderParty)
theirTradedPokemons.forEach { pk ->
val idx = party.indexOf(pk)
if (idx != -1) newSelectedIndices.add(idx)
}
val tradedSlot = party.indexOf(myTradedPokemon)
val opposingTradedSlot = traderParty.indexOf(theirTradedPokemon)
party[tradedSlot] = theirTradedPokemon
traderParty[opposingTradedSlot] = myTradedPokemon
trade.oppositeAcceptedMyOffer.set(false)
selectedPartyIndices.clear()
selectedPartyIndices.addAll(newSelectedIndices)
val newOffers = selectedPartyIndices.mapNotNull { idx ->
party[idx]?.let { it.pokemonId to PartyPosition(idx) }
}
CobblemonNetwork.sendToServer(UpdateTradeOfferPacket(newOffers))
CobblemonNetwork.sendToServer(UpdateTradeOfferPacket(Pair(theirTradedPokemon.pokemonId, PartyPosition(tradedSlot))))
rebuildWidgets()
}
trade.oppositeOffer.subscribe { newOffer: List<Pokemon> ->
setOfferedPokemon(pokemonList = newOffer, isOpposing = true)
trade.oppositeOffer.subscribe { newOffer: Pokemon? ->
setOfferedPokemon(pokemon = newOffer, isOpposing = true)
}
trade.myOffer.subscribe { myOffer: List<Pokemon> ->
setOfferedPokemon(pokemonList = myOffer)
trade.myOffer.subscribe { myOffer: Pokemon? ->
setOfferedPokemon(pokemon = myOffer)
}
trade.oppositeAcceptedMyOffer.subscribe {
@@ -262,16 +216,9 @@ class TradeGUI(
pokemon = pokemon,
parent = this,
onPress = {
if (!trade.acceptedOppositeOffer && !tradeProcessing && pokemon != null) {
if (selectedPartyIndices.contains(partyIndex)) {
selectedPartyIndices.remove(partyIndex)
} else if (selectedPartyIndices.size < 6) {
selectedPartyIndices.add(partyIndex)
}
val newOffers = selectedPartyIndices.mapNotNull { idx ->
party[idx]?.let { it.pokemonId to PartyPosition(idx) }
}
CobblemonNetwork.sendToServer(UpdateTradeOfferPacket(newOffers))
if (!trade.acceptedOppositeOffer && !tradeProcessing) {
val pk = if (offeredPokemon?.uuid == pokemon?.pokemonId) null else pokemon
CobblemonNetwork.sendToServer(UpdateTradeOfferPacket(pk?.let { it.pokemonId to PartyPosition(partyIndex) }))
playSound(CobblemonSounds.GUI_CLICK)
}
}
@@ -303,8 +250,8 @@ class TradeGUI(
).also { widget -> addRenderableWidget(widget) }
}
setOfferedPokemon(pokemonList = offeredPokemons.toList(), isOpposing = false)
setOfferedPokemon(pokemonList = opposingPokemons.toList(), isOpposing = true)
setOfferedPokemon(pokemon = offeredPokemon, isOpposing = false)
setOfferedPokemon(pokemon = opposingOfferedPokemon, isOpposing = true)
offeredPokemonMarkings = MarkingsWidget(x + 74.5, y + 21, offeredPokemon, false)
opposingOfferedPokemonMarkings = MarkingsWidget(x + 177.5, y + 21, opposingOfferedPokemon, false)
@@ -337,7 +284,7 @@ class TradeGUI(
if (tradeAnimationProgress > REVERSE_ANIMATION_TICK)
(REVERSE_ANIMATION_TICK + TRADE_ANIMATION_FRAMES - tradeAnimationProgress)
else (tradeAnimationProgress - MODEL_SCALE_BUFFER_FRAMES)
) * TRADE_ANIMATION_HEIGHT
) * TRADE_ANIMATION_HEIGHT
blitk(
matrixStack = matrices,
texture = tradeAnimationResource,
@@ -366,56 +313,20 @@ class TradeGUI(
// Render Model Portraits
var scale = PORTRAIT_SCALE
var scaleOffsetY = PORTRAIT_MODEL_OFFSET_Y
var isShrinking = false
if (tradeProcessing) {
val scaleInterval = if (tradeAnimationProgress > REVERSE_ANIMATION_TICK) (MAX_TRADE_PROGRESS - tradeAnimationProgress) else tradeAnimationProgress
scale = (PORTRAIT_SCALE - (scaleInterval * PORTRAIT_SCALE_MULTIPLIER)).coerceIn(0F, PORTRAIT_SCALE)
scaleOffsetY = (45.0 - (45.0 / PORTRAIT_SCALE) * scale) + PORTRAIT_MODEL_OFFSET_Y
isShrinking = true
}
val shrinkPercentage = if (isShrinking) 1.0F - (scale / PORTRAIT_SCALE) else 0.0F
val myCenterXDest = x + 70 + (PORTRAIT_SIZE / 2.0)
val myCenterYDest = y + 30 + (PORTRAIT_SIZE / 2.0)
val opCenterXDest = x + 145 + (PORTRAIT_SIZE / 2.0)
val opCenterYDest = y + 30 + (PORTRAIT_SIZE / 2.0)
if (scale > 0F) {
context.enableScissor(backgroundX, backgroundY, backgroundX + BASE_BACKGROUND_WIDTH, backgroundY + BASE_BACKGROUND_HEIGHT)
offeredPokemonModel?.baseScale = scale
offeredPokemonModel?.offsetY = scaleOffsetY
offeredPokemonModel?.render(context, mouseX, mouseY, delta)
offeredPokemonModels.forEachIndexed { i, model ->
val posAndScale = getModelPositionAndScale(i, offeredPokemons.size, x + 70, y + 30)
val originalScale = posAndScale.second
model.baseScale = if (isShrinking) (originalScale / PORTRAIT_SCALE) * scale else originalScale
model.offsetY = if (isShrinking) scaleOffsetY else PORTRAIT_MODEL_OFFSET_Y
val startCenterX = posAndScale.first.first + (PORTRAIT_SIZE / 2.0)
val startCenterY = posAndScale.first.second + (PORTRAIT_SIZE / 2.0)
context.pose().pushPose()
context.pose().translate((myCenterXDest - startCenterX) * shrinkPercentage, (myCenterYDest - startCenterY) * shrinkPercentage, 0.0)
model.render(context, mouseX, mouseY, delta)
context.pose().popPose()
}
opposingOfferedPokemonModels.forEachIndexed { i, model ->
val posAndScale = getModelPositionAndScale(i, opposingPokemons.size, x + 145, y + 30)
val originalScale = posAndScale.second
model.baseScale = if (isShrinking) (originalScale / PORTRAIT_SCALE) * scale else originalScale
model.offsetY = if (isShrinking) scaleOffsetY else PORTRAIT_MODEL_OFFSET_Y
val startCenterX = posAndScale.first.first + (PORTRAIT_SIZE / 2.0)
val startCenterY = posAndScale.first.second + (PORTRAIT_SIZE / 2.0)
context.pose().pushPose()
context.pose().translate((opCenterXDest - startCenterX) * shrinkPercentage, (opCenterYDest - startCenterY) * shrinkPercentage, 0.0)
model.render(context, mouseX, mouseY, delta)
context.pose().popPose()
}
opposingOfferedPokemonModel?.baseScale = scale
opposingOfferedPokemonModel?.offsetY = scaleOffsetY
opposingOfferedPokemonModel?.render(context, mouseX, mouseY, delta)
context.disableScissor()
}
@@ -430,46 +341,8 @@ class TradeGUI(
renderInfoLabels(context, x, y)
children().filterIsInstance<PartySlot>().forEach { slot ->
if (slot.isHovered(mouseX, mouseY)) {
val hoveredId = slot.pokemon?.pokemonId
if (slot.isOpposing && slot.hasSelected()) {
opposingPokemons.find { it.uuid == hoveredId }?.let { opposingOfferedPokemon = it }
} else if (!slot.isOpposing) {
val matchingModel = offeredPokemons.find { it.uuid == hoveredId }
if (matchingModel != null) {
offeredPokemon = matchingModel
} else {
val realPokemon = com.cobblemon.mod.common.client.CobblemonClient.storage.party.find { it?.uuid == hoveredId }
if (realPokemon != null) {
offeredPokemon = realPokemon
}
}
}
}
}
val currentOffered = offeredPokemon
if (currentOffered != null) {
renderPokemonInfo(currentOffered, false, context, x, y, mouseX, mouseY)
if (::offeredPokemonMarkings.isInitialized) {
offeredPokemonMarkings.visible = true
if (offeredPokemonMarkings.pokemon != currentOffered) offeredPokemonMarkings.setActivePokemon(currentOffered)
}
} else {
if (::offeredPokemonMarkings.isInitialized) offeredPokemonMarkings.visible = false
}
val currentOpposing = opposingOfferedPokemon
if (currentOpposing != null) {
renderPokemonInfo(currentOpposing, true, context, x, y, mouseX, mouseY)
if (::opposingOfferedPokemonMarkings.isInitialized) {
opposingOfferedPokemonMarkings.visible = true
if (opposingOfferedPokemonMarkings.pokemon != currentOpposing) opposingOfferedPokemonMarkings.setActivePokemon(currentOpposing)
}
} else {
if (::opposingOfferedPokemonMarkings.isInitialized) opposingOfferedPokemonMarkings.visible = false
}
renderPokemonInfo(offeredPokemon, false, context, x, y, mouseX, mouseY)
renderPokemonInfo(opposingOfferedPokemon, true, context, x, y, mouseX, mouseY)
if (trade.acceptedOppositeOffer) {
blitk(
@@ -558,25 +431,19 @@ class TradeGUI(
super.render(context, mouseX, mouseY, delta)
val ttOffered = offeredPokemon
if (ttOffered != null) {
// Item Tooltip
if (!ttOffered.heldItemNoCopy().isEmpty) {
val itemX = x + 50
val itemY = y + 125
val itemHovered = mouseX.toFloat() in (itemX.toFloat()..(itemX.toFloat() + 16)) && mouseY.toFloat() in (itemY.toFloat()..(itemY.toFloat() + 16))
if (itemHovered) context.renderTooltip(Minecraft.getInstance().font, ttOffered.heldItemNoCopy(), mouseX, mouseY)
}
// Item Tooltip
if (offeredPokemon != null && !offeredPokemon!!.heldItemNoCopy().isEmpty) {
val itemX = x + 50
val itemY = y + 125
val itemHovered = mouseX.toFloat() in (itemX.toFloat()..(itemX.toFloat() + 16)) && mouseY.toFloat() in (itemY.toFloat()..(itemY.toFloat() + 16))
if (itemHovered) context.renderTooltip(Minecraft.getInstance().font, offeredPokemon!!.heldItemNoCopy(), mouseX, mouseY)
}
val ttOpposing = opposingOfferedPokemon
if (ttOpposing != null) {
if (!ttOpposing.heldItemNoCopy().isEmpty) {
val itemX = x + 227
val itemY = y + 125
val itemHovered = mouseX.toFloat() in (itemX.toFloat()..(itemX.toFloat() + 16)) && mouseY.toFloat() in (itemY.toFloat()..(itemY.toFloat() + 16))
if (itemHovered) context.renderTooltip(Minecraft.getInstance().font, ttOpposing.heldItemNoCopy(), mouseX, mouseY)
}
if (opposingOfferedPokemon != null && !opposingOfferedPokemon!!.heldItemNoCopy().isEmpty) {
val itemX = x + 227
val itemY = y + 125
val itemHovered = mouseX.toFloat() in (itemX.toFloat()..(itemX.toFloat() + 16)) && mouseY.toFloat() in (itemY.toFloat()..(itemY.toFloat() + 16))
if (itemHovered) context.renderTooltip(Minecraft.getInstance().font, opposingOfferedPokemon!!.heldItemNoCopy(), mouseX, mouseY)
}
}
@@ -613,13 +480,11 @@ class TradeGUI(
}
if (tradeAnimationProgress == (MAX_TRADE_PROGRESS + CRY_BUFFER)) {
offeredPokemonModels.forEach {
it.state.activeAnimations.clear()
it.state.addFirstAnimation(setOf("cry"))
}
opposingOfferedPokemonModels.forEach {
it.state.activeAnimations.clear()
it.state.addFirstAnimation(setOf("cry"))
if (offeredPokemonModel !== null && opposingOfferedPokemonModel !== null) {
offeredPokemonModel!!.state.activeAnimations.clear()
offeredPokemonModel!!.state.addFirstAnimation(setOf("cry"))
opposingOfferedPokemonModel!!.state.activeAnimations.clear()
opposingOfferedPokemonModel!!.state.addFirstAnimation(setOf("cry"))
}
}
@@ -650,140 +515,41 @@ class TradeGUI(
override fun renderMenuBackground(context: GuiGraphics) {}
private fun setOfferedPokemon(pokemonList: List<Pokemon>, isOpposing: Boolean = false) {
private fun setOfferedPokemon(pokemon: Pokemon?, isOpposing: Boolean = false) {
protectiveTicks = 20
if (isOpposing) {
val wasEmpty = opposingPokemons.isEmpty()
val currentViewedUuid = if (opposingGridMode) null else opposingOfferedPokemon?.uuid
opposingPokemons.clear()
opposingPokemons.addAll(pokemonList)
val matchingPokemon = opposingPokemons.find { it.uuid == currentViewedUuid }
if (matchingPokemon != null) {
opposingOfferedPokemon = matchingPokemon
if (::opposingOfferedPokemonMarkings.isInitialized) opposingOfferedPokemonMarkings.setActivePokemon(opposingOfferedPokemon)
} else {
opposingOfferedPokemon = opposingPokemons.lastOrNull()
if (::opposingOfferedPokemonMarkings.isInitialized) opposingOfferedPokemonMarkings.setActivePokemon(opposingOfferedPokemon)
if (wasEmpty && opposingOfferedPokemon != null) {
opposingGridMode = false
} else if (!opposingGridMode) {
opposingGridMode = true
}
}
trade.acceptedOppositeOffer = false
} else {
val wasEmpty = offeredPokemons.isEmpty()
val currentViewedUuid = if (myGridMode) null else offeredPokemon?.uuid
offeredPokemons.clear()
offeredPokemons.addAll(pokemonList)
val matchingPokemon = offeredPokemons.find { it.uuid == currentViewedUuid }
if (matchingPokemon != null) {
offeredPokemon = matchingPokemon
if (::offeredPokemonMarkings.isInitialized) offeredPokemonMarkings.setActivePokemon(offeredPokemon)
} else {
offeredPokemon = offeredPokemons.lastOrNull()
if (::offeredPokemonMarkings.isInitialized) offeredPokemonMarkings.setActivePokemon(offeredPokemon)
if (wasEmpty && offeredPokemon != null) {
myGridMode = false
} else if (!myGridMode) {
myGridMode = true
}
}
}
rebuildSelectedModels(isOpposing)
}
private fun rebuildSelectedModels(isOpposing: Boolean) {
val x = (width - BASE_WIDTH) / 2
val y = (height - BASE_HEIGHT) / 2
if (isOpposing) {
opposingOfferedPokemonModels.clear()
val total = opposingPokemons.size
opposingPokemons.forEachIndexed { i, pk ->
val (pos, currentScale) = getModelPositionAndScale(i, total, x + 145, y + 30)
opposingOfferedPokemonModels.add(ModelWidget(
pX = pos.first, pY = pos.second,
pWidth = PORTRAIT_SIZE, pHeight = PORTRAIT_SIZE,
pokemon = pk.asRenderablePokemon(),
baseScale = currentScale,
rotationY = 35F,
offsetY = PORTRAIT_MODEL_OFFSET_Y
))
}
opposingOfferedPokemon = pokemon
opposingOfferedPokemonModel = if (pokemon != null) ModelWidget(
pX = x + 145,
pY = y + 30,
pWidth = PORTRAIT_SIZE,
pHeight = PORTRAIT_SIZE,
pokemon = pokemon.asRenderablePokemon(),
baseScale = PORTRAIT_SCALE,
rotationY = 35F,
offsetY = PORTRAIT_MODEL_OFFSET_Y
) else null
if (::opposingOfferedPokemonMarkings.isInitialized) opposingOfferedPokemonMarkings.setActivePokemon(opposingOfferedPokemon)
trade.acceptedOppositeOffer = false
} else {
offeredPokemonModels.clear()
val total = offeredPokemons.size
offeredPokemons.forEachIndexed { i, pk ->
val (pos, currentScale) = getModelPositionAndScale(i, total, x + 70, y + 30)
offeredPokemonModels.add(ModelWidget(
pX = pos.first, pY = pos.second,
pWidth = PORTRAIT_SIZE, pHeight = PORTRAIT_SIZE,
pokemon = pk.asRenderablePokemon(),
baseScale = currentScale,
rotationY = 325F,
offsetY = PORTRAIT_MODEL_OFFSET_Y
))
}
offeredPokemon = pokemon
offeredPokemonModel = if (pokemon != null) ModelWidget(
pX = x + 70,
pY = y + 30,
pWidth = PORTRAIT_SIZE,
pHeight = PORTRAIT_SIZE,
pokemon = pokemon.asRenderablePokemon(),
baseScale = PORTRAIT_SCALE,
rotationY = 325F,
offsetY = PORTRAIT_MODEL_OFFSET_Y
) else null
if (::offeredPokemonMarkings.isInitialized) offeredPokemonMarkings.setActivePokemon(offeredPokemon)
}
}
private fun getModelPositionAndScale(index: Int, total: Int, baseX: Int, baseY: Int): Pair<Pair<Int, Int>, Float> {
val scale = when (total) {
1 -> PORTRAIT_SCALE
2 -> PORTRAIT_SCALE * 0.75f
3 -> PORTRAIT_SCALE * 0.65f
4 -> PORTRAIT_SCALE * 0.55f
else -> PORTRAIT_SCALE * 0.5f
}
if (total <= 1) {
return Pair(Pair(baseX, baseY), scale)
}
val rowLength1 = when (total) {
2, 3, 4 -> 2
else -> 3
}
val rowLength2 = total - rowLength1
val isBottomRow = index >= rowLength1
val row = if (isBottomRow) 1 else 0
val col = if (isBottomRow) index - rowLength1 else index
val currentRowLength = if (isBottomRow) rowLength2 else rowLength1
val colSpacing = when (total) {
2 -> 35
3 -> 30
4 -> 25
else -> 23
}
val rowSpacing = when (total) {
2, 3 -> 30
4 -> 28
else -> 25
}
val totalWidth = (currentRowLength - 1) * colSpacing
val startX = baseX - (totalWidth / 2)
val totalHeight = if (rowLength2 > 0) rowSpacing else 0
var startY = baseY + 12 - (totalHeight / 2)
if (total >= 4) {
startY += 8
}
val posX = startX + (col * colSpacing)
val posY = startY + (row * rowSpacing)
return Pair(Pair(posX, posY), scale)
}
private fun playSound(soundEvent: SoundEvent): SoundInstance {
val soundInstance = SimpleSoundInstance.forUI(soundEvent, 1.0F)
Minecraft.getInstance().soundManager.play(soundInstance)
@@ -791,10 +557,10 @@ class TradeGUI(
}
private fun cancelTradeSound() {
if (tradeSoundInstance != null) Minecraft.getInstance().soundManager.stop(tradeSoundInstance!!)
if (tradeSoundInstance !== null) Minecraft.getInstance().soundManager.stop(tradeSoundInstance)
}
public fun renderPokemonInfo(pokemon: Pokemon?, isOpposing: Boolean, context: GuiGraphics, x: Int, y: Int, mouseX: Int, mouseY: Int) {
private fun renderPokemonInfo(pokemon: Pokemon?, isOpposing: Boolean, context: GuiGraphics, x: Int, y: Int, mouseX: Int, mouseY: Int) {
if (pokemon != null) {
val matrices = context.pose()
// Level
@@ -1281,4 +1047,4 @@ class TradeGUI(
scale = SCALE
)
}
}
}
@@ -1,30 +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.net.bag
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.item.bag.CobblemonBagMenu
import com.cobblemon.mod.common.net.messages.client.bag.UpdateBagMenuDataPacket
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object UpdateBagMenuDataHandler : ServerNetworkPacketHandler<UpdateBagMenuDataPacket> {
override fun handle(packet: UpdateBagMenuDataPacket, server: MinecraftServer, player: ServerPlayer) {
if (player.containerMenu !is CobblemonBagMenu) {
Cobblemon.LOGGER.debug("Player {} interacted with invalid menu {}", player, player.containerMenu)
return
}
val menu = player.containerMenu as? CobblemonBagMenu ?: return
menu.currentlySelectedCategory = packet.categoryId
menu.scroll = packet.scroll
menu.setupSlotsBasedOnContent()
}
}
@@ -1,28 +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.net.bag
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.item.bag.CobblemonBagMenu
import com.cobblemon.mod.common.net.messages.client.bag.UseItemOnPokemonFromBagPacket
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object UseItemOnPokemonFromBagHandler: ServerNetworkPacketHandler<UseItemOnPokemonFromBagPacket> {
override fun handle(packet: UseItemOnPokemonFromBagPacket, server: MinecraftServer, player: ServerPlayer) {
if (player.containerMenu !is CobblemonBagMenu) {
Cobblemon.LOGGER.debug("Player {} interacted with invalid menu {}", player, player.containerMenu)
return
}
val menu = player.containerMenu as? CobblemonBagMenu ?: return
menu.useHeldItemOnPokemon(packet.partySlot)
}
}
@@ -0,0 +1,22 @@
/*
* 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.net.pokeradar
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.gui.pokeradar.PokeRadarGUI
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarScanResultPacket
import net.minecraft.client.Minecraft
object PokeRadarScanResultHandler : ClientNetworkPacketHandler<PokeRadarScanResultPacket> {
override fun handle(packet: PokeRadarScanResultPacket, client: Minecraft) {
ClientPokeRadar.results[packet.fishing] = packet.entries
(client.screen as? PokeRadarGUI)?.onDataChanged()
}
}
@@ -0,0 +1,23 @@
/*
* 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.net.pokeradar
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.gui.pokeradar.PokeRadarGUI
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarSyncPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarState
import net.minecraft.client.Minecraft
object PokeRadarSyncHandler : ClientNetworkPacketHandler<PokeRadarSyncPacket> {
override fun handle(packet: PokeRadarSyncPacket, client: Minecraft) {
ClientPokeRadar.onSync(PokeRadarState.fromJson(packet.json))
(client.screen as? PokeRadarGUI)?.onDataChanged()
}
}
@@ -0,0 +1,23 @@
/*
* 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.net.pokeradar
import com.cobblemon.mod.common.api.net.ClientNetworkPacketHandler
import com.cobblemon.mod.common.client.gui.pokeradar.PokeRadarGUI
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarTrackingStatePacket
import net.minecraft.client.Minecraft
object PokeRadarTrackingStateHandler : ClientNetworkPacketHandler<PokeRadarTrackingStatePacket> {
override fun handle(packet: PokeRadarTrackingStatePacket, client: Minecraft) {
val wasActive = ClientPokeRadar.trackingActive
ClientPokeRadar.onTrackingState(packet.active, packet.found, packet.navpoint, packet.pos)
if (wasActive != packet.active) (client.screen as? PokeRadarGUI)?.onDataChanged()
}
}
@@ -15,9 +15,9 @@ import net.minecraft.client.Minecraft
object TradeAcceptanceChangedHandler : ClientNetworkPacketHandler<TradeAcceptanceChangedPacket> {
override fun handle(packet: TradeAcceptanceChangedPacket, client: Minecraft) {
if (CobblemonClient.trade?.myOffer?.get()?.any { it.uuid == packet.pokemonId } == true) {
if (CobblemonClient.trade?.myOffer?.get()?.uuid == packet.pokemonId) {
CobblemonClient.trade!!.oppositeAcceptedMyOffer.set(packet.accepted)
} else if (CobblemonClient.trade?.oppositeOffer?.get()?.any { it.uuid == packet.pokemonId } == true) {
} else if (CobblemonClient.trade?.oppositeOffer?.get()?.uuid == packet.pokemonId) {
CobblemonClient.trade!!.acceptedOppositeOffer = packet.accepted
}
}
@@ -16,6 +16,6 @@ import net.minecraft.client.Minecraft
object TradeCompletedHandler : ClientNetworkPacketHandler<TradeCompletedPacket> {
override fun handle(packet: TradeCompletedPacket, client: Minecraft) {
val trade = CobblemonClient.trade ?: return
trade.completedEmitter.emit(packet.pokemonIds1 to packet.pokemonIds2)
trade.completedEmitter.emit(packet.pokemonId1 to packet.pokemonId2)
}
}
@@ -20,7 +20,7 @@ import net.minecraft.client.Minecraft
object TradeStartedHandler : ClientNetworkPacketHandler<TradeStartedPacket> {
override fun handle(packet: TradeStartedPacket, client: Minecraft) {
Cobblemon.LOGGER.info("Trade started with {}", packet.traderId)
Cobblemon.LOGGER.error("handle trade start from: " + packet.traderId)
val trade = ClientTrade()
CobblemonClient.trade = trade
Minecraft.getInstance().setScreen(
@@ -18,9 +18,9 @@ object TradeUpdatedHandler : ClientNetworkPacketHandler<TradeUpdatedPacket> {
val trade = CobblemonClient.trade ?: return
if (packet.playerId == Minecraft.getInstance().player?.uuid) {
trade.myOffer.set(packet.pokemons)
trade.myOffer.set(packet.pokemon)
} else {
trade.oppositeOffer.set(packet.pokemons)
trade.oppositeOffer.set(packet.pokemon)
}
trade.oppositeAcceptedMyOffer.set(false)
trade.acceptedOppositeOffer = false
@@ -0,0 +1,100 @@
/*
* 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.pokeradar
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.pokeradar.PokeRadarConstants
import com.cobblemon.mod.common.pokeradar.PokeRadarState
import com.cobblemon.mod.common.pokeradar.RadarEntry
import com.cobblemon.mod.common.pokeradar.TrackingQuery
import net.minecraft.client.Minecraft
import net.minecraft.client.resources.sounds.SimpleSoundInstance
import net.minecraft.sounds.SoundEvent
import net.minecraft.util.Mth
import net.minecraft.world.phys.Vec3
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.sqrt
object ClientPokeRadar {
var state = PokeRadarState()
private var cooldownEnd = 0L
val results = mutableMapOf<Boolean, List<RadarEntry>>()
var fishing = false
var lureLevel = 0
var sortAscending = false
var draft: TrackingQuery? = null
var trackingActive = false
private set
var targetFound = false
private set
private var targetIsNavpoint = false
private var targetPos: Vec3? = null
val cooldownSeconds
get() = ((cooldownEnd - System.currentTimeMillis()) / 1000.0).let { Mth.ceil(it) }.coerceAtLeast(0)
fun onSync(newState: PokeRadarState) {
state = newState
cooldownEnd = System.currentTimeMillis() + newState.cooldown
trackingActive = newState.tracking
if (!trackingActive) {
targetFound = false
targetPos = null
}
}
fun onTrackingState(active: Boolean, found: Boolean, navpoint: Boolean, pos: Vec3) {
if (found && !targetFound) playTrackingSound(CobblemonSounds.POKE_RADAR_LOCK_ON)
if (targetFound && !found) playTrackingSound(CobblemonSounds.POKE_RADAR_POWER_DOWN)
trackingActive = active
state.tracking = active
targetFound = found
targetIsNavpoint = navpoint
targetPos = pos.takeIf { found }
}
fun playUiSound(sound: SoundEvent) = Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(sound, 1F))
private fun playTrackingSound(sound: SoundEvent) {
if (!state.muted) playUiSound(sound)
}
// TODO: Placeholder Art
fun spriteState(): Int {
if (!trackingActive || !targetFound) return 0
val pos = targetPos ?: return 0
val player = Minecraft.getInstance().player ?: return 0
val dx = pos.x - player.x
val dz = pos.z - player.z
val targetYaw = Math.toDegrees(atan2(-dx, dz))
val relative = Mth.wrapDegrees(targetYaw - player.yRot)
val side = if (relative > 0) 1 else 0
val distance = if (targetIsNavpoint) sqrt(dx * dx + dz * dz) else pos.distanceTo(player.position())
val direction = PokeRadarConstants.stepState(abs(relative), PokeRadarConstants.DIRECTION_STEPS)
val distanceState = PokeRadarConstants.stepState(
distance,
if (targetIsNavpoint) PokeRadarConstants.NAVPOINT_DISTANCE_STEPS else PokeRadarConstants.POKEMON_DISTANCE_STEPS
)
return 1 + side * 16 + direction * 4 + distanceState
}
fun reset() {
state = PokeRadarState()
results.clear()
draft = null
cooldownEnd = 0
trackingActive = false
targetFound = false
targetPos = null
}
}
@@ -0,0 +1,31 @@
/*
* 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.pokeradar
import com.cobblemon.mod.common.util.cobblemonResource
/**
* Defines the available Poké Radar variants and their resource locations.
*
* @author MeAlam
* @since 1.0.0
*/
enum class PokeRadarType {
BLACK,
BLUE,
GREEN,
PINK,
RED,
WHITE,
YELLOW;
fun getTexturePath() = cobblemonResource("textures/gui/pokedex/pokedex_base_${this.name.lowercase()}.png")
fun getItemModelPath(additionalState: String? = null) = cobblemonResource("item/pokedex_${this.name.lowercase()}_model${if (additionalState != null) "_$additionalState" else ""}")
fun getItemSpritePath() = cobblemonResource("pokedex_${this.name.lowercase()}")
}
@@ -11,6 +11,7 @@ package com.cobblemon.mod.common.client.render.item
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.api.cooking.Seasonings
import com.cobblemon.mod.common.client.pokeradar.ClientPokeRadar
import com.cobblemon.mod.common.client.pot.CookingQuality
import com.cobblemon.mod.common.entity.fishing.PokeRodFishingBobberEntity
import com.cobblemon.mod.common.item.interactive.PokerodItem
@@ -24,6 +25,12 @@ import net.minecraft.world.entity.player.Player
object CobblemonModelPredicateRegistry {
fun registerPredicates() {
// TODO: Placeholder Art
CobblemonItems.pokeradars.forEach { radar ->
ItemProperties.register(radar, cobblemonResource("poke_radar_state")) { _, _, _, _ ->
ClientPokeRadar.spriteState() / 32F
}
}
val rods = listOf(
CobblemonItems.AZURE_ROD,
@@ -1,65 +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.layer
import com.cobblemon.mod.common.client.CobblemonBakingOverrides
import com.cobblemon.mod.common.item.bag.CobblemonBagItem
import com.mojang.blaze3d.vertex.PoseStack
import com.mojang.math.Axis
import net.minecraft.client.Minecraft
import net.minecraft.client.model.PlayerModel
import net.minecraft.client.renderer.MultiBufferSource
import net.minecraft.client.renderer.entity.RenderLayerParent
import net.minecraft.client.renderer.entity.layers.RenderLayer
import net.minecraft.client.renderer.texture.OverlayTexture
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemDisplayContext
class CobblemonBagRenderer<T : Player>(renderLayerParent: RenderLayerParent<T, PlayerModel<T>>): RenderLayer<T, PlayerModel<T>>(renderLayerParent) {
override fun render(
poseStack: PoseStack,
bufferSource: MultiBufferSource,
packedLight: Int,
player: T,
limbSwing: Float,
limbSwingAmount: Float,
partialTick: Float,
ageInTicks: Float,
netHeadYaw: Float,
headPitch: Float
) {
val bagItem = player.getItemBySlot(EquipmentSlot.CHEST)
if (bagItem.item !is CobblemonBagItem) return
val model = CobblemonBakingOverrides.bagModels[bagItem.item]?.getModel() ?: return
player.level().profiler.push("cobblemon_bag_render")
poseStack.pushPose()
parentModel.body.translateAndRotate(poseStack)
poseStack.rotateAround(Axis.ZP.rotationDegrees(180F), 0F, 1F, 0F)
poseStack.translate(0.0, 1.0, 0.0)
Minecraft.getInstance().itemRenderer.render(
bagItem,
ItemDisplayContext.FIXED,
false,
poseStack,
bufferSource,
packedLight,
OverlayTexture.NO_OVERLAY,
model
)
poseStack.popPose()
player.level().profiler.pop()
}
}
@@ -14,12 +14,12 @@ import com.cobblemon.mod.common.pokemon.Pokemon
import java.util.UUID
class ClientTrade {
var myOffer = SettableObservable<List<Pokemon>>(emptyList())
var oppositeOffer = SettableObservable<List<Pokemon>>(emptyList())
var myOffer = SettableObservable<Pokemon?>(null)
var oppositeOffer = SettableObservable<Pokemon?>(null)
var tradeProcessing = SettableObservable(Pair(false, false))
var oppositeAcceptedMyOffer = SettableObservable(false)
var acceptedOppositeOffer = false
var completedEmitter = SimpleObservable<Pair<List<UUID>, List<UUID>>>()
var completedEmitter = SimpleObservable<Pair<UUID, UUID>>()
var cancelEmitter = SimpleObservable<Unit>()
}
@@ -47,6 +47,10 @@ class CobblemonConfig {
@IntConstraint(min = 0, max = 1000)
var maxPokemonFriendship = 255
@CobblemonConfigField(Category.Pokemon, lang = "power_item_ride_stat_gain_interval_seconds", SERVER)
@IntConstraint(min = -1, max = Int.MAX_VALUE)
var powerItemRideStatGainIntervalSeconds = 120
@CobblemonConfigField(Category.Pokemon, lang = "announce_drop_items", SERVER)
var announceDropItems = true
@CobblemonConfigField(Category.Pokemon, lang = "default_drop_item_method", SERVER)
@@ -237,12 +241,6 @@ class CobblemonConfig {
@CobblemonConfigField(Category.Spawning, lang = "honey_slather_shiny_chance", SERVER)
var honeySlatherShinyChance = 4000
@CobblemonConfigField(Category.Spawning, lang = "manaphy_shiny_chance", SERVER)
var manaphyShinyChance = 200
@CobblemonConfigField(Category.Spawning, lang = "manaphy_alpha_chance", SERVER)
var manaphyAlphaChance = 50
@CobblemonConfigField(Category.Pokemon, lang = "shiny_notice_particles_distance", CLIENT)
var shinyNoticeParticlesDistance = 24F
@@ -416,6 +414,9 @@ class CobblemonConfig {
@CobblemonConfigField(Category.World, lang = "type_gem_tick_chance", SERVER)
var typeGemTickChance = 1.0f
@CobblemonConfigField(Category.Spawning, lang = "poke_radar_cooldown", SERVER)
var pokeRadarCooldown = 60.0f
fun clone(): CobblemonConfig {
val newConfig = CobblemonConfig()
CobblemonConfig::class.memberProperties.forEach { property ->
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.data
import com.cobblemon.mod.common.*
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.api.abilities.Abilities
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.berry.Berries
import com.cobblemon.mod.common.api.cooking.Seasonings
import com.cobblemon.mod.common.api.data.DataProvider
@@ -121,7 +120,6 @@ object CobblemonDataProvider : DataProvider {
this.register(SpawnBaitEffects, reloadable = false)
this.register(CobblemonRideSettings, reloadable = true)
this.register(TechnicalMachines, reloadable = false)
this.register(BagCategories, reloadable = false)
SpawnBait.Effects.setupEffects()
PlatformEvents.SERVER_PLAYER_LOGOUT.subscribe {
@@ -160,4 +160,5 @@ class CobblemonChestBoatEntity(entityType: EntityType<CobblemonChestBoatEntity>,
private const val INVENTORY_SLOTS = 27
}
}
@@ -49,6 +49,7 @@ import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokeballPacket
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.pokemon.ai.PokemonBrain
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import com.cobblemon.mod.common.util.*
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
@@ -369,6 +370,11 @@ class EmptyPokeBallEntity : ThrowableItemProjectile, PosableEntity, WaterDragMod
level().sendBlockUpdated(blockPos, blockState, blockState, 3)
}
PokeRadarManager.addToChain(
player,
pokemon.pokemon.species.resourceIdentifier.toString()
)
CobblemonEvents.POKEMON_CAPTURED.post(PokemonCapturedEvent(pokemon.pokemon, player, this))
}
}
@@ -22,6 +22,7 @@ import com.cobblemon.mod.common.api.molang.ObjectValue
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.feature.TickingSpeciesFeature
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.riding.stats.RidingStat
import com.cobblemon.mod.common.api.spawning.fishing.FishingSpawnCause.Companion.DROPS_REROLL_ASPECT
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.battles.BattleRegistry
@@ -46,10 +47,15 @@ import kotlin.math.*
/** Handles purely server logic for a Pokémon */
class PokemonServerDelegate : PokemonSideDelegate {
companion object {
private const val RIDE_STAT_GAIN_AMOUNT = 1F
}
lateinit var entity: PokemonEntity
var acknowledgedHPValue = -1
var acknowledgedLevel = -1
val passengerOffsets = mutableMapOf<Int, Vec3>()
private var rideStatGainAnchor: Vec3? = null
/** Mocked properties exposed to the client [PokemonEntity]. */
private val mock: PokemonProperties?
@@ -355,9 +361,30 @@ class PokemonServerDelegate : PokemonSideDelegate {
}
}
val rideStatGainIntervalSeconds = Cobblemon.config.powerItemRideStatGainIntervalSeconds
if (rideStatGainIntervalSeconds > 0) {
val rideStatGainIntervalTicks = rideStatGainIntervalSeconds * 20L
if (entity.level().gameTime % rideStatGainIntervalTicks == 0L) {
trainRideStats()
}
}
updateTrackedValues()
}
private fun trainRideStats() {
val position = entity.position()
val anchor = rideStatGainAnchor
rideStatGainAnchor = position
if (anchor == null || anchor == position || entity.passengers.isEmpty()) return
val heldItem = entity.pokemon.heldItemNoCopy()
if (heldItem.isEmpty) return
val stat = RidingStat.entries.firstOrNull { heldItem.`is`(it.powerItem) } ?: return
entity.pokemon.addRideBoost(stat, RIDE_STAT_GAIN_AMOUNT)
}
fun updateShownItem() {
val trackedShownItem = when {
// Show Hand Item if Held item is hidden
@@ -31,7 +31,6 @@ import net.minecraft.world.item.BlockItem
import com.cobblemon.mod.common.platform.events.ServerPlayerEvent
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreTypes
import com.cobblemon.mod.common.item.GemItem
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.platform.events.PlatformEvents
import com.cobblemon.mod.common.util.effectiveName
import com.cobblemon.mod.common.util.getPlayer
@@ -165,21 +164,26 @@ object AdvancementHandler : EventHandler {
}
fun onTradeCompleted(event : TradeEvent.Post) {
onTradeCompleted(event.tradeParticipant1Pokemon, event.tradeParticipant2Pokemon)
onTradeCompleted(event.tradeParticipant2Pokemon, event.tradeParticipant1Pokemon)
}
private fun onTradeCompleted(received: List<Pokemon>, traded: List<Pokemon>) {
val player = received.firstOrNull()?.getOwnerPlayer() ?: return
received.forEach { receivedPokemon ->
traded.forEach { tradedPokemon -> CobblemonCriteria.TRADE_POKEMON.trigger(player, TradePokemonContext(tradedPokemon, receivedPokemon)) }
val player1 = event.tradeParticipant1Pokemon.getOwnerPlayer()
val player2 = event.tradeParticipant2Pokemon.getOwnerPlayer()
if (player1 != null) {
CobblemonCriteria.TRADE_POKEMON.trigger(player1, TradePokemonContext(event.tradeParticipant1Pokemon, event.tradeParticipant2Pokemon))
val playerData = Cobblemon.playerDataManager.getGenericData(player1)
val advancementData = playerData.advancementData
advancementData.updateTotalTradedCount()
advancementData.updateAspectsCollected(player1, event.tradeParticipant2Pokemon)
CobblemonCriteria.COLLECT_ASPECT.trigger(player1, advancementData.aspectsCollected)
Cobblemon.playerDataManager.saveSingle(playerData, PlayerInstancedDataStoreTypes.GENERAL)
}
if (player2 != null) {
CobblemonCriteria.TRADE_POKEMON.trigger(player2, TradePokemonContext(event.tradeParticipant2Pokemon, event.tradeParticipant1Pokemon))
val playerData = Cobblemon.playerDataManager.getGenericData(player2)
val advancementData = playerData.advancementData
advancementData.updateTotalTradedCount()
advancementData.updateAspectsCollected(player2, event.tradeParticipant1Pokemon)
CobblemonCriteria.COLLECT_ASPECT.trigger(player2, advancementData.aspectsCollected)
Cobblemon.playerDataManager.saveSingle(playerData, PlayerInstancedDataStoreTypes.GENERAL)
}
val playerData = Cobblemon.playerDataManager.getGenericData(player)
val advancementData = playerData.advancementData
advancementData.updateTotalTradedCount()
received.forEach { advancementData.updateAspectsCollected(player, it) }
CobblemonCriteria.COLLECT_ASPECT.trigger(player, advancementData.aspectsCollected)
Cobblemon.playerDataManager.saveSingle(playerData, PlayerInstancedDataStoreTypes.GENERAL)
}
/**
@@ -110,8 +110,8 @@ object StatHandler : EventHandler {
}
fun onTradeCompleted(event : TradeEvent.Post) {
event.tradeParticipant1Pokemon.firstOrNull()?.getOwnerPlayer()?.awardStat(getStat(Cobblemon.statistics.TRADED))
event.tradeParticipant2Pokemon.firstOrNull()?.getOwnerPlayer()?.awardStat(getStat(Cobblemon.statistics.TRADED))
event.tradeParticipant1Pokemon.getOwnerPlayer()?.awardStat(getStat(Cobblemon.statistics.TRADED))
event.tradeParticipant2Pokemon.getOwnerPlayer()?.awardStat(getStat(Cobblemon.statistics.TRADED))
}
fun onFossilRevived(event : FossilRevivedEvent) {
@@ -0,0 +1,35 @@
/*
* 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.item
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.api.text.gray
import com.cobblemon.mod.common.pokeradar.Navpoint
import com.cobblemon.mod.common.util.lang
import net.minecraft.network.chat.Component
import net.minecraft.world.item.DyeColor
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.TooltipFlag
/** Blank, written and encrypted Nav Chips. Equipped by right-clicking them onto a Poké Radar in the inventory. */
class NavChipItem(val encrypted: Boolean) : CobblemonItem(Properties().stacksTo(1)) {
override fun appendHoverText(stack: ItemStack, context: TooltipContext, tooltip: MutableList<Component>, type: TooltipFlag) {
val chip = stack.get(CobblemonItemComponents.NAV_CHIP)
when {
chip == null -> tooltip.add(lang("item.nav_chip.blank").gray())
encrypted -> tooltip.add(lang("item.nav_chip.title", Navpoint.HIDDEN_TITLE).gray())
else -> {
tooltip.add(lang("item.nav_chip.title", chip.title).gray())
tooltip.add(lang("item.nav_chip.coordinates", chip.x, chip.z).gray())
tooltip.add(lang("item.nav_chip.color", Component.translatable("color.minecraft.${DyeColor.byId(chip.color).getName()}")).gray())
}
}
}
}
@@ -0,0 +1,101 @@
/*
* 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.item
import com.cobblemon.mod.common.api.text.gray
import com.cobblemon.mod.common.client.gui.pokeradar.PokeRadarGUI
import com.cobblemon.mod.common.client.pokeradar.PokeRadarType
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import com.cobblemon.mod.common.util.lang
import net.minecraft.core.component.DataComponents
import net.minecraft.network.chat.Component
import net.minecraft.server.level.ServerPlayer
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResultHolder
import net.minecraft.world.entity.SlotAccess
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.ClickAction
import net.minecraft.world.inventory.Slot
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.ItemUtils
import net.minecraft.world.item.TooltipFlag
import net.minecraft.world.item.component.ItemContainerContents
import net.minecraft.world.level.Level
class PokeRadarItem(val type: PokeRadarType) : CobblemonItem(Properties().stacksTo(1)) {
companion object {
fun getChip(radar: ItemStack): ItemStack =
radar.get(DataComponents.CONTAINER)?.nonEmptyItemsCopy()?.firstOrNull() ?: ItemStack.EMPTY
fun setChip(radar: ItemStack, chip: ItemStack) {
if (chip.isEmpty) radar.remove(DataComponents.CONTAINER)
else radar.set(DataComponents.CONTAINER, ItemContainerContents.fromItems(listOf(chip.copyWithCount(1))))
}
fun heldRadar(player: Player): ItemStack? =
InteractionHand.entries.map(player::getItemInHand).firstOrNull { it.item is PokeRadarItem }
}
override fun use(level: Level, player: Player, usedHand: InteractionHand): InteractionResultHolder<ItemStack> {
if (level.isClientSide) {
PokeRadarGUI.open(type)
}
return InteractionResultHolder.sidedSuccess(player.getItemInHand(usedHand), level.isClientSide)
}
override fun overrideOtherStackedOnMe(
radar: ItemStack,
cursor: ItemStack,
slot: Slot,
clickAction: ClickAction,
player: Player,
slotAccess: SlotAccess
): Boolean {
if (clickAction != ClickAction.SECONDARY || !slot.allowModification(player)) return false
val equipped = getChip(radar)
if (cursor.isEmpty) {
if (equipped.isEmpty) return false
setChip(radar, ItemStack.EMPTY)
slotAccess.set(equipped)
player.playSound(SoundEvents.ITEM_FRAME_REMOVE_ITEM, 0.8F, 1F)
return true
}
if (cursor.item !is NavChipItem) return false
setChip(radar, cursor)
cursor.shrink(1)
if (!equipped.isEmpty) slotAccess.set(equipped)
player.playSound(SoundEvents.ITEM_FRAME_ADD_ITEM, 0.8F, 1F)
if (player is ServerPlayer) {
PokeRadarManager.importChip(player, getChip(radar))
}
return true
}
override fun onDestroyed(itemEntity: ItemEntity) {
ItemUtils.onContainerDestroyed(itemEntity, listOf(getChip(itemEntity.item)).filterNot { it.isEmpty })
}
override fun appendHoverText(
stack: ItemStack,
context: TooltipContext,
tooltip: MutableList<Component>,
type: TooltipFlag
) {
val chip = getChip(stack)
tooltip.add(
if (chip.isEmpty) lang("item.poke_radar.no_chip").gray()
else lang("item.poke_radar.chip", chip.hoverName).gray()
)
}
}
@@ -1,99 +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.item.bag
import net.minecraft.core.HolderLookup
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import net.minecraft.world.Container
import net.minecraft.world.ContainerHelper
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import kotlin.math.min
class CobblemonBagContainer: Container {
val items: MutableList<ItemStack> = mutableListOf()
override fun getContainerSize(): Int {
return items.size
}
override fun getItem(slot: Int): ItemStack {
if (slot >= items.size) return ItemStack.EMPTY
return items[slot]
}
override fun isEmpty(): Boolean {
return items.isEmpty()
}
override fun removeItem(slot: Int, amount: Int): ItemStack {
if (slot >= items.size) return ItemStack.EMPTY
val itemStack = items[slot].split(amount)
if (items[slot].isEmpty) {
items.removeAt(slot)
}
return itemStack
}
override fun removeItemNoUpdate(slot: Int): ItemStack { return ItemStack.EMPTY }
override fun clearContent() {
items.clear()
setChanged()
}
override fun setChanged() {
}
override fun setItem(slot: Int, stack: ItemStack) {} // Obsolete
override fun stillValid(player: Player): Boolean {
return true
}
override fun getMaxStackSize(): Int {
return 99999
}
fun fromTag(tag: ListTag, levelRegistry: HolderLookup.Provider) {
items.clear()
tag.forEach {
val compoundTag = it as CompoundTag
val count = compoundTag.getInt("count")
compoundTag.putInt("count", 1)
val item = ItemStack.parse(levelRegistry, it)
item.ifPresent { theItem ->
theItem.count = count
items.add(theItem)
}
}
}
fun createTag(levelRegistry: HolderLookup.Provider): ListTag {
val tag = ListTag()
items.forEach {
val fakeItem = it.copyWithCount(1)
val compoundTag = fakeItem.save(levelRegistry) as CompoundTag
compoundTag.putInt("count", it.count) // ItemStack does not save count above 99 for some reason, so we save it ourselves
tag.add(compoundTag)
}
return tag
}
fun dropAll(player: Player) {
items.forEach {
player.drop(it, true, false)
}
items.clear()
}
}
@@ -1,54 +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.item.bag
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.item.CobblemonItem
import com.cobblemon.mod.common.bag.BagEntity
import net.minecraft.client.Minecraft
import net.minecraft.client.resources.sounds.SimpleSoundInstance
import net.minecraft.core.Holder
import net.minecraft.network.chat.Component
import net.minecraft.sounds.SoundEvent
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResultHolder
import net.minecraft.world.MenuProvider
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.item.Equipable
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
class CobblemonBagItem: CobblemonItem(Properties().stacksTo(1)), MenuProvider, Equipable {
override fun use(level: Level, player: Player, usedHand: InteractionHand): InteractionResultHolder<ItemStack?> {
val itemStack = player.getItemInHand(usedHand)
player.openMenu(this)
return InteractionResultHolder.success(itemStack)
}
override fun createMenu(i: Int, inventory: Inventory, player: Player): AbstractContainerMenu {
val bagEntity = (player as? BagEntity)
val container = bagEntity?.`cobblemon$getBagContainer`() ?: CobblemonBagContainer()
return CobblemonBagMenu(i, inventory, container)
}
override fun getDisplayName(): Component? {
return Component.translatable("cobblemon.container.bag")
}
override fun getEquipmentSlot(): EquipmentSlot = EquipmentSlot.CHEST
override fun getEquipSound(): Holder<SoundEvent?>? {
Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(CobblemonSounds.ITEM_BAG_EQUIP, 1.0F))
return null
}
}
@@ -1,428 +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.item.bag
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonMenuType
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.advancement.CobblemonCriteria
import com.cobblemon.mod.common.advancement.criterion.PokemonInteractContext
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.item.PokemonSelectingItem
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.util.isInBattle
import net.minecraft.CrashReport
import net.minecraft.ReportedException
import net.minecraft.client.Minecraft
import net.minecraft.client.resources.sounds.SimpleSoundInstance
import net.minecraft.core.NonNullList
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.server.level.ServerPlayer
import net.minecraft.sounds.SoundEvent
import net.minecraft.world.InteractionResult
import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.inventory.ClickAction
import net.minecraft.world.inventory.ClickType
import net.minecraft.world.inventory.Slot
import net.minecraft.world.item.ItemStack
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
class CobblemonBagMenu: AbstractContainerMenu {
companion object {
val BAG_SLOTS = 0..31
private val PARTY_SLOTS = 32..37
private val INVENTORY_SLOTS = 38..64
private val HOTBAR_SLOTS = 65..73
}
private val playerInventory: Inventory
private val bagContainer: CobblemonBagContainer
private val partyContainer: SimpleContainer
private var serverParty: PartyStore? = null
var currentlySelectedCategory = -1
var scroll = 0
var maxScroll = 0
var categoryItemCounts = mutableListOf<Int>()
constructor(containerId: Int, playerInventory: Inventory): super(CobblemonMenuType.COBBLEMON_BAG, containerId) {
this.playerInventory = playerInventory
this.bagContainer = CobblemonBagContainer()
this.partyContainer = SimpleContainer(6)
for (i in 0..<BagCategories.getOrderedCategoriesList().size) { //Pre-init so Screen does not crash
categoryItemCounts.add(0)
}
initializeSlots(playerInventory)
}
constructor(containerId: Int, playerInventory: Inventory, bagContainer: CobblemonBagContainer): super(CobblemonMenuType.COBBLEMON_BAG, containerId) {
this.playerInventory = playerInventory
this.bagContainer = bagContainer
this.partyContainer = SimpleContainer(6)
this.serverParty = Cobblemon.storage.getParty(playerInventory.player as ServerPlayer)
initializeSlots(playerInventory)
setupSlotsBasedOnContent()
calculateCategoriesItemCounts()
}
private fun initializeSlots(playerInventory: Inventory) {
for ((index, _) in BAG_SLOTS.withIndex()) {
val i = index / 8
val j = index % 8
addSlot(CobblemonBagSlot(bagContainer, -1, 81 + j * 18, 50 + i * 18))
}
for ((index, _) in PARTY_SLOTS.withIndex()) {
val xPos = 46
val yPos = 32 + 33 * index
if (serverParty != null) {
addSlot(CobblemonBagPartySlot(partyContainer, index,
{ serverParty?.get(index) != null },
{ serverParty?.get(index)?.heldItem() ?: ItemStack.EMPTY },
xPos, yPos))
} else {
addSlot(CobblemonBagPartySlot(partyContainer, index,
{ CobblemonClient.storage.party.get(index) != null },
{ CobblemonClient.storage.party.get(index)?.heldItem() ?: ItemStack.EMPTY },
xPos, yPos))
}
}
for ((index, _) in INVENTORY_SLOTS.withIndex()) {
val i = index / 9
val j = index % 9
addSlot(Slot(playerInventory, 9 + index, 81 + j * 18, 142 + i * 18))
}
for ((index, _) in HOTBAR_SLOTS.withIndex()) {
addSlot(Slot(playerInventory, index, 81 + index * 18, 200))
}
}
fun setupSlotsBasedOnContent() {
BAG_SLOTS.forEach {
(getSlot(it) as CobblemonBagSlot).let {
it.simulatedSlot = -1
it.slotOverflowValue = 0
}
}
var slotId = BAG_SLOTS.first - 8 * scroll
bagContainer.items.forEachIndexed { index, itemStack ->
if (currentlySelectedCategory == -1 || BagCategories.getOrderedCategoriesList()[currentlySelectedCategory].itemIsValid(itemStack)) {
val stackCount = ceil(itemStack.count.toFloat() / itemStack.maxStackSize).toInt()
for (i in 0..<stackCount) {
if (slotId in BAG_SLOTS) {
val slot = getSlot(slotId) as CobblemonBagSlot
slot.simulatedSlot = index
slot.slotOverflowValue = i
}
slotId += 1
if (slotId > BAG_SLOTS.last) return@forEachIndexed
}
}
}
updateMaxScroll()
}
fun calculateCategoriesItemCounts() {
val orderedCategories = BagCategories.getOrderedCategoriesList()
categoryItemCounts.clear()
for (i in 0..<orderedCategories.size) {
categoryItemCounts.add(0)
}
bagContainer.items.forEach { itemStack ->
for (i in 0..<orderedCategories.size) {
val category = orderedCategories[i]
if (category.itemIsValid(itemStack)) {
categoryItemCounts[i] += itemStack.count
return@forEach
}
}
}
}
fun changeCategory(categoryId: Int) {
currentlySelectedCategory = categoryId
scroll = 0
setupSlotsBasedOnContent()
}
fun updateMaxScroll() {
var itemCount = 0
bagContainer.items.forEach { itemStack ->
if (currentlySelectedCategory == -1 || BagCategories.getOrderedCategoriesList()[currentlySelectedCategory].itemIsValid(itemStack)) {
itemCount += ceil(itemStack.count.toFloat() / itemStack.maxStackSize).toInt()
}
}
val rowsWithItems = (itemCount - 1) / 8 + 1
maxScroll = max(rowsWithItems - 3, 0)
}
override fun stillValid(player: Player): Boolean {
return true //Add some extra logic like checking for maybe bag item existance
}
override fun sendAllDataToRemote() { //We want to send more info than just the slots
val items = NonNullList.create<ItemStack>()
for (i in PARTY_SLOTS.first..HOTBAR_SLOTS.last) {
this.remoteSlots[i] = this.slots[i].item.copy()
items.add(this.remoteSlots[i].copy())
}
this.remoteCarried = this.carried.copy()
bagContainer.items.forEach {
items.add(it.copy())
}
if (this.synchronizer != null) {
this.synchronizer!!.sendInitialData(this, items, this.remoteCarried, this.remoteDataSlots.toIntArray())
}
}
override fun initializeContents(stateId: Int, items: List<ItemStack>, carried: ItemStack) {
bagContainer.items.clear()
items.forEachIndexed { index, stack ->
val adjustedIndex = index + PARTY_SLOTS.first
if (adjustedIndex in PARTY_SLOTS.first..HOTBAR_SLOTS.last) {
this.slots[adjustedIndex].set(stack)
} else {
bagContainer.items.add(stack)
}
}
this.carried = carried
this.stateId = stateId
setupSlotsBasedOnContent()
calculateCategoriesItemCounts()
}
override fun clicked(slotId: Int, button: Int, clickType: ClickType, player: Player) {
if (slotId in BAG_SLOTS) {
try {
doBagClick(slotId, button, clickType, player)
} catch (exception: Exception) {
val crashReport = CrashReport.forThrowable(exception, "Container click")
val crashReportCategory = crashReport.addCategory("Click info")
crashReportCategory.setDetail("Menu Type") {
if (this.menuType != null) BuiltInRegistries.MENU.getKey(this.menuType!!)
.toString() else "<no type>"
}
crashReportCategory.setDetail("Menu Class") { this.javaClass.getCanonicalName() }
crashReportCategory.setDetail("Slot Count", this.slots.size)
crashReportCategory.setDetail("Slot", slotId)
crashReportCategory.setDetail("Button", button)
crashReportCategory.setDetail("Type", clickType)
throw ReportedException(crashReport)
}
return
} else if (slotId in PARTY_SLOTS) {
onPartySlotClick(slotId, button, clickType, player)
}
super.clicked(slotId, button, clickType, player)
}
// We handle the bag slots completely differently than normal slots, but a lot of default logic is cut
private fun doBagClick(slotId: Int, button: Int, clickType: ClickType, player: Player) {
val slot = (getSlot(slotId) as? CobblemonBagSlot) ?: return
val slotItem = slot.item
if (clickType == ClickType.PICKUP && (button == 0 || button == 1)) {
val primaryButton = if (button == 0) ClickAction.PRIMARY else ClickAction.SECONDARY
val carriedStack = carried
if (carriedStack.isEmpty) {
if (!slotItem.isEmpty) {
val pickupCount = if (primaryButton == ClickAction.PRIMARY) slotItem.count else (slotItem.count + 1) / 2
val removedItemStack = slot.remove(pickupCount)
if (!removedItemStack.isEmpty) {
carried = removedItemStack
slot.onTake(player, removedItemStack)
getAndReduceCategoryCount(removedItemStack)
}
playSound(CobblemonSounds.ITEM_BAG_ITEM_OUT)
setupSlotsBasedOnContent()
}
} else {
val (categoryId, allowedTransfer) = calculateInsertCount(carriedStack)
if (allowedTransfer <= 0) return
val transferCount = if (primaryButton == ClickAction.PRIMARY) min(carriedStack.count, allowedTransfer) else 1
bagContainer.items.forEachIndexed { index, slotStack ->
if (ItemStack.isSameItemSameComponents(carriedStack, slotStack) && !tryItemClickBehaviourOverride(player, primaryButton, CobblemonBagSlot(bagContainer, index, 0, 0), slotStack, carriedStack)
) { // Provide a slot with index equal to the item, as there is not really any 'real' slots
slotStack.grow(transferCount)
carriedStack.shrink(transferCount)
categoryItemCounts[categoryId] += transferCount
playSound(CobblemonSounds.ITEM_BAG_ITEM_IN)
setupSlotsBasedOnContent()
return
}
}
val transferItem = carriedStack.split(transferCount)
bagContainer.items.add(transferItem)
categoryItemCounts[categoryId] += transferCount
playSound(CobblemonSounds.ITEM_BAG_ITEM_IN)
setupSlotsBasedOnContent()
}
} else if (clickType == ClickType.QUICK_MOVE && (button == 0 || button == 1)) {
quickMoveStackFromBag(player, slot)
} else if (clickType == ClickType.CLONE && player.hasInfiniteMaterials() && carried.isEmpty && !slotItem.isEmpty) {
carried = slotItem.copyWithCount(slotItem.maxStackSize)
} else if (clickType == ClickType.THROW && carried.isEmpty && !slotItem.isEmpty) {
val throwCount = if (button == 0) 1 else min(slotItem.count, slotItem.maxStackSize)
val bagSize = bagContainer.items.size
val removedItemStack = slot.remove(throwCount)
player.drop(removedItemStack, true)
playSound(CobblemonSounds.ITEM_BAG_ITEM_OUT)
getAndReduceCategoryCount(removedItemStack)
if (bagSize != bagContainer.items.size) {
setupSlotsBasedOnContent()
}
}
}
//Handle party slot clicked
private fun onPartySlotClick(slotId: Int, button: Int, clickType: ClickType, player: Player) {
val slotItem = getSlot(slotId).item
if (clickType == ClickType.CLONE && player.hasInfiniteMaterials() && carried.isEmpty && !slotItem.isEmpty) {
carried = slotItem.copyWithCount(slotItem.maxStackSize)
} else if (clickType != ClickType.PICKUP) return
if (serverParty == null) return // Client does nothing
if (!carried.isEmpty && (isBlacklisted(carried) || !isWhitelisted(carried))) return //Blacklisted and Whitelisted checks
val index = slotId - PARTY_SLOTS.first
val pokemon = serverParty?.get(index) ?: return
val heldItem = pokemon.heldItem()
if (carried.isEmpty || carried.count <= 1) { // Can Swap/Pickup
val returned = pokemon.swapHeldItem(carried, aiCanDrop = false)
carried = returned
broadcastChanges()
} else if (heldItem.isEmpty) { // Can Placedown
pokemon.swapHeldItem(carried, aiCanDrop = false)
broadcastChanges()
}
}
//Handled only by server
fun useHeldItemOnPokemon(partySlot: Int) {
if (carried.isEmpty) return
val pokemon = serverParty?.get(partySlot) ?: return
val item = carried.item as? PokemonSelectingItem ?: return
val player = playerInventory.player as? ServerPlayer ?: return
if (player.isInBattle()) return
val interaction = item.applyToPokemon(player, carried, pokemon)
if (interaction?.result == InteractionResult.SUCCESS) {
CobblemonCriteria.POKEMON_INTERACT.trigger(player, PokemonInteractContext(pokemon.species.resourceIdentifier, BuiltInRegistries.ITEM.getKey(carried.item)))
broadcastChanges()
}
}
private fun isBlacklisted(stack: ItemStack): Boolean =
BuiltInRegistries.ITEM.getTagOrEmpty(CobblemonItemTags.BLACKLISTED_ITEMS_TO_HOLD).any()
&& stack.`is`(CobblemonItemTags.BLACKLISTED_ITEMS_TO_HOLD)
private fun isWhitelisted(stack: ItemStack): Boolean =
BuiltInRegistries.ITEM.getTagOrEmpty(CobblemonItemTags.WHITELISTED_ITEMS_TO_HOLD).none()
|| stack.`is`(CobblemonItemTags.WHITELISTED_ITEMS_TO_HOLD)
override fun quickMoveStack(player: Player, index: Int): ItemStack { // This will only be called by base inventory
if (index < 0 || index >= slots.size) return ItemStack.EMPTY
val slot = slots[index]
val itemStack = slot.item
val (categoryId, allowedTransfer) = calculateInsertCount(itemStack)
if (allowedTransfer <= 0) return ItemStack.EMPTY
val transferCount = min(itemStack.count, allowedTransfer)
if (slot.hasItem()) {
bagContainer.items.forEach { slotStack ->
if (ItemStack.isSameItemSameComponents(slotStack, itemStack)) {
slotStack.grow(transferCount)
itemStack.shrink(transferCount)
categoryItemCounts[categoryId] += transferCount
playSound(CobblemonSounds.ITEM_BAG_ITEM_IN)
setupSlotsBasedOnContent()
return ItemStack.EMPTY
}
}
bagContainer.items.add(itemStack.split(transferCount))
categoryItemCounts[categoryId] += transferCount
playSound(CobblemonSounds.ITEM_BAG_ITEM_IN)
setupSlotsBasedOnContent()
}
return ItemStack.EMPTY
}
fun quickMoveStackFromBag(player: Player, slot: CobblemonBagSlot) { //Called by bag items
val transferStack = slot.item
val startingCount = transferStack.count
if (moveItemStackTo(transferStack, INVENTORY_SLOTS.first, HOTBAR_SLOTS.last + 1, false)) {
val itemsMoved = startingCount - transferStack.count
getAndReduceCategoryCount(slot.remove(itemsMoved))
playSound(CobblemonSounds.ITEM_BAG_ITEM_OUT)
setupSlotsBasedOnContent()
}
}
fun calculateInsertCount(stack: ItemStack): Pair<Int, Int> {
if (stack.isEmpty) return -1 to 0
BagCategories.getOrderedCategoriesList().forEachIndexed { index, category ->
if (category.itemIsValid(stack)) {
val maxAllowed = max(category.maxCount - categoryItemCounts[index], 0)
return index to min(stack.count, maxAllowed)
}
}
return -1 to 0
}
fun getAndReduceCategoryCount(stack: ItemStack) {
if (stack.isEmpty) return
BagCategories.getOrderedCategoriesList().forEachIndexed { index, category ->
if (category.itemIsValid(stack)) {
categoryItemCounts[index] -= stack.count
return
}
}
}
override fun canTakeItemForPickAll(stack: ItemStack, slot: Slot): Boolean {
return slot.index !in BAG_SLOTS
}
fun playSound(soundEvent: SoundEvent) {
Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(soundEvent, 1.0F))
}
}
@@ -1,37 +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.item.bag
import com.cobblemon.mod.common.pokemon.Pokemon
import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.Slot
import net.minecraft.world.item.ItemStack
class CobblemonBagPartySlot(
container: SimpleContainer,
index: Int,
val activeGetter: () -> Boolean,
val itemGetter: () -> ItemStack,
x: Int,
y: Int
): Slot(container, index, x, y) {
override fun getMaxStackSize(): Int = 1
override fun mayPlace(stack: ItemStack): Boolean = false
override fun mayPickup(player: Player): Boolean = false
override fun getItem(): ItemStack {
return itemGetter.invoke()
}
override fun isActive(): Boolean {
return activeGetter.invoke()
}
}
@@ -1,41 +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.item.bag
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.Slot
import net.minecraft.world.item.ItemStack
import java.util.Optional
import kotlin.math.min
class CobblemonBagSlot(
container: CobblemonBagContainer,
var simulatedSlot: Int, //Cant override base slot variable so it is forever -1
x: Int,
y: Int
): Slot(container, 0, x, y) {
var slotOverflowValue = 0
override fun set(stack: ItemStack) {}
override fun getItem(): ItemStack {
if (simulatedSlot == -1) return ItemStack.EMPTY
val itemStack = container.getItem(simulatedSlot)
val count = min(itemStack.count - itemStack.maxStackSize * slotOverflowValue, itemStack.maxStackSize)
return itemStack.copyWithCount(count)
}
override fun remove(amount: Int): ItemStack {
if (simulatedSlot == -1) return ItemStack.EMPTY
return container.removeItem(simulatedSlot, amount)
}
override fun mayPlace(stack: ItemStack): Boolean = false
override fun mayPickup(player: Player): Boolean = false
}
@@ -0,0 +1,38 @@
/*
* 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.item.components
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import io.netty.buffer.ByteBuf
import net.minecraft.network.codec.ByteBufCodecs
import net.minecraft.network.codec.StreamCodec
/** The location stored on a Nav Chip. */
data class NavChipComponent(
val title: String,
val x: Int,
val z: Int,
val color: Int,
val dimension: String
) {
companion object {
val CODEC: Codec<NavChipComponent> = RecordCodecBuilder.create { builder ->
builder.group(
Codec.STRING.optionalFieldOf("title", "").forGetter { it.title },
Codec.INT.fieldOf("x").forGetter { it.x },
Codec.INT.fieldOf("z").forGetter { it.z },
Codec.INT.optionalFieldOf("color", 0).forGetter { it.color },
Codec.STRING.optionalFieldOf("dimension", "minecraft:overworld").forGetter { it.dimension }
).apply(builder, ::NavChipComponent)
}
val PACKET_CODEC: StreamCodec<ByteBuf, NavChipComponent> = ByteBufCodecs.fromCodec(CODEC)
}
}
@@ -477,25 +477,6 @@ object CobblemonItemGroups {
entries.accept(CobblemonItems.TYPE_GEM_BLOCK_STEEL)
entries.accept(CobblemonItems.TYPE_GEM_BLOCK_FAIRY)
entries.accept(CobblemonItems.BLANK_PLATE)
entries.accept(CobblemonItems.FLAME_PLATE)
entries.accept(CobblemonItems.SPLASH_PLATE)
entries.accept(CobblemonItems.ZAP_PLATE)
entries.accept(CobblemonItems.MEADOW_PLATE)
entries.accept(CobblemonItems.ICICLE_PLATE)
entries.accept(CobblemonItems.FIST_PLATE)
entries.accept(CobblemonItems.TOXIC_PLATE)
entries.accept(CobblemonItems.EARTH_PLATE)
entries.accept(CobblemonItems.SKY_PLATE)
entries.accept(CobblemonItems.MIND_PLATE)
entries.accept(CobblemonItems.INSECT_PLATE)
entries.accept(CobblemonItems.STONE_PLATE)
entries.accept(CobblemonItems.SPOOKY_PLATE)
entries.accept(CobblemonItems.DRACO_PLATE)
entries.accept(CobblemonItems.DREAD_PLATE)
entries.accept(CobblemonItems.IRON_PLATE)
entries.accept(CobblemonItems.PIXIE_PLATE)
entries.accept(CobblemonItems.POLISHED_TUMBLESTONE)
entries.accept(CobblemonItems.POLISHED_TUMBLESTONE_STAIRS)
entries.accept(CobblemonItems.POLISHED_TUMBLESTONE_SLAB)
@@ -964,8 +945,10 @@ object CobblemonItemGroups {
CobblemonItems.pokeBalls.forEach(entries::accept)
CobblemonItems.pokeRods.forEach(entries::accept)
CobblemonItems.pokedexes.forEach(entries::accept)
entries.accept(CobblemonItems.TRAINER_PACK)
entries.accept(CobblemonItems.TRAINER_BAG)
CobblemonItems.pokeradars.forEach(entries::accept)
entries.accept(CobblemonItems.BLANK_NAV_CHIP)
entries.accept(CobblemonItems.NAV_CHIP)
entries.accept(CobblemonItems.ENCRYPTED_NAV_CHIP)
}
private fun blocksInjections(injector: Injector) {
@@ -0,0 +1,93 @@
/*
* 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.loot
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.item.components.NavChipComponent
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.core.BlockPos
import net.minecraft.core.registries.Registries
import net.minecraft.tags.StructureTags
import net.minecraft.tags.TagKey
import net.minecraft.world.item.DyeColor
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.levelgen.structure.Structure
import net.minecraft.world.level.storage.loot.LootContext
import net.minecraft.world.level.storage.loot.functions.LootItemConditionalFunction
import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType
import net.minecraft.world.level.storage.loot.parameters.LootContextParams
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition
/**
* The Nav Chip version of `minecraft:exploration_map`: finds the nearest [destination] structure and writes it
* onto the chip. Use it on `cobblemon:nav_chip` or `cobblemon:encrypted_nav_chip`.
*
* ```json
* {
* "function": "cobblemon:set_nav_chip_destination",
* "destination": "cobblemon:shipwreck_cove",
* "name": "Shipwreck Cove",
* "color": "red",
* "skip_existing_chunks": true,
* "scatter": 0
* }
* ```
* [scatter] > 0 stores a "close by" point up to that many blocks away instead of the exact location.
*/
class SetNavChipDestinationFunction(
conditions: List<LootItemCondition>,
val destination: TagKey<Structure>,
val searchRadius: Int,
val skipExistingChunks: Boolean,
val name: String,
val color: DyeColor,
val scatter: Int
) : LootItemConditionalFunction(conditions) {
override fun getType(): LootItemFunctionType<SetNavChipDestinationFunction> = TYPE
override fun run(stack: ItemStack, context: LootContext): ItemStack {
val origin = context.getParamOrNull(LootContextParams.ORIGIN)
?: context.getParamOrNull(LootContextParams.THIS_ENTITY)?.position()
?: return stack
val level = context.level
val found =
level.findNearestMapStructure(destination, BlockPos.containing(origin), searchRadius, skipExistingChunks)
?: return stack
val random = context.random
val x = found.x + if (scatter > 0) random.nextInt(scatter * 2 + 1) - scatter else 0
val z = found.z + if (scatter > 0) random.nextInt(scatter * 2 + 1) - scatter else 0
stack.set(
CobblemonItemComponents.NAV_CHIP,
NavChipComponent(name, x, z, color.id, level.dimension().location().toString())
)
return stack
}
companion object {
val CODEC: MapCodec<SetNavChipDestinationFunction> = RecordCodecBuilder.mapCodec { instance ->
commonFields(instance).and(
instance.group(
TagKey.codec(Registries.STRUCTURE).optionalFieldOf("destination", StructureTags.ON_TREASURE_MAPS)
.forGetter { it.destination },
Codec.INT.optionalFieldOf("search_radius", 50).forGetter { it.searchRadius },
Codec.BOOL.optionalFieldOf("skip_existing_chunks", true).forGetter { it.skipExistingChunks },
Codec.STRING.optionalFieldOf("name", "").forGetter { it.name },
DyeColor.CODEC.optionalFieldOf("color", DyeColor.WHITE).forGetter { it.color },
Codec.INT.optionalFieldOf("scatter", 0).forGetter { it.scatter }
)
).apply(instance, ::SetNavChipDestinationFunction)
}
val TYPE = LootItemFunctionType(CODEC)
}
}
@@ -1,28 +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.net.messages.client.bag
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class UpdateBagMenuDataPacket(val categoryId: Int, val scroll: Int): NetworkPacket<UpdateBagMenuDataPacket> {
companion object {
val ID = cobblemonResource("update_bag_menu_data")
fun decode(buffer: RegistryFriendlyByteBuf): UpdateBagMenuDataPacket {
return UpdateBagMenuDataPacket(buffer.readInt(), buffer.readInt())
}
}
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeInt(categoryId)
buffer.writeInt(scroll)
}
}
@@ -1,32 +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.net.messages.client.data
import com.cobblemon.mod.common.api.bag.BagCategories
import com.cobblemon.mod.common.api.bag.BagCategory
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class BagCategoriesSyncPacket(categories: List<BagCategory>): DataRegistrySyncPacket<BagCategory, BagCategoriesSyncPacket>(categories) {
companion object {
val ID = cobblemonResource("bag_categories")
fun decode(buffer: RegistryFriendlyByteBuf) = BagCategoriesSyncPacket(emptyList()).apply { decodeBuffer(buffer) }
}
override val id = ID
override fun encodeEntry(buffer: RegistryFriendlyByteBuf, entry: BagCategory) {
entry.encode(buffer)
}
override fun decodeEntry(buffer: RegistryFriendlyByteBuf): BagCategory = BagCategory.decode(buffer)
override fun synchronizeDecoded(entries: Collection<BagCategory>) {
BagCategories.reload(entries.associateBy { it.identifier })
}
}
@@ -0,0 +1,32 @@
/*
* 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.net.messages.client.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.pokeradar.RadarEntry
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class PokeRadarScanResultPacket(val fishing: Boolean, val entries: List<RadarEntry>) : NetworkPacket<PokeRadarScanResultPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeBoolean(fishing)
buffer.writeVarInt(entries.size)
entries.forEach { it.encode(buffer) }
}
companion object {
val ID = cobblemonResource("poke_radar_scan_result")
fun decode(buffer: RegistryFriendlyByteBuf): PokeRadarScanResultPacket {
val fishing = buffer.readBoolean()
return PokeRadarScanResultPacket(fishing, List(buffer.readVarInt()) { RadarEntry.decode(buffer) })
}
}
}
@@ -6,21 +6,21 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.net.messages.client.bag
package com.cobblemon.mod.common.net.messages.client.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class UseItemOnPokemonFromBagPacket(val partySlot: Int): NetworkPacket<UseItemOnPokemonFromBagPacket> {
companion object {
val ID = cobblemonResource("use_item_on_pokemon_from_bag")
fun decode(buffer: RegistryFriendlyByteBuf): UseItemOnPokemonFromBagPacket {
return UseItemOnPokemonFromBagPacket(buffer.readInt())
}
}
class PokeRadarSyncPacket(val json: String) : NetworkPacket<PokeRadarSyncPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeInt(partySlot)
buffer.writeUtf(json, MAX_LENGTH)
}
}
companion object {
const val MAX_LENGTH = 1 shl 20
val ID = cobblemonResource("poke_radar_sync")
fun decode(buffer: RegistryFriendlyByteBuf) = PokeRadarSyncPacket(buffer.readUtf(MAX_LENGTH))
}
}
@@ -0,0 +1,35 @@
/*
* 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.net.messages.client.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.world.phys.Vec3
class PokeRadarTrackingStatePacket(
val active: Boolean,
val found: Boolean,
val navpoint: Boolean = false,
val pos: Vec3 = Vec3.ZERO
) : NetworkPacket<PokeRadarTrackingStatePacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeBoolean(active)
buffer.writeBoolean(found)
buffer.writeBoolean(navpoint)
buffer.writeVec3(pos)
}
companion object {
val ID = cobblemonResource("poke_radar_tracking_state")
fun decode(buffer: RegistryFriendlyByteBuf) =
PokeRadarTrackingStatePacket(buffer.readBoolean(), buffer.readBoolean(), buffer.readBoolean(), buffer.readVec3())
}
}
@@ -23,19 +23,16 @@ import java.util.UUID
* @author Hiroku
* @since March 5th, 2023
*/
class TradeCompletedPacket(val pokemonIds1: List<UUID>, val pokemonIds2: List<UUID>) : NetworkPacket<TradeCompletedPacket> {
class TradeCompletedPacket(val pokemonId1: UUID, val pokemonId2: UUID) : NetworkPacket<TradeCompletedPacket> {
companion object {
val ID = cobblemonResource("trade_completed")
fun decode(buffer: RegistryFriendlyByteBuf) = TradeCompletedPacket(
buffer.readList { it.readUUID() },
buffer.readList { it.readUUID() }
)
fun decode(buffer: RegistryFriendlyByteBuf) = TradeCompletedPacket(buffer.readUUID(), buffer.readUUID())
}
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeCollection(pokemonIds1) { buf, id -> buf.writeUUID(id) }
buffer.writeCollection(pokemonIds2) { buf, id -> buf.writeUUID(id) }
buffer.writeUUID(pokemonId1)
buffer.writeUUID(pokemonId2)
}
}
@@ -12,6 +12,10 @@ import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.net.UnsplittablePacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readNullable
import com.cobblemon.mod.common.util.readUUID
import com.cobblemon.mod.common.util.writeNullable
import com.cobblemon.mod.common.util.writeUUID
import net.minecraft.network.RegistryFriendlyByteBuf
import java.util.UUID
@@ -23,18 +27,15 @@ import java.util.UUID
* @author Hiroku
* @since March 5th, 2023
*/
class TradeUpdatedPacket(val playerId: UUID, val pokemons: List<Pokemon>) : NetworkPacket<TradeUpdatedPacket>, UnsplittablePacket {
class TradeUpdatedPacket(val playerId: UUID, val pokemon: Pokemon?) : NetworkPacket<TradeUpdatedPacket>, UnsplittablePacket {
companion object {
val ID = cobblemonResource("trade_updated")
fun decode(buffer: RegistryFriendlyByteBuf) = TradeUpdatedPacket(
buffer.readUUID(),
buffer.readList { Pokemon.S2C_CODEC.decode(it as RegistryFriendlyByteBuf) }
)
fun decode(buffer: RegistryFriendlyByteBuf) = TradeUpdatedPacket(buffer.readUUID(), buffer.readNullable { Pokemon.S2C_CODEC.decode(buffer) })
}
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeUUID(playerId)
buffer.writeCollection(pokemons) { buf, pokemon -> Pokemon.S2C_CODEC.encode(buf as RegistryFriendlyByteBuf, pokemon) }
buffer.writeNullable(pokemon) { _, pokemon -> Pokemon.S2C_CODEC.encode(buffer, pokemon) }
}
}
@@ -0,0 +1,33 @@
/*
* 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.net.messages.server.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.pokeradar.Navpoint
import com.cobblemon.mod.common.pokeradar.PokeRadarState
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class PokeRadarNavpointPacket(val action: Action, val navpoint: Navpoint) : NetworkPacket<PokeRadarNavpointPacket> {
enum class Action { SAVE, DELETE, UPLOAD }
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeEnum(action)
buffer.writeUtf(PokeRadarState.GSON.toJson(navpoint))
}
companion object {
val ID = cobblemonResource("poke_radar_navpoint")
fun decode(buffer: RegistryFriendlyByteBuf) = PokeRadarNavpointPacket(
buffer.readEnum(Action::class.java),
PokeRadarState.GSON.fromJson(buffer.readUtf(), Navpoint::class.java)
)
}
}
@@ -0,0 +1,26 @@
/*
* 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.net.messages.server.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class PokeRadarScanPacket(val fishing: Boolean, val lureLevel: Int) : NetworkPacket<PokeRadarScanPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeBoolean(fishing)
buffer.writeVarInt(lureLevel)
}
companion object {
val ID = cobblemonResource("poke_radar_scan")
fun decode(buffer: RegistryFriendlyByteBuf) = PokeRadarScanPacket(buffer.readBoolean(), buffer.readVarInt())
}
}
@@ -0,0 +1,28 @@
/*
* 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.net.messages.server.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarPage
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class PokeRadarSettingsPacket(val page: PokeRadarPage, val muted: Boolean) : NetworkPacket<PokeRadarSettingsPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeEnum(page)
buffer.writeBoolean(muted)
}
companion object {
val ID = cobblemonResource("poke_radar_settings")
fun decode(buffer: RegistryFriendlyByteBuf) =
PokeRadarSettingsPacket(buffer.readEnum(PokeRadarPage::class.java), buffer.readBoolean())
}
}
@@ -0,0 +1,29 @@
/*
* 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.net.messages.server.pokeradar
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarState
import com.cobblemon.mod.common.pokeradar.TrackingQuery
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
class PokeRadarTrackingPacket(val query: TrackingQuery?) : NetworkPacket<PokeRadarTrackingPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeNullable(query) { buf, q -> buf.writeUtf(PokeRadarState.GSON.toJson(q)) }
}
companion object {
val ID = cobblemonResource("poke_radar_tracking")
fun decode(buffer: RegistryFriendlyByteBuf) = PokeRadarTrackingPacket(
buffer.readNullable { PokeRadarState.GSON.fromJson(it.readUtf(), TrackingQuery::class.java) }
)
}
}
@@ -11,30 +11,26 @@ package com.cobblemon.mod.common.net.messages.server.trade
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.storage.party.PartyPosition
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readList
import com.cobblemon.mod.common.util.readNullable
import com.cobblemon.mod.common.util.readPartyPosition
import com.cobblemon.mod.common.util.readUUID
import com.cobblemon.mod.common.util.writeCollection
import com.cobblemon.mod.common.util.writeNullable
import com.cobblemon.mod.common.util.writePartyPosition
import com.cobblemon.mod.common.util.writeUUID
import net.minecraft.network.RegistryFriendlyByteBuf
import java.util.UUID
class UpdateTradeOfferPacket(val newOffers: List<Pair<UUID, PartyPosition>>): NetworkPacket<UpdateTradeOfferPacket> {
class UpdateTradeOfferPacket(val newOffer: Pair<UUID, PartyPosition>?): NetworkPacket<UpdateTradeOfferPacket> {
companion object {
val ID = cobblemonResource("update_trade_offer")
fun decode(buffer: RegistryFriendlyByteBuf) = UpdateTradeOfferPacket(
buffer.readList { it.readUUID() to it.readPartyPosition() }
)
fun decode(buffer: RegistryFriendlyByteBuf) = UpdateTradeOfferPacket(buffer.readNullable { buffer.readUUID() to buffer.readPartyPosition() })
}
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeCollection(newOffers) { buf, (pokemonId, partyPosition) ->
buf.writeUUID(pokemonId)
buf.writePartyPosition(partyPosition)
buffer.writeNullable(newOffer) { buffer, (pokemonId, partyPosition) ->
buffer.writeUUID(pokemonId)
buffer.writePartyPosition(partyPosition)
}
}
}
@@ -0,0 +1,24 @@
/*
* 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.net.serverhandling.pokeradar
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarNavpointPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object PokeRadarNavpointHandler : ServerNetworkPacketHandler<PokeRadarNavpointPacket> {
override fun handle(packet: PokeRadarNavpointPacket, server: MinecraftServer, player: ServerPlayer) =
when (packet.action) {
PokeRadarNavpointPacket.Action.SAVE -> PokeRadarManager.saveNavpoint(player, packet.navpoint)
PokeRadarNavpointPacket.Action.DELETE -> PokeRadarManager.deleteNavpoint(player, packet.navpoint.id)
PokeRadarNavpointPacket.Action.UPLOAD -> PokeRadarManager.uploadNavpoint(player, packet.navpoint.id)
}
}
@@ -0,0 +1,20 @@
/*
* 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.net.serverhandling.pokeradar
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarScanPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object PokeRadarScanHandler : ServerNetworkPacketHandler<PokeRadarScanPacket> {
override fun handle(packet: PokeRadarScanPacket, server: MinecraftServer, player: ServerPlayer) =
PokeRadarManager.scan(player, packet.fishing, packet.lureLevel)
}
@@ -0,0 +1,20 @@
/*
* 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.net.serverhandling.pokeradar
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarSettingsPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object PokeRadarSettingsHandler : ServerNetworkPacketHandler<PokeRadarSettingsPacket> {
override fun handle(packet: PokeRadarSettingsPacket, server: MinecraftServer, player: ServerPlayer) =
PokeRadarManager.updateSettings(player, packet.page, packet.muted)
}
@@ -0,0 +1,20 @@
/*
* 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.net.serverhandling.pokeradar
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.net.messages.server.pokeradar.PokeRadarTrackingPacket
import com.cobblemon.mod.common.pokeradar.PokeRadarManager
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object PokeRadarTrackingHandler : ServerNetworkPacketHandler<PokeRadarTrackingPacket> {
override fun handle(packet: PokeRadarTrackingPacket, server: MinecraftServer, player: ServerPlayer) =
PokeRadarManager.setTracking(player, packet.query)
}
@@ -20,7 +20,7 @@ object ChangeTradeAcceptanceHandler : ServerNetworkPacketHandler<ChangeTradeAcce
override fun handle(packet: ChangeTradeAcceptancePacket, server: MinecraftServer, player: ServerPlayer) {
val trade = TradeManager.getActiveTrade(player.uuid) ?: return player.sendPacket(TradeCancelledPacket())
val tradeParticipant = trade.getTradeParticipant(player.uuid)
if (trade.getOpposingOffer(tradeParticipant).pokemon.any { it.uuid == packet.pokemonOfferId }) {
if (trade.getOpposingOffer(tradeParticipant).pokemon?.uuid == packet.pokemonOfferId) {
trade.updateAcceptance(tradeParticipant, packet.newAcceptance)
}
}
@@ -20,7 +20,7 @@ object PerformTradeHandler : ServerNetworkPacketHandler<PerformTradePacket> {
override fun handle(packet: PerformTradePacket, server: MinecraftServer, player: ServerPlayer) {
val trade = TradeManager.getActiveTrade(player.uuid) ?: return player.sendPacket(TradeCancelledPacket())
val tradeParticipant = trade.getTradeParticipant(player.uuid)
if (trade.getOpposingOffer(tradeParticipant).pokemon.any { it.uuid == packet.pokemonOfferId }) {
if (trade.getOpposingOffer(tradeParticipant).pokemon?.uuid == packet.pokemonOfferId) {
trade.performTrade(tradeParticipant)
}
}
@@ -12,7 +12,6 @@ import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.net.messages.server.trade.CancelTradePacket
import com.cobblemon.mod.common.net.messages.server.trade.UpdateTradeOfferPacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.trade.TradeManager
import com.cobblemon.mod.common.util.party
import net.minecraft.server.MinecraftServer
@@ -22,16 +21,20 @@ object UpdateTradeOfferHandler : ServerNetworkPacketHandler<UpdateTradeOfferPack
override fun handle(packet: UpdateTradeOfferPacket, server: MinecraftServer, player: ServerPlayer) {
val trade = TradeManager.getActiveTrade(player.uuid) ?: return player.sendPacket(CancelTradePacket())
val tradeParticipant = trade.getTradeParticipant(player.uuid)
val newOffers = packet.newOffers
val validPokemons = mutableListOf<Pokemon>()
val party = player.party()
for ((pokemonId, partyPosition) in newOffers) {
val newOffer = packet.newOffer
if (newOffer == null) {
trade.updateOffer(tradeParticipant, null)
} else {
val (pokemonId, partyPosition) = newOffer
val party = player.party()
val pokemon = party[partyPosition]
if (pokemon != null && pokemon.uuid == pokemonId && pokemon.tradeable) {
validPokemons.add(pokemon)
if (pokemon == null || pokemon.uuid != pokemonId) {
return
} else if (!pokemon.tradeable) {
return
} else {
trade.updateOffer(tradeParticipant, pokemon)
}
}
trade.updateOffer(tradeParticipant, validPokemons)
}
}
@@ -0,0 +1,14 @@
/*
* 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.pokeradar
enum class GeneralAttribute {
SHINY, ALPHA, UNREGISTERED, UNCAUGHT,
HP_EV, ATTACK_EV, DEFENCE_EV, SPECIAL_ATTACK_EV, SPECIAL_DEFENCE_EV, SPEED_EV
}
@@ -0,0 +1,34 @@
/*
* 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.pokeradar
import net.minecraft.world.item.DyeColor
import java.util.*
data class Navpoint(
var id: String = UUID.randomUUID().toString(),
var title: String = DEFAULT_TITLE,
var x: Int = 0,
var z: Int = 0,
var color: Int = DyeColor.WHITE.id,
var dimension: String = "minecraft:overworld",
var encrypted: Boolean = false,
var discovered: Boolean = false,
var created: Long = 0
) {
val locked get() = encrypted && !discovered
fun dyeColor(): DyeColor = DyeColor.byId(color)
companion object {
const val DEFAULT_TITLE = "New Location"
const val MAX_TITLE_LENGTH = 32
const val HIDDEN_TITLE = "?????"
}
}
@@ -0,0 +1,29 @@
/*
* 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.pokeradar
object PokeRadarConstants {
const val TRACK_RANGE = 128.0
const val ENCRYPTED_REVEAL_RANGE = 64.0
const val NAVPOINT_REACHED_RANGE = 3.0
const val MAX_TRACKED_SPECIES = 6
const val MAX_NAVPOINTS = 256
val POKEMON_DISTANCE_STEPS = doubleArrayOf(64.0, 24.0, 8.0)
val NAVPOINT_DISTANCE_STEPS = doubleArrayOf(128.0, 48.0, 16.0)
val DIRECTION_STEPS = doubleArrayOf(90.0, 45.0, 15.0)
fun stepState(value: Double, steps: DoubleArray) = steps.count { value < it }
fun chainMultiplier(chain: Int) = when {
chain >= 100 -> 40F
chain >= 50 -> 10F
chain >= 25 -> 2F
else -> 1F
}
}
@@ -0,0 +1,256 @@
/*
* 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.pokeradar
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.pokedex.PokedexEntryProgress
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.storage.player.PlayerDataExtensionRegistry
import com.cobblemon.mod.common.item.NavChipItem
import com.cobblemon.mod.common.item.PokeRadarItem
import com.cobblemon.mod.common.item.components.NavChipComponent
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarScanResultPacket
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarSyncPacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.pokedex
import net.minecraft.server.level.ServerPlayer
import net.minecraft.sounds.SoundEvent
import net.minecraft.sounds.SoundSource
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
import kotlin.math.abs
object PokeRadarManager {
const val REVEAL_CHECK_INTERVAL = 20
const val MAX_COORDINATE = Level.MAX_LEVEL_SIZE
fun register() {
PlayerDataExtensionRegistry.register(PokeRadarPlayerData.NAME, PokeRadarPlayerData::class.java)
}
fun shinyChainMultiplier(player: ServerPlayer, pokemon: Pokemon): Float {
val state = data(player)
return if (state.chainSpecies == pokemon.species.resourceIdentifier.toString()) {
PokeRadarConstants.chainMultiplier(state.chainCount)
} else 1F
}
fun data(player: ServerPlayer): PokeRadarState {
val extraData = Cobblemon.playerDataManager.getGenericData(player).extraData
val existing = extraData[PokeRadarPlayerData.NAME] as? PokeRadarPlayerData
return (existing ?: PokeRadarPlayerData().also { extraData[PokeRadarPlayerData.NAME] = it }).state
}
fun sync(player: ServerPlayer) {
val state = data(player)
val clientView = state.copy(
navpoints = state.navpoints.map {
if (it.locked) it.copy(title = Navpoint.HIDDEN_TITLE, x = 0, z = 0) else it.copy()
}.toMutableList(),
tracking = PokeRadarTracker.isTracking(player),
cooldown = (state.cooldown - System.currentTimeMillis()).coerceAtLeast(0)
)
PokeRadarSyncPacket(clientView.toJson()).sendToPlayer(player)
}
fun play(player: ServerPlayer, sound: SoundEvent) = player.playNotifySound(sound, SoundSource.PLAYERS, 1F, 1F)
fun notify(player: ServerPlayer, key: String, vararg args: Any) {
player.sendSystemMessage(lang(key, *args), true)
play(player, CobblemonSounds.POKE_RADAR_NOTIFICATION)
}
fun scan(player: ServerPlayer, fishing: Boolean, lureLevel: Int) {
if (PokeRadarItem.heldRadar(player) == null) return sync(player)
val state = data(player)
val now = System.currentTimeMillis()
if (now < state.cooldown) {
sync(player)
return
}
state.cooldown = now + (Cobblemon.config.pokeRadarCooldown * 1000).toLong()
play(player, CobblemonSounds.POKE_RADAR_SCAN)
PokeRadarScanResultPacket(
fishing,
PokeRadarScanner.scan(player, fishing, lureLevel.coerceIn(0, 3))
).sendToPlayer(player)
sync(player)
}
fun updateSettings(player: ServerPlayer, page: PokeRadarPage, muted: Boolean) {
data(player).apply { lastPage = page; this.muted = muted }
}
fun setTracking(player: ServerPlayer, requested: TrackingQuery?) {
if (requested == null) {
PokeRadarTracker.stop(player)
return
}
if (PokeRadarItem.heldRadar(player) == null) return
val query = sanitize(player, requested) ?: run {
PokeRadarTracker.stop(player)
return
}
data(player).query = query
PokeRadarTracker.start(player, query)
sync(player)
}
private fun sanitize(player: ServerPlayer, requested: TrackingQuery): TrackingQuery? {
val query = requested.copyDeep()
when (query.mode) {
TrackingMode.GENERAL -> {
query.general.removeIf { false }
if (query.general.isEmpty()) return null
}
TrackingMode.POKEMON -> {
val dex = player.pokedex()
query.species = query.species.distinct()
.mapNotNull { id -> PokemonSpecies.getByIdentifier(id.asIdentifierDefaultingNamespace()) }
.filter { dex.getHighestKnowledgeForSpecies(it.resourceIdentifier) != PokedexEntryProgress.UNREGISTERED }
.map { it.resourceIdentifier.toString() }
.take(PokeRadarConstants.MAX_TRACKED_SPECIES)
.toMutableList()
if (query.species.isEmpty()) return null
if (query.species.size > 1) {
return TrackingQuery(mode = TrackingMode.POKEMON, species = query.species)
}
}
TrackingMode.NAVPOINT -> {
val navpoint =
data(player).navpoints.find { it.id == query.navpointId }?.takeUnless { it.locked } ?: return null
if (navpoint.dimension != player.level().dimension().location().toString()) {
player.sendSystemMessage(lang("poke_radar.navpoint.wrong_dimension"), true)
return null
}
return TrackingQuery(mode = TrackingMode.NAVPOINT, navpointId = navpoint.id)
}
}
return query
}
fun saveNavpoint(player: ServerPlayer, requested: Navpoint) {
if (PokeRadarItem.heldRadar(player) == null) return
val navpoints = data(player).navpoints
val title = requested.title.trim().take(Navpoint.MAX_TITLE_LENGTH).ifEmpty { Navpoint.DEFAULT_TITLE }
if (abs(requested.x) > MAX_COORDINATE || abs(requested.z) > MAX_COORDINATE) return
val color = requested.color.coerceIn(0, 15)
val existing = navpoints.find { it.id == requested.id }
if (existing != null) {
if (existing.locked) return
existing.title = title
existing.x = requested.x
existing.z = requested.z
existing.color = color
} else {
if (navpoints.size >= PokeRadarConstants.MAX_NAVPOINTS) {
player.sendSystemMessage(lang("poke_radar.navpoint.full"), true)
return
}
navpoints.add(
Navpoint(
title = title,
x = requested.x,
z = requested.z,
color = color,
dimension = player.level().dimension().location().toString(),
created = System.currentTimeMillis()
)
)
}
sync(player)
}
fun deleteNavpoint(player: ServerPlayer, id: String) {
if (PokeRadarTracker.isTrackingNavpoint(player, id)) PokeRadarTracker.stop(player)
if (data(player).navpoints.removeIf { it.id == id }) sync(player)
}
fun uploadNavpoint(player: ServerPlayer, id: String) {
val radar = PokeRadarItem.heldRadar(player) ?: return
val chip = PokeRadarItem.getChip(radar)
when {
chip.isEmpty -> player.sendSystemMessage(lang("poke_radar.chip.none"), true)
chip.`is`(CobblemonItems.BLANK_NAV_CHIP) -> {
val navpoint = data(player).navpoints.find { it.id == id } ?: return
if (navpoint.encrypted) {
player.sendSystemMessage(lang("poke_radar.chip.encrypted_upload"), true)
return
}
val written = ItemStack(CobblemonItems.NAV_CHIP)
written.set(
CobblemonItemComponents.NAV_CHIP,
NavChipComponent(navpoint.title, navpoint.x, navpoint.z, navpoint.color, navpoint.dimension)
)
PokeRadarItem.setChip(radar, written)
notify(player, "poke_radar.chip.uploaded", navpoint.title)
}
else -> importChip(player, chip)
}
}
fun importChip(player: ServerPlayer, chip: ItemStack) {
val data = chip.get(CobblemonItemComponents.NAV_CHIP) ?: return
val encrypted = (chip.item as? NavChipItem)?.encrypted == true
val navpoints = data(player).navpoints
if (navpoints.any { it.x == data.x && it.z == data.z && it.dimension == data.dimension }) return
if (navpoints.size >= PokeRadarConstants.MAX_NAVPOINTS) {
player.sendSystemMessage(lang("poke_radar.navpoint.full"), true)
return
}
navpoints.add(
Navpoint(
title = data.title.take(Navpoint.MAX_TITLE_LENGTH).ifEmpty { Navpoint.DEFAULT_TITLE },
x = data.x.coerceIn(-MAX_COORDINATE, MAX_COORDINATE),
z = data.z.coerceIn(-MAX_COORDINATE, MAX_COORDINATE),
color = data.color.coerceIn(0, 15),
dimension = data.dimension,
encrypted = encrypted,
created = System.currentTimeMillis()
)
)
notify(player, "poke_radar.chip.imported", if (encrypted) Navpoint.HIDDEN_TITLE else data.title)
sync(player)
}
fun revealEncryptedNavpoints(player: ServerPlayer) {
val dimension = player.level().dimension().location().toString()
val range = PokeRadarConstants.ENCRYPTED_REVEAL_RANGE
val revealed = data(player).navpoints.filter {
it.locked && it.dimension == dimension &&
(it.x + 0.5 - player.x).let { dx -> (it.z + 0.5 - player.z).let { dz -> dx * dx + dz * dz } } <= range * range
}
if (revealed.isEmpty()) return
revealed.forEach {
it.discovered = true
notify(player, "poke_radar.navpoint.decrypted", it.title)
}
sync(player)
}
fun addToChain(player: ServerPlayer, species: String) {
val state = data(player)
if (state.chainSpecies == species) {
state.chainCount++
} else {
state.chainSpecies = species
state.chainCount = 1
}
sync(player)
}
}
@@ -0,0 +1,11 @@
/*
* 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.pokeradar
enum class PokeRadarPage { RADAR, TRACKING, NAV }
@@ -0,0 +1,27 @@
/*
* 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.pokeradar
import com.cobblemon.mod.common.api.storage.player.PlayerDataExtension
import com.google.gson.JsonObject
class PokeRadarPlayerData(var state: PokeRadarState = PokeRadarState()) : PlayerDataExtension {
override fun name() = NAME
override fun serialize(): JsonObject = (PokeRadarState.GSON.toJsonTree(state) as JsonObject).also {
it.addProperty(PlayerDataExtension.NAME_KEY, NAME)
}
override fun deserialize(json: JsonObject): PlayerDataExtension =
PokeRadarPlayerData(PokeRadarState.GSON.fromJson(json, PokeRadarState::class.java) ?: PokeRadarState())
companion object {
const val NAME = "poke_radar"
}
}
@@ -0,0 +1,127 @@
/*
* 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.pokeradar
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.Cobblemon.config
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.spawning.BestSpawner
import com.cobblemon.mod.common.api.spawning.SpawnCause
import com.cobblemon.mod.common.api.spawning.detail.PokemonHerdSpawnDetail
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.fishing.FishingSpawnCause
import com.cobblemon.mod.common.api.spawning.influence.SpawningInfluence
import com.cobblemon.mod.common.api.spawning.position.FishingSpawnablePosition
import com.cobblemon.mod.common.api.spawning.position.SpawnablePosition
import com.cobblemon.mod.common.api.spawning.position.calculators.SpawnablePositionCalculator.Companion.prioritizedAreaCalculators
import com.cobblemon.mod.common.api.spawning.spawner.FishingSpawnerFactory
import com.cobblemon.mod.common.api.spawning.spawner.Spawner
import com.cobblemon.mod.common.api.spawning.spawner.SpawningZoneInput
import com.cobblemon.mod.common.duck.ServerLevelDuck
import com.cobblemon.mod.common.item.interactive.PokerodItem
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.spawner
import net.minecraft.server.level.ServerPlayer
import net.minecraft.util.Mth
import net.minecraft.world.item.ItemStack
object PokeRadarScanner {
const val BOSS_BUCKET = "boss"
fun scan(player: ServerPlayer, fishing: Boolean, lureLevel: Int): List<RadarEntry> {
if (!config.enableSpawning ||
(player.serverLevel() as ServerLevelDuck).`cobblemon$getLevelResourceLocation`() in config.worldSpawningBlocklist
) {
return emptyList()
}
val (spawner, positions, influences) = if (fishing) fishingPositions(player, lureLevel) else worldPositions(
player
)
val bucketWeights = spawner.buckets.toMutableMap()
influences.forEach { it.affectBucketWeights(bucketWeights) }
bucketWeights.remove(BOSS_BUCKET)
val perBucket = bucketWeights.keys.associateWith { spawner.selector.getProbabilities(spawner, it, positions) }
.filterValues { it.isNotEmpty() }
val totalBucketWeight = perBucket.keys.sumOf { bucketWeights[it]!!.toDouble() }.toFloat()
if (totalBucketWeight <= 0F) return emptyList()
val combined = mutableMapOf<String, Pair<SpawnDetail, Float>>()
perBucket.forEach { (bucket, probabilities) ->
val bucketShare = bucketWeights[bucket]!! / totalBucketWeight
probabilities.forEach { (detail, percent) ->
val previous = combined[detail.id]?.second ?: 0F
combined[detail.id] = detail to previous + percent * bucketShare
}
}
return combined.values.mapNotNull { (detail, percent) -> toEntry(detail, percent) }
}
private fun toEntry(detail: SpawnDetail, percent: Float): RadarEntry? {
val members = when (detail) {
is PokemonSpawnDetail -> listOfNotNull(member(detail.pokemon, 1F))
is PokemonHerdSpawnDetail -> detail.herdablePokemon.mapNotNull { member(it.pokemon, it.weight) }
else -> emptyList()
}
if (members.isEmpty()) return null
return RadarEntry(detail.id, detail is PokemonHerdSpawnDetail, percent, members)
}
private fun member(properties: PokemonProperties, weight: Float): RadarEntry.Member? {
val speciesId = properties.species?.takeUnless { it.equals("random", true) } ?: return null
val species = PokemonSpecies.getByIdentifier(speciesId.asIdentifierDefaultingNamespace()) ?: return null
return RadarEntry.Member(species.resourceIdentifier, properties.asString(), weight)
}
private fun worldPositions(player: ServerPlayer): Triple<Spawner, List<SpawnablePosition>, List<SpawningInfluence>> {
val spawner = player.spawner
val slice = Cobblemon.spawningZoneGenerator.generate(
spawner = spawner,
input = SpawningZoneInput(
cause = SpawnCause(spawner, player),
world = player.serverLevel(),
baseX = Mth.ceil(player.x - config.spawningZoneDiameter / 2F),
baseY = Mth.ceil(player.y - config.spawningZoneHeight / 2F),
baseZ = Mth.ceil(player.z - config.spawningZoneDiameter / 2F),
length = config.spawningZoneDiameter,
height = config.spawningZoneHeight,
width = config.spawningZoneDiameter
)
)
val positions = Cobblemon.areaSpawnablePositionResolver.resolve(spawner, prioritizedAreaCalculators, slice)
return Triple(spawner, positions, spawner.copyInfluences() + slice.unconditionalInfluences)
}
private fun fishingPositions(
player: ServerPlayer,
lureLevel: Int
): Triple<Spawner, List<SpawnablePosition>, List<SpawningInfluence>> {
val spawner = BestSpawner.fishingSpawner
val rod = player.inventory.items.firstOrNull { it.item is PokerodItem } ?: ItemStack(CobblemonItems.POKE_ROD)
val cause = FishingSpawnCause(spawner = spawner, entity = player, rodStack = rod, lureLevel = lureLevel)
val ctx = FishingSpawnerFactory.Context(
player = player,
rodStack = rod,
lureLevel = lureLevel,
luckOfTheSeaLevel = 0,
world = player.serverLevel(),
pos = player.blockPosition(),
spawner = spawner
)
val influences = FishingSpawnerFactory.buildPositionInfluences(ctx)
val position = FishingSpawnablePosition(cause, ctx.world, ctx.pos, influences)
return Triple(spawner, listOf(position), spawner.copyInfluences() + influences)
}
}
@@ -0,0 +1,30 @@
/*
* 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.pokeradar
import com.google.gson.Gson
data class PokeRadarState(
var lastPage: PokeRadarPage = PokeRadarPage.RADAR,
var muted: Boolean = false,
var chainSpecies: String? = null,
var chainCount: Int = 0,
var navpoints: MutableList<Navpoint> = mutableListOf(),
var query: TrackingQuery? = null,
var tracking: Boolean = false,
var cooldown: Long = 0
) {
fun toJson(): String = GSON.toJson(this)
companion object {
val GSON = Gson()
fun fromJson(json: String): PokeRadarState = GSON.fromJson(json, PokeRadarState::class.java) ?: PokeRadarState()
}
}
@@ -0,0 +1,165 @@
/*
* 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.pokeradar
import com.cobblemon.mod.common.api.pokedex.PokedexEntryProgress
import com.cobblemon.mod.common.api.pokemon.stats.Stat
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.pokeradar.PokeRadarTrackingStatePacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.pokedex
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.phys.Vec3
import java.util.*
object PokeRadarTracker {
private const val UPDATE_INTERVAL = 10
private const val SEARCH_INTERVAL = 20
private const val VERTICAL_SEARCH = 64.0
private class Session(val query: TrackingQuery) {
var target: UUID? = null
}
private val sessions = mutableMapOf<UUID, Session>()
fun isTracking(player: ServerPlayer) = player.uuid in sessions
fun isTrackingNavpoint(player: ServerPlayer, navpointId: String) =
sessions[player.uuid]?.query?.let { it.mode == TrackingMode.NAVPOINT && it.navpointId == navpointId } == true
fun start(player: ServerPlayer, query: TrackingQuery) {
sessions[player.uuid] = Session(query)
PokeRadarTrackingStatePacket(active = true, found = false).sendToPlayer(player)
update(player, sessions[player.uuid]!!, search = true)
}
fun stop(player: ServerPlayer, notify: Boolean = true) {
if (sessions.remove(player.uuid) != null && notify) {
PokeRadarTrackingStatePacket(active = false, found = false).sendToPlayer(player)
PokeRadarManager.sync(player)
}
}
fun forget(playerId: UUID) {
sessions.remove(playerId)
}
fun tick(server: MinecraftServer) {
val tick = server.tickCount
if (tick % UPDATE_INTERVAL != 0 || sessions.isEmpty()) return
sessions.entries.toList().forEach { (uuid, session) ->
val player = server.playerList.getPlayer(uuid) ?: return@forEach run { sessions.remove(uuid) }
update(player, session, search = tick % SEARCH_INTERVAL == 0)
}
}
private fun update(player: ServerPlayer, session: Session, search: Boolean) {
if (session.query.mode == TrackingMode.NAVPOINT) {
updateNavpoint(player, session.query)
return
}
val current = session.target?.let { player.serverLevel().getEntity(it) as? PokemonEntity }
if (session.target != null && (current == null || !isValidTarget(player, current))) {
session.target = null
PokeRadarTrackingStatePacket(active = true, found = false).sendToPlayer(player)
}
val target = current?.takeIf { session.target != null }
?: if (search) findTarget(player, session.query)?.also { session.target = it.uuid } else null
if (target != null) {
PokeRadarTrackingStatePacket(
active = true,
found = true,
navpoint = false,
pos = target.position()
).sendToPlayer(player)
}
}
private fun updateNavpoint(player: ServerPlayer, query: TrackingQuery) {
val navpoint = PokeRadarManager.data(player).navpoints.find { it.id == query.navpointId }
if (navpoint == null || navpoint.dimension != player.level().dimension().location().toString()) {
stop(player)
return
}
val pos = Vec3(navpoint.x + 0.5, player.y, navpoint.z + 0.5)
if (pos.distanceTo(player.position()) <= PokeRadarConstants.NAVPOINT_REACHED_RANGE) {
PokeRadarManager.notify(player, "poke_radar.navpoint.reached", navpoint.title)
stop(player)
return
}
PokeRadarTrackingStatePacket(active = true, found = true, navpoint = true, pos = pos).sendToPlayer(player)
}
private fun isValidTarget(player: ServerPlayer, entity: PokemonEntity) =
entity.isAlive && !entity.isRemoved && entity.pokemon.isWild() &&
entity.level() == player.level() &&
entity.distanceToSqr(player) <= PokeRadarConstants.TRACK_RANGE * PokeRadarConstants.TRACK_RANGE
private fun findTarget(player: ServerPlayer, query: TrackingQuery): PokemonEntity? {
val range = PokeRadarConstants.TRACK_RANGE
val box = player.boundingBox.inflate(range, VERTICAL_SEARCH, range)
return player.serverLevel()
.getEntitiesOfClass(PokemonEntity::class.java, box) {
isValidTarget(player, it) && matches(
player,
query,
it.pokemon
)
}
.minByOrNull { it.distanceToSqr(player) }
}
private val EV_ATTRIBUTES: Map<GeneralAttribute, Stat> = mapOf(
GeneralAttribute.HP_EV to Stats.HP,
GeneralAttribute.ATTACK_EV to Stats.ATTACK,
GeneralAttribute.DEFENCE_EV to Stats.DEFENCE,
GeneralAttribute.SPECIAL_ATTACK_EV to Stats.SPECIAL_ATTACK,
GeneralAttribute.SPECIAL_DEFENCE_EV to Stats.SPECIAL_DEFENCE,
GeneralAttribute.SPEED_EV to Stats.SPEED
)
fun matches(player: ServerPlayer, query: TrackingQuery, pokemon: Pokemon): Boolean = when (query.mode) {
TrackingMode.GENERAL -> query.general.toList().all { attribute ->
when (attribute) {
GeneralAttribute.SHINY -> pokemon.shiny
GeneralAttribute.ALPHA -> pokemon.isAlpha
GeneralAttribute.UNREGISTERED -> knowledge(player, pokemon) == PokedexEntryProgress.UNREGISTERED
GeneralAttribute.UNCAUGHT -> knowledge(player, pokemon) != PokedexEntryProgress.OWNED
else -> (pokemon.form.evYield[EV_ATTRIBUTES[attribute]] ?: 0) > 0
}
}
TrackingMode.POKEMON -> pokemon.species.resourceIdentifier.toString() in query.species && (query.species.size > 1 || matchesSpeciesAttributes(
query,
pokemon
))
TrackingMode.NAVPOINT -> false
}
private fun matchesSpeciesAttributes(query: TrackingQuery, pokemon: Pokemon): Boolean {
val size = if (pokemon.isAlpha) "XL" else pokemon.getSizeCategory().name
return (!query.shiny || pokemon.shiny) &&
(!query.alpha || pokemon.isAlpha) &&
(!query.maxIv || Stats.PERMANENT.any { pokemon.ivs[it] == 31 }) &&
(query.ability == null || pokemon.ability.name == query.ability) &&
(query.nature == null || pokemon.nature.name.toString() == query.nature) &&
(query.genders.isEmpty() || pokemon.gender.name in query.genders) &&
(query.sizes.isEmpty() || size in query.sizes)
}
private fun knowledge(player: ServerPlayer, pokemon: Pokemon) =
player.pokedex().getHighestKnowledgeForSpecies(pokemon.species.resourceIdentifier)
}
@@ -0,0 +1,41 @@
/*
* 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.pokeradar
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.resources.ResourceLocation
data class RadarEntry(
val id: String,
val isHerd: Boolean,
val percentage: Float,
val members: List<Member>
) {
data class Member(val species: ResourceLocation, val properties: String, val weight: Float)
fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeUtf(id)
buffer.writeBoolean(isHerd)
buffer.writeFloat(percentage)
buffer.writeCollection(members) { buf, member ->
buf.writeResourceLocation(member.species)
buf.writeUtf(member.properties)
buf.writeFloat(member.weight)
}
}
companion object {
fun decode(buffer: RegistryFriendlyByteBuf) = RadarEntry(
id = buffer.readUtf(),
isHerd = buffer.readBoolean(),
percentage = buffer.readFloat(),
members = buffer.readList { Member(it.readResourceLocation(), it.readUtf(), it.readFloat()) }
)
}
}
@@ -0,0 +1,11 @@
/*
* 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.pokeradar
enum class TrackingMode { GENERAL, POKEMON, NAVPOINT }
@@ -0,0 +1,30 @@
/*
* 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.pokeradar
data class TrackingQuery(
var mode: TrackingMode = TrackingMode.GENERAL,
var general: MutableSet<GeneralAttribute> = mutableSetOf(),
var species: MutableList<String> = mutableListOf(),
var shiny: Boolean = false,
var alpha: Boolean = false,
var maxIv: Boolean = false,
var ability: String? = null,
var nature: String? = null,
var genders: MutableSet<String> = mutableSetOf(),
var sizes: MutableSet<String> = mutableSetOf(),
var navpointId: String? = null
) {
fun copyDeep() = copy(
general = general.toMutableSet(),
species = species.toMutableList(),
genders = genders.toMutableSet(),
sizes = sizes.toMutableSet()
)
}
@@ -19,7 +19,7 @@ class ActiveTrade(val player1: TradeParticipant, val player2: TradeParticipant)
fun getOffer(tradeParticipant: TradeParticipant) = if (tradeParticipant == player1) player1Offer else player2Offer
fun getOpposingOffer(tradeParticipant: TradeParticipant) = if (tradeParticipant == player1) player2Offer else player1Offer
fun updateOffer(tradeParticipant: TradeParticipant, pokemon: List<Pokemon>) {
fun updateOffer(tradeParticipant: TradeParticipant, pokemon: Pokemon?) {
getOffer(tradeParticipant).updateOffer(pokemon)
getOffer(getOppositePlayer(tradeParticipant)).accepted = false
player1.updateOffer(this, tradeParticipant, pokemon)
@@ -30,9 +30,8 @@ class ActiveTrade(val player1: TradeParticipant, val player2: TradeParticipant)
val offer = getOpposingOffer(tradeParticipant)
if (offer.accepted != acceptance) {
offer.accepted = acceptance
val firstId = offer.pokemon.firstOrNull()?.uuid ?: java.util.UUID.randomUUID()
getOppositePlayer(tradeParticipant).changeTradeAcceptance(this, firstId, acceptance)
tradeParticipant.changeTradeAcceptance(this, firstId, acceptance)
getOppositePlayer(tradeParticipant).changeTradeAcceptance(this, offer.pokemon!!.uuid, acceptance)
tradeParticipant.changeTradeAcceptance(this, offer.pokemon!!.uuid, acceptance)
}
if (offer.accepted && getOffer(tradeParticipant).accepted) {
@@ -52,8 +51,8 @@ class ActiveTrade(val player1: TradeParticipant, val player2: TradeParticipant)
activeTrade = this,
player1 = player1,
player2 = player2,
pokemon1 = player1Offer.pokemon,
pokemon2 = player2Offer.pokemon
pokemon1 = player1Offer.pokemon!!,
pokemon2 = player2Offer.pokemon!!
)
}
}
@@ -65,14 +64,12 @@ class ActiveTrade(val player1: TradeParticipant, val player2: TradeParticipant)
}
fun completeTrade() {
val uuids1 = player1Offer.pokemon.map { it.uuid }
val uuids2 = player2Offer.pokemon.map { it.uuid }
player1.completeTrade(this, uuids1, uuids2)
player2.completeTrade(this, uuids2, uuids1)
player1.completeTrade(this, player1Offer.pokemon!!.uuid, player2Offer.pokemon!!.uuid)
player2.completeTrade(this, player2Offer.pokemon!!.uuid, player1Offer.pokemon!!.uuid)
player1Offer.pokemon = emptyList()
player1Offer.pokemon = null
player1Offer.accepted = false
player2Offer.pokemon = emptyList()
player2Offer.pokemon = null
player2Offer.accepted = false
}
}
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff. Show more