Compare commits

..
Author SHA1 Message Date
Tyzillion 75908c9f0c Updated Branch to latest main and got marks working. 2024-11-30 00:04:42 -05:00
Tyzillion dde9c47cd6 Merge branch 'main' of https://gitlab.com/cable-mc/cobblemon into marks_and_memories 2024-11-30 00:02:22 -05:00
Tyzillion d8eb63b74f Merge branch 'main' of https://gitlab.com/cable-mc/cobblemon into marks_and_memories
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/battles/pokemon/BattlePokemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/command/TestCommand.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Pokemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/DataKeys.kt
#	common/src/main/resources/assets/cobblemon/lang/en_us.json
2024-11-28 23:32:20 -05:00
Lily ba7d23d1e2 remove name field cuz it's not needed 2024-02-22 19:24:17 -05:00
Lily ecae1dce56 implemented pokemon marks 2024-02-22 13:10:55 -05:00
Lily d66154bf62 started on marks/memories 2024-02-21 18:24:29 -05:00
239 changed files with 1459 additions and 3568 deletions

No files matched your search

-6
View File
@@ -51,8 +51,6 @@
- Added new sounds for Poké Balls bouncing off of Pokémon and landing on the ground during capture.
- Added a unique set of sounds for Ancient Poké Balls.
- Added a sound for using Exp Candy and Rare Candy items.
- Added raft platforms for non-swimming, non-flying Pokémon to stand on during battles that take place on the water's surface. (Flying Pokémon will fly over water in battle, and water breathing Pokémon will swim in water during battle.)
- Added `hiddenability=false` option to `/spawnpokemon` and `/pokemonedit` commands, allowing the Pokémon's ability to be reverted to a normal ability.
### Pokémon Added
#### Gen 1
@@ -341,11 +339,8 @@
- A high jump indicates 2 shakes.
- A medium jump indicates 3 shakes.
- A short jump indicates that you caught the Pokémon.
- Pokémon sent out during battle will spawn facing their opponent.
- Pokémon sent out outside a battle will spawn facing their trainer.
### Fixes
- Fixed Ability Patches not reverting Hidden Abilities back to Normal Abilities.
- Fixed awarding Pokémon experience upon forfeiting battles.
- Scaled down Amaura's fetus model to avoid clipping through the tank while animating.
- Fixed Cubone's cry not having a sound.
@@ -426,7 +421,6 @@
- Delay when successfully catching a Pokémon in an Ancient Poké Ball has been increased to account for the new sounds and particles.
- Prevent summary stats tab from making sounds when clicking on an already open tab.
- Fixed display case not being able to be fed items from underneath.
- Fixed Pokémon battling in water continuously sinking to the bottom.
### Developer
- `SpawnCause` is now an implementation of `SpawningInfluence`.
@@ -10,6 +10,7 @@ package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.Cobblemon;
import com.cobblemon.mod.common.ModAPI;
import com.cobblemon.mod.common.client.CobblemonBakingOverrides;
import com.cobblemon.mod.common.item.PokeBallItem;
import com.cobblemon.mod.common.item.PokedexItem;
import com.mojang.blaze3d.vertex.PoseStack;
@@ -19,9 +20,7 @@ import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
@@ -53,33 +52,25 @@ public abstract class ItemRendererMixin {
)
private void cobblemon$overrideItemModel(ItemStack stack, ItemDisplayContext renderMode, boolean leftHanded, PoseStack matrices, MultiBufferSource multiBufferSource, int light, int overlay, BakedModel model, CallbackInfo ci) {
boolean shouldBe2d = renderMode == ItemDisplayContext.GUI || renderMode == ItemDisplayContext.FIXED;
if (shouldBe2d) {
ResourceLocation resourceLocation = null;
if (stack.getItem() instanceof PokeBallItem pokeBallItem) resourceLocation = pokeBallItem.getPokeBall().getModel2d();
else if (stack.getItem() instanceof PokedexItem pokedexItem) resourceLocation = pokedexItem.getType().getItemSpritePath();
if (resourceLocation != null) {
BakedModel replacementModel = this.itemModelShaper.getModelManager().getModel(new ModelResourceLocation(resourceLocation, "inventory"));
if (!cobblemon$isSameModel(model, replacementModel)) {
ci.cancel();
render(stack, renderMode, leftHanded, matrices, multiBufferSource, light, overlay, replacementModel);
}
if (!shouldBe2d && stack.getItem() instanceof PokedexItem) {
BakedModel replacementModel = CobblemonBakingOverrides.INSTANCE.getPokedexOverride(((PokedexItem) stack.getItem()).getType()).getModel();
if (!cobblemon$isSameModel(model, replacementModel)) {
ci.cancel();
render(stack, renderMode, leftHanded, matrices, multiBufferSource, light, overlay, replacementModel);
}
} else if (shouldBe2d && stack.getItem() instanceof PokeBallItem pokeBallItem) {
BakedModel replacementModel = this.itemModelShaper.getModelManager().getModel(new ModelResourceLocation(pokeBallItem.getPokeBall().getModel2d(), "inventory"));
if (!cobblemon$isSameModel(model, replacementModel)) {
ci.cancel();
render(stack, renderMode, leftHanded, matrices, multiBufferSource, light, overlay, replacementModel);
}
}
}
@Inject(method = "getModel", at = @At("HEAD"), cancellable = true)
private void cobblemon$getItemModel(ItemStack stack, Level world, LivingEntity entity, int seed, CallbackInfoReturnable<BakedModel> cir) {
ResourceLocation resourceLocation = null;
if (stack.getItem() instanceof PokeBallItem pokeBallItem) resourceLocation = pokeBallItem.getPokeBall().getModel3d();
else if (stack.getItem() instanceof PokedexItem pokedexItem) {
boolean isScanModel = entity instanceof Player && entity.getUseItem() == stack && entity.isUsingItem();
boolean canOpenScreen = entity != null && ((entity.getOffhandItem() == stack && !(entity.getMainHandItem().getItem() instanceof PokedexItem)) || entity.getMainHandItem() == stack);
resourceLocation = pokedexItem.getType().getItemModelPath(isScanModel ? "scanning" : (canOpenScreen ? null : "off"));
}
if (resourceLocation != null) {
BakedModel model = this.itemModelShaper.getModelManager().getModel(new ModelResourceLocation(resourceLocation, MODEL_PATH));
private void cobblemon$bakePokeballModel(ItemStack stack, Level world, LivingEntity entity, int seed, CallbackInfoReturnable<BakedModel> cir) {
if (stack.getItem() instanceof PokeBallItem pokeBallItem) {
BakedModel model = this.itemModelShaper.getModelManager().getModel(new ModelResourceLocation(pokeBallItem.getPokeBall().getModel3d(), MODEL_PATH));
ClientLevel clientWorld = world instanceof ClientLevel ? (ClientLevel) world : null;
BakedModel overriddenModel = model.getOverrides().resolve(model, stack, clientWorld, entity, seed);
cir.setReturnValue(overriddenModel == null ? this.itemModelShaper.getModelManager().getMissingModel() : overriddenModel);
@@ -52,11 +52,10 @@ public abstract class LecternBlockMixin {
if (lecternEntity instanceof LecternBlockEntity) {
((LecternBlockEntity) lecternEntity).setItemStack((pokedexItemStack));
world.playSound(null, blockPos, CobblemonSounds.POKEDEX_CLOSE, SoundSource.BLOCKS, 0.5F, 1.25F);
cir.setReturnValue(ItemInteractionResult.SUCCESS);
} else {
cir.setReturnValue(itemStack.isEmpty() && interactionHand == InteractionHand.MAIN_HAND ? ItemInteractionResult.SKIP_DEFAULT_BLOCK_INTERACTION : ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION);
}
world.playSound(null, blockPos, CobblemonSounds.POKEDEX_CLOSE, SoundSource.BLOCKS, 0.5F, 1.25F);
cir.setReturnValue(itemStack.isEmpty() && interactionHand == InteractionHand.MAIN_HAND ? ItemInteractionResult.SKIP_DEFAULT_BLOCK_INTERACTION : ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION);
}
}
}
@@ -22,7 +22,7 @@ public abstract class MinecraftDedicatedServerMixin implements ServerInterface {
@Inject(method = "shouldDiscardEntity", at = @At(value = "HEAD"), cancellable = true)
public void cobblemon$allowPokemonSpawns(Entity entity, CallbackInfoReturnable<Boolean> callback) {
if (entity instanceof PokemonEntity) {
if(entity instanceof PokemonEntity) {
callback.setReturnValue(false);
}
}
@@ -81,7 +81,6 @@ import com.cobblemon.mod.common.config.constraint.IntConstraint
import com.cobblemon.mod.common.config.starter.StarterConfig
import com.cobblemon.mod.common.data.CobblemonDataProvider
import com.cobblemon.mod.common.events.AdvancementHandler
import com.cobblemon.mod.common.events.FlowHandler
import com.cobblemon.mod.common.events.PokedexHandler
import com.cobblemon.mod.common.events.ServerTickHandler
import com.cobblemon.mod.common.net.messages.client.settings.ServerSettingsPacket
@@ -289,8 +288,6 @@ object Cobblemon {
CobblemonEvents.POKEMON_PROPERTY_INITIALISED.emit(Unit)
FlowHandler.setup()
ifDedicatedServer {
isDedicatedServer = true
}
@@ -1,78 +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
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.value.MoValue
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.data.DataRegistry
import com.cobblemon.mod.common.api.molang.ExpressionLike
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
import com.cobblemon.mod.common.net.messages.client.data.FlowRegistrySyncPacket
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.endsWith
import java.util.concurrent.ExecutionException
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.server.packs.PackType
import net.minecraft.server.packs.resources.ResourceManager
/**
* Holds all the flows that are loaded from the server's data packs. A flow is foldered under the event identifier,
* which can be Cobblemon's namespace but can also be minecraft or any other namespace someone has added hooks for.
* The value of the map is a list of MoLang scripts that will execute when that event occurs.
*
* @author Hiroku
* @since February 24th, 2024
*/
object CobblemonFlows : DataRegistry {
override val id = cobblemonResource("flows")
override val observable = SimpleObservable<CobblemonFlows>()
override val type = PackType.SERVER_DATA
override fun sync(player: ServerPlayer) {
player.sendPacket(FlowRegistrySyncPacket(clientFlows.entries))
}
val runtime by lazy { MoLangRuntime().setup() } // Lazy for if someone adds to generalFunctions in MoLangFunctions
val clientFlows = hashMapOf<ResourceLocation, MutableList<ExpressionLike>>()
val flows = hashMapOf<ResourceLocation, MutableList<ExpressionLike>>()
override fun reload(manager: ResourceManager) {
val folderBeforeNameRegex = ".*\\/([^\\/]+)\\/[^\\/]+\$".toRegex()
manager.listResources("flows") { path -> path.endsWith(CobblemonScripts.MOLANG_EXTENSION) }.forEach { (identifier, resource) ->
resource.openAsReader().use { stream ->
stream.buffered().use { reader ->
try {
val expression = reader.readText().asExpressionLike()
val event = folderBeforeNameRegex.find(identifier.path)?.groupValues?.get(1)
?: throw IllegalArgumentException("Invalid flow path: $identifier. Should have a folder structure that includes the name of the event being flowed.")
if (identifier.path.startsWith("flows/client/")) {
clientFlows.getOrPut(ResourceLocation.fromNamespaceAndPath(identifier.namespace, event)) { mutableListOf() }.add(expression)
} else {
flows.getOrPut(ResourceLocation.fromNamespaceAndPath(identifier.namespace, event)) { mutableListOf() }.add(expression)
}
} catch (exception: Exception) {
throw ExecutionException("Error loading MoLang script for flow: $identifier", exception)
}
}
}
}
Cobblemon.LOGGER.info("Loaded ${CobblemonScripts.scripts.size} flows and ${CobblemonScripts.clientScripts.size} client flows")
observable.emit(this)
}
fun run(eventResourceLocation: ResourceLocation, context: Map<String, MoValue>) {
flows[eventResourceLocation]?.forEach { it.resolve(runtime, context) }
}
}
@@ -171,6 +171,14 @@ interface CobblemonImplementation {
*/
fun server(): MinecraftServer?
/**
* Handles platform independent reloading of a [JsonDataRegistry].
*
* @param registry The [JsonDataRegistry] to reload.
* @param manager The [ResourceManager] to reload from.
*/
fun <T> reloadJsonRegistry(registry: JsonDataRegistry<T>, manager: ResourceManager): HashMap<ResourceLocation, T>
/**
* Registers an item to the [ComposterBlock].
*
@@ -19,7 +19,7 @@ import com.cobblemon.mod.common.api.text.gray
import com.cobblemon.mod.common.block.BerryBlock
import com.cobblemon.mod.common.block.MintBlock
import com.cobblemon.mod.common.block.MintBlock.MintType
import com.cobblemon.mod.common.client.pokedex.PokedexType
import com.cobblemon.mod.common.client.pokedex.PokedexTypes
import com.cobblemon.mod.common.entity.boat.CobblemonBoatType
import com.cobblemon.mod.common.item.*
import com.cobblemon.mod.common.item.armor.CobblemonArmorTrims
@@ -155,19 +155,19 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
val pokedexes = mutableListOf<PokedexItem>()
@JvmField
val POKEDEX_RED = pokedexItem(PokedexType.RED)
val POKEDEX_RED = pokedexItem(PokedexTypes.RED)
@JvmField
val POKEDEX_YELLOW = pokedexItem(PokedexType.YELLOW)
val POKEDEX_YELLOW = pokedexItem(PokedexTypes.YELLOW)
@JvmField
val POKEDEX_GREEN = pokedexItem(PokedexType.GREEN)
val POKEDEX_GREEN = pokedexItem(PokedexTypes.GREEN)
@JvmField
val POKEDEX_BLUE = pokedexItem(PokedexType.BLUE)
val POKEDEX_BLUE = pokedexItem(PokedexTypes.BLUE)
@JvmField
val POKEDEX_PINK = pokedexItem(PokedexType.PINK)
val POKEDEX_PINK = pokedexItem(PokedexTypes.PINK)
@JvmField
val POKEDEX_BLACK = pokedexItem(PokedexType.BLACK)
val POKEDEX_BLACK = pokedexItem(PokedexTypes.BLACK)
@JvmField
val POKEDEX_WHITE = pokedexItem(PokedexType.WHITE)
val POKEDEX_WHITE = pokedexItem(PokedexTypes.WHITE)
@JvmField
val VIVICHOKE = compostableItem("vivichoke")
@@ -1248,7 +1248,7 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
return item
}
private fun pokedexItem(type: PokedexType): PokedexItem {
private fun pokedexItem(type: PokedexTypes): PokedexItem {
val item = create("pokedex_${type.name.lowercase()}", PokedexItem(type))
pokedexes.add(item)
return item
@@ -54,13 +54,14 @@ import com.cobblemon.mod.common.client.net.toast.ToastPacketHandler
import com.cobblemon.mod.common.client.net.trade.*
import com.cobblemon.mod.common.net.PacketRegisterInfo
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.battle.*
import com.cobblemon.mod.common.net.messages.client.callback.OpenMoveCallbackPacket
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyCallbackPacket
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyMoveCallbackPacket
import com.cobblemon.mod.common.net.messages.client.data.*
import com.cobblemon.mod.common.net.messages.client.data.PropertiesCompletionRegistrySyncPacket
import com.cobblemon.mod.common.net.messages.client.data.UnlockReloadPacket
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueClosedPacket
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueOpenedPacket
import com.cobblemon.mod.common.net.messages.client.effect.RunPosableMoLangPacket
@@ -75,7 +76,6 @@ import com.cobblemon.mod.common.net.messages.client.pasture.ClosePasturePacket
import com.cobblemon.mod.common.net.messages.client.pasture.OpenPasturePacket
import com.cobblemon.mod.common.net.messages.client.pasture.PokemonPasturedPacket
import com.cobblemon.mod.common.net.messages.client.pasture.PokemonUnpasturedPacket
import com.cobblemon.mod.common.net.messages.client.pokedex.ServerConfirmedRegisterPacket
import com.cobblemon.mod.common.net.messages.client.pokemon.update.*
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.AddEvolutionPacket
import com.cobblemon.mod.common.net.messages.client.pokemon.update.evolution.ClearEvolutionsPacket
@@ -87,6 +87,7 @@ import com.cobblemon.mod.common.net.messages.client.spawn.SpawnNPCPacket
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokeballPacket
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokemonPacket
import com.cobblemon.mod.common.net.messages.client.starter.OpenStarterUIPacket
import com.cobblemon.mod.common.net.messages.client.SetClientPlayerDataPacket
import com.cobblemon.mod.common.net.messages.client.storage.RemoveClientPokemonPacket
import com.cobblemon.mod.common.net.messages.client.storage.SwapClientPokemonPacket
import com.cobblemon.mod.common.net.messages.client.storage.party.InitializePartyPacket
@@ -95,13 +96,10 @@ import com.cobblemon.mod.common.net.messages.client.storage.party.SetPartyPokemo
import com.cobblemon.mod.common.net.messages.client.storage.party.SetPartyReferencePacket
import com.cobblemon.mod.common.net.messages.client.storage.pc.*
import com.cobblemon.mod.common.net.messages.client.toast.ToastPacket
import com.cobblemon.mod.common.net.messages.client.trade.*
import com.cobblemon.mod.common.net.messages.client.ui.InteractPokemonUIPacket
import com.cobblemon.mod.common.net.messages.client.ui.PokedexUIPacket
import com.cobblemon.mod.common.net.messages.client.ui.SummaryUIPacket
import com.cobblemon.mod.common.net.messages.server.*
import com.cobblemon.mod.common.net.messages.server.battle.*
import com.cobblemon.mod.common.net.messages.server.block.AdjustBlockEntityViewerCountPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectCancelledPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectedPacket
import com.cobblemon.mod.common.net.messages.server.callback.party.PartyPokemonSelectedPacket
@@ -114,7 +112,6 @@ import com.cobblemon.mod.common.net.messages.server.npc.SaveNPCPacket
import com.cobblemon.mod.common.net.messages.server.pasture.PasturePokemonPacket
import com.cobblemon.mod.common.net.messages.server.pasture.UnpastureAllPokemonPacket
import com.cobblemon.mod.common.net.messages.server.pasture.UnpasturePokemonPacket
import com.cobblemon.mod.common.net.messages.server.pokedex.scanner.FinishScanningPacket
import com.cobblemon.mod.common.net.messages.server.pokedex.scanner.StartScanningPacket
import com.cobblemon.mod.common.net.messages.server.pokemon.interact.InteractPokemonPacket
import com.cobblemon.mod.common.net.messages.server.pokemon.update.SetNicknamePacket
@@ -130,10 +127,7 @@ import com.cobblemon.mod.common.net.messages.server.storage.pc.MovePartyPokemonT
import com.cobblemon.mod.common.net.messages.server.storage.pc.ReleasePCPokemonPacket
import com.cobblemon.mod.common.net.messages.server.storage.pc.SwapPCPokemonPacket
import com.cobblemon.mod.common.net.messages.server.storage.pc.UnlinkPlayerFromPCPacket
import com.cobblemon.mod.common.net.messages.server.trade.*
import com.cobblemon.mod.common.net.serverhandling.*
import com.cobblemon.mod.common.net.serverhandling.battle.*
import com.cobblemon.mod.common.net.serverhandling.block.AdjustBlockEntityViewerCountHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectCancelledHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectedHandler
import com.cobblemon.mod.common.net.serverhandling.callback.party.PartyPokemonSelectedHandler
@@ -147,8 +141,6 @@ import com.cobblemon.mod.common.net.serverhandling.npc.SaveNPCHandler
import com.cobblemon.mod.common.net.serverhandling.pasture.PasturePokemonHandler
import com.cobblemon.mod.common.net.serverhandling.pasture.UnpastureAllPokemonHandler
import com.cobblemon.mod.common.net.serverhandling.pasture.UnpasturePokemonHandler
import com.cobblemon.mod.common.net.serverhandling.pokedex.scanner.FinishScanningHandler
import com.cobblemon.mod.common.net.serverhandling.pokedex.scanner.StartScanningHandler
import com.cobblemon.mod.common.net.serverhandling.pokemon.interact.InteractPokemonHandler
import com.cobblemon.mod.common.net.serverhandling.pokemon.update.SetNicknameHandler
import com.cobblemon.mod.common.net.serverhandling.starter.RequestStarterScreenHandler
@@ -166,6 +158,19 @@ import com.cobblemon.mod.common.net.serverhandling.storage.pc.MovePartyPokemonTo
import com.cobblemon.mod.common.net.serverhandling.storage.pc.ReleasePartyPokemonHandler
import com.cobblemon.mod.common.net.serverhandling.storage.pc.SwapPCPokemonHandler
import com.cobblemon.mod.common.net.serverhandling.storage.pc.UnlinkPlayerFromPCHandler
import com.cobblemon.mod.common.net.serverhandling.trade.AcceptTradeRequestHandler
import com.cobblemon.mod.common.net.serverhandling.trade.CancelTradeHandler
import com.cobblemon.mod.common.net.serverhandling.trade.ChangeTradeAcceptanceHandler
import com.cobblemon.mod.common.net.serverhandling.trade.OfferTradeHandler
import com.cobblemon.mod.common.net.serverhandling.trade.UpdateTradeOfferHandler
import com.cobblemon.mod.common.net.messages.server.battle.*
import com.cobblemon.mod.common.net.serverhandling.battle.*
import com.cobblemon.mod.common.net.messages.client.pokedex.ServerConfirmedRegisterPacket
import com.cobblemon.mod.common.net.messages.client.trade.*
import com.cobblemon.mod.common.net.messages.server.pokedex.scanner.FinishScanningPacket
import com.cobblemon.mod.common.net.messages.server.trade.*
import com.cobblemon.mod.common.net.serverhandling.pokedex.scanner.FinishScanningHandler
import com.cobblemon.mod.common.net.serverhandling.pokedex.scanner.StartScanningHandler
import com.cobblemon.mod.common.net.serverhandling.trade.*
import com.cobblemon.mod.common.util.server
import net.minecraft.server.level.ServerPlayer
@@ -303,7 +308,8 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(PokedexDexSyncPacket.ID, PokedexDexSyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(DexEntrySyncPacket.ID, DexEntrySyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(FishingBaitRegistrySyncPacket.ID, FishingBaitRegistrySyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(FlowRegistrySyncPacket.ID, FlowRegistrySyncPacket::decode, DataRegistrySyncPacketHandler()))
list.add(PacketRegisterInfo(MarksRegistrySyncPacket.ID, MarksRegistrySyncPacket::decode, DataRegistrySyncPacketHandler()))
// Effects
list.add(PacketRegisterInfo(SpawnSnowstormParticlePacket.ID, SpawnSnowstormParticlePacket::decode, SpawnSnowstormParticleHandler))
@@ -354,7 +360,7 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(CloseNPCEditorPacket.ID, CloseNPCEditorPacket::decode, CloseNPCEditorHandler))
list.add(PacketRegisterInfo(OpenNPCEditorPacket.ID, OpenNPCEditorPacket::decode, OpenNPCEditorHandler))
// Pokédex scanning
//Pokedex scanning
list.add(PacketRegisterInfo(ServerConfirmedRegisterPacket.ID, ServerConfirmedRegisterPacket::decode, ServerConfirmedRegisterHandler))
return list
}
@@ -412,7 +418,7 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(OfferTradePacket.ID, OfferTradePacket::decode, OfferTradeHandler))
list.add(PacketRegisterInfo(UpdateTradeOfferPacket.ID, UpdateTradeOfferPacket::decode, UpdateTradeOfferHandler))
// Pokédex scanning
// Pokedex scanning
list.add(PacketRegisterInfo(StartScanningPacket.ID, StartScanningPacket::decode, StartScanningHandler))
list.add(PacketRegisterInfo(FinishScanningPacket.ID, FinishScanningPacket::decode, FinishScanningHandler))
@@ -421,9 +427,6 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(UnpasturePokemonPacket.ID, UnpasturePokemonPacket::decode, UnpasturePokemonHandler))
list.add(PacketRegisterInfo(UnpastureAllPokemonPacket.ID, UnpastureAllPokemonPacket::decode, UnpastureAllPokemonHandler))
// Block entity
list.add(PacketRegisterInfo(AdjustBlockEntityViewerCountPacket.ID, AdjustBlockEntityViewerCountPacket::decode, AdjustBlockEntityViewerCountHandler))
// Move select packets
list.add(PacketRegisterInfo(MoveSelectedPacket.ID, MoveSelectedPacket::decode, MoveSelectedHandler))
list.add(PacketRegisterInfo(MoveSelectCancelledPacket.ID, MoveSelectCancelledPacket::decode, MoveSelectCancelledHandler))
@@ -260,10 +260,6 @@ object CobblemonSounds : PlatformRegistry<Registry<SoundEvent>, ResourceKey<Regi
@JvmField
val MOVE_QUICKATTACK_TARGET = this.create("move.quickattack.target")
@JvmField
val MOVE_PURSUIT_TARGET = this.create("move.pursuit.target")
@JvmField
val MOVE_PSYCHIC_TARGET = this.create("move.psychic.target")
@JvmField
val IMPACT_NORMAL = this.create("impact.normal")
@@ -1,25 +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.ai.config.task
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BrainConfigurationContext
import com.cobblemon.mod.common.entity.ai.LookInDirectionTask
import com.cobblemon.mod.common.util.asExpression
import net.minecraft.world.entity.LivingEntity
class LookInDirectionTaskConfig : SingleTaskConfig {
var yaw: Expression = "0".asExpression()
var pitch: Expression = "0".asExpression()
override fun createTask(
entity: LivingEntity,
brainConfigurationContext: BrainConfigurationContext
) = LookInDirectionTask(yaw, pitch)
}
@@ -172,15 +172,4 @@ The 'flee_attacker' type creates a task that will make the entity flee from its
The 'flee_nearest_hostile' type creates a task that will make the entity flee from the nearest hostile entity when it is hurt.
- `condition`: A MoLang expression (with `q.entity` as the entity) that determines if this entire task should exist on the entity or not. This runs at the time of entity creation, not on tick.
- `speedMultiplier`: A MoLang expression that determines the speed multiplier for fleeing from the nearest hostile. Defaults to 0.5 which is an elevated speed to usual.
- `desiredDistance`: A MoLang expression that determines the distance from the nearest hostile that the entity should try to maintain. Defaults to 9.
### run_script
The 'run_script' type creates a task that will run a MoLang script every tick on this entity. This has the risk of being very laggy
if the script is doing expensive things. Remember to use `q.entity.world.game_time` and `math.mod` to do intermittent actions inside
the script to avoid lagging the game.
- `script`: A resource location identifying the script to run. This should be in the `molang` datapack folder.
### look_in_direction
The 'look_in_direction' type creates a task that will make the entity look in a specific direction at all times where they aren't being told to look elsewhere.
- `yaw`: A MoLang expression that determines the yaw angle (degrees) of the entity. Defaults to `0`.
- `pitch`: A MoLang expression that determines the pitch angle (degrees) of the entity. Defaults to `0`.
- `desiredDistance`: A MoLang expression that determines the distance from the nearest hostile that the entity should try to maintain. Defaults to 9.
@@ -1,49 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.config.task
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.api.ai.BrainConfigurationContext
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.withQueryValue
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.BehaviorControl
import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder
import net.minecraft.world.entity.ai.behavior.declarative.Trigger
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Runs a registered MoLang script (from the molang datapack folder) each tick.
*
* It's up to the user to not make expensive ass scripts. Remember you can access the game time
* from q.entity.level.game_time which can be used with a modulo operator to make something intermittent.
*
* @author Hiroku
* @since December 2nd, 2024
*/
class RunScript : SingleTaskConfig {
val script = cobblemonResource("dummy")
override fun createTask(
entity: LivingEntity,
brainConfigurationContext: BrainConfigurationContext
): BehaviorControl<in LivingEntity>? = BehaviorBuilder.create {
it.group(
it.registered(MemoryModuleType.LOOK_TARGET) // I think I need to have at least something here?
).apply(it) { _ ->
Trigger { world, entity, _ ->
runtime.withQueryValue("entity", (entity as? PosableEntity)?.struct ?: entity.asMostSpecificMoLangValue())
return@Trigger CobblemonScripts.run(script, runtime) == DoubleValue.ONE
}
}
}
}
@@ -58,8 +58,6 @@ fun interface TaskConfig {
"calm_down" to CalmDownTaskConfig::class.java,
"flee_attacker" to FleeAttackerTaskConfig::class.java,
"flee_nearest_hostile" to FleeNearestHostileTaskConfig::class.java,
"run_script" to RunScript::class.java,
"look_in_direction" to LookInDirectionTaskConfig::class.java,
)
val runtime = MoLangRuntime().setup()
@@ -41,7 +41,6 @@ import com.cobblemon.mod.common.battles.dispatch.WaitDispatch
import com.cobblemon.mod.common.battles.interpreter.ContextManager
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.npc.NPCBattleActor
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
@@ -94,6 +93,7 @@ open class PokemonBattle(
.filterIsInstance<LastBattleCriticalHitsEvolutionProgress>()
.forEach { it.reset() }
}
actor.setupStruct()
}
}
@@ -303,11 +303,6 @@ open class PokemonBattle(
actors.forEach { actor ->
actor.pokemonList.forEach { battlePokemon ->
battlePokemon.entity?.let { entity -> battlePokemon.postBattleEntityOperation(entity) }
if (battlePokemon.effectedPokemon.entity != null
&& battlePokemon.effectedPokemon.entity?.beamMode == 0
&& battlePokemon.effectedPokemon.entity?.platform != PlatformType.NONE) {
battlePokemon.effectedPokemon.tryRecallWithAnimation()
}
}
}
sendUpdate(BattleEndPacket())
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.api.battles.model.actor
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.battles.ActiveBattlePokemon
import com.cobblemon.mod.common.battles.ForcePassActionResponse
@@ -37,7 +36,7 @@ abstract class BattleActor(
pokemonList.forEach { it.actor = this }
}
val struct = asMoLangValue()
val struct = QueryStruct(hashMapOf())
lateinit var showdownId: String
lateinit var battle: PokemonBattle
@@ -140,6 +139,10 @@ abstract class BattleActor(
battle.writeShowdownAction(">$showdownId ${showdownMessages.joinToString()}")
}
open fun setupStruct() {
struct.addFunction("uuid") { StringValue(uuid.toString()) }
}
abstract fun getName(): MutableComponent
/**
@@ -9,11 +9,8 @@
package com.cobblemon.mod.common.api.data
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.util.endsWith
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.util.concurrent.ExecutionException
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.packs.resources.ResourceManager
@@ -45,24 +42,7 @@ interface JsonDataRegistry<T> : DataRegistry {
val resourcePath: String
override fun reload(manager: ResourceManager) {
val data = hashMapOf<ResourceLocation, T>()
manager.listResources(resourcePath) { path -> path.endsWith(JSON_EXTENSION) }.forEach { (identifier, resource) ->
if (identifier.namespace == "pixelmon") {
return@forEach
}
resource.open().use { stream ->
stream.bufferedReader().use { reader ->
val resolvedIdentifier = ResourceLocation.fromNamespaceAndPath(identifier.namespace, File(identifier.path).nameWithoutExtension)
try {
data[resolvedIdentifier] = gson.fromJson(reader, typeToken.type)
} catch (exception: Exception) {
throw ExecutionException("Error loading JSON for data: $identifier", exception)
}
}
}
}
reload(data)
this.reload(Cobblemon.implementation.reloadJsonRegistry(this, manager))
}
/**
@@ -21,13 +21,13 @@ import com.cobblemon.mod.common.util.adapters.DialogueTextAdapter
import com.cobblemon.mod.common.util.adapters.ExpressionAdapter
import com.cobblemon.mod.common.util.adapters.ExpressionLikeAdapter
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.cobblemon.mod.common.util.adapters.TranslatedTextAdapter
import com.cobblemon.mod.common.util.adapters.TextAdapter
import com.cobblemon.mod.common.util.cobblemonResource
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.packs.PackType
/**
@@ -56,7 +56,7 @@ object Dialogues : JsonDataRegistry<Dialogue> {
.registerTypeAdapter(DialogueText::class.java, DialogueTextAdapter)
.registerTypeAdapter(Expression::class.java, ExpressionAdapter)
.registerTypeAdapter(ExpressionLike::class.java, ExpressionLikeAdapter)
.registerTypeAdapter(MutableComponent::class.java, TranslatedTextAdapter)
.registerTypeAdapter(MutableComponent::class.java, TextAdapter)
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.also { gsonObservable.emit(it) }
.create()
@@ -19,8 +19,8 @@ import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
* @author Segfault Guy
* @since April 6th, 2023
*/
data class BattleFaintedEvent(
override val battle: PokemonBattle,
val killed: BattlePokemon,
val context: BattleContext
data class BattleFaintedEvent (
override val battle: PokemonBattle,
val killed: BattlePokemon,
val context: BattleContext
) : BattleEvent
@@ -18,6 +18,8 @@ import com.cobblemon.mod.common.battles.actor.PlayerBattleActor
* @since March 25th 2023
*/
data class BattleFledEvent (
override val battle: PokemonBattle,
val player: PlayerBattleActor
) : BattleEvent
@@ -8,14 +8,8 @@
package com.cobblemon.mod.common.api.events.battles
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.MoValue
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.BattleActor
import com.cobblemon.mod.common.battles.actor.PlayerBattleActor
import com.cobblemon.mod.common.entity.npc.NPCBattleActor
import com.cobblemon.mod.common.util.asArrayValue
/**
* Event fired when a battle is won by some number of [BattleActor]s.
@@ -28,20 +22,4 @@ data class BattleVictoryEvent (
val winners : List<BattleActor>,
val losers : List<BattleActor>,
val wasWildCapture : Boolean
) : BattleEvent {
val context = mutableMapOf<String, MoValue>(
"battle" to battle.struct,
"winners" to winners.asArrayValue { it.struct },
"losers" to losers.asArrayValue { it.struct },
"was_wild_capture" to DoubleValue(wasWildCapture),
"player_winners" to winners.filter { it.type == ActorType.PLAYER }.asArrayValue { it.struct },
"player_losers" to losers.filter { it.type == ActorType.PLAYER }.asArrayValue { it.struct },
"npc_winners" to winners.filter { it.type == ActorType.NPC }.asArrayValue { it.struct },
"npc_losers" to losers.filter { it.type == ActorType.NPC }.asArrayValue { it.struct },
"wild_pokemon_winners" to winners.filter { it.type == ActorType.WILD }.asArrayValue { it.struct },
"wild_pokemon_losers" to losers.filter { it.type == ActorType.WILD }.asArrayValue { it.struct },
"players" to battle.actors.filter { it.type == ActorType.PLAYER }.asArrayValue { it.struct },
"npcs" to battle.actors.filter { it.type == ActorType.NPC }.asArrayValue { it.struct },
"wild_pokemon" to battle.actors.filter { it.type == ActorType.WILD }.asArrayValue { it.struct }
)
}
) : BattleEvent
@@ -8,23 +8,12 @@
package com.cobblemon.mod.common.api.events.pokemon
import com.bedrockk.molang.runtime.value.MoValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.itemRegistry
import net.minecraft.core.registries.Registries
import net.minecraft.server.level.ServerPlayer
data class PokemonCapturedEvent (
val pokemon: Pokemon,
val player: ServerPlayer,
val pokeBallEntity: EmptyPokeBallEntity
) {
val context = mutableMapOf<String, MoValue>(
"pokemon" to pokemon.struct,
"player" to player.asMoLangValue(),
"poke_ball" to pokeBallEntity.struct,
"item" to player.level().itemRegistry.wrapAsHolder(pokeBallEntity.pokeBall.item).asMoLangValue(Registries.ITEM)
)
}
)
@@ -24,7 +24,7 @@ abstract class ParentWidget(
component: Component
): Renderable, AbstractWidget(pX, pY, pWidth, pHeight, component) {
val children: MutableList<GuiEventListener> = mutableListOf()
private val children: MutableList<GuiEventListener> = mutableListOf()
/**
* Adds Widget to the children list
@@ -22,8 +22,6 @@ import com.cobblemon.mod.common.CobblemonActivities
import com.cobblemon.mod.common.CobblemonBlockEntities
import com.cobblemon.mod.common.CobblemonMemories
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.BattleActor
import com.cobblemon.mod.common.api.dialogue.PlayerDialogueFaceProvider
import com.cobblemon.mod.common.api.dialogue.ReferenceDialogueFaceProvider
import com.cobblemon.mod.common.api.moves.animations.ActionEffectContext
@@ -39,23 +37,17 @@ import com.cobblemon.mod.common.api.storage.pc.PCPosition
import com.cobblemon.mod.common.api.storage.pc.PCStore
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.battles.actor.PlayerBattleActor
import com.cobblemon.mod.common.client.render.models.blockbench.wavefunction.WaveFunctions
import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.entity.npc.NPCBattleActor
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.net.messages.client.animation.PlayPosableAnimationPacket
import com.cobblemon.mod.common.net.messages.client.effect.RunPosableMoLangPacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import java.util.UUID
import kotlin.math.sqrt
import net.minecraft.commands.arguments.EntityAnchorArgument
import net.minecraft.core.BlockPos
import net.minecraft.core.Holder
import net.minecraft.core.Registry
import net.minecraft.core.registries.BuiltInRegistries
@@ -67,23 +59,14 @@ import net.minecraft.nbt.StringTag
import net.minecraft.nbt.Tag
import net.minecraft.resources.ResourceKey
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.tags.TagKey
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.damagesource.DamageTypes
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.LightningBolt
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BlockPosTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.MemoryStatus
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.player.Player
import net.minecraft.world.level.Level
import net.minecraft.world.level.Level.ExplosionInteraction
import net.minecraft.world.level.biome.Biome
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.dimension.DimensionType
@@ -98,25 +81,6 @@ import net.minecraft.world.phys.Vec3
*/
object MoLangFunctions {
val generalFunctions = hashMapOf<String, java.util.function.Function<MoParams, Any>>(
"print" to java.util.function.Function { params ->
val message = params.get<MoValue>(0).asString()
Cobblemon.LOGGER.info(message)
},
"replace" to java.util.function.Function { params ->
val text = params.getString(0)
val search = params.getString(1)
val replace = params.getString(2)
return@Function StringValue(text.replace(search, replace))
},
"is_blank" to java.util.function.Function { params ->
val arg = params.get<MoValue>(0)
return@Function DoubleValue((arg is StringValue && (arg.value.isBlank() || arg.value.toDoubleOrNull() == 0.0)) || (arg is DoubleValue && arg.value == 0.0))
},
"run_command" to java.util.function.Function { params ->
val command = params.getString(0)
val server = server() ?: return@Function DoubleValue.ZERO
server.commands.performPrefixedCommand(server.createCommandSourceStack(), command)
},
"is_int" to java.util.function.Function { params -> DoubleValue(params.get<MoValue>(0).asString().isInt()) },
"is_number" to java.util.function.Function { params -> DoubleValue(params.get<MoValue>(0).asString().toDoubleOrNull() != null) },
"to_number" to java.util.function.Function { params -> DoubleValue(params.get<MoValue>(0).asString().toDoubleOrNull() ?: 0.0) },
@@ -151,93 +115,19 @@ object MoLangFunctions {
runtime.environment.variable = params.environment.variable
runtime.environment.context = params.environment.context
val script = params.getString(0).asIdentifierDefaultingNamespace()
CobblemonScripts.run(script, runtime) ?: DoubleValue.ZERO
CobblemonScripts.run(script, runtime) ?: DoubleValue(0)
},
"run_molang" to java.util.function.Function { params ->
val runtime = MoLangRuntime()
runtime.environment.query = params.environment.query
runtime.environment.variable = params.environment.variable
runtime.environment.context = params.environment.context
val expression = params.getString(0).asExpressionLike()
runtime.resolve(expression)
},
)
val biomeFunctions = mutableListOf<(Holder<Biome>) -> HashMap<String, java.util.function.Function<MoParams, Any>>>()
val worldFunctions = mutableListOf<(Holder<Level>) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
{ worldHolder ->
val world = worldHolder.value()
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
map.put("game_time") { _ -> DoubleValue(world.gameTime.toDouble()) }
map.put("time_of_day") {
val time = world.dayTime % 24000
return@put DoubleValue(time.toDouble())
}
map.put("server") { _ -> server()?.asMoLangValue() ?: DoubleValue.ZERO }
map.put("is_raining_at") { params ->
val x = params.getInt(0)
val y = params.getInt(1)
val z = params.getInt(2)
return@put DoubleValue(world.isRainingAt(BlockPos(x, y, z)))
}
map.put("is_chunk_loaded_at") { params ->
val x = params.getInt(0)
val y = params.getInt(1)
val z = params.getInt(2)
return@put DoubleValue(world.isLoaded(BlockPos(x, y, z)))
}
map.put("is_thundering") { _ -> DoubleValue(world.isThundering) }
map.put("is_raining") { _ -> DoubleValue(world.isRaining) }
map.put("set_block") { params ->
val x = params.getInt(0)
val y = params.getInt(1)
val z = params.getInt(2)
val block = world.blockRegistry.get(params.getString(3).asIdentifierDefaultingNamespace())
?: run {
Cobblemon.LOGGER.error("Unknown block: ${params.getString(3)}")
return@put DoubleValue.ZERO
}
world.setBlock(BlockPos(x, y, z), block.defaultBlockState(), Block.UPDATE_ALL)
}
map.put("get_block") { params ->
val x = params.getInt(0)
val y = params.getInt(1)
val z = params.getInt(2)
val block = world.getBlockState(BlockPos(x, y, z)).block
return@put world.blockRegistry.wrapAsHolder(block).asMoLangValue(Registries.BLOCK)
}
map.put("spawn_explosion") { params ->
val x = params.getDouble(0)
val y = params.getDouble(1)
val z = params.getDouble(2)
val range = params.getDouble(3).toFloat()
world.explode(null, x, y, z, range, ExplosionInteraction.valueOf(params.getStringOrNull(4)?.uppercase() ?: ExplosionInteraction.TNT.name))
}
map.put("spawn_lightning") { params ->
val x = params.getDouble(0)
val y = params.getDouble(1)
val z = params.getDouble(2)
val lightning = LightningBolt(EntityType.LIGHTNING_BOLT, world)
lightning.setPos(x, y, z)
world.addFreshEntity(lightning)
return@put DoubleValue.ONE
}
map.put("get_entities_around") { params ->
val x = params.getDouble(0)
val y = params.getDouble(1)
val z = params.getDouble(2)
val range = params.getDouble(3) * 2
val entities = world.getEntities(null, AABB.ofSize(Vec3(x, y, z), range, range, range))
return@put entities
.filterIsInstance<LivingEntity>()
.map { it.asMostSpecificMoLangValue() }
.asArrayValue()
}
return@mutableListOf map
"run_command" to java.util.function.Function { params ->
val command = params.getString(0)
server()?.let {
return@Function DoubleValue(it.commands.dispatcher.execute(command, it.createCommandSourceStack()))
} ?: return@Function DoubleValue.ZERO
}
)
val dimensionTypeFunctions = mutableListOf<(Holder<DimensionType>) -> HashMap<String, java.util.function.Function<MoParams, Any>>>()
val blockFunctions = mutableListOf<(Holder<Block>) -> HashMap<String, java.util.function.Function<MoParams, Any>>>()
val biomeFunctions = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
val worldFunctions = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
val dimensionTypeFunctions = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
val blockFunctions = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
val playerFunctions = mutableListOf<(Player) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
{ player ->
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
@@ -251,7 +141,7 @@ object MoLangFunctions {
map.put("saturation_level") { _ -> DoubleValue(player.foodData.saturationLevel) }
map.put("tell") { params ->
val message = params.getString(0).text()
val overlay = params.getBooleanOrNull(1) == true
val overlay = params.getBooleanOrNull(1) ?: false
player.displayClientMessage(message, overlay)
}
map.put("teleport") { params ->
@@ -270,12 +160,7 @@ object MoLangFunctions {
environment.query = player.asMoLangValue()
environment
}
map.put("is_player") { DoubleValue.ONE }
if (player is ServerPlayer) {
map.put("run_command") { params ->
val command = params.getString(0)
player.server.commands.performPrefixedCommand(player.createCommandSourceStack(), command)
}
map.put("is_party_at_full_health") { _ ->
DoubleValue(player.party().none(Pokemon::canBeHealed)) }
map.put("can_heal_at_healer") { params ->
@@ -303,46 +188,11 @@ object MoLangFunctions {
map.put("save_data") { _ -> Cobblemon.molangData.save(player.uuid) }
map.put("in_battle") { DoubleValue(player.isInBattle()) }
map.put("battle") { player.getBattleState()?.first?.struct ?: DoubleValue.ZERO }
map.put("get_npc_data") { params ->
val npcId = (params.get<MoValue>(0) as? ObjectValue<NPCEntity>)?.obj?.stringUUID ?: params.getString(0)
val data = Cobblemon.molangData.load(player.uuid)
if (data.map.containsKey(npcId)) {
return@put data.map[npcId]!!
} else {
val vars = VariableStruct()
data.map[npcId] = vars
return@put vars
}
}
map.put("get_npc_variable") { params ->
val npcId = (params.get<MoValue>(0) as? ObjectValue<NPCEntity>)?.obj?.stringUUID ?: params.getString(0)
val variable = params.getString(1)
val data = Cobblemon.molangData.load(player.uuid)
if (data.map.containsKey(npcId)) {
return@put (data.map[npcId] as VariableStruct).map[variable] ?: DoubleValue.ZERO
}
}
map.put("set_npc_variable") { params ->
val npcId = (params.get<MoValue>(0) as? ObjectValue<NPCEntity>)?.obj?.stringUUID ?: params.getString(0)
val variable = params.getString(1)
val value = params.get<MoValue>(2)
val saveAfterwards = params.getBooleanOrNull(3) != false
val data = Cobblemon.molangData.load(player.uuid)
if (data.map.containsKey(npcId)) {
(data.map[npcId] as VariableStruct).map[variable] = value
if (saveAfterwards) {
Cobblemon.molangData.save(player.uuid)
}
return@put DoubleValue.ONE
} else {
return@put DoubleValue.ZERO
}
}
}
map
}
)
val entityFunctions: MutableList<(LivingEntity) -> HashMap<String, java.util.function.Function<MoParams, Any>>> = mutableListOf<(LivingEntity) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
val entityFunctions = mutableListOf<(LivingEntity) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
{ entity ->
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
map.put("uuid") { _ -> StringValue(entity.uuid.toString()) }
@@ -351,28 +201,6 @@ object MoLangFunctions {
val source = DamageSource(entity.level().registryAccess().registryOrThrow(Registries.DAMAGE_TYPE).getHolder(DamageTypes.GENERIC).get())
entity.hurt(source, amount.toFloat())
}
map.put("walk_to") { params ->
val x = params.getDouble(0)
val y = params.getDouble(1)
val z = params.getDouble(2)
val speedMultiplier = params.getDoubleOrNull(3) ?: 0.35
if (entity is PathfinderMob) {
if (entity.brain.checkMemory(MemoryModuleType.WALK_TARGET, MemoryStatus.REGISTERED)) {
entity.brain.setMemory(MemoryModuleType.WALK_TARGET, WalkTarget(Vec3(x, y, z), speedMultiplier.toFloat(), 1))
entity.brain.setMemory(MemoryModuleType.LOOK_TARGET, BlockPosTracker(Vec3(x, y + entity.eyeHeight, z)))
} else {
entity.navigation.moveTo(x, y, z, speedMultiplier)
entity.lookControl.setLookAt(Vec3(x, y + entity.eyeHeight, z))
}
}
}
map.put("has_walk_target") { _ ->
if (entity is PathfinderMob) {
DoubleValue(entity.brain.getMemory(MemoryModuleType.WALK_TARGET).isPresent || entity.isPathFinding)
} else {
DoubleValue.ZERO
}
}
map.put("is_sneaking") { _ -> DoubleValue(entity.isShiftKeyDown) }
map.put("is_sprinting") { _ -> DoubleValue(entity.isSprinting) }
map.put("is_flying") { _ -> DoubleValue(entity.isFallFlying) }
@@ -384,14 +212,8 @@ object MoLangFunctions {
map.put("is_on_fire") { _ -> DoubleValue(entity.isOnFire) }
map.put("is_invisible") { _ -> DoubleValue(entity.isInvisible) }
map.put("is_sleeping") { _ -> DoubleValue(entity.isSleeping) }
map.put("is_riding") { _ -> DoubleValue(entity.isPassenger) }
map.put("is_riding") { _ -> DoubleValue(entity.isPassenger()) }
map.put("health") { _ -> DoubleValue(entity.health) }
map.put("distance_to_pos") { params ->
val x = params.getDouble(0)
val y = params.getDouble(1)
val z = params.getDouble(2)
return@put DoubleValue(sqrt(entity.distanceToSqr(Vec3(x, y, z))))
}
map.put("max_health") { _ -> DoubleValue(entity.maxHealth) }
map.put("name") { _ -> StringValue(entity.effectiveName().string) }
map.put("yaw") { _ -> DoubleValue(entity.yRot.toDouble()) }
@@ -433,21 +255,6 @@ object MoLangFunctions {
return@put DoubleValue.ZERO
}
}
map.put("get_nearby_entities") { params ->
val distance = params.getDouble(0)
val entities = entity.level().getEntities(entity, AABB.ofSize(entity.position(), distance, distance, distance))
return@put entities
.filterIsInstance<LivingEntity>()
.map { it.asMostSpecificMoLangValue() }
.asArrayValue()
}
if (entity is PosableEntity) {
map.put("play_animation") { params ->
val animation = params.getString(0)
val packet = PlayPosableAnimationPacket(entity.id, setOf(animation), emptyList())
packet.sendToPlayersAround(entity.x, entity.y, entity.z, 64.0, entity.level().dimension())
}
}
map
}
)
@@ -508,9 +315,9 @@ object MoLangFunctions {
}
}
return@put DoubleValue.ONE
return@put DoubleValue(1)
}
return@put DoubleValue.ZERO
return@put DoubleValue(0)
}
map.put("put_pokemon_in_healer") { params ->
val healer = npc.level().getBlockEntity(params.get<ArrayStruct>(0).asBlockPos(), CobblemonBlockEntities.HEALING_MACHINE).orElse(null) ?: return@put DoubleValue.ZERO
@@ -529,8 +336,6 @@ object MoLangFunctions {
map.put("environment") { _ -> npc.runtime.environment }
map.put("party") { npc.party?.struct ?: DoubleValue.ZERO }
map.put("has_party") { DoubleValue(npc.party != null) }
map.put("is_npc") { DoubleValue.ONE }
map.put("can_battle") { DoubleValue(npc.party?.any { it.currentHealth > 0 } == true || npc.npc.party?.isStatic == false) }
map
}
)
@@ -550,26 +355,10 @@ object MoLangFunctions {
return@put actor.struct
}
map.put("stop") { _ -> battle.stop() }
map.put("actors") { battle.actors.toList().asArrayValue { it.struct } }
map
}
)
val battleActorFunctions = mutableListOf<(BattleActor) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
{ battleActor ->
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
map.put("is_npc") { DoubleValue(battleActor.type == ActorType.NPC) }
map.put("is_player") { DoubleValue(battleActor.type == ActorType.PLAYER) }
map.put("is_wild") { DoubleValue(battleActor.type == ActorType.WILD) }
if (battleActor is NPCBattleActor) {
map.put("npc") { battleActor.entity.struct }
} else if (battleActor is PlayerBattleActor) {
map.put("player") { battleActor.entity?.asMoLangValue() ?: DoubleValue.ZERO }
}
return@mutableListOf map
}
)
val pokemonFunctions = mutableListOf<(Pokemon) -> HashMap<String, java.util.function.Function<MoParams, Any>>>(
{ pokemon ->
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
@@ -608,7 +397,6 @@ object MoLangFunctions {
map.put("is_moving") { DoubleValue((pokemonEntity.moveControl as? PokemonMoveControl)?.hasWanted() == true) }
map.put("is_flying") { DoubleValue(pokemonEntity.getBehaviourFlag(PokemonBehaviourFlag.FLYING)) }
map.put("has_aspect") { DoubleValue(it.getString(0) in pokemonEntity.aspects) }
map.put("is_pokemon") { DoubleValue.ONE }
map
}
)
@@ -747,68 +535,10 @@ object MoLangFunctions {
}
)
val serverFunctions: MutableList<(MinecraftServer) -> HashMap<String, java.util.function.Function<MoParams, Any>>> = mutableListOf(
{ server ->
val map = hashMapOf<String, java.util.function.Function<MoParams, Any>>()
map.put("get_world") { params ->
val world = server.getLevel(
ResourceKey.create(
Registries.DIMENSION,
params.getString(0).asIdentifierDefaultingNamespace(namespace = "minecraft")
)
) ?: return@put DoubleValue.ZERO
return@put world
.registryAccess()
.registryOrThrow(Registries.DIMENSION)
.wrapAsHolder(world)
.asWorldMoLangValue()
}
map.put("broadcast") { params ->
val message = params.getString(0)
server.playerList.broadcastSystemMessage(message.text(), params.getBooleanOrNull(1) == true)
return@put DoubleValue.ONE
}
map.put("get_player_by_uuid") { params ->
val uuid = UUID.fromString(params.getString(0))
val player = server.playerList.getPlayer(uuid) ?: return@put DoubleValue.ZERO
return@put player.asMoLangValue()
}
map.put("get_player_by_username") { params ->
val username = params.getString(0)
val player = server.playerList.getPlayerByName(username) ?: return@put DoubleValue.ZERO
return@put player.asMoLangValue()
}
map.put("data") { params ->
val data = Cobblemon.molangData.load(UUID(0L, 0L))
return@put data
}
map.put("save_data") {
Cobblemon.molangData.save(UUID(0L, 0L))
return@put DoubleValue.ONE
}
// Maybe later...
// map.put("stop") { params ->
// Cobblemon.LOGGER.warn("Server is being stopped from a MoLang script.")
// server.stopServer()
// }
return@mutableListOf map
}
)
fun Holder<Biome>.asBiomeMoLangValue() = asMoLangValue(Registries.BIOME).addFunctions(biomeFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
fun Holder<Level>.asWorldMoLangValue() = asMoLangValue(Registries.DIMENSION).addFunctions(worldFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
fun Holder<Block>.asBlockMoLangValue() = asMoLangValue(Registries.BLOCK).addFunctions(blockFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
fun MinecraftServer.asMoLangValue() = ObjectValue(this).addStandardFunctions().addFunctions(serverFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
fun Holder<DimensionType>.asDimensionTypeMoLangValue() = asMoLangValue(Registries.DIMENSION_TYPE).addFunctions(dimensionTypeFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
fun Holder<Biome>.asBiomeMoLangValue() = asMoLangValue(Registries.BIOME).addFunctions(biomeFunctions)
fun Holder<Level>.asWorldMoLangValue() = asMoLangValue(Registries.DIMENSION).addFunctions(worldFunctions)
fun Holder<Block>.asBlockMoLangValue() = asMoLangValue(Registries.BLOCK).addFunctions(blockFunctions)
fun Holder<DimensionType>.asDimensionTypeMoLangValue() = asMoLangValue(Registries.DIMENSION_TYPE).addFunctions(dimensionTypeFunctions)
fun Player.asMoLangValue(): ObjectValue<Player> {
val value = ObjectValue(
obj = this,
@@ -856,17 +586,6 @@ object MoLangFunctions {
return value
}
fun PokemonEntity.asMoLangValue(): ObjectValue<PokemonEntity> {
val value = ObjectValue(
obj = this,
stringify = { it.pokemon.uuid.toString() }
)
value.addFunctions(entityFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
value.addFunctions(pokemonFunctions.flatMap { it(this.pokemon).entries.map { it.key to it.value } }.toMap()) // Convenience
value.addFunctions(pokemonEntityFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
return value
}
fun PokemonBattle.asMoLangValue(): ObjectValue<PokemonBattle> {
val value = ObjectValue(
obj = this,
@@ -876,15 +595,6 @@ object MoLangFunctions {
return value
}
fun BattleActor.asMoLangValue(): ObjectValue<BattleActor> {
val value = ObjectValue(
obj = this,
stringify = { it.toString() }
)
value.addFunctions(battleActorFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap())
return value
}
fun SpawningContext.asMoLangValue(): ObjectValue<SpawningContext> {
val value = ObjectValue(
obj = this,
@@ -894,18 +604,6 @@ object MoLangFunctions {
return value
}
/**
* Different functions exist depending on
*/
fun LivingEntity.asMostSpecificMoLangValue(): ObjectValue<out LivingEntity> {
return when (this) {
is Player -> asMoLangValue()
is PokemonEntity -> struct
is NPCEntity -> struct
else -> ObjectValue(this).also { it.addStandardFunctions().addFunctions(entityFunctions.flatMap { it(this).entries.map { it.key to it.value } }.toMap()) }
}
}
fun <T> Holder<T>.asMoLangValue(key: ResourceKey<Registry<T>>): ObjectValue<Holder<T>> {
val value = ObjectValue(
obj = this,
@@ -1,27 +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.net.serializers
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.network.codec.StreamCodec
import net.minecraft.network.syncher.EntityDataSerializer
object PlatformTypeDataSerializer : EntityDataSerializer<PlatformType> {
// TODO: This ID only looks it's used by NeoForge and that hasn't been tested yet
val ID = cobblemonResource("platform_type")
fun read(buf: RegistryFriendlyByteBuf) = PlatformType.entries[buf.readInt()]
override fun copy(value: PlatformType) = value
fun write(buf: RegistryFriendlyByteBuf, value: PlatformType) {
buf.writeInt(value.ordinal)
}
override fun codec() = StreamCodec.of(::write, ::read)
}
@@ -70,7 +70,7 @@ object NPCClasses : JsonDataRegistry<NPCClass> {
.registerTypeAdapter(MoValue::class.java, MoValueAdapter)
.registerTypeAdapter(NPCClass::class.java, NPCClassAdapter)
.registerTypeAdapter(Activity::class.java, ActivityAdapter)
.registerTypeAdapter(Component::class.java, TranslatedTextAdapter)
.registerTypeAdapter(Component::class.java, TextAdapter)
.registerTypeAdapter(WeightedAspect::class.java, WeightedAspectAdapter)
.registerTypeAdapter(BrainConfig::class.java, BrainConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
@@ -9,12 +9,10 @@
package com.cobblemon.mod.common.api.npc
import com.cobblemon.mod.common.api.npc.partyproviders.PoolPartyProvider
import com.cobblemon.mod.common.api.npc.partyproviders.ScriptPartyProvider
import com.cobblemon.mod.common.api.npc.partyproviders.SimplePartyProvider
import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.google.gson.JsonElement
import net.minecraft.server.level.ServerPlayer
/**
* A provider of a party for battling the NPC. Completely custom party providers will only display
@@ -27,14 +25,13 @@ interface NPCPartyProvider {
companion object {
val types = mutableMapOf<String, (String) -> NPCPartyProvider>(
SimplePartyProvider.TYPE to { SimplePartyProvider() },
PoolPartyProvider.TYPE to { PoolPartyProvider() },
ScriptPartyProvider.TYPE to { ScriptPartyProvider() }
PoolPartyProvider.TYPE to { PoolPartyProvider() }
)
}
val type: String
val isStatic: Boolean
fun provide(npc: NPCEntity, level: Int, players: List<ServerPlayer> = emptyList()): NPCPartyStore
fun provide(npc: NPCEntity, level: Int): NPCPartyStore
// Why did I opt for manual JSON loading??? I must have had a reason but I can't remember. Maybe for S2C? Use a codec doofus
fun loadFromJSON(json: JsonElement)
}
@@ -67,7 +67,7 @@ object NPCPresets : JsonDataRegistry<NPCPreset> {
.registerTypeAdapter(NPCVariationProvider::class.java, NPCVariationProviderAdapter)
.registerTypeAdapter(Activity::class.java, ActivityAdapter)
.registerTypeAdapter(MoValue::class.java, MoValueAdapter)
.registerTypeAdapter(Component::class.java, TranslatedTextAdapter)
.registerTypeAdapter(Component::class.java, TextAdapter)
.registerTypeAdapter(BrainConfig::class.java, BrainConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
.registerTypeAdapter(TypeToken.getParameterized(RegistryLikeCondition::class.java, Biome::class.java).type, BiomeLikeConditionAdapter)
@@ -57,8 +57,8 @@ any number of presets and the properties of those presets will be merged into th
"variableName": "challenge_distance",
"displayName": "cobblemon.npc.challenge_distance",
"description": "cobblemon.npc.challenge_distance.description",
"type": "NUMBER",
"defaultValue": "5"
"type": "number",
"default": "5"
}
],
"names": [
@@ -178,19 +178,19 @@ An example situation of using this is if there is an NPC class preset that defin
challenging a player when they come within a certain range. Inside that class preset, the AI script may
need to know at what distance the player will be engaged. This can be defined in the NPC class preset as
a config variable, and therefore any NPC class that relies on this preset will have that config variable
and present it to users when they set up an NPC of that class.
and present it to users when they setup an NPC of that class.
"config": [
{
"variableName": "challenge_distance",
"displayName": "cobblemon.npc.challenge_distance.name",
"description": "cobblemon.npc.challenge_distance.desc",
"type": "NUMBER",
"defaultValue": "5"
"displayName": "cobblemon.npc.challenge_distance",
"description": "cobblemon.npc.challenge_distance.description",
"type": "number",
"default": "5"
}
]
The "type" of variable is one of: `STRING`, `NUMBER`, or `BOOLEAN`. The type is used to preset a more
The "type" of variable is one of: `string`, `number`, or `boolean`. The type is used to preset a more
appropriate input field for the user when they are setting up the NPC.
### names
@@ -298,10 +298,6 @@ depend on visual aspects of the NPC. For example, if the NPC has a variation for
certain Pokémon to be `"weight": "q.npc.has_aspect('dirty') ? -1 : 0"` which would make it a guaranteed party Pokémon for "dirty" NPCs
and impossible for all other variations of the NPC.
The MoLang environment used for the pool party provider contains q.level for the seed level, q.npc for the NPC, as well as q.players for
an array of all players that are challenging the NPC. The players list is only present for dynamic parties. If it is specifically
a single battle challenge and this is a dynamic party, there will also be a `q.player`, for convenience.
"party": {
"type": "pool",
"minPokemon": "3",
@@ -348,33 +344,6 @@ a single battle challenge and this is a dynamic party, there will also be a `q.p
]
}
#### script
The "script" party type is a way to define a party of Pokémon using a MoLang script. The script can modify a q.party struct,
primarily using function calls such as `q.party.add_by_properties('pikachu shiny)`.
There is an `isStatic` property to control whether the party is static or dynamic. There is a `script` property which is a
resource location pointing to the script that should be located in the `molang` datapack folder.
The MoLang environment used for the script party provider contains q.level for the seed level, q.npc for the NPC, as well as q.players for
an array of all players that are challenging the NPC. The players list is only present for dynamic parties. If it is specifically
a single battle challenge and this is a dynamic party, there will also be a `q.player`, for convenience.
"party": {
"type": "script",
"isStatic": true,
"script": "cobblemon:npc_party"
}
An example script might be:
t.use_butterfree = math.random_integer(1, 2) == 1;
t.use_butterfree ? {
q.party.add_by_properties('butterfree level=' + (q.level + 3));
} : {
q.party.add_by_properties('beedrill level=' + (q.level + 3));
};
q.party.add_by_properties('pidgey');
### autoHealParty
Whether or not the NPC's party will be healed between battles. If the NPC has a dynamic party, this option will
do nothing. If the NPC has a static party and this option is false, their Pokémon will not be healed and the
@@ -13,11 +13,6 @@ import com.bedrockk.molang.runtime.value.MoValue
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.asTranslated
import com.cobblemon.mod.common.util.readString
import com.cobblemon.mod.common.util.readText
import com.cobblemon.mod.common.util.writeString
import com.cobblemon.mod.common.util.writeText
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.network.chat.Component
/**
@@ -35,38 +30,10 @@ class NPCConfigVariable(
val type: NPCVariableType = NPCVariableType.NUMBER,
val defaultValue: String = "0",
) {
companion object {
fun decode(buffer: RegistryFriendlyByteBuf): NPCConfigVariable {
return NPCConfigVariable(
buffer.readString(),
buffer.readText(),
buffer.readText(),
buffer.readEnum(NPCVariableType::class.java),
buffer.readString()
)
}
}
enum class NPCVariableType {
NUMBER,
TEXT,
BOOLEAN;
fun toMoValue(value: String): MoValue {
return when (this) {
TEXT -> StringValue(value)
BOOLEAN -> DoubleValue(value.let { it == "1" || it.toBooleanStrictOrNull() == true })
else -> DoubleValue(value.toDouble())
}
}
}
fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeString(variableName)
buffer.writeText(displayName)
buffer.writeText(description)
buffer.writeEnum(type)
buffer.writeString(defaultValue)
STRING,
BOOLEAN
}
fun apply(npc: NPCEntity, value: MoValue) {
@@ -74,6 +41,11 @@ class NPCConfigVariable(
}
fun applyDefault(npc: NPCEntity) {
npc.config.setDirectly(variableName, type.toMoValue(defaultValue))
val value = when (type) {
NPCVariableType.STRING -> StringValue(defaultValue)
NPCVariableType.BOOLEAN -> DoubleValue(defaultValue.toBoolean())
else -> DoubleValue(defaultValue.toDouble())
}
npc.config.set(variableName.split(".").iterator(), value)
}
}
@@ -10,14 +10,11 @@ package com.cobblemon.mod.common.api.npc.partyproviders
import com.bedrockk.molang.Expression
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.npc.NPCPartyProvider
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.asArrayValue
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
@@ -26,7 +23,6 @@ import com.cobblemon.mod.common.util.withQueryValue
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import net.minecraft.server.level.ServerPlayer
/**
* A provider of a party for battling the NPC. It generates a party using a more complex process
@@ -97,22 +93,16 @@ class PoolPartyProvider : NPCPartyProvider {
}
}
fun formulateParty(npc: NPCEntity, level: Int, players: List<ServerPlayer>, party: NPCPartyStore) {
fun formulateParty(npc: NPCEntity, level: Int, party: NPCPartyStore) {
val runtime = MoLangRuntime().setup().withQueryValue("npc", npc.struct)
runtime.withQueryValue("level", DoubleValue(level))
runtime.withQueryValue("players", players.asArrayValue { it.asMoLangValue() })
if (players.size == 1) {
// This is for the convenience, most cases will be pvn one player
runtime.withQueryValue("player", players.first().asMoLangValue())
}
val minPokemon = runtime.resolveInt(this.minPokemon)
val maxPokemon = runtime.resolveInt(this.maxPokemon)
var desiredPokemonCount = (minPokemon..maxPokemon).random()
val workingPool = pool.filter { level in it.npcLevels && runtime.resolveInt(it.selectableTimes) > 0 }.toMutableList()
val workingPool = pool.filter { level in it.npcLevels }.toMutableList()
val useCounts = mutableMapOf<DynamicPokemon, Int>()
while (desiredPokemonCount > 0 && workingPool.any { it.hasWeight(runtime) }) {
while (desiredPokemonCount > 0 && workingPool.filter { it.hasWeight(runtime) }.isNotEmpty()) {
val selected = workingPool.filter { it.getWeight(runtime) == -1F }.randomOrNull()
?: workingPool.weightedSelection { it.getWeight(runtime) }
?: break
@@ -131,9 +121,9 @@ class PoolPartyProvider : NPCPartyProvider {
}
}
override fun provide(npc: NPCEntity, level: Int, players: List<ServerPlayer>): NPCPartyStore {
override fun provide(npc: NPCEntity, level: Int): NPCPartyStore {
val party = NPCPartyStore(npc)
formulateParty(npc, level, players, party)
formulateParty(npc, level, party)
return party
}
}
@@ -1,64 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.npc.partyproviders
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.npc.NPCPartyProvider
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.asArrayValue
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.toProperties
import com.cobblemon.mod.common.util.withQueryValue
import com.google.gson.JsonElement
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
class ScriptPartyProvider : NPCPartyProvider {
companion object {
const val TYPE = "script"
}
override val type = TYPE
override var isStatic: Boolean = true
var script: ResourceLocation = cobblemonResource("dummy")
override fun loadFromJSON(json: JsonElement) {
isStatic = json.asJsonObject.get("isStatic")?.asBoolean != false
script = json.asJsonObject.get("script").asString.asIdentifierDefaultingNamespace()
}
override fun provide(npc: NPCEntity, level: Int, players: List<ServerPlayer>): NPCPartyStore {
val runtime = MoLangRuntime().setup().withQueryValue("npc", npc.struct)
runtime.withQueryValue("level", DoubleValue(level))
runtime.withQueryValue("players", players.asArrayValue { it.asMoLangValue() })
if (players.size == 1) {
// This is for the convenience, most cases will be pvn one player
runtime.withQueryValue("player", players.first().asMoLangValue())
}
val npcParty = NPCPartyStore(npc)
runtime.withQueryValue("party", npcParty.struct)
if (!CobblemonScripts.scripts.containsKey(script)) {
Cobblemon.LOGGER.error("Script $script not found in script registry.")
npcParty.add("magikarp".toProperties().create())
return npcParty
}
CobblemonScripts.run(identifier = script, runtime = runtime)
return npcParty
}
}
@@ -14,7 +14,6 @@ import com.cobblemon.mod.common.api.storage.party.NPCPartyStore
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.toProperties
import com.google.gson.JsonElement
import net.minecraft.server.level.ServerPlayer
/**
* A basic party provider that just produces a [NPCPartyStore] based on a simple list of [PokemonProperties].
@@ -53,7 +52,7 @@ class SimplePartyProvider : NPCPartyProvider {
}
}
override fun provide(npc: NPCEntity, level: Int, players: List<ServerPlayer>): NPCPartyStore {
override fun provide(npc: NPCEntity, level: Int): NPCPartyStore {
val pokemon = pokemon.map { it.copy().also { it.level = it.level ?: level }.create() }
val party = NPCPartyStore(npc)
pokemon.forEach(party::add)
@@ -19,6 +19,8 @@ import com.cobblemon.mod.common.api.events.pokemon.ShinyChanceCalculationEvent
import com.cobblemon.mod.common.api.moves.Moves
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.aspect.AspectProvider
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMark
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.properties.CustomPokemonProperty
@@ -36,7 +38,7 @@ import com.cobblemon.mod.common.pokemon.RenderablePokemon
import com.cobblemon.mod.common.pokemon.status.PersistentStatus
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.isDouble
import com.cobblemon.mod.common.util.isInt
import com.cobblemon.mod.common.util.isUuid
import com.cobblemon.mod.common.util.server
import com.cobblemon.mod.common.util.simplify
@@ -59,6 +61,7 @@ import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
@@ -186,10 +189,10 @@ open class PokemonProperties {
private fun parseIntProperty(keyPairs: MutableList<Pair<String, String?>>, labels: Iterable<String>): Int? {
val matchingKeyPair = getMatchedKeyPair(keyPairs, labels) ?: return null
val value = matchingKeyPair.second
return if (value == null || !value.isDouble()) {
return if (value == null || !value.isInt()) {
null
} else {
value.toDouble().toInt()
value.toInt()
}
}
@@ -639,6 +642,7 @@ open class PokemonProperties {
val custom = ListTag()
customProperties.map { StringTag.valueOf(it.asString()) }.forEach { custom.add(it) }
nbt.put(DataKeys.POKEMON_PROPERTIES_CUSTOM, custom)
return nbt
}
@@ -671,6 +675,7 @@ open class PokemonProperties {
// This is kinda gross
custom.forEach { customProperties.addAll(parse(it.asString).customProperties) }
updateAspects()
return this
}
@@ -736,6 +741,7 @@ open class PokemonProperties {
// This is still kinda gross
custom?.forEach { customProperties.addAll(parse(it.asString).customProperties) }
updateAspects()
return this
}
@@ -789,7 +795,7 @@ open class PokemonProperties {
}
fun copy(): PokemonProperties {
return PokemonProperties().loadFromJSON(this.saveToJSON())
return PokemonProperties().loadFromJSON(saveToJSON())
}
// If the config value is at least 1, then do 1/x and use that as the property chance
@@ -0,0 +1,17 @@
package com.cobblemon.mod.common.api.pokemon.marks
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.api.multiblock.condition.OrCondition
import net.minecraft.resources.ResourceLocation
class PokemonMark(
id: ResourceLocation,
val title: String,
val description: String,
val icon: ResourceLocation,
val chance: Float = 1.0f
) {
@Transient
var identifier = id
internal set
}
@@ -0,0 +1,49 @@
package com.cobblemon.mod.common.api.pokemon.marks
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.MarksRegistrySyncPacket
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.cobblemon.mod.common.util.cobblemonResource
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.server.packs.PackType
object PokemonMarks: JsonDataRegistry<PokemonMark> {
override val id = cobblemonResource("marks")
override val type = PackType.SERVER_DATA
override val observable = SimpleObservable<PokemonMarks>()
override val gson = GsonBuilder()
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.create()
override val typeToken = TypeToken.get(PokemonMark::class.java)
override val resourcePath = "marks"
val marks = hashMapOf<ResourceLocation, PokemonMark>()
override fun reload(data: Map<ResourceLocation, PokemonMark>) {
this.marks.clear()
data.forEach { id, mark ->
try {
mark.identifier = id
this.marks[id] = mark
} catch(e: Exception) {
Cobblemon.LOGGER.error("Failed to load mark: {}", id, e)
}
}
Cobblemon.LOGGER.info("Loaded {} marks", this.marks.size)
this.observable.emit(this)
}
override fun sync(player: ServerPlayer) {
MarksRegistrySyncPacket(all()).sendToPlayer(player)
}
fun all() = this.marks.values.toList()
}
@@ -50,13 +50,13 @@ enum class Stats(override val identifier: ResourceLocation, override val display
val BATTLE_ONLY: Set<Stat> = EnumSet.of(EVASION, ACCURACY)
/** Gets the [Stat] from the respective Showdown id. */
fun getStat(statKey: String) = when(statKey.lowercase()) {
fun getStat(statKey: String) = when(statKey) {
"hp" -> HP
"atk", "attack" -> ATTACK // Hyper Cutter states the full stat name "Attack"
"def", "defense" -> DEFENCE // Big Pecks states the full stat name "Defense"
"atk", "Attack" -> ATTACK // Hyper Cutter states the full stat name "Attack"
"def", "Defense" -> DEFENCE // Big Pecks states the full stat name "Defense"
"spa" -> SPECIAL_ATTACK
"spd" -> SPECIAL_DEFENCE
"spe", "speed" -> SPEED
"spe" -> SPEED
"evasion" -> EVASION
else -> ACCURACY
}
@@ -18,7 +18,6 @@ import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.net.messages.client.data.ScriptRegistrySyncPacket
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.contextOrEmpty
import com.cobblemon.mod.common.util.endsWith
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
@@ -65,6 +64,6 @@ object CobblemonScripts : DataRegistry {
}
fun run(identifier: ResourceLocation, runtime: MoLangRuntime): MoValue? {
return scripts[identifier]?.resolve(runtime, runtime.contextOrEmpty)
return scripts[identifier]?.resolve(runtime)
}
}
@@ -52,7 +52,7 @@ open class PartyStore(override val uuid: UUID) : PokemonStore<PartyPosition>() {
override fun iterator() = slots.filterNotNull().iterator()
/** Gets the Pokémon at the specified slot. It will return null if the slot is empty or the given slot is out of bounds. */
fun get(slot: Int) = slot.takeIf { it < slots.size && it >= 0 }?.let { slots[it] }
operator fun get(slot: Int) = slot.takeIf { it < slots.size && it >= 0 }?.let { slots[it] }
override operator fun get(position: PartyPosition) = get(position.slot)
/** Sets the Pokémon at the specified slot. */
@@ -315,7 +315,7 @@ object BattleBuilder {
): BattleStartResult {
val playerTeam = party.toBattleTeam(clone = cloneParties, healPokemon = healFirst, leadingPokemon = leadingPokemon)
val playerActor = PlayerBattleActor(player.uuid, playerTeam)
val npcParty = npcEntity.getPartyForChallenge(listOf(player))
val npcParty = npcEntity.getPartyForChallenge(player)
val errors = ErroredBattleStart()
if (playerActor.pokemonList.size < battleFormat.battleType.slotsPerActor) {
@@ -10,14 +10,17 @@ package com.cobblemon.mod.common.battles.interpreter.instructions
import com.cobblemon.mod.common.api.battles.interpreter.BattleMessage
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.text.yellow
import com.cobblemon.mod.common.battles.ShowdownInterpreter
import com.cobblemon.mod.common.battles.dispatch.InstructionSet
import com.cobblemon.mod.common.battles.dispatch.InterpreterInstruction
import com.cobblemon.mod.common.entity.pokemon.effects.IllusionEffect
import com.cobblemon.mod.common.net.messages.client.battle.BattleSwapPokemonPacket
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.setPositionSafely
import com.cobblemon.mod.common.util.swap
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.phys.Vec3
import java.util.logging.Level
/**
@@ -29,30 +32,58 @@ import com.cobblemon.mod.common.util.swap
*/
class SwapInstruction(val message: BattleMessage, val instructionSet: InstructionSet): InterpreterInstruction {
override fun invoke(battle: PokemonBattle) {
// TODO: more error checks
battle.dispatchWaiting {
val battlePokemonA = message.battlePokemon(0, battle) ?: return@dispatchWaiting
val pnxA = message.argumentAt(0)?.substring(0, 3)
var posA: Vec3? = null
val (actor, activePokemonA) = battle.getActorAndActiveSlotFromPNX(pnxA!!)
if (battlePokemonA.entity == null) {
posA = ShowdownInterpreter.getSendoutPosition(battle, activePokemonA, battlePokemonA.actor)
} else {
posA = battlePokemonA.entity?.position()
}
val activeBattlePokemonB = activePokemonA.getAdjacentAllies().firstOrNull()
if (activeBattlePokemonB != null) {
if(activeBattlePokemonB != null) {
val pnxB = activeBattlePokemonB.getPNX()
val (actorB, activePokemonB) = battle.getActorAndActiveSlotFromPNX(pnxB)
// Swap the position of the 2 on the field
var posB: Vec3? = null
if (activePokemonB.battlePokemon?.entity == null) {
// target slot is likely fainted
posB = ShowdownInterpreter.getSendoutPosition(battle, activePokemonB, actorB)
} else {
posB = activePokemonB.battlePokemon?.entity?.position()
}
if (posB != null && battlePokemonA.entity != null) {
battlePokemonA.entity?.setPositionSafely(posB)
} else if(posB != null) {
if (activePokemonA.battlePokemon?.entity != null) {
activePokemonA.battlePokemon?.entity?.setPositionSafely(posB)
} else {
activePokemonB.position.let {
if (it != null) {
activePokemonB.position = Pair<ServerLevel, Vec3>(it.first, posB)
}
}
}
}
if(posA != null) {
if (activePokemonB.battlePokemon?.entity != null) {
activePokemonB.battlePokemon?.entity?.setPositionSafely(posA)
} else {
activePokemonA.position.let {
if (it != null) {
activePokemonB.position = Pair<ServerLevel, Vec3>(it.first, posA)
}
}
}
}
// Swap references of the 2 pokemon
actor.activePokemon.swap((pnxA[2] - 'a'), (pnxB[2] - 'a'))
val posA = ShowdownInterpreter.getSendoutPosition(battle, activePokemonA, battlePokemonA.actor) ?: activePokemonA.position?.second
if (posA != null && battlePokemonA.entity != null) {
battlePokemonA.entity?.setPositionSafely(battlePokemonA.entity!!.getAjustedSendoutPosition(posA))
}
val posB = ShowdownInterpreter.getSendoutPosition(battle, activePokemonB, battlePokemonA.actor) ?: activePokemonB.position?.second
val battlePokemonB = activePokemonB.battlePokemon
if (posB != null && battlePokemonB?.entity != null) {
activePokemonB.battlePokemon?.entity?.setPositionSafely(battlePokemonB.entity!!.getAjustedSendoutPosition(posB))
}
// Notify clients of the swap
battle.sendUpdate(BattleSwapPokemonPacket(pnxA))
@@ -12,6 +12,7 @@ import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.api.moves.MoveSet
import com.cobblemon.mod.common.api.pokemon.helditem.HeldItemManager
import com.cobblemon.mod.common.api.pokemon.helditem.HeldItemProvider
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.api.pokemon.stats.Stat
import com.cobblemon.mod.common.battles.actor.MultiPokemonBattleActor
import com.cobblemon.mod.common.battles.actor.PokemonBattleActor
@@ -24,6 +25,8 @@ import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.properties.BattleCloneProperty
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import java.util.UUID
import net.minecraft.network.chat.MutableComponent
@@ -82,7 +85,7 @@ open class BattlePokemon(
* The [HeldItemManager] backing this [BattlePokemon].
*/
val heldItemManager: HeldItemManager by lazy { HeldItemProvider.provide(this) }
val contextManager = ContextManager()
open fun getName(): MutableComponent {
@@ -91,6 +94,14 @@ open class BattlePokemon(
displayPokemon.getDisplayName()
} else {
battleLang("owned_pokemon", actor.getName(), displayPokemon.getDisplayName())
// val mark = effectedPokemon.selectedMark
val mark = PokemonMarks.marks[cobblemonResource("resurrected")]
if (mark != null) {
return lang(mark.title, effectedPokemon.getDisplayName())
} else {
battleLang("owned_pokemon", actor.getName(), effectedPokemon.getDisplayName())
}
}
}
@@ -8,14 +8,10 @@
package com.cobblemon.mod.common.block
import com.cobblemon.mod.common.CobblemonBlockEntities
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.block.entity.LecternBlockEntity
import com.cobblemon.mod.common.block.entity.ViewerCountBlockEntity
import com.cobblemon.mod.common.item.PokedexItem
import com.cobblemon.mod.common.net.messages.client.ui.PokedexUIPacket
import com.cobblemon.mod.common.util.playSoundServer
import com.cobblemon.mod.common.util.toVec3d
import com.mojang.serialization.MapCodec
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
@@ -33,7 +29,6 @@ import net.minecraft.world.level.Level
import net.minecraft.world.level.LevelReader
import net.minecraft.world.level.block.*
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.block.state.properties.DirectionProperty
@@ -57,8 +52,6 @@ class LecternBlock(properties: Properties): BaseEntityBlock(properties) {
override fun codec() = CODEC
override fun <T : BlockEntity> getTicker(world: Level, blockState: BlockState, BlockWithEntityType: BlockEntityType<T>) = createTickerHelper(BlockWithEntityType, CobblemonBlockEntities.LECTERN, ViewerCountBlockEntity.TICKER::tick)
override fun getRenderShape(blockState: BlockState?) = RenderShape.MODEL
override fun getOcclusionShape(blockState: BlockState?, blockGetter: BlockGetter?, blockPos: BlockPos?): VoxelShape = MinecraftLecternBlock.SHAPE_COMMON
@@ -124,15 +117,12 @@ class LecternBlock(properties: Properties): BaseEntityBlock(properties) {
if (!itemStack.isEmpty && itemStack.item is PokedexItem) {
if (!level.isClientSide) {
if (player.isCrouching) takeStoredItem(blockEntity, blockState, level, blockPos, player)
else {
blockEntity.incrementViewerCount()
PokedexUIPacket(type = (blockEntity.getItemStack().item as PokedexItem).type, blockPos = blockPos).sendToPlayer(player as ServerPlayer)
level.playSoundServer(position = blockPos.toVec3d(), sound = CobblemonSounds.POKEDEX_OPEN, volume = 0.25F)
}
else PokedexUIPacket((blockEntity.getItemStack().item as PokedexItem).type).sendToPlayer(player as ServerPlayer)
}
else if (!player.isCrouching) player.playSound(CobblemonSounds.POKEDEX_OPEN)
}
}
return InteractionResult.SUCCESS_NO_ITEM_USED
return InteractionResult.CONSUME
}
override fun isPathfindable(blockState: BlockState?, pathComputationType: PathComputationType?) = false
@@ -13,12 +13,17 @@ import net.minecraft.core.BlockPos
import net.minecraft.core.HolderLookup
import net.minecraft.core.NonNullList
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.protocol.Packet
import net.minecraft.network.protocol.game.ClientGamePacketListener
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket
import net.minecraft.world.ContainerHelper
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
class LecternBlockEntity(blockPos: BlockPos, blockState: BlockState) : ViewerCountBlockEntity(CobblemonBlockEntities.LECTERN, blockPos, blockState) {
class LecternBlockEntity(blockPos: BlockPos, blockState: BlockState) : BlockEntity(CobblemonBlockEntities.LECTERN, blockPos, blockState) {
val inventory: NonNullList<ItemStack> = NonNullList.withSize(1, ItemStack.EMPTY)
override fun saveAdditional(compoundTag: CompoundTag, registryLookup: HolderLookup.Provider) {
@@ -31,6 +36,10 @@ class LecternBlockEntity(blockPos: BlockPos, blockState: BlockState) : ViewerCou
ContainerHelper.loadAllItems(compoundTag, inventory, registryLookup)
}
override fun getUpdatePacket(): Packet<ClientGamePacketListener>? {
return ClientboundBlockEntityDataPacket.create(this)
}
override fun getUpdateTag(registryLookup: HolderLookup.Provider): CompoundTag {
return this.saveWithoutMetadata(registryLookup)
}
@@ -42,16 +51,23 @@ class LecternBlockEntity(blockPos: BlockPos, blockState: BlockState) : ViewerCou
fun setItemStack(itemStack: ItemStack) {
if (level != null) {
inventory[0] = itemStack
updateBlock(level!!)
onItemUpdate(level!!)
}
}
fun removeItemStack(): ItemStack {
if (level != null) {
val itemStack = ContainerHelper.removeItem(inventory, 0, 1)
updateBlock(level!!)
onItemUpdate(level!!)
return itemStack
}
return ItemStack.EMPTY
}
}
private fun onItemUpdate(level: Level) {
val oldState = level.getBlockState(blockPos)
level.sendBlockUpdated(blockPos, oldState, level.getBlockState(blockPos), Block.UPDATE_ALL)
level.updateNeighbourForOutputSignal(blockPos, level.getBlockState(blockPos).block)
setChanged()
}
}
@@ -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.block.entity
import com.cobblemon.mod.common.util.DataKeys
import net.minecraft.core.BlockPos
import net.minecraft.core.HolderLookup
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.protocol.Packet
import net.minecraft.network.protocol.game.ClientGamePacketListener
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket
import net.minecraft.world.entity.player.Player
import net.minecraft.world.level.ClipContext
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.entity.EntityTypeTest
import net.minecraft.world.phys.AABB
open class ViewerCountBlockEntity(type: BlockEntityType<*>?, blockPos: BlockPos, blockState: BlockState) : BlockEntity(type, blockPos, blockState) {
companion object {
internal val TICKER = BlockEntityTicker<ViewerCountBlockEntity> { world, _, _, blockEntity ->
if (world.isClientSide) return@BlockEntityTicker
blockEntity.checkUsers(blockEntity.getInRangeViewerCount(world, blockEntity.blockPos))
}
}
var viewerCount: Int = 0
private fun checkUsers(inRangeViewers: Int) {
if (inRangeViewers < viewerCount) changeViewerCount(inRangeViewers)
}
override fun saveAdditional(compoundTag: CompoundTag, registryLookup: HolderLookup.Provider) {
super.saveAdditional(compoundTag, registryLookup)
compoundTag.putInt(DataKeys.BLOCK_ENTITY_USER_AMOUNT, viewerCount)
}
override fun loadAdditional(compoundTag: CompoundTag, registryLookup: HolderLookup.Provider) {
super.loadAdditional(compoundTag, registryLookup)
viewerCount = if (compoundTag.contains(DataKeys.BLOCK_ENTITY_USER_AMOUNT)) compoundTag.getInt(DataKeys.BLOCK_ENTITY_USER_AMOUNT) else 0
}
override fun getUpdatePacket(): Packet<ClientGamePacketListener>? {
return ClientboundBlockEntityDataPacket.create(this)
}
override fun getUpdateTag(registryLookup: HolderLookup.Provider): CompoundTag {
return this.saveWithoutMetadata(registryLookup)
}
fun updateBlock(level: Level) {
val oldState = level.getBlockState(blockPos)
level.sendBlockUpdated(blockPos, oldState, level.getBlockState(blockPos), Block.UPDATE_ALL)
level.updateNeighbourForOutputSignal(blockPos, level.getBlockState(blockPos).block)
setChanged()
}
private fun isPlayerLookingAt(world: Level, player: Player, blockPos: BlockPos): Boolean {
val vec3 = player.eyePosition
val vec32 = vec3.add(player.calculateViewVector(player.xRot, player.yRot).scale(player.blockInteractionRange()))
val blockHitResult = world.clip(ClipContext(vec3, vec32, ClipContext.Block.OUTLINE, ClipContext.Fluid.ANY, player))
return blockPos == blockHitResult.blockPos
}
private fun getInRangeViewerCount(world: Level, pos: BlockPos, range: Double = 5.0): Int {
val box = AABB(
pos.x.toDouble() - range,
pos.y.toDouble() - range,
pos.z.toDouble() - range,
(pos.x + 1).toDouble() + range,
(pos.y + 1).toDouble() + range,
(pos.z + 1).toDouble() + range
)
return world.getEntities(EntityTypeTest.forClass(Player::class.java), box) { player: Player? -> isPlayerLookingAt(world, player!!, pos) }.size
}
fun changeViewerCount(amount: Int) {
if (level != null) {
viewerCount = maxOf(0, amount)
updateBlock(level!!)
}
}
fun incrementViewerCount() = changeViewerCount(viewerCount + 1)
fun decrementViewerCount() = changeViewerCount(viewerCount - 1)
}
@@ -9,6 +9,7 @@
package com.cobblemon.mod.common.client
import com.cobblemon.mod.common.BakingOverride
import com.cobblemon.mod.common.client.pokedex.PokedexTypes
import com.cobblemon.mod.common.util.cobblemonModel
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.client.resources.model.ModelResourceLocation
@@ -103,9 +104,51 @@ object CobblemonBakingOverrides {
cobblemonModel("surprise_mulch", "none")
)
// Items
val POKEDEX_BLACK = registerOverride(
cobblemonResource("item/pokedex_black_model"),
cobblemonModel("pokedex_black_model", "inventory")
)
val POKEDEX_BLUE = registerOverride(
cobblemonResource("item/pokedex_blue_model"),
cobblemonModel("pokedex_blue_model", "inventory")
)
val POKEDEX_GREEN = registerOverride(
cobblemonResource("item/pokedex_green_model"),
cobblemonModel("pokedex_green_model", "inventory")
)
val POKEDEX_PINK = registerOverride(
cobblemonResource("item/pokedex_pink_model"),
cobblemonModel("pokedex_pink_model", "inventory")
)
val POKEDEX_RED = registerOverride(
cobblemonResource("item/pokedex_red_model"),
cobblemonModel("pokedex_red_model", "inventory")
)
val POKEDEX_WHITE = registerOverride(
cobblemonResource("item/pokedex_white_model"),
cobblemonModel("pokedex_white_model", "inventory")
)
val POKEDEX_YELLOW = registerOverride(
cobblemonResource("item/pokedex_yellow_model"),
cobblemonModel("pokedex_yellow_model", "inventory")
)
fun getPokedexOverride(type: PokedexTypes): BakingOverride {
return when (type) {
PokedexTypes.BLACK -> POKEDEX_BLACK
PokedexTypes.BLUE -> POKEDEX_BLUE
PokedexTypes.GREEN -> POKEDEX_GREEN
PokedexTypes.PINK -> POKEDEX_PINK
PokedexTypes.WHITE -> POKEDEX_WHITE
PokedexTypes.YELLOW -> POKEDEX_YELLOW
PokedexTypes.RED -> POKEDEX_RED
}
}
fun registerOverride(modelLocation: ResourceLocation, modelIdentifier: ModelResourceLocation): BakingOverride {
val result = BakingOverride(modelLocation, modelIdentifier)
models.add(result)
return result
}
}
}
@@ -224,7 +224,7 @@ class PartyOverlay : Gui(Minecraft.getInstance()) {
drawScaledText(
context = context,
text = pokemon.getDisplayName(),
text = pokemon.getDisplayNameNoTitle(),
x = panelX + selectedOffsetX + 2.5F,
y = indexY + 25,
scale = SCALE
@@ -8,8 +8,8 @@
package com.cobblemon.mod.common.client.gui.npc
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.client.gui.npc.widgets.ConfigVariableList
import com.cobblemon.mod.common.client.gui.npc.widgets.NPCRenderWidget
import com.cobblemon.mod.common.client.gui.npc.widgets.SimpleNPCTextInputWidget
import com.cobblemon.mod.common.net.messages.client.npc.dto.NPCConfigurationDTO
@@ -27,6 +27,8 @@ class NPCEditorScreen(
companion object {
const val BASE_WIDTH = 331
const val BASE_HEIGHT = 161
private val baseResource = cobblemonResource("textures/gui/npc/editor_base.png")
}
val middleX: Int
@@ -41,13 +43,13 @@ class NPCEditorScreen(
override fun init() {
super.init()
addRenderableOnly(NPCRenderWidget(leftX + 6, topY + 22, dto.npcClass, dto.aspects))
addRenderableOnly(NPCRenderWidget(leftX + 6, topY + 32, dto.npcClass, dto.aspects))
addRenderableWidget(SimpleNPCTextInputWidget(
texture = cobblemonResource("textures/gui/npc/basic_text_input.png"),
getter = { dto.npcName.string },
setter = { dto.npcName = it.text() },
x = leftX + 6,
y = topY + 80,
x = leftX + 79,
y = topY + 14,
width = 130,
height = 22
))
@@ -58,8 +60,8 @@ class NPCEditorScreen(
dto.aspects.clear()
dto.aspects.addAll(it.split(",").map { it.trim() })
},
x = leftX + 6,
y = topY + 100,
x = leftX + 79,
y = topY + 36,
width = 130,
height = 40,
maxLength = 75,
@@ -71,23 +73,21 @@ class NPCEditorScreen(
SaveNPCPacket(npcId, dto).sendToServer()
this.minecraft!!.setScreen(null)
}
.pos(leftX + BASE_WIDTH - 42, topY + BASE_HEIGHT - 8)
.pos(leftX + BASE_WIDTH - 42, topY + BASE_HEIGHT - 18)
.size(40, 16)
.build()
)
addRenderableWidget(ConfigVariableList(leftX + 200, topY + 30, this))
}
override fun render(context: GuiGraphics, mouseX: Int, mouseY: Int, delta: Float) {
// blitk(
// matrixStack = context.pose(),
// texture = baseResource,
// x = leftX,
// y = topY,
// height = BASE_HEIGHT,
// width = BASE_WIDTH
// )
blitk(
matrixStack = context.pose(),
texture = baseResource,
x = leftX,
y = topY,
height = BASE_HEIGHT,
width = BASE_WIDTH
)
super.render(context, mouseX, mouseY, delta)
}
}
@@ -1,229 +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.npc.widgets
import com.cobblemon.mod.common.api.npc.NPCClasses
import com.cobblemon.mod.common.api.npc.configuration.NPCConfigVariable
import com.cobblemon.mod.common.api.npc.configuration.NPCConfigVariable.NPCVariableType
import com.cobblemon.mod.common.client.gui.npc.NPCEditorScreen
import com.cobblemon.mod.common.client.gui.npc.widgets.ConfigVariableList.ConfigVariable
import com.cobblemon.mod.common.client.render.drawScaledText
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.ContainerObjectSelectionList
import net.minecraft.client.gui.components.CycleButton
import net.minecraft.client.gui.components.EditBox
import net.minecraft.client.gui.components.Tooltip
import net.minecraft.client.gui.components.events.GuiEventListener
import net.minecraft.client.gui.narration.NarratableEntry
class ConfigVariableList(
val listX: Int,
val listY: Int,
val parent: NPCEditorScreen
) : ContainerObjectSelectionList<ConfigVariable>(
Minecraft.getInstance(),
WIDTH, // width
HEIGHT, // height
0, // top
SLOT_HEIGHT + SLOT_SPACING
) {
companion object {
const val WIDTH = 200
const val HEIGHT = 120
const val SLOT_WIDTH = 160
const val SLOT_HEIGHT = 33
const val SLOT_SPACING = 0
}
private var scrolling = false
override fun getRowWidth() = SLOT_WIDTH
init {
this.x = listX
this.y = listY
correctSize()
setRenderHeader(false, 0)
val npcClass = NPCClasses.getByIdentifier(parent.dto.npcClass)
if (npcClass != null) {
npcClass.config.forEach { t ->
val value = parent.dto.variables[t.variableName] ?: t.defaultValue
addEntry(ConfigVariable(t, value, this))
}
}
}
override fun getScrollbarPosition() = x + width - 3
public override fun addEntry(entry: ConfigVariable) = super.addEntry(entry)
public override fun removeEntry(entry: ConfigVariable) = super.removeEntry(entry)
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, partialTicks: Float) {
correctSize()
super.renderWidget(context, mouseX, mouseY, partialTicks)
// Scroll Overlay
// blitk(
// matrixStack = context.pose(),
// texture = scrollOverlayResource,
// x = listX,
// y = listY - 13,
// height = 131,
// width = WIDTH
// )
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
updateScrollingState(mouseX, mouseY)
if (scrolling) {
focused = getEntryAtPosition(mouseX, mouseY)
isDragging = true
}
return super.mouseClicked(mouseX, mouseY, button)
}
override fun mouseDragged(mouseX: Double, mouseY: Double, button: Int, deltaX: Double, deltaY: Double): Boolean {
if (scrolling) {
if (mouseY < this.listY) {
scrollAmount = 0.0
} else if (mouseY > bottom) {
scrollAmount = maxScroll.toDouble()
} else {
scrollAmount += deltaY
}
}
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
private fun updateScrollingState(mouseX: Double, mouseY: Double) {
scrolling = mouseX >= this.scrollbarPosition.toDouble()
&& mouseX < (this.scrollbarPosition + 3).toDouble()
&& mouseY >= listY
&& mouseY < bottom
}
override fun renderListBackground(context: GuiGraphics) {}
private fun correctSize() {
setRectangle(WIDTH, HEIGHT, listX, (listY - 4))
// setX(listX)
}
fun isHovered(mouseX: Double, mouseY: Double) = mouseX.toFloat() in (x.toFloat()..(x.toFloat() + WIDTH)) && mouseY.toFloat() in (y.toFloat()..(y.toFloat() + HEIGHT))
class ConfigVariable(val variable: NPCConfigVariable, val value: String, private val parent: ConfigVariableList) : Entry<ConfigVariable>() {
val client: Minecraft = Minecraft.getInstance()
var _focused = false
var children = mutableListOf<GuiEventListener>()
var textValue = value
var booleanValue = value.let { it.toDoubleOrNull() == 1.0 || it.toBooleanStrictOrNull() == true }
val editBox = EditBox(
client.font,
parent.listX,
parent.listY + 4,
if (variable.type == NPCVariableType.NUMBER) SLOT_WIDTH - 100 else SLOT_WIDTH,
SLOT_HEIGHT - 8,
variable.displayName,
).also {
it.tooltip = Tooltip.create(variable.description)
it.height = SLOT_HEIGHT - 16
it.setMaxLength(250)
it.value = value
it.setResponder {
textValue = it
parent.parent.dto.variables[variable.variableName] = it
}
if (variable.type == NPCVariableType.NUMBER) {
it.setFilter { value -> value.toDoubleOrNull() != null || value.isBlank() || value == "." || value == "-" }
}
}
val cycleButton = CycleButton.onOffBuilder(booleanValue).create(variable.displayName) { _, value ->
booleanValue = value
parent.parent.dto.variables[variable.variableName] = if (value) "1" else "0"
}.also {
it.height = SLOT_HEIGHT - 14
it.width = SLOT_WIDTH - 8
it.tooltip = Tooltip.create(variable.description)
}
init {
if (variable.type == NPCVariableType.BOOLEAN) {
children.add(cycleButton)
} else {
children.add(editBox)
}
}
override fun isFocused() = _focused
override fun setFocused(focused: Boolean) {
this._focused = focused
}
override fun children() = children
override fun narratables(): List<NarratableEntry> {
return children.filterIsInstance<NarratableEntry>()
}
override fun render(
context: GuiGraphics,
index: Int,
rowTop: Int,
rowLeft: Int,
rowWidth: Int,
rowHeight: Int,
mouseX: Int,
mouseY: Int,
isHovered: Boolean,
partialTicks: Float
) {
val x = rowLeft - 4
val y = rowTop
val matrixStack = context.pose()
// blitk(
// matrixStack = matrixStack,
// texture = slotResource,
// x = x,
// y = y,
// height = SLOT_HEIGHT,
// width = rowWidth,
// vOffset = if (isHovered) SLOT_HEIGHT else 0,
// textureHeight = SLOT_HEIGHT * 2
// )
if (variable.type == NPCVariableType.BOOLEAN) {
cycleButton.x = x
cycleButton.y = y + 6
cycleButton.render(context, mouseX, mouseY, partialTicks)
} else {
drawScaledText(
context = context,
text = variable.displayName.visualOrderText,
x = x,
y = y + 4
)
editBox.x = x
editBox.y = y + 14
editBox.render(context, mouseX, mouseY, partialTicks)
}
}
// override fun mouseClicked(mouseX: Double, mouseY: Double, delta: Int): Boolean {
// if (moveButton.isHovered(mouseX, mouseY) && canUnpasture()) {
// moveButton.onPress()
// return true
// }
// return false
// }
}
}
@@ -242,7 +242,7 @@ class PCGUI(
drawScaledText(
context = context,
font = CobblemonResources.DEFAULT_LARGE,
text = pokemon.getDisplayName().bold(),
text = pokemon.getDisplayNameNoTitle().bold(),
x = x + 12,
y = y + 11.5,
shadow = true
@@ -47,9 +47,8 @@ import com.cobblemon.mod.common.client.gui.pokedex.widgets.PokemonInfoWidget
import com.cobblemon.mod.common.client.gui.pokedex.widgets.SearchWidget
import com.cobblemon.mod.common.client.gui.pokedex.widgets.SizeWidget
import com.cobblemon.mod.common.client.gui.pokedex.widgets.StatsWidget
import com.cobblemon.mod.common.client.pokedex.PokedexType
import com.cobblemon.mod.common.client.pokedex.PokedexTypes
import com.cobblemon.mod.common.client.render.drawScaledText
import com.cobblemon.mod.common.net.messages.server.block.AdjustBlockEntityViewerCountPacket
import com.cobblemon.mod.common.pokemon.abilities.HiddenAbility
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
@@ -60,7 +59,6 @@ import net.minecraft.client.gui.components.events.GuiEventListener
import net.minecraft.client.gui.narration.NarratableEntry
import net.minecraft.client.gui.screens.Screen
import net.minecraft.client.resources.sounds.SimpleSoundInstance
import net.minecraft.core.BlockPos
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import net.minecraft.sounds.SoundEvent
@@ -72,9 +70,8 @@ import net.minecraft.sounds.SoundEvent
* @since February 24, 2024
*/
class PokedexGUI private constructor(
val type: PokedexType,
val initSpecies: ResourceLocation?,
val blockPos: BlockPos?
val type: PokedexTypes,
val initSpecies: ResourceLocation?
): Screen(Component.translatable("cobblemon.ui.pokedex.title")) {
companion object {
private val screenBackground = cobblemonResource("textures/gui/pokedex/pokedex_screen.png")
@@ -100,9 +97,9 @@ class PokedexGUI private constructor(
/**
* Attempts to open this screen for a client.
*/
fun open(pokedex: ClientPokedexManager, type: PokedexType, species: ResourceLocation? = null, blockPos: BlockPos? = null) {
fun open(pokedex: ClientPokedexManager, type: PokedexTypes, species: ResourceLocation? = null) {
val mc = Minecraft.getInstance()
val screen = PokedexGUI(type, species, blockPos)
val screen = PokedexGUI(type, species)
mc.setScreen(screen)
}
}
@@ -344,7 +341,6 @@ class PokedexGUI private constructor(
}
override fun onClose() {
if (blockPos != null) AdjustBlockEntityViewerCountPacket(blockPos, false).sendToServer()
playSound(CobblemonSounds.POKEDEX_CLOSE)
super.onClose()
}
@@ -9,7 +9,6 @@
package com.cobblemon.mod.common.client.gui.pokedex.widgets
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.api.gui.ParentWidget
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.pokedex.entry.PokedexEntry
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
@@ -689,7 +688,6 @@ class PokemonInfoWidget(val pX: Int, val pY: Int, val updateForm: (PokedexForm)
fun isWithinPortraitSpace(mouseX: Double, mouseY: Double): Boolean =
mouseX.toInt() in pX + 15..(pX + 15 + PORTRAIT_POKE_BALL_WIDTH)
&& mouseY.toInt() in pY + 25..(pY + 25 + PORTRAIT_POKE_BALL_HEIGHT)
&& !children.any { it.isMouseOver(mouseX, mouseY) && it is ScaledButton }
private fun isSelectedPokemonOwned(): Boolean {
return currentEntry?.let { CobblemonClient.clientPokedexData.getKnowledgeForSpecies(it.speciesId) } == PokedexEntryProgress.CAUGHT
@@ -52,7 +52,7 @@ class NicknameEntryWidget(
this.updateNickname(pokemonName)
}
}
value = pokemon.getDisplayName().string
value = pokemon.getDisplayNameNoTitle().string
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
@@ -166,7 +166,7 @@ class PartySlotWidget(
drawScaledText(
context = context,
text = slotPokemon.getDisplayName(),
text = slotPokemon.getDisplayNameNoTitle(),
x = x + 4,
y = y + 20,
scale = halfScale
@@ -18,7 +18,7 @@ import net.minecraft.client.Minecraft
object PokedexUIPacketHandler: ClientNetworkPacketHandler<PokedexUIPacket> {
override fun handle(packet: PokedexUIPacket, client: Minecraft) {
try {
PokedexGUI.open(CobblemonClient.clientPokedexData, packet.type, packet.initSpecies, packet.blockPos)
PokedexGUI.open(CobblemonClient.clientPokedexData, packet.type, packet.initSpecies)
} catch (e: Exception) {
Cobblemon.LOGGER.debug("Failed to open the Pokedex from the Pokedex UI packet", e)
}
@@ -10,16 +10,14 @@ package com.cobblemon.mod.common.client.pokedex
import com.cobblemon.mod.common.util.cobblemonResource
enum class PokedexType {
RED,
YELLOW,
GREEN,
BLUE,
PINK,
enum class PokedexTypes {
BLACK,
WHITE;
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()}")
}
@@ -14,7 +14,6 @@ import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.block.DisplayCaseBlock
import com.cobblemon.mod.common.block.entity.DisplayCaseBlockEntity
import com.cobblemon.mod.common.client.render.models.blockbench.repository.RenderContext
import com.cobblemon.mod.common.item.PokedexItem
import com.mojang.blaze3d.vertex.PoseStack
import com.mojang.math.Axis
import net.minecraft.client.Minecraft
@@ -160,7 +159,6 @@ class DisplayCaseRenderer(ctx: BlockEntityRendererProvider.Context) : BlockEntit
stack.item is BedItem -> PositioningType.BED
stack.item is BannerItem -> PositioningType.BANNER
stack.`is`(CobblemonItemTags.POKE_BALLS) -> PositioningType.POKE_BALL
stack.item is PokedexItem -> PositioningType.POKEDEX
stack.item == CobblemonItems.RELIC_COIN_POUCH -> PositioningType.COIN_POUCH
stack.item == CobblemonItems.PASTURE -> PositioningType.PASTURE
//stack.item == CobblemonItems.POKEMON_MODEL -> PositioningType.ITEM_MODEL
@@ -177,7 +175,6 @@ class DisplayCaseRenderer(ctx: BlockEntityRendererProvider.Context) : BlockEntit
val rotY: Float = 0f
) {
POKE_BALL(1f, 1f, 1f, 0f, 0.04f, 0f),
POKEDEX(1f, 1f, 1f, 0f, 0.04f, 0f, 180f),
BLOCK_MODEL(1f, 1f, 1f, 0f, -0.15f, 0f),
ITEM_MODEL(1f, 1f, 1f, 0f, 0.04f, 0f),
BED(1f, 1f, 1f, 0f, -0.02f, 0f),
@@ -8,30 +8,21 @@
package com.cobblemon.mod.common.client.render.block
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.ModAPI
import com.cobblemon.mod.common.block.entity.LecternBlockEntity
import com.cobblemon.mod.common.item.PokedexItem
import com.mojang.blaze3d.vertex.PoseStack
import com.mojang.math.Axis
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.MultiBufferSource
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider
import net.minecraft.client.resources.model.ModelResourceLocation
import net.minecraft.core.Direction
import net.minecraft.world.item.*
import net.minecraft.world.level.block.HorizontalDirectionalBlock
import net.minecraft.world.level.block.state.BlockState
import org.spongepowered.asm.mixin.Unique
class LecternBlockEntityRenderer(ctx: BlockEntityRendererProvider.Context) : BlockEntityRenderer<LecternBlockEntity> {
@Unique
private val MODEL_PATH = if (Cobblemon.implementation.modAPI == ModAPI.FABRIC) "fabric_resource" else "standalone"
override fun render(blockEntity: LecternBlockEntity, tickDelta: Float, poseStack: PoseStack, multiBufferSource: MultiBufferSource, light: Int, overlay: Int ) {
if (blockEntity !is LecternBlockEntity) return
if (!blockEntity.isEmpty()) {
@@ -44,15 +35,7 @@ class LecternBlockEntityRenderer(ctx: BlockEntityRendererProvider.Context) : Blo
poseStack.mulPose(Axis.YP.rotationDegrees(-yRot))
poseStack.mulPose(Axis.XP.rotationDegrees(22.5F))
poseStack.translate(0.0, 0.0, 0.13)
if (blockEntity.getItemStack().item is PokedexItem) {
val resourceLocation = (blockEntity.getItemStack().item as PokedexItem).type.getItemModelPath(if (blockEntity.viewerCount > 0) "flat" else "flat_off")
val model = Minecraft.getInstance().itemRenderer.itemModelShaper.getModelManager().getModel(ModelResourceLocation(resourceLocation, MODEL_PATH))
Minecraft.getInstance().itemRenderer.render(blockEntity.getItemStack(), ItemDisplayContext.GROUND, false, poseStack, multiBufferSource, light, overlay, model)
} else {
Minecraft.getInstance().itemRenderer.renderStatic(blockEntity.getItemStack(), ItemDisplayContext.GROUND, light, overlay, poseStack, multiBufferSource, blockEntity.level, 0)
}
Minecraft.getInstance().itemRenderer.renderStatic(blockEntity.getItemStack(), ItemDisplayContext.GROUND, light, overlay, poseStack, multiBufferSource, blockEntity.level, 0)
poseStack.popPose()
}
}
@@ -105,7 +105,7 @@ class BedrockSoundKeyframe(
if (entity != null) {
entity.level().playLocalSound(entity, soundEvent, entity.soundSource, 1F, 1F)
} else {
Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(soundEvent, 1F, 1F))
Minecraft.getInstance().soundManager.play(SimpleSoundInstance.forUI(soundEvent, 1F))
}
}
}
@@ -21,21 +21,21 @@ import com.cobblemon.mod.common.client.keybind.keybinds.PartySendBinding
import com.cobblemon.mod.common.client.render.models.blockbench.PosableModel
import com.cobblemon.mod.common.client.render.models.blockbench.PosableState
import com.cobblemon.mod.common.client.render.models.blockbench.pokemon.PosablePokemonEntityModel
import com.cobblemon.mod.common.client.render.models.blockbench.repository.MiscModelRepository
import com.cobblemon.mod.common.client.render.models.blockbench.repository.PokeBallModelRepository
import com.cobblemon.mod.common.client.render.models.blockbench.repository.PokemonModelRepository
import com.cobblemon.mod.common.client.render.models.blockbench.repository.RenderContext
import com.cobblemon.mod.common.client.render.pokeball.PokeBallPosableState
import com.cobblemon.mod.common.client.render.renderBeaconBeam
import com.cobblemon.mod.common.client.settings.ServerSettings
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity.Companion.SPAWN_DIRECTION
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.util.*
import com.cobblemon.mod.common.util.effectiveName
import com.cobblemon.mod.common.util.isLookingAt
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.math.DoubleRange
import com.cobblemon.mod.common.util.math.geometry.toRadians
import com.cobblemon.mod.common.util.math.remap
@@ -120,17 +120,6 @@ class PokemonRenderer(
clientDelegate
)
}
if(entity.platform != PlatformType.NONE) {
drawPlatform(
poseMatrix,
entity,
(entity.delegate as PokemonClientDelegate).entityScaleModifier,
buffer,
packedLight,
)
// keeps the pokemon's root on the raft
poseMatrix.translate(0.0, 0.25 * (entity.delegate as PokemonClientDelegate).entityScaleModifier, 0.0)
}
modelNow.setLayerContext(buffer, clientDelegate, PokemonModelRepository.getLayers(entity.pokemon.species.resourceIdentifier, clientDelegate))
@@ -360,7 +349,7 @@ class PokemonRenderer(
val matrix4f = matrices.last().pose()
val opacity = (Minecraft.getInstance().options.getBackgroundOpacity(0.25F) * 255.0F).toInt() shl 24
var label = if (ServerSettings.displayEntityNameLabel &&
!Cobblemon.config.displayNameForUnknownPokemon &&
!Cobblemon.config.diplayNameForUnknownPokemon &&
CobblemonClient.clientPokedexData.getKnowledgeForSpecies(entity.pokemon.species.resourceIdentifier) == PokedexEntryProgress.NONE) {
Component.literal("???")
} else if (ServerSettings.displayEntityNameLabel) {
@@ -436,23 +425,4 @@ class PokemonRenderer(
model.resetLayerContext()
matrixStack.popPose()
}
private fun drawPlatform(
matrixStack: PoseStack,
entity: PokemonEntity,
scale: Float = 1F,
buff: MultiBufferSource,
packedLight: Int,
) {
val (modelResource, textureResource) = PlatformType.getModelWithTexture(entity.platform)
val model = MiscModelRepository.modelOf(modelResource) ?: return
matrixStack.pushPose()
matrixStack.mulPose(Axis.ZP.rotationDegrees(180f))
matrixStack.rotateAround(Axis.YP.rotationDegrees(entity.entityData.get(SPAWN_DIRECTION)), 0.0f, 0f, 0.0f)
matrixStack.scale(scale, scale, scale)
val buffer = ItemRenderer.getFoilBufferDirect(buff, RenderType.entityCutout(textureResource), false, false)
model.render(matrixStack, buffer, packedLight, OverlayTexture.NO_OVERLAY, -0x1)
matrixStack.popPose()
}
}
@@ -9,10 +9,15 @@
package com.cobblemon.mod.common.command
import com.cobblemon.mod.common.api.permission.CobblemonPermissions
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.command.argument.PokemonPropertiesArgumentType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.alias
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.commandLang
import com.cobblemon.mod.common.util.permission
import com.cobblemon.mod.common.util.toBlockPos
@@ -25,6 +30,7 @@ import net.minecraft.commands.Commands.argument
import net.minecraft.commands.Commands.literal
import net.minecraft.commands.arguments.coordinates.Vec3Argument
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.phys.Vec3
import net.minecraft.world.level.Level
@@ -71,6 +77,8 @@ object SpawnPokemon {
throw NO_SPECIES_EXCEPTION.create()
}
val pokemonEntity = properties.createEntity(world)
println("${pokemonEntity.pokemon.marks}")
pokemonEntity.moveTo(pos.x, pos.y, pos.z, pokemonEntity.yRot, pokemonEntity.xRot)
pokemonEntity.entityData.set(PokemonEntity.SPAWN_DIRECTION, pokemonEntity.random.nextFloat() * 360F)
if (world.addFreshEntity(pokemonEntity)) {
@@ -16,6 +16,8 @@ import com.cobblemon.mod.common.api.abilities.Abilities
import com.cobblemon.mod.common.api.item.ability.AbilityChanger
import com.cobblemon.mod.common.api.npc.NPCClasses
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMark
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.api.scheduling.ServerTaskTracker
import com.cobblemon.mod.common.api.scheduling.taskBuilder
import com.cobblemon.mod.common.api.text.green
@@ -38,41 +40,68 @@ import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.mojang.brigadier.Command
import com.mojang.brigadier.CommandDispatcher
import com.mojang.brigadier.arguments.StringArgumentType
import com.mojang.brigadier.context.CommandContext
import com.mojang.brigadier.suggestion.SuggestionProvider
import com.mojang.brigadier.suggestion.Suggestions
import com.mojang.brigadier.suggestion.SuggestionsBuilder
import net.minecraft.commands.CommandSourceStack
import net.minecraft.commands.Commands
import net.minecraft.server.level.ServerPlayer
import net.minecraft.network.chat.Component
import net.minecraft.world.phys.AABB
import com.mojang.serialization.JsonOps
import com.sun.jdi.connect.Connector
import net.minecraft.commands.SharedSuggestionProvider
import net.minecraft.commands.arguments.ResourceLocationArgument
import net.minecraft.resources.ResourceLocation
import java.io.File
import java.io.PrintWriter
import java.util.concurrent.CompletableFuture
import kotlin.collections.get
import kotlin.comparisons.then
import kotlin.text.get
@Suppress("unused")
object TestCommand {
private val MARK_SUGGESTIONS: SuggestionProvider<CommandSourceStack> = SuggestionProvider { context, builder ->
suggestMarks(builder)
}
fun register(dispatcher: CommandDispatcher<CommandSourceStack>) {
val command = Commands.literal("testcommand")
.requires { it.hasPermission(4) }
.executes(::execute)
.then(Commands.argument("mark", ResourceLocationArgument.id())
.suggests(MARK_SUGGESTIONS)
.executes(::execute))
dispatcher.register(command)
}
private fun suggestMarks(builder: SuggestionsBuilder): CompletableFuture<Suggestions> {
return SharedSuggestionProvider.suggest(PokemonMarks.marks.keys.map { it.toString() }, builder)
}
@Suppress("SameReturnValue")
private fun execute(context: CommandContext<CommandSourceStack>): Int {
if (context.source.entity !is ServerPlayer) {
return Command.SINGLE_SUCCESS
}
val player = context.source.playerOrException
val mark: PokemonMark = PokemonMarks.marks[ResourceLocationArgument.getId(context, "mark")]!!
player.party()[0]!!.marks.add(mark)
try {
//this.testCodecOutput(context)
val player = context.source.entity as ServerPlayer
player.party().forEach { it.currentHealth = it.hp / 2 }
val npc = NPCEntity(player.level())
npc.setPos(player.x, player.y, player.z)
npc.npc = NPCClasses.getByName("standard")!!
npc.initialize(50)
player.level().addFreshEntity(npc)
// val player = context.source.entity as ServerPlayer
// player.party().forEach { it.currentHealth = it.hp / 2 }
// val npc = NPCEntity(player.level())
// npc.setPos(player.x, player.y, player.z)
// npc.npc = NPCClasses.getByName("standard")!!
// npc.initialize(50)
// player.level().addFreshEntity(npc)
// val evolutionEntity = GenericBedrockEntity(world = player.level())
// evolutionEntity.apply {
// category = cobblemonResource("evolution")
@@ -178,7 +178,7 @@ class CobblemonConfig {
var displayEntityNameLabel = true
@NodeCategory(Category.Pokemon)
var displayNameForUnknownPokemon = false
var diplayNameForUnknownPokemon = false
@NodeCategory(Category.Pokemon)
var displayEntityLabelsWhenCrouchingOnly = true
@@ -10,7 +10,6 @@ package com.cobblemon.mod.common.data
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.CobblemonFlows
import com.cobblemon.mod.common.CobblemonBrainConfigs
import com.cobblemon.mod.common.CobblemonMechanics
import com.cobblemon.mod.common.api.abilities.Abilities
@@ -37,6 +36,7 @@ import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.pokemon.feature.GlobalSpeciesFeatures
import com.cobblemon.mod.common.api.pokemon.feature.SpeciesFeatureAssignments
import com.cobblemon.mod.common.api.pokemon.feature.SpeciesFeatures
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
import com.cobblemon.mod.common.api.spawning.CobblemonSpawnPools
import com.cobblemon.mod.common.api.spawning.CobblemonSpawnRules
@@ -92,7 +92,7 @@ object CobblemonDataProvider : DataProvider {
this.register(DexEntryAdditions)
this.register(Dexes)
this.register(DexAdditions)
this.register(CobblemonFlows)
this.register(PokemonMarks)
CobblemonSpawnPools.load()
this.register(PokeRods)
@@ -1,61 +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.entity
import com.cobblemon.mod.common.pokemon.FormData
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.resources.ResourceLocation
import java.util.EnumSet
/**
* The type of a platform. Used to give pokemon a "surface" to stand on over water.
*
* @author JazzMcNade
* @since September 29th, 2024
*/
enum class PlatformType {
NONE,
WATER_XS,
WATER_S,
WATER_M,
WATER_L,
WATER_XL;
companion object {
val WATER = EnumSet.of(WATER_XS, WATER_S, WATER_M, WATER_L, WATER_XL)
fun getModelWithTexture(type: PlatformType) : Pair<ResourceLocation, ResourceLocation> {
return when (type) {
WATER_XS -> Pair(cobblemonResource("water_platform_xs.geo"), cobblemonResource("textures/platforms/water_platform_xs.png"))
WATER_S -> Pair(cobblemonResource("water_platform_s.geo"), cobblemonResource("textures/platforms/water_platform_s.png"))
WATER_M -> Pair(cobblemonResource("water_platform_m.geo"), cobblemonResource("textures/platforms/water_platform_m.png"))
WATER_L -> Pair(cobblemonResource("water_platform_l.geo"), cobblemonResource("textures/platforms/water_platform_l.png"))
WATER_XL -> Pair(cobblemonResource("water_platform_xl.geo"), cobblemonResource("textures/platforms/water_platform_xl.png"))
else -> Pair(cobblemonResource("water_platform_xs.geo"), cobblemonResource("textures/platforms/water_platform_xs"))
}
}
fun getPlatformTypeForPokemon(form: FormData) : PlatformType {
val width = form.hitbox.width * form.baseScale
return if (width <= 0.511) {
WATER_XS
} else if (width < 1.01) {
WATER_S
} else if (width < 1.8) {
WATER_M
} else if (width < 2.875) {
WATER_L
} else {
WATER_XL
}
}
}
}
@@ -16,7 +16,7 @@ import net.minecraft.world.entity.ai.behavior.declarative.Trigger
import net.minecraft.world.entity.ai.memory.MemoryModuleType
object AttackAngryAtTask {
fun create(): OneShot<in LivingEntity> = BehaviorBuilder.create {
fun create(): OneShot<in LivingEntity> = BehaviorBuilder.create {
it.group(
it.present(MemoryModuleType.ANGRY_AT),
it.registered(MemoryModuleType.ATTACK_TARGET)
@@ -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.entity.ai
import com.bedrockk.molang.Expression
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.google.common.collect.ImmutableMap
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.Behavior
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.MemoryStatus
class LookInDirectionTask(
val yaw: Expression = "0".asExpression(),
val pitch: Expression = "0".asExpression()
) : Behavior<LivingEntity>(ImmutableMap.of(MemoryModuleType.LOOK_TARGET, MemoryStatus.VALUE_ABSENT), 0, 0) {
override fun canStillUse(level: ServerLevel, entity: LivingEntity, gameTime: Long): Boolean {
return !entity.brain.getMemory(MemoryModuleType.LOOK_TARGET).isPresent
}
override fun checkExtraStartConditions(level: ServerLevel, owner: LivingEntity): Boolean {
return owner is PathfinderMob && !owner.brain.getMemory(MemoryModuleType.LOOK_TARGET).isPresent
}
override fun stop(level: ServerLevel, entity: LivingEntity, gameTime: Long) {
}
override fun tick(level: ServerLevel, entity: LivingEntity, gameTime: Long) {
entity as PathfinderMob
val runtime = MoLangRuntime().setup()
runtime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val yaw = (runtime.resolveFloat(this.yaw) + 90) * Math.PI / 180.0
val pitch = runtime.resolveFloat(this.pitch) * Math.PI / 180.0 * -1
val xDisp = Math.cos(yaw)
val zDisp = Math.sin(yaw)
val yDisp = Math.sin(pitch)
entity.lookControl.setLookAt(entity.x + xDisp, entity.y + entity.eyeHeight + yDisp, entity.z + zDisp)
}
}
@@ -350,7 +350,7 @@ class PokeRodFishingBobberEntity(type: EntityType<out PokeRodFishingBobberEntity
entityData.set(CAUGHT_FISH, true)
}
} else if (this.waitCountdown > 0) {
this.waitCountdown -= i + lureLevel
this.waitCountdown -= i
var f = 0.15f
if (this.waitCountdown < 20) {
f += (20 - this.waitCountdown).toFloat() * 0.05f
@@ -392,9 +392,10 @@ class PokeRodFishingBobberEntity(type: EntityType<out PokeRodFishingBobberEntity
// set the time it takes to wait for a hooked item or pokemon
this.waitCountdown = Mth.nextInt(random, 100, 600)
this.waitCountdown -= this.lureLevel * 20 * 5
if (this.waitCountdown <= 0)
this.waitCountdown = 1
if (this.waitCountdown < 0)
this.waitCountdown = 0
else {
// check for the bait on the hook and see if the waitCountdown is reduced
if (checkReduceBiteTime(bobberBait))
@@ -732,7 +733,7 @@ class PokeRodFishingBobberEntity(type: EntityType<out PokeRodFishingBobberEntity
hookedEntity = level().getEntity(hookedEntityID)
}
afterOnServer(seconds = 1.0F) {
afterOnServer(seconds = 0.1F) {
if (player !in player.level().players()) {
return@afterOnServer
}
@@ -8,6 +8,7 @@
package com.cobblemon.mod.common.entity.npc
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.api.battles.model.actor.AIBattleActor
import com.cobblemon.mod.common.api.battles.model.actor.ActorType
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
@@ -48,6 +49,11 @@ class NPCBattleActor(
skill
)
override fun setupStruct() {
super.setupStruct()
struct.addFunction("skill") { DoubleValue(skill) }
}
override fun sendUpdate(packet: NetworkPacket<*>) {
super.sendUpdate(packet)
if (packet is BattleEndPacket) {
@@ -126,20 +126,17 @@ class NPCEntity(world: Level) : AgeableMob(CobblemonEntities.NPC, world), Npc, P
var allowProjectileHits: Boolean? = null
fun getPartyForChallenge(players: List<ServerPlayer>): NPCPartyStore? {
fun getPartyForChallenge(player: ServerPlayer): NPCPartyStore? {
val party = this.party
return if (party != null) {
party
} else if (npc.party?.isStatic == false) {
npc.party?.provide(this, level, players)
npc.party?.provide(this, level)
} else {
null
}
}
/** Oi, dev, you no touch this one. This one is for [com.cobblemon.mod.common.api.npc.variation.NPCVariationProvider]s. */
val variationAspects = mutableSetOf<String>()
/** You can add to this one if you want, that's ok. */
val appliedAspects = mutableSetOf<String>()
override val delegate = if (world.isClientSide) {
com.cobblemon.mod.common.client.entity.NPCClientDelegate()
@@ -286,7 +283,7 @@ class NPCEntity(world: Level) : AgeableMob(CobblemonEntities.NPC, world), Npc, P
override fun getBrain() = super.getBrain() as Brain<NPCEntity>
fun updateAspects() {
entityData.set(ASPECTS, appliedAspects + variationAspects)
entityData.set(ASPECTS, appliedAspects)
}
fun isInBattle() = battleIds.isNotEmpty()
@@ -320,7 +317,6 @@ class NPCEntity(world: Level) : AgeableMob(CobblemonEntities.NPC, world), Npc, P
nbt.put(DataKeys.NPC_LEVEL, IntTag.valueOf(level))
nbt.putString(DataKeys.NPC_CLASS, npc.id.toString())
nbt.put(DataKeys.NPC_ASPECTS, ListTag().also { list -> appliedAspects.forEach { list.add(StringTag.valueOf(it)) } })
nbt.put(DataKeys.NPC_VARIATION_ASPECTS, ListTag().also { list -> variationAspects.forEach { list.add(StringTag.valueOf(it)) } })
interaction?.let {
val interactionNBT = CompoundTag()
interactionNBT.putString(DataKeys.NPC_INTERACT_TYPE, it.type)
@@ -378,7 +374,6 @@ class NPCEntity(world: Level) : AgeableMob(CobblemonEntities.NPC, world), Npc, P
data = MoLangFunctions.readMoValueFromNBT(nbt.getCompound(DataKeys.NPC_DATA)) as VariableStruct
config = if (nbt.contains(DataKeys.NPC_CONFIG)) MoLangFunctions.readMoValueFromNBT(nbt.getCompound(DataKeys.NPC_CONFIG)) as VariableStruct else VariableStruct()
appliedAspects.addAll(nbt.getList(DataKeys.NPC_ASPECTS, Tag.TAG_STRING.toInt()).map { it.asString })
variationAspects.addAll(nbt.getList(DataKeys.NPC_VARIATION_ASPECTS, Tag.TAG_STRING.toInt()).map { it.asString })
nbt.getCompound(DataKeys.NPC_INTERACTION).takeIf { !it.isEmpty }?.let { nbt ->
val type = nbt.getString("type")
val configType = NPCInteractConfiguration.types[type] ?: return@let
@@ -454,10 +449,10 @@ class NPCEntity(world: Level) : AgeableMob(CobblemonEntities.NPC, world), Npc, P
}
fun initialize(level: Int) {
variationAspects.clear()
appliedAspects.clear()
entityData.set(LEVEL, level)
npc.config.forEach { it.applyDefault(this) }
npc.variations.values.forEach { this.variationAspects.addAll(it.provideAspects(this)) }
npc.variations.values.forEach { this.appliedAspects.addAll(it.provideAspects(this)) }
if (party == null || npc.party != null) {
party = npc.party?.takeIf { it.isStatic }?.provide(this, level)
}
@@ -46,7 +46,6 @@ import com.cobblemon.mod.common.net.messages.client.effect.SpawnSnowstormEntityP
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokeballPacket
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
import com.cobblemon.mod.common.util.asArrayValue
import com.cobblemon.mod.common.util.*
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
@@ -119,7 +118,6 @@ class EmptyPokeBallEntity : ThrowableItemProjectile, PosableEntity, WaterDragMod
override val struct = QueryStruct(hashMapOf())
.addFunction("capture_state") { StringValue(captureState.name) }
.addFunction("ball_type") { StringValue(pokeBall.name.toString()) }
.addFunction("aspects") { aspects.asArrayValue { StringValue(it) } }
override fun defineSynchedData(builder: SynchedEntityData.Builder) {
pokeBall = PokeBalls.POKE_BALL
@@ -8,11 +8,9 @@
package com.cobblemon.mod.common.entity.pokemon
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonEntities
import com.cobblemon.mod.common.CobblemonItems
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.cobblemon.mod.common.*
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.drop.DropTable
import com.cobblemon.mod.common.api.entity.Despawner
import com.cobblemon.mod.common.api.entity.PokemonSender
@@ -26,8 +24,6 @@ import com.cobblemon.mod.common.api.molang.MoLangFunctions.addEntityFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addPokemonEntityFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addPokemonFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addStandardFunctions
import com.cobblemon.mod.common.api.molang.ObjectValue
import com.cobblemon.mod.common.api.net.serializers.PlatformTypeDataSerializer
import com.cobblemon.mod.common.api.net.serializers.PoseTypeDataSerializer
import com.cobblemon.mod.common.api.net.serializers.StringSetDataSerializer
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
@@ -49,7 +45,6 @@ import com.cobblemon.mod.common.battles.BattleBuilder
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.block.entity.PokemonPastureBlockEntity
import com.cobblemon.mod.common.client.entity.PokemonClientDelegate
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.PosableEntity
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.generic.GenericBedrockEntity
@@ -76,28 +71,14 @@ import com.cobblemon.mod.common.pokemon.activestate.InactivePokemonState
import com.cobblemon.mod.common.pokemon.activestate.ShoulderedState
import com.cobblemon.mod.common.pokemon.ai.FormPokemonBehaviour
import com.cobblemon.mod.common.pokemon.evolution.variants.ItemInteractionEvolution
import com.cobblemon.mod.common.pokemon.feature.StashHandler
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.getBitForByte
import com.cobblemon.mod.common.util.giveOrDropItemStack
import com.cobblemon.mod.common.util.isPokemonEntity
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.party
import com.cobblemon.mod.common.util.playSoundServer
import com.cobblemon.mod.common.util.setBitForByte
import com.cobblemon.mod.common.util.toNbtList
import com.cobblemon.mod.common.pokemon.feature.StashHandler
import com.cobblemon.mod.common.util.*
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules
import com.mojang.serialization.Codec
import java.util.EnumSet
import java.util.Optional
import java.util.UUID
import java.util.concurrent.CompletableFuture
import net.minecraft.core.BlockPos
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.core.registries.Registries
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.NbtOps
import net.minecraft.nbt.NbtUtils
import net.minecraft.nbt.StringTag
import net.minecraft.network.chat.Component
@@ -106,10 +87,14 @@ import net.minecraft.network.protocol.Packet
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket
import net.minecraft.network.protocol.game.ClientGamePacketListener
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket
import net.minecraft.network.protocol.game.DebugPackets
import net.minecraft.network.syncher.EntityDataAccessor
import net.minecraft.network.syncher.EntityDataSerializers
import net.minecraft.network.syncher.SynchedEntityData
import com.mojang.serialization.Codec
import net.minecraft.nbt.NbtOps
import net.minecraft.network.protocol.game.DebugPackets
import java.util.*
import java.util.concurrent.CompletableFuture
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerEntity
import net.minecraft.server.level.ServerLevel
@@ -122,15 +107,7 @@ import net.minecraft.world.InteractionResult
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.damagesource.DamageTypes
import net.minecraft.world.effect.MobEffects
import net.minecraft.world.entity.AgeableMob
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.EntityDimensions
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.entity.ExperienceOrb
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.Pose
import net.minecraft.world.entity.Shearable
import net.minecraft.world.entity.*
import net.minecraft.world.entity.ai.attributes.AttributeSupplier
import net.minecraft.world.entity.ai.attributes.Attributes
import net.minecraft.world.entity.ai.control.MoveControl
@@ -164,7 +141,6 @@ open class PokemonEntity(
@JvmStatic val MOVING = SynchedEntityData.defineId(PokemonEntity::class.java, EntityDataSerializers.BOOLEAN)
@JvmStatic val BEHAVIOUR_FLAGS = SynchedEntityData.defineId(PokemonEntity::class.java, EntityDataSerializers.BYTE)
@JvmStatic val PHASING_TARGET_ID = SynchedEntityData.defineId(PokemonEntity::class.java, EntityDataSerializers.INT)
@JvmStatic val PLATFORM_TYPE = SynchedEntityData.defineId(PokemonEntity::class.java, PlatformTypeDataSerializer)
@JvmStatic val BEAM_MODE = SynchedEntityData.defineId(PokemonEntity::class.java, EntityDataSerializers.BYTE)
@JvmStatic val BATTLE_ID = SynchedEntityData.defineId(PokemonEntity::class.java, EntityDataSerializers.OPTIONAL_UUID)
@JvmStatic val ASPECTS = SynchedEntityData.defineId(PokemonEntity::class.java, StringSetDataSerializer)
@@ -284,16 +260,11 @@ open class PokemonEntity(
/** The pokeball exposed to the client. Used for sendout animation. */
val exposedBall: PokeBall get() = this.effects.mockEffect?.exposedBall ?: this.pokemon.caughtBall
var platform : PlatformType
get() = entityData.get(PLATFORM_TYPE)
set(value) { entityData.set(PLATFORM_TYPE, value) }
override val struct: ObjectValue<PokemonEntity> = ObjectValue(this).also {
it.addStandardFunctions()
.addEntityFunctions(this)
.addPokemonFunctions(pokemon)
.addPokemonEntityFunctions(this)
}
override val struct: QueryStruct = QueryStruct(hashMapOf())
.addStandardFunctions()
.addEntityFunctions(this)
.addPokemonFunctions(pokemon)
.addPokemonEntityFunctions(this)
init {
@@ -312,7 +283,6 @@ open class PokemonEntity(
builder.define(MOVING, false)
builder.define(BEHAVIOUR_FLAGS, 0)
builder.define(BEAM_MODE, 0)
builder.define(PLATFORM_TYPE, PlatformType.NONE)
builder.define(PHASING_TARGET_ID, -1)
builder.define(BATTLE_ID, Optional.empty())
builder.define(ASPECTS, emptySet())
@@ -363,7 +333,7 @@ open class PokemonEntity(
// val targetPos = node?.blockPos
// if (targetPos == null || world.getBlockState(targetPos.up()).isAir) {
return if (state.`is`(FluidTags.WATER) && !isEyeInFluid(FluidTags.WATER)) {
behaviour.moving.swim.canWalkOnWater || platform != PlatformType.NONE
behaviour.moving.swim.canWalkOnWater
} else if (state.`is`(FluidTags.LAVA) && !isEyeInFluid(FluidTags.LAVA)) {
behaviour.moving.swim.canWalkOnLava
} else {
@@ -389,21 +359,9 @@ open class PokemonEntity(
override fun tick() {
super.tick()
if (isBattling) {
// Deploy a platform if a non-wild Pokemon is touching water but not underwater.
// This can't be done in the BattleMovementGoal as the sleep goal will override it.
if (ticksLived > 5 && platform == PlatformType.NONE
&& this.ownerUUID != null
&& isInWater && !isUnderWater
&& !exposedForm.behaviour.moving.swim.canBreatheUnderwater && !exposedForm.behaviour.moving.swim.canWalkOnWater) {
platform = PlatformType.getPlatformTypeForPokemon((exposedForm))
}
} else {
// Battle clone destruction
if (this.beamMode == 0 && this.isBattleClone()) {
discard()
return
}
if (!this.isBattling && this.beamMode == 0 && this.isBattleClone()) {
discard()
return
}
// We will be handling idle logic ourselves thank you
@@ -682,10 +640,6 @@ open class PokemonEntity(
enablePoseTypeRecalculation = nbt.getBoolean(DataKeys.POKEMON_RECALCULATE_POSE)
}
if (nbt.contains(DataKeys.POKEMON_PLATFORM_TYPE)) {
entityData.set(PLATFORM_TYPE, PlatformType.valueOf(nbt.getString(DataKeys.POKEMON_PLATFORM_TYPE)))
}
CobblemonEvents.POKEMON_ENTITY_LOAD.postThen(
event = PokemonEntityLoadEvent(this, nbt),
ifSucceeded = {},
@@ -1163,90 +1117,6 @@ open class PokemonEntity(
return true
}
/**
* Adjusts a given sent out position based on the local environment.
* Returns the new position and a PlatformType if the pokemon should be placed on one.
*/
fun getAjustedSendoutPosition(pos: Vec3) : Vec3 {
var platform = PlatformType.NONE
var blockPos = BlockPos(pos.x.toInt(), pos.y.toInt(), pos.z.toInt())
var blockLookCount = 5
var foundSurface = false
val form = this.exposedForm
var result = pos
if (this.level().isWaterAt(blockPos)) {
// look upward for a water surface
var testPos = blockPos
if (!form.behaviour.moving.swim.canBreatheUnderwater || form.behaviour.moving.fly.canFly) {
// move sendout pos to surface if it's near
for (i in 0..blockLookCount) {
// Try to find a surface...
val blockState = this.level().getBlockState(testPos)
if (blockState.fluidState.isEmpty) {
if(blockState.getCollisionShape(this.level(), testPos).isEmpty) {
foundSurface = true
}
// No space above the water surface
break
}
testPos = testPos.above()
}
if (foundSurface) {
val hasHeadRoom = !collidesWithBlock(Vec3(blockPos.x.toDouble(), (blockPos.y).toDouble(), (blockPos.z).toDouble()))
if (hasHeadRoom) {
result = Vec3(result.x, testPos.y.toDouble(), result.z)
}
} else {
foundSurface = false
}
}
} else if (this.level().isEmptyBlock(blockPos)) {
// look downward for a water surface
blockLookCount = 64 // Higher because the pokemon can fall down to water below
var testPos = BlockPos(pos.x.toInt(), pos.y.toInt(), pos.z.toInt())
for (i in 0..blockLookCount) {
// Try to find a surface...
val blockState = this.level().getBlockState(testPos)
if (!blockState.fluidState.isEmpty) {
foundSurface = true
break
}
if (!blockState.getCollisionShape(this.level(), testPos).isEmpty) {
break
}
testPos = testPos.below()
}
}
if (foundSurface) {
val canFly = form.behaviour.moving.fly.canFly
if (canFly) {
val hasHeadRoom = !collidesWithBlock(Vec3(blockPos.x.toDouble(), (result.y + 1), (blockPos.z).toDouble()))
if (hasHeadRoom) {
result = Vec3(result.x, result.y + 1.0, result.z)
}
} else if (form.behaviour.moving.swim.canBreatheUnderwater && !form.behaviour.moving.swim.canWalkOnWater) {
// Use half hitbox height for swimmers
val halfHeight = form.hitbox.height * form.baseScale / 2.0
for (i in 1..halfHeight.toInt()) {
blockPos = blockPos.below()
if (!this.level().isWaterAt(blockPos) || !this.level().getBlockState(blockPos).getCollisionShape(this.level(), blockPos).isEmpty) {
break
}
}
result = Vec3(result.x, result.y + halfHeight - halfHeight.toInt(), result.z)
} else {
platform = if (form.behaviour.moving.swim.canWalkOnWater || collidesWithBlock(Vec3(result.x, result.y, result.z))) PlatformType.NONE else PlatformType.getPlatformTypeForPokemon(form)
}
}
this.platform = platform
return result
}
private fun Entity.collidesWithBlock(pos: Vec3) : Boolean {
return level().getBlockCollisions(this, boundingBox.move(pos)).iterator().hasNext()
}
override fun remove(reason: RemovalReason) {
val stateEntity = (pokemon.state as? ActivePokemonState)?.entity
super.remove(reason)
@@ -1326,10 +1196,6 @@ open class PokemonEntity(
super.travel(movementInput)
this.updateBlocksTraveled(prevBlockPos)
}
if (isBattling && this.isInWater) {
// Prevent swimmers from sinking in battle
this.deltaMovement = Vec3(deltaMovement.x, 0.0, deltaMovement.z)
}
}
private fun updateBlocksTraveled(fromBp: BlockPos) {
@@ -16,7 +16,6 @@ import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.activestate.ActivePokemonState
@@ -115,7 +114,7 @@ class PokemonServerDelegate : PokemonSideDelegate {
}
entity.entityData.set(PokemonEntity.ASPECTS, trackedAspects)
entity.entityData.set(PokemonEntity.LABEL_LEVEL, entity.pokemon.level)
entity.entityData.set(PokemonEntity.MOVING, entity.platform == PlatformType.NONE && entity.deltaMovement.multiply(1.0, if (entity.onGround()) 0.0 else 1.0, 1.0).length() > 0.005F)
entity.entityData.set(PokemonEntity.MOVING, entity.deltaMovement.multiply(1.0, if (entity.onGround()) 0.0 else 1.0, 1.0).length() > 0.005F)
entity.entityData.set(PokemonEntity.FRIENDSHIP, entity.pokemon.friendship)
entity.entityData.set(PokemonEntity.CAUGHT_BALL, trackedBall)
@@ -12,7 +12,6 @@ import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addStandardFunctions
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
@@ -27,13 +26,12 @@ import net.minecraft.tags.FluidTags
import net.minecraft.util.Mth
import net.minecraft.world.entity.ai.attributes.Attributes
import net.minecraft.world.entity.ai.control.MoveControl
import net.minecraft.world.level.material.FluidState
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.AABB
import net.minecraft.world.phys.Vec3
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
class PokemonMoveControl(val pokemonEntity: PokemonEntity) : MoveControl(pokemonEntity) {
companion object {
@@ -44,8 +42,6 @@ class PokemonMoveControl(val pokemonEntity: PokemonEntity) : MoveControl(pokemon
it.environment.query.addStandardFunctions().addFunctions(pokemonEntity.struct.functions)
}
private var waterLevel : Double = 0.0
override fun tick() {
if (pokemonEntity.pokemon.status?.status == Statuses.SLEEP || pokemonEntity.isDeadOrDying) {
pokemonEntity.speed = 0F
@@ -193,106 +189,12 @@ class PokemonMoveControl(val pokemonEntity: PokemonEntity) : MoveControl(pokemon
}
// Float
if (mob.isEyeInFluid(FluidTags.WATER) && behaviour.moving.swim.canSwimInWater && !this.pokemonEntity.isBattling) {
if (mob.isEyeInFluid(FluidTags.WATER) && behaviour.moving.swim.canSwimInWater) {
pokemonEntity.yya = 0.2F
}
// In battle water antics
// Borrowing hard from Minecraft's Boat logic
if (this.pokemonEntity.isBattling && mob.isInWater) {
var e = 0.0F
val exposedForm = this.pokemonEntity.exposedForm
if (isUnderwater()) {
if (this.pokemonEntity.platform != PlatformType.NONE) {
// Float up if on a platform
e = 0.3F
}
} else if (checkInWater()) {
if (this.pokemonEntity.platform != PlatformType.NONE ) {
// Hold Steady
e = ((this.waterLevel - this.pokemonEntity.y) / this.pokemonEntity.bbHeight).toFloat()
} else if (exposedForm.behaviour.moving.swim.canBreatheUnderwater) {
// allow swimmers to sink a bit into the water
e = -1.5F
}
}
if (Mth.abs(e) > VERY_CLOSE) {
val vec32: Vec3 = this.pokemonEntity.deltaMovement
this.pokemonEntity.setDeltaMovement(vec32.x, (vec32.y + e * (this.pokemonEntity.gravity / 0.65)) * 0.75, vec32.z)
}
}
}
}
/*
* Returns the ideal water level y position of a given pokemon during battle.
* This is separate for the eye height check and is dependent on if the pokemon is rafted or swimming.
*/
private fun getStableBattleFloatHeight(): Double {
val aABB: AABB = this.pokemonEntity.boundingBox
return if (this.pokemonEntity.exposedForm.behaviour.moving.swim.canBreatheUnderwater) ((aABB.maxY - aABB.minY) / 2.0) else 0.05
}
/*
* Returns true if a pokemon is touching a water block.
* Based on vanilla Minecraft's Boat.checkInWater()
*/
private fun checkInWater(): Boolean {
val aABB: AABB = mob.boundingBox
val i = Mth.floor(aABB.minX)
val j = Mth.ceil(aABB.maxX)
val k = Mth.floor(aABB.minY)
val l = Mth.ceil(aABB.minY + 0.001)
val m = Mth.floor(aABB.minZ)
val n = Mth.ceil(aABB.maxZ)
var bl = false
this.waterLevel = -1.7976931348623157E308
val mutableBlockPos = BlockPos.MutableBlockPos()
for (o in i until j) {
for (p in k until l) {
for (q in m until n) {
mutableBlockPos[o, p] = q
val fluidState: FluidState = mob.level().getFluidState(mutableBlockPos)
if (fluidState.`is`(FluidTags.WATER)) {
val f = p.toFloat() + fluidState.getHeight(mob.level(), mutableBlockPos)
this.waterLevel = max(f.toDouble(), waterLevel)
bl = bl or (aABB.minY < f.toDouble())
}
}
}
}
return bl
}
/*
* Returns true if a pokemon's y level is below it's idealized float height in battle.
* Based on vanilla Minecraft's Boat.isUnderWater()
*/
private fun isUnderwater(): Boolean {
val aABB: AABB = this.pokemonEntity.boundingBox
val d = aABB.minY + getStableBattleFloatHeight()
val i = Mth.floor(aABB.minX)
val j = Mth.ceil(aABB.maxX)
val k = Mth.floor(aABB.minY)
val l = Mth.ceil(aABB.maxY)
val m = Mth.floor(aABB.minZ)
val n = Mth.ceil(aABB.maxZ)
val bl = false
val mutableBlockPos = BlockPos.MutableBlockPos()
for (o in i until j) {
for (p in k until l) {
for (q in m until n) {
mutableBlockPos[o, p] = q
val fluidState: FluidState = mob.level().getFluidState(mutableBlockPos)
if (fluidState.`is`(FluidTags.WATER) && d < (mutableBlockPos.y.toFloat() + fluidState.getHeight(mob.level(), mutableBlockPos)).toDouble()) {
return true
}
}
}
}
return bl
}
private fun isWalkable(xMovement: Float, zMovement: Float): Boolean {
val entityNavigation = mob.navigation
val pathNodeMaker = entityNavigation.nodeEvaluator
@@ -36,7 +36,7 @@ class PokemonNavigation(val world: Level, val pokemonEntity: PokemonEntity) : Gr
// Lazy init because navigation is instantiated during entity construction and pokemonEntity.form isn't set yet.
// (pokemonEntity.behaviour is a shortcut to pokemonEntity.form.behaviour)
// It's JVM field instantiation order stuff, too niche to explain further.
val moving: MoveBehaviour by lazy { pokemonEntity.exposedSpecies.behaviour.moving }
val moving: MoveBehaviour by lazy { pokemonEntity.behaviour.moving }
var cachedCurrentNode: Node? = null
var currentNodeDistance = 0F
@@ -176,7 +176,7 @@ class PokemonNavigation(val world: Level, val pokemonEntity: PokemonEntity) : Gr
var target = target
var blockPos: BlockPos
if (this.world.getBlockState(target).isAir && !pokemonEntity.exposedSpecies.behaviour.moving.fly.canFly) {
if (this.world.getBlockState(target).isAir && !pokemonEntity.behaviour.moving.fly.canFly) {
blockPos = target.below()
while (blockPos.y > this.world.minBuildHeight && this.world.getBlockState(blockPos).isAir) {
blockPos = blockPos.below()
@@ -237,7 +237,7 @@ class PokemonNavigation(val world: Level, val pokemonEntity: PokemonEntity) : Gr
// pokemonEntity.discard()
// return false
// If we just started moving and it's to an open node, fly
if (node.type == PathType.OPEN && pokemonEntity.exposedForm.behaviour.moving.fly.canFly && !pokemonEntity.isFlying()) {
if (node.type == PathType.OPEN && pokemonEntity.form.behaviour.moving.fly.canFly && !pokemonEntity.isFlying()) {
pokemonEntity.setBehaviourFlag(PokemonBehaviourFlag.FLYING, true)
}
}
@@ -9,24 +9,17 @@
package com.cobblemon.mod.common.entity.pokemon.ai.goals
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import net.minecraft.world.entity.ai.goal.Goal
import net.minecraft.world.phys.Vec3
class PokemonInBattleMovementGoal(val entity: PokemonEntity, val range: Int) : Goal() {
var battlePos : Vec3? = null
var hasMovedToPos = false
override fun canUse(): Boolean {
return entity.isBattling && entity.getCurrentPoseType() != PoseType.SLEEP
return entity.isBattling && getClosestPokemonEntity() != null && entity.getCurrentPoseType() != PoseType.SLEEP
}
override fun start() {
super.start()
battlePos = entity.position()
entity.navigation.stop()
}
@@ -43,21 +36,5 @@ class PokemonInBattleMovementGoal(val entity: PokemonEntity, val range: Int) : G
if (closestPokemonEntity != null) {
entity.lookControl.setLookAt(closestPokemonEntity.x, closestPokemonEntity.eyeY, closestPokemonEntity.z)
}
if (entity.exposedForm.behaviour.moving.fly.canFly) {
// Flyer logic
if (!hasMovedToPos) {
entity.navigation.moveTo(battlePos!!.x, battlePos!!.y, battlePos!!.z, 1.0)
hasMovedToPos = true
}
if (entity.ticksLived > 1 && !entity.onGround() && !entity.getBehaviourFlag(PokemonBehaviourFlag.FLYING)) {
// Let flyers fly in battle if they're in the air
entity.setBehaviourFlag(PokemonBehaviourFlag.FLYING, true)
}
}
if (entity.platform != PlatformType.NONE && entity.onGround()) {
// If the pokemon is on a non-fluid surface, remove the platform.
entity.platform = PlatformType.NONE
}
}
}
@@ -12,7 +12,6 @@ import com.cobblemon.mod.common.api.entity.pokemon.*
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonPropertyExtractor
import com.cobblemon.mod.common.api.scheduling.afterOnServer
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.effect.SpawnSnowstormEntityParticlePacket
import com.cobblemon.mod.common.pokemon.Pokemon
@@ -46,12 +45,6 @@ class IllusionEffect(
override fun revert(entity: PokemonEntity, future: CompletableFuture<PokemonEntity>) {
entity.effects.mockEffect = null
if (!entity.exposedForm.behaviour.moving.fly.canFly && entity.getBehaviourFlag(PokemonBehaviourFlag.FLYING)) {
// Transitioning from a flying form to a non-flying form.
// If we were flying, need to turn the behavior flag off or the pokemon will continue to float in the air.
entity.setBehaviourFlag(PokemonBehaviourFlag.FLYING, false)
}
afterOnServer(seconds = 1.0F) {
entity.cry()
if (entity.pokemon.shiny) SpawnSnowstormEntityParticlePacket(cobblemonResource("shiny_ring"), entity.id, listOf("shiny_particles", "middle")).sendToPlayersAround(entity.x, entity.y, entity.z, 64.0, entity.level().dimension())
@@ -1,25 +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.events
import com.cobblemon.mod.common.CobblemonFlows
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.util.cobblemonResource
/**
* Handles the registration of the default Cobblemon event hooks into flows.
*/
object FlowHandler {
fun setup() {
CobblemonEvents.POKEMON_CAPTURED.subscribe { CobblemonFlows.run(cobblemonResource("pokemon_captured"), it.context) }
CobblemonEvents.BATTLE_VICTORY.subscribe { CobblemonFlows.run(cobblemonResource("battle_victory"), it.context) }
}
}
@@ -9,7 +9,7 @@
package com.cobblemon.mod.common.item
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.pokedex.PokedexType
import com.cobblemon.mod.common.client.pokedex.PokedexTypes
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.isLookingAt
import net.minecraft.client.player.LocalPlayer
@@ -24,7 +24,7 @@ import net.minecraft.world.item.UseAnim
import net.minecraft.world.level.Level
import net.minecraft.world.phys.AABB
class PokedexItem(val type: PokedexType): CobblemonItem(Item.Properties().stacksTo(1)) {
class PokedexItem(val type: PokedexTypes): CobblemonItem(Item.Properties().stacksTo(1)) {
override fun getUseAnimation(itemStack: ItemStack): UseAnim? = UseAnim.TOOT_HORN
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.item.interactive.ability
import com.cobblemon.mod.common.api.abilities.*
import com.cobblemon.mod.common.api.item.ability.AbilityChanger
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.abilities.HiddenAbilityType
// TODO Polish me down the line when we actually release the item in the mod, we need a way to select the ability
@@ -21,11 +20,8 @@ open class AbilityTypeChanger<T : PotentialAbility>(
) : AbilityChanger<T> {
override fun queryPossible(pokemon: Pokemon): Set<AbilityTemplate> {
val currentType = this.findCurrent(pokemon)
val targetType = if (currentType == HiddenAbilityType) CommonAbilityType else this.type
return pokemon.form.abilities
.filter { it.type == targetType && it.template != pokemon.ability.template }
val ofType = pokemon.form.abilities.filter { it.type == this.type }
return ofType.filter { it.template != pokemon.ability.template }
.map { it.template }
.toSet()
}
@@ -1,56 +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.CobblemonFlows
import com.cobblemon.mod.common.api.molang.ExpressionLike
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readIdentifier
import com.cobblemon.mod.common.util.readString
import com.cobblemon.mod.common.util.writeIdentifier
import com.cobblemon.mod.common.util.writeString
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.resources.ResourceLocation
/**
* A packet that synchronizes the flow registry with the client.
*
* @author Hiroku
* @since February 24th, 2024
*/
class FlowRegistrySyncPacket(entries: Collection<Map.Entry<ResourceLocation, List<ExpressionLike>>>) : DataRegistrySyncPacket<Map.Entry<ResourceLocation, List<ExpressionLike>>, FlowRegistrySyncPacket>(entries){
companion object {
val ID = cobblemonResource("flow_registry_sync")
fun decode(buffer: RegistryFriendlyByteBuf): FlowRegistrySyncPacket = FlowRegistrySyncPacket(emptyList()).apply { decodeBuffer(buffer) }
}
override val id = ID
override fun encodeEntry(buffer: RegistryFriendlyByteBuf, entry: Map.Entry<ResourceLocation, List<ExpressionLike>>) {
buffer.writeIdentifier(entry.key)
buffer.writeCollection(entry.value) { _, expression -> buffer.writeString(expression.toString()) }
}
override fun decodeEntry(buffer: RegistryFriendlyByteBuf): Map.Entry<ResourceLocation, List<ExpressionLike>> {
val key = buffer.readIdentifier()
val value = buffer.readList { buffer.readString().asExpressionLike() }
return object : Map.Entry<ResourceLocation, List<ExpressionLike>> {
override val key = key
override val value = value
}
}
override fun synchronizeDecoded(entries: Collection<Map.Entry<ResourceLocation, List<ExpressionLike>>>) {
entries.map { (identifier, flows) ->
val existing = CobblemonFlows.clientFlows.getOrPut(identifier) { mutableListOf() }
existing += flows
}
}
}
@@ -0,0 +1,42 @@
package com.cobblemon.mod.common.net.messages.client.data
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMark
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readIdentifier
import com.cobblemon.mod.common.util.readString
import com.cobblemon.mod.common.util.writeIdentifier
import com.cobblemon.mod.common.util.writeString
import net.minecraft.network.RegistryFriendlyByteBuf
class MarksRegistrySyncPacket(marks: List<PokemonMark>): DataRegistrySyncPacket<PokemonMark, MarksRegistrySyncPacket>(marks) {
companion object {
val ID = cobblemonResource("marks")
fun decode(buffer: RegistryFriendlyByteBuf) = MarksRegistrySyncPacket(emptyList()).apply { decodeBuffer(buffer) }
}
override val id = ID
override fun encodeEntry(buffer: RegistryFriendlyByteBuf, entry: PokemonMark) {
buffer.writeIdentifier(entry.identifier)
buffer.writeIdentifier(entry.icon)
buffer.writeString(entry.title)
buffer.writeString(entry.description)
buffer.writeFloat(entry.chance)
}
override fun decodeEntry(buffer: RegistryFriendlyByteBuf): PokemonMark {
return PokemonMark(
id = buffer.readIdentifier(),
icon = buffer.readIdentifier(),
title = buffer.readString(),
description = buffer.readString(),
chance = buffer.readFloat()
)
}
override fun synchronizeDecoded(entries: Collection<PokemonMark>) {
PokemonMarks.reload(entries.associateBy { it.identifier })
}
}
@@ -16,13 +16,7 @@ import com.cobblemon.mod.common.api.npc.configuration.NPCBattleConfiguration
import com.cobblemon.mod.common.api.npc.configuration.NPCInteractConfiguration
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readIdentifier
import com.cobblemon.mod.common.util.readString
import com.cobblemon.mod.common.util.readText
import com.cobblemon.mod.common.util.writeIdentifier
import com.cobblemon.mod.common.util.writeString
import com.cobblemon.mod.common.util.writeText
import com.cobblemon.mod.common.util.*
import io.netty.buffer.ByteBuf
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.network.chat.MutableComponent
@@ -35,7 +29,6 @@ class NPCConfigurationDTO : Encodable, Decodable {
var interactionInherited: Boolean = false
var interaction: NPCInteractConfiguration? = null
var aspects: MutableSet<String> = mutableSetOf()
var variables: MutableMap<String, String> = mutableMapOf()
constructor()
@@ -46,7 +39,6 @@ class NPCConfigurationDTO : Encodable, Decodable {
interactionInherited = npcEntity.interaction == null
interaction = npcEntity.interaction ?: npcEntity.npc.interaction
aspects = npcEntity.appliedAspects
variables = npcEntity.config.map.map { it.key to it.value.asString() }.toMap().toMutableMap()
}
override fun encode(buffer: RegistryFriendlyByteBuf) {
@@ -59,11 +51,6 @@ class NPCConfigurationDTO : Encodable, Decodable {
value.encode(buffer)
}
buffer.writeCollection(aspects, ByteBuf::writeString)
buffer.writeMap(
variables,
{ _, it -> buffer.writeString(it) },
{ _, it -> buffer.writeString(it) },
)
}
override fun decode(buffer: RegistryFriendlyByteBuf) {
@@ -77,10 +64,6 @@ class NPCConfigurationDTO : Encodable, Decodable {
configType.clazz.getConstructor().newInstance().also { it.decode(buffer) }
}
aspects = buffer.readList { buffer.readString() }.toMutableSet()
variables = buffer.readMap(
{ buffer.readString() },
{ buffer.readString() },
).toMutableMap()
}
fun apply(entity: NPCEntity) {
@@ -95,9 +78,5 @@ class NPCConfigurationDTO : Encodable, Decodable {
}
entity.appliedAspects.clear()
entity.appliedAspects.addAll(aspects)
variables.forEach { (key, value) ->
val variable = entity.npc.config.find { it.variableName == key } ?: return@forEach
entity.config.setDirectly(key, variable.type.toMoValue(value))
}
}
}
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.net.messages.client.spawn
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.Gender
@@ -34,7 +33,6 @@ class SpawnPokemonPacket(
private val battleId: UUID?,
private val phasingTargetId: Int,
private val beamMode: Byte,
private val platform: PlatformType,
private val nickname: MutableComponent?,
private val labelLevel: Int,
private val poseType: PoseType,
@@ -60,7 +58,6 @@ class SpawnPokemonPacket(
entity.battleId,
entity.phasingTargetId,
entity.beamMode.toByte(),
entity.platform,
entity.pokemon.nickname,
if (Cobblemon.config.displayEntityLevelLabel) entity.entityData.get(PokemonEntity.LABEL_LEVEL) else -1,
entity.entityData.get(PokemonEntity.POSE_TYPE),
@@ -84,7 +81,6 @@ class SpawnPokemonPacket(
buffer.writeNullable(this.battleId) { pb, value -> pb.writeUUID(value) }
buffer.writeInt(this.phasingTargetId)
buffer.writeByte(this.beamMode.toInt())
buffer.writeEnumConstant(this.platform)
buffer.writeNullable(this.nickname) { _, v -> buffer.writeText(v) }
buffer.writeInt(this.labelLevel)
buffer.writeEnumConstant(this.poseType)
@@ -110,7 +106,6 @@ class SpawnPokemonPacket(
}
entity.phasingTargetId = this.phasingTargetId
entity.beamMode = this.beamMode.toInt()
entity.platform = this.platform
entity.battleId = this.battleId
entity.entityData.set(PokemonEntity.LABEL_LEVEL, labelLevel)
entity.entityData.set(PokemonEntity.SPECIES, entity.pokemon.species.resourceIdentifier.toString())
@@ -138,7 +133,6 @@ class SpawnPokemonPacket(
val battleId = buffer.readNullable { buffer.readUUID() }
val phasingTargetId = buffer.readInt()
val beamModeEmitter = buffer.readByte()
val platform = buffer.readEnumConstant(PlatformType::class.java)
val nickname = buffer.readNullable { buffer.readText().copy() }
val labelLevel = buffer.readInt()
val poseType = buffer.readEnumConstant(PoseType::class.java)
@@ -150,7 +144,7 @@ class SpawnPokemonPacket(
val freezeFrame = buffer.readFloat()
val vanillaPacket = decodeVanillaPacket(buffer)
return SpawnPokemonPacket(ownerId, scaleModifier, speciesId, gender, shiny, formName, aspects, battleId, phasingTargetId, beamModeEmitter, platform, nickname, labelLevel, poseType, unbattlable, hideLabel, caughtBall, spawnAngle, friendship, freezeFrame, vanillaPacket)
return SpawnPokemonPacket(ownerId, scaleModifier, speciesId, gender, shiny, formName, aspects, battleId, phasingTargetId, beamModeEmitter, nickname, labelLevel, poseType, unbattlable, hideLabel, caughtBall, spawnAngle, friendship, freezeFrame, vanillaPacket)
}
}
@@ -10,9 +10,14 @@ package com.cobblemon.mod.common.net.messages.client.ui
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.client.net.gui.PokedexUIPacketHandler
import com.cobblemon.mod.common.client.pokedex.PokedexType
import com.cobblemon.mod.common.util.*
import net.minecraft.core.BlockPos
import com.cobblemon.mod.common.client.pokedex.PokedexTypes
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readEnumConstant
import com.cobblemon.mod.common.util.readIdentifier
import com.cobblemon.mod.common.util.readString
import com.cobblemon.mod.common.util.writeEnumConstant
import com.cobblemon.mod.common.util.writeIdentifier
import com.cobblemon.mod.common.util.writeString
import net.minecraft.network.RegistryFriendlyByteBuf
import net.minecraft.resources.ResourceLocation
@@ -21,19 +26,18 @@ import net.minecraft.resources.ResourceLocation
*
* Handled by [PokedexUIPacketHandler].
*/
class PokedexUIPacket(val type: PokedexType, val initSpecies: ResourceLocation? = null, val blockPos: BlockPos? = null): NetworkPacket<PokedexUIPacket> {
class PokedexUIPacket(val type: PokedexTypes, val initSpecies: ResourceLocation? = null): NetworkPacket<PokedexUIPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeEnumConstant(type)
buffer.writeNullable(initSpecies) { pb, value -> pb.writeIdentifier(value) }
buffer.writeNullable(blockPos) { pb, value -> pb.writeBlockPos(value) }
}
companion object {
val ID = cobblemonResource("pokedex_ui")
fun decode(buffer: RegistryFriendlyByteBuf) = PokedexUIPacket(buffer.readEnumConstant(PokedexType::class.java), buffer.readNullable { it.readIdentifier() }, buffer.readNullable { it.readBlockPos() })
fun decode(buffer: RegistryFriendlyByteBuf) = PokedexUIPacket(buffer.readEnumConstant(PokedexTypes::class.java), buffer.readNullable { it.readIdentifier() })
}
}
@@ -1,31 +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.server.block
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.net.serverhandling.block.AdjustBlockEntityViewerCountHandler
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.core.BlockPos
import net.minecraft.network.RegistryFriendlyByteBuf
/**
* Handled by [AdjustBlockEntityViewerCountHandler].
*/
class AdjustBlockEntityViewerCountPacket(val blockPos: BlockPos, val increment: Boolean) : NetworkPacket<AdjustBlockEntityViewerCountPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeBlockPos(blockPos)
buffer.writeBoolean(increment)
}
companion object {
val ID = cobblemonResource("adjust_block_entity_viewer_count")
fun decode(buffer: RegistryFriendlyByteBuf): AdjustBlockEntityViewerCountPacket = AdjustBlockEntityViewerCountPacket(buffer.readBlockPos(), buffer.readBoolean())
}
}
@@ -1,25 +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.serverhandling.block
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.block.entity.ViewerCountBlockEntity
import com.cobblemon.mod.common.net.messages.server.block.AdjustBlockEntityViewerCountPacket
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object AdjustBlockEntityViewerCountHandler : ServerNetworkPacketHandler<AdjustBlockEntityViewerCountPacket> {
override fun handle(packet: AdjustBlockEntityViewerCountPacket, server: MinecraftServer, player: ServerPlayer) {
val blockEntity = player.level().getBlockEntity(packet.blockPos)
if (blockEntity != null && blockEntity is ViewerCountBlockEntity) {
if (packet.increment) blockEntity.incrementViewerCount()
else blockEntity.decrementViewerCount()
}
}
}
@@ -8,9 +8,6 @@
package com.cobblemon.mod.common.pokeball
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokeball.catching.CaptureEffect
import com.cobblemon.mod.common.api.pokeball.catching.CatchRateModifier
@@ -42,12 +39,6 @@ open class PokeBall(
val throwPower: Float,
val ancient: Boolean
) {
val struct = QueryStruct(hashMapOf())
.addFunction("name") { StringValue(name.toString()) }
.addFunction("water_drag_value") { DoubleValue(waterDragValue) }
.addFunction("throw_power") { DoubleValue(throwPower) }
.addFunction("is_ancient") { DoubleValue(ancient) }
// .addFunction("item") { } // requires a registry which is hard
// This gets attached during item registry
internal lateinit var item: PokeBallItem
@@ -14,7 +14,7 @@ import com.cobblemon.mod.common.api.pokedex.PokedexLearnedInformation
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.pokedex.PokedexGUI
import com.cobblemon.mod.common.client.pokedex.PokedexScannerRenderer
import com.cobblemon.mod.common.client.pokedex.PokedexType
import com.cobblemon.mod.common.client.pokedex.PokedexTypes
import com.cobblemon.mod.common.net.messages.client.pokedex.ServerConfirmedRegisterPacket
import com.cobblemon.mod.common.net.messages.server.pokedex.scanner.FinishScanningPacket
import com.cobblemon.mod.common.net.messages.server.pokedex.scanner.StartScanningPacket
@@ -60,7 +60,7 @@ class PokedexUsageContext {
var innerRingRotation: Float = 0F
var zoomLevel: Float = 0F
var newPokemonInfo: PokedexLearnedInformation = PokedexLearnedInformation.NONE
var type: PokedexType = PokedexType.RED
var type: PokedexTypes = PokedexTypes.RED
var availableInfoFrames: MutableList<Boolean?> = mutableListOf(null, null, null, null)
val renderer: PokedexScannerRenderer = PokedexScannerRenderer()
@@ -128,7 +128,7 @@ class PokedexUsageContext {
}
}
fun openPokedexGUI(types: PokedexType = PokedexType.RED, speciesId: ResourceLocation? = null) {
fun openPokedexGUI(types: PokedexTypes = PokedexTypes.RED, speciesId: ResourceLocation? = null) {
PokedexGUI.open(CobblemonClient.clientPokedexData, types, speciesId)
playSound(CobblemonSounds.POKEDEX_OPEN)
}
@@ -14,8 +14,6 @@ import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.abilities.Abilities
import com.cobblemon.mod.common.api.abilities.Ability
import com.cobblemon.mod.common.api.abilities.AbilityPool
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.api.battles.model.actor.EntityBackedBattleActor
import com.cobblemon.mod.common.api.data.ShowdownIdentifiable
import com.cobblemon.mod.common.api.entity.PokemonSender
import com.cobblemon.mod.common.api.events.CobblemonEvents
@@ -50,6 +48,8 @@ import com.cobblemon.mod.common.api.pokemon.feature.SynchronizedSpeciesFeature
import com.cobblemon.mod.common.api.pokemon.feature.SynchronizedSpeciesFeatureProvider
import com.cobblemon.mod.common.api.pokemon.friendship.FriendshipMutationCalculator
import com.cobblemon.mod.common.api.pokemon.labels.CobblemonPokemonLabels
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMark
import com.cobblemon.mod.common.api.pokemon.marks.PokemonMarks
import com.cobblemon.mod.common.api.pokemon.moves.LearnsetQuery
import com.cobblemon.mod.common.api.pokemon.stats.Stat
import com.cobblemon.mod.common.api.pokemon.stats.Stats
@@ -66,12 +66,10 @@ import com.cobblemon.mod.common.api.types.ElementalType
import com.cobblemon.mod.common.api.types.ElementalTypes
import com.cobblemon.mod.common.api.types.tera.TeraType
import com.cobblemon.mod.common.api.types.tera.TeraTypes
import com.cobblemon.mod.common.battles.ActiveBattlePokemon
import com.cobblemon.mod.common.battles.ShowdownInterpreter
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.config.CobblemonConfig
import com.cobblemon.mod.common.datafixer.CobblemonSchemas
import com.cobblemon.mod.common.datafixer.CobblemonTypeReferences
import com.cobblemon.mod.common.entity.PlatformType
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.effects.IllusionEffect
@@ -110,6 +108,7 @@ import com.cobblemon.mod.common.util.playSoundServer
import com.cobblemon.mod.common.util.server
import com.cobblemon.mod.common.util.setPositionSafely
import com.cobblemon.mod.common.util.toBlockPos
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.mojang.datafixers.util.Pair
import com.mojang.serialization.Codec
@@ -127,6 +126,7 @@ import kotlin.random.Random
import net.minecraft.core.BlockPos
import net.minecraft.core.RegistryAccess
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import net.minecraft.nbt.NbtOps
import net.minecraft.nbt.StringTag
import net.minecraft.network.RegistryFriendlyByteBuf
@@ -134,6 +134,7 @@ import net.minecraft.network.chat.MutableComponent
import net.minecraft.network.chat.contents.PlainTextContents
import net.minecraft.network.codec.ByteBufCodecs
import net.minecraft.network.codec.StreamCodec
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.tags.FluidTags
@@ -152,7 +153,8 @@ import net.minecraft.world.level.block.MagmaBlock
import net.minecraft.world.level.block.SweetBerryBushBlock
import net.minecraft.world.level.block.WitherRoseBlock
import net.minecraft.world.phys.Vec3
import kotlin.math.*
import kotlin.collections.get
import kotlin.toString
enum class OriginalTrainerType : StringRepresentable {
NONE, PLAYER, NPC;
@@ -234,7 +236,14 @@ open class Pokemon : ShowdownIdentifiable {
_nickname.emit(value)
}
fun getDisplayName(): MutableComponent = nickname?.copy()?.takeIf { it.contents != PlainTextContents.EMPTY } ?: species.translatedName.copy()
fun getDisplayName(mark: PokemonMark? = selectedMark): MutableComponent =
if (mark != null) {
nickname?.copy()?.takeIf { it.contents != PlainTextContents.EMPTY }?.append(" ")?.append(lang(mark.title)) ?: species.translatedName.copy().append(" ").append(lang(mark.title))
} else {
nickname?.copy()?.takeIf { it.contents != PlainTextContents.EMPTY } ?: species.translatedName.copy()
}
fun getDisplayNameNoTitle() = nickname?.copy()?.takeIf { it.contents != PlainTextContents.EMPTY } ?: species.translatedName.copy()
var level = 1
set(value) {
@@ -432,6 +441,8 @@ open class Pokemon : ShowdownIdentifiable {
_originalTrainerName.emit(value)
}
val marks = mutableListOf<PokemonMark>()
var selectedMark: PokemonMark? = PokemonMarks.marks[cobblemonResource("resurrected")]
/**
* All moves that the Pokémon has, at some point, known. This is to allow players to
@@ -568,11 +579,10 @@ open class Pokemon : ShowdownIdentifiable {
SeasonFeatureHandler.updateSeason(this, level, position.toBlockPos())
val entity = PokemonEntity(level, this)
illusion?.start(entity)
val adjustedPosition = entity.getAjustedSendoutPosition(position)
val sentOut = entity.setPositionSafely(adjustedPosition)
val sentOut = entity.setPositionSafely(position)
//If sendout failed, fall back
if (!sentOut) {
entity.setPos(adjustedPosition.x, adjustedPosition.y, adjustedPosition.z)
entity.setPos(position.x, position.y, position.z)
}
mutation(entity)
level.addFreshEntity(entity)
@@ -592,6 +602,18 @@ open class Pokemon : ShowdownIdentifiable {
mutation: (PokemonEntity) -> Unit = {},
): CompletableFuture<PokemonEntity> {
// send out raft if over water
if (position != null) {
// todo if send out position is over water then add a raft entity to stand on
if (level.isWaterAt(
BlockPos(
position.x.toInt(),
position.y.toInt() - 1,
position.z.toInt()
)
) && this.species.types.all { it != ElementalTypes.WATER && it != ElementalTypes.FLYING }) {
}
}
// Handle special case of shouldered Cobblemon
if (this.state is ShoulderedState) {
@@ -611,44 +633,6 @@ open class Pokemon : ShowdownIdentifiable {
val owner = getOwnerEntity()
if (owner is LivingEntity) {
owner.swing(InteractionHand.MAIN_HAND, true)
val spawnDirection: Vec3
var spawnYaw: Double
if (battleId != null) {
// Look for an opposing opponent to face
val battle = Cobblemon.battleRegistry.getBattle(battleId)
val activeBattlePokemon = battle?.activePokemon?.firstOrNull { activePokemon -> activePokemon.battlePokemon?.originalPokemon?.uuid == it.pokemon.uuid }
val opposingActiveBattlePokemon = (activeBattlePokemon?.getOppositeOpponent() as ActiveBattlePokemon?)
var opposingEntityPos = opposingActiveBattlePokemon?.battlePokemon?.entity?.position()
if (opposingEntityPos == null) {
// Can't find the opposing pokemon, it probably doesn't exist yet. Try to calculate the opponent's sendout position
val opposingEntityBattleActor = battle?.actors?.first { battleActor ->
battleActor is EntityBackedBattleActor<*> && battleActor.entity != null && battleActor.entity?.uuid !== owner.uuid
} as EntityBackedBattleActor<*>
if (activeBattlePokemon != null) {
opposingEntityPos = ShowdownInterpreter.getSendoutPosition(battle, activeBattlePokemon, opposingEntityBattleActor as BattleActor)
}
if (opposingEntityPos == null) {
// Sendout calculation failed, fallback to using the opposing actor's position
opposingEntityPos = opposingEntityBattleActor.initialPos
}
}
spawnDirection = opposingEntityPos?.subtract(it.position()) ?: position.subtract(owner.position())
val battleYaw = (atan2(spawnDirection.z, spawnDirection.x) * 180.0 / PI) - 90.0
spawnYaw = battleYaw
} else {
// Non-battle send out, face the trainer
spawnDirection = position.subtract(owner.position())
spawnYaw = atan2(spawnDirection.z, spawnDirection.x) * 180.0 / PI + 102.5
}
// In some edge cases, I suspect we are producing NaN's here. This actually leads into a really big problem.
// Why? Because on tick, LivingEntity tries to bring rotations back within one loop around 0-360 using while loops.
// NaN resists arithmetic, so the while loops run forever and the server thread will hang trying to normalize
// this angle. Better to catch it here and correct it. Y'know. If this is actually the problem. I believe!
if (!spawnYaw.isFinite()) {
spawnYaw = 0.0
}
it.entityData.set(PokemonEntity.SPAWN_DIRECTION, spawnYaw.toFloat())
}
if (owner != null) {
level.playSoundServer(owner.position(), CobblemonSounds.POKE_BALL_THROW, volume = 0.6F)
@@ -658,10 +642,6 @@ open class Pokemon : ShowdownIdentifiable {
it.beamMode = 1
it.battleId = battleId
if (it.battleId == null) {
it.platform = PlatformType.NONE
}
it.after(seconds = THROW_DURATION) {
it.phasingTargetId = -1
}
@@ -953,22 +933,45 @@ open class Pokemon : ShowdownIdentifiable {
fun removeHeldItem(): ItemStack = this.swapHeldItem(ItemStack.EMPTY)
fun saveToNBT(registryAccess: RegistryAccess, nbt: CompoundTag = CompoundTag()): CompoundTag {
val markList = marks.map { it.identifier.toString() }.map { StringTag.valueOf(it) }
nbt.put(DataKeys.POKEMON_MARKS, ListTag().also { it.addAll(markList) })
if (selectedMark != null) {
nbt.put(DataKeys.SELECTED_MARK, StringTag.valueOf(selectedMark!!.identifier.toString()))
}
return this.saveTo(registryAccess.createSerializationContext(NbtOps.INSTANCE), nbt).orThrow as CompoundTag
}
fun loadFromNBT(registryAccess: RegistryAccess, nbt: CompoundTag): Pokemon {
this.loadFrom(registryAccess.createSerializationContext(NbtOps.INSTANCE), nbt)
val markList = nbt.get(DataKeys.POKEMON_MARKS) as ListTag
markList.forEach { PokemonMarks.marks[ResourceLocation.tryParse(it.asString)]?.let { it1 -> this.marks.add(it1) } }
if (nbt.contains(DataKeys.SELECTED_MARK)) {
val markOrNull = PokemonMarks.marks[ResourceLocation.tryParse(nbt.getString(DataKeys.SELECTED_MARK))]
if (markOrNull != null) selectedMark = markOrNull
}
return this
}
fun saveToJSON(registryAccess: RegistryAccess, json: JsonObject = JsonObject()): JsonObject {
val ops = registryAccess.createSerializationContext(JsonOps.INSTANCE)
val marksList = JsonArray()
marks.forEach { marksList.add(it.identifier.toString()) }
json.add(DataKeys.POKEMON_MARKS, marksList)
if (selectedMark != null) json.addProperty(DataKeys.SELECTED_MARK, selectedMark!!.identifier.toString())
return this.saveTo(ops, json).orThrow as JsonObject
}
fun loadFromJSON(registryAccess: RegistryAccess, json: JsonObject): Pokemon {
val ops = registryAccess.createSerializationContext(JsonOps.INSTANCE)
this.loadFrom(ops, json)
json.getAsJsonArray(DataKeys.POKEMON_MARKS).forEach {
val markId = ResourceLocation.tryParse(it.asString)
if (markId != null && PokemonMarks.marks[markId] != null) this.marks.add(PokemonMarks.marks[markId]!!)
}
if (json.has(DataKeys.SELECTED_MARK)) {
val markOrNull = PokemonMarks.marks[ResourceLocation.tryParse(json.get(DataKeys.SELECTED_MARK).toString())]
if (markOrNull != null) selectedMark = markOrNull
}
return this
}
@@ -94,7 +94,8 @@ abstract class PokemonStats : Iterable<Map.Entry<Stat, Int>> {
Stats.PERMANENT.forEach { stat ->
val identifier = this.cleanStatIdentifier(stat.identifier)
json.get(identifier)?.asInt?.coerceIn(this.acceptableRange)?.let { this.stats[stat] = it }
this[stat] = json.get(identifier)?.asInt?.coerceIn(this.acceptableRange)
?: this.defaultValue
}
return this
}
@@ -8,9 +8,6 @@
package com.cobblemon.mod.common.pokemon
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.Priority
@@ -164,21 +161,6 @@ class Species : ClientDataSynchronizer<Species>, ShowdownIdentifiable {
var lightingData: LightingData? = null
private set
@Transient
val struct = QueryStruct(hashMapOf())
.addFunction("identifier") { StringValue(this.resourceIdentifier.toString()) }
.addFunction("primary_type") { StringValue(this.primaryType.name) }
.addFunction("secondary_type") { StringValue(this.secondaryType?.name ?: "null") }
.addFunction("experience_group") { StringValue(this.experienceGroup.name) }
.addFunction("height") { DoubleValue(this.height) }
.addFunction("weight") { DoubleValue(this.weight) }
.addFunction("base_scale") { DoubleValue(this.baseScale) }
.addFunction("hitbox_width") { DoubleValue(this.hitbox.width) }
.addFunction("hitbox_height") { DoubleValue(this.hitbox.height) }
.addFunction("hitbox_fixed") { DoubleValue(this.hitbox.fixed) }
.addFunction("catch_rate") { DoubleValue(this.catchRate) }
fun initialize() {
Cobblemon.statProvider.provide(this)
this.forms.forEach { it.initialize(this) }
@@ -8,7 +8,6 @@
package com.cobblemon.mod.common.pokemon.properties
import com.cobblemon.mod.common.api.abilities.CommonAbilityType
import com.cobblemon.mod.common.api.properties.CustomPokemonProperty
import com.cobblemon.mod.common.api.properties.CustomPokemonPropertyType
import com.cobblemon.mod.common.pokemon.Pokemon
@@ -24,20 +23,15 @@ import com.cobblemon.mod.common.pokemon.abilities.HiddenAbilityType
object HiddenAbilityPropertyType : CustomPokemonPropertyType<HiddenAbilityProperty> {
override val keys = setOf("hiddenability", "ha")
override val needsKey = true
override fun fromString(value: String?) =
when {
value == null || value.lowercase() in listOf("true", "yes") -> HiddenAbilityProperty(true)
value.lowercase() in listOf("false", "no") -> HiddenAbilityProperty(false)
else -> null
}
override fun examples() = setOf("yes", "no")
override fun fromString(value: String?) = HiddenAbilityProperty()
override fun examples() = emptySet<String>()
}
class HiddenAbilityProperty (var value: Boolean) : CustomPokemonProperty {
class HiddenAbilityProperty : CustomPokemonProperty {
override fun asString() = "hiddenability"
override fun apply(pokemon: Pokemon) {
val possible = pokemon.form.abilities.mapping.flatMap { it.value }
.filter { it.type == getAbilityType() }
.filter { it.type == HiddenAbilityType }
val picked = possible.randomOrNull() ?: return
pokemon.updateAbility(picked.template.create(false))
}
@@ -45,7 +39,5 @@ class HiddenAbilityProperty (var value: Boolean) : CustomPokemonProperty {
override fun matches(pokemon: Pokemon) = pokemon.form.abilities.mapping
.flatMap { it.value }
.find { it.template == pokemon.ability.template }
?.type == getAbilityType()
private fun getAbilityType() = if (this.value) HiddenAbilityType else CommonAbilityType
?.type == HiddenAbilityType
}
@@ -146,7 +146,6 @@ internal object PropertiesCompletionProvider : DataRegistry {
this.inject(setOf("tradeable"), setOf("yes", "no"))
this.inject(setOf("originaltrainer", "ot"), setOf(""))
this.inject(setOf("originaltrainertype", "ottype"), setOf("None", "Player", "NPC"))
this.inject(setOf("nickname", "nick"), setOf(""))
Stats.PERMANENT.forEach{ stat ->
val statName = stat.toString().lowercase()
@@ -65,11 +65,13 @@ object DataKeys {
const val POKEMON_COUNTS_TOWARDS_SPAWN_CAP = "CountsTowardsSpawnCap"
const val POKEMON_FREEZE_FRAME = "FreezeFrame"
const val POKEMON_RECALCULATE_POSE = "RecalculatePose"
const val POKEMON_PLATFORM_TYPE = "PlatformType"
const val POKEMON_ORIGINAL_TRAINER = "PokemonOriginalTrainer"
const val POKEMON_ORIGINAL_TRAINER_TYPE = "PokemonOriginalTrainerType"
const val POKEMON_MARKS = "Marks"
const val SELECTED_MARK = "CurrentMark"
const val POKEMON_PROPERTIES_MOVES = "Moves"
const val POKEMON_PROPERTIES_HELDITEM = "HeldItem"
@@ -94,7 +96,7 @@ object DataKeys {
const val STORE_BOX_COUNT_LOCKED = "BoxCountLocked"
const val STORE_BACKUP = "BackupStore"
// Pokédex Keys
// Pokedex Keys
const val POKEDEX_TYPE = "PokedexType"
const val NUM_ENCOUNTED_WILD = "NumberEncounteredWild"
const val NUM_ENCOUNTED_BATTLE = "NumberEncounteredBattle"
@@ -112,26 +114,28 @@ object DataKeys {
const val TETHERING_PLAYER_ID = "PlayerId"
const val TETHERING_ENTITY_ID = "EntityId"
// Form stuff
/* Form stuff */
const val ALOLAN = "alolan"
const val GALARIAN = "galarian"
const val HISUIAN = "hisuian"
const val VALENCIAN = "valencian"
const val CRYSTAL = "crystal"
/* ---------- */
const val POKEMON_PROPERTIES = "Properties"
const val POKEMON_PROPERTIES_CUSTOM = "CustomProperties"
const val POKEMON_PROPERTIES_ORIGINAL_TEXT = "OriginalText"
const val POKEMON_SPECIES_TEXT = "SpeciesText"
// Healer Block
/* Healer Block */
const val HEALER_MACHINE_USER = "MachineUser"
const val HEALER_MACHINE_POKEBALLS = "MachinePokeBalls"
const val HEALER_MACHINE_TIME_LEFT = "MachineTimeLeft"
const val HEALER_MACHINE_CHARGE = "MachineCharge"
const val HEALER_MACHINE_INFINITE = "MachineInfinite"
/* ----------- */
// Pokémon Item
// Pokemon Item
const val POKEMON_ITEM_SPECIES = "species"
const val POKEMON_ITEM_ASPECTS = "aspects"
const val POKEMON_ITEM_TINT_RED = "TintRed"
@@ -160,11 +164,11 @@ object DataKeys {
const val SHOULDER_ASPECTS = "shoulder_aspects"
const val SHOULDER_SCALE_MODIFIER = "shoulder_scale"
// Multi-Block
//Multiblock Stuff
const val MULTIBLOCK_STORAGE = "MultiblockStore"
const val CONTROLLER_BLOCK = "ControllerBlock"
// FossilMultiblockStructure Serialization
//FossilMultiblockStructure Serialization
const val MONITOR_POS = "MonitorPos"
const val TANK_BASE_POS = "TankBasePos"
const val ANALYZER_POS = "AnalyzerPos"
@@ -181,10 +185,7 @@ object DataKeys {
const val FOSSIL_OWNER = "FossilOwner"
const val FOSSIL_STATE = "FossilState"
// Generic Block Entity
const val BLOCK_ENTITY_USER_AMOUNT = "userAmount"
// Generic Bedrock Entity
/* Generic Bedrock Entity */
const val GENERIC_BEDROCK_CATEGORY = "Category"
const val GENERIC_BEDROCK_ASPECTS = "Aspects"
const val GENERIC_BEDROCK_POSE_TYPE = "PoseType"
@@ -202,7 +203,6 @@ object DataKeys {
const val NPC_PARTY = "Party"
const val NPC_PARTY_TYPE = "PartyType"
const val NPC_ASPECTS = "AppliedAspects"
const val NPC_VARIATION_ASPECTS = "VariationAspects"
const val NPC_DATA = "Data"
const val NPC_CONFIG = "Config"
const val NPC_INTERACTION = "Interaction"
@@ -37,7 +37,6 @@ fun String.asTranslated() = Component.translatable(this)
fun String.asResource() = ResourceLocation.parse(this)
fun String.asTranslated(vararg data: Any) = Component.translatable(this, *data)
fun String.isInt() = this.toIntOrNull() != null
fun String.isDouble() = this.toDoubleOrNull() != null
fun String.isHigherVersion(other: String): Boolean {
val thisSplits = split(".")
val thatSplits = other.split(".")
@@ -41,7 +41,7 @@ fun MoLangRuntime.resolve(expression: Expression, context: Map<String, MoValue>
}
// expression.evaluate(MoScope(), environment)
} catch (e: Exception) {
throw IllegalArgumentException("Unable to evaluate expression: ${expression.getString()}", e)
throw IllegalArgumentException("Unable to parse expression: ${expression.getString()}", e)
}
fun MoLangRuntime.resolveDouble(expression: Expression, context: Map<String, MoValue> = contextOrEmpty): Double = resolve(expression, context).asDouble()
fun MoLangRuntime.resolveFloat(expression: Expression, context: Map<String, MoValue> = contextOrEmpty): Float = resolve(expression, context).asDouble().toFloat()
@@ -210,16 +210,8 @@ fun MoLangEnvironment.cloneFrom(other: MoLangEnvironment): MoLangEnvironment {
return this
}
fun BlockPos.toArrayStruct() = listOf(x, y, z).asArrayValue(::DoubleValue)
fun <T> Collection<T>.asArrayValue(mapper: (T) -> MoValue): ArrayStruct {
val array = ArrayStruct()
forEachIndexed { index, value -> array.setDirectly("$index", mapper(value)) }
return array
}
fun Iterable<MoValue>.asArrayValue(): ArrayStruct {
val array = ArrayStruct()
forEachIndexed { index, value -> array.setDirectly("$index", value) }
return array
fun BlockPos.toArrayStruct() = ArrayStruct().apply {
map["0"] = DoubleValue(x)
map["1"] = DoubleValue(y)
map["2"] = DoubleValue(z)
}
@@ -28,7 +28,6 @@ import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.ChunkPos
import net.minecraft.world.level.Level
import net.minecraft.world.level.biome.Biome
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.phys.AABB
@@ -154,8 +153,6 @@ val Level.enchantmentRegistry: Registry<Enchantment>
get() = registryAccess().registryOrThrow(Registries.ENCHANTMENT)
val Level.activityRegistry: Registry<Activity>
get() = registryAccess().registryOrThrow(Registries.ACTIVITY)
val Level.blockRegistry: Registry<Block>
get() = registryAccess().registryOrThrow(Registries.BLOCK)
fun Vec3.traceDownwards(
world: Level,
@@ -13,26 +13,21 @@ import com.cobblemon.mod.common.api.dialogue.ExpressionLikeDialogueText
import com.cobblemon.mod.common.api.dialogue.WrappedDialogueText
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.util.asExpressionLike
import com.cobblemon.mod.common.util.asTranslated
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import com.mojang.serialization.JsonOps
import java.lang.reflect.Type
import net.minecraft.network.chat.ComponentSerialization
object DialogueTextAdapter : JsonDeserializer<DialogueText> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): DialogueText {
return if (json.isJsonPrimitive) {
WrappedDialogueText(json.asString.asTranslated())
WrappedDialogueText(json.asString.text())
} else if (json.isJsonArray) {
ExpressionLikeDialogueText(json.asJsonArray.map { it.asString }.asExpressionLike())
} else {
val obj = json.asJsonObject
val typeId = obj.get("type")?.asString ?: run {
return WrappedDialogueText(ComponentSerialization.CODEC.decode(JsonOps.INSTANCE, json).result().get().first.copy())
}
val typeId = obj.get("type").asString
val clazz = DialogueText.types[typeId] ?: throw JsonParseException("Unknown dialogue text type $typeId")
context.deserialize(json, clazz)
}
@@ -15,7 +15,6 @@ import com.cobblemon.mod.common.api.npc.NPCPartyProvider
import com.cobblemon.mod.common.api.npc.NPCPreset
import com.cobblemon.mod.common.api.npc.NPCPresets
import com.cobblemon.mod.common.api.npc.configuration.NPCBattleConfiguration
import com.cobblemon.mod.common.api.npc.configuration.NPCConfigVariable
import com.cobblemon.mod.common.api.npc.configuration.NPCInteractConfiguration
import com.cobblemon.mod.common.api.npc.variation.NPCVariationProvider
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
@@ -61,10 +60,6 @@ object NPCClassAdapter : JsonDeserializer<NPCClass> {
obj.get("battleConfiguration")?.let { npcClass.battleConfiguration = ctx.deserialize(it, NPCBattleConfiguration::class.java) }
obj.get("interaction")?.let { npcClass.interaction = ctx.deserialize(it, NPCInteractConfiguration::class.java) }
obj.get("canDespawn")?.let { npcClass.canDespawn = it.asBoolean }
obj.get("config")?.let {
val obj = it.asJsonArray
obj.forEach { npcClass.config.add(ctx.deserialize(it, NPCConfigVariable::class.java)) }
}
obj.get("variations")?.let {
val obj = it.asJsonObject
obj.entrySet().forEach { (key, value) ->
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff. Show more