Compare commits

..
51 changed files with 1303 additions and 696 deletions

No files matched your search

+1 -18
View File
@@ -2,24 +2,7 @@
## [1.8.5 (MONTH xth, 2026)](#1-8-5)
### Additions
- You can now drag to select multiple Pokémon inside the PC menu.
### Pokémon Added
#### Generation 4
#### Generation 5
#### Generation 6
#### Generation 7
#### Generation 8
#### Generation 9
### Model updates for the following Pokémon
### Animation updates for the following Pokémon
- You can now view the biome, level, and date you caught a Pokémon.
- Added the `healersSetSpawn` gamerule. When enabled, using a healing machine will set your spawnpoint.
- A Pokémon holding a Power item now gains 1 point in the corresponding riding stat every two minutes while being ridden. The interval is configurable, and can be disabled with `-1`.
- Added sounds to Play rough, Gigaton Hammer and Pyro Ball
@@ -10,6 +10,7 @@ package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.client.sound.BattleMusicController;
import com.cobblemon.mod.common.client.sound.SoundTracker;
import com.cobblemon.mod.common.client.sound.conditional.ConditionalSoundsRegistry;
import com.cobblemon.mod.common.duck.SoundEngineDuck;
import com.cobblemon.mod.common.duck.SoundManagerDuck;
import net.minecraft.client.resources.sounds.BiomeAmbientSoundsHandler;
@@ -18,12 +19,15 @@ import net.minecraft.client.resources.sounds.UnderwaterAmbientSoundInstances;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.client.sounds.SoundManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.sounds.SoundSource;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@@ -36,6 +40,12 @@ public abstract class SoundManagerMixin implements SoundManagerDuck {
@Shadow @Final
private SoundEngine soundEngine;
/** After sounds.json is applied, reload conditional sounds so their entries join vanilla's weighted pick in the fresh sound registry. */
@Inject(method = "apply(Lnet/minecraft/client/sounds/SoundManager$Preparations;Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/util/profiling/ProfilerFiller;)V", at = @At("TAIL"), require = 1)
private void cobblemon$addConditionalSounds(@Coerce Object preparations, ResourceManager resourceManager, ProfilerFiller profiler, CallbackInfo ci) {
ConditionalSoundsRegistry.INSTANCE.reload(resourceManager);
}
// Never-ending ambient loops are a special exception (they are only initiated once) and should always be paused if filtered.
private boolean isAmbientLoop(SoundInstance sound) {
return sound instanceof BiomeAmbientSoundsHandler.LoopSoundInstance || sound instanceof UnderwaterAmbientSoundInstances.UnderwaterAmbientSoundInstance;
@@ -566,7 +566,6 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(SwapPartyPokemonPacket.ID, SwapPartyPokemonPacket::decode, SwapPartyPokemonHandler))
list.add(PacketRegisterInfo(MovePCPokemonPacket.ID, MovePCPokemonPacket::decode, MovePCPokemonHandler))
list.add(PacketRegisterInfo(MovePCPokemonBatchPacket.ID, MovePCPokemonBatchPacket::decode, MovePCPokemonBatchHandler))
list.add(PacketRegisterInfo(MovePartyPokemonPacket.ID, MovePartyPokemonPacket::decode, MovePartyPokemonHandler))
list.add(PacketRegisterInfo(SwapPCPartyPokemonPacket.ID, SwapPCPartyPokemonPacket::decode, SwapPCPartyPokemonHandler))
@@ -0,0 +1,17 @@
/*
* 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.audio
import com.mojang.datafixers.util.Either
import com.mojang.serialization.Codec
object AudioCodecs {
val STRING_OR_LIST: Codec<List<String>> = Codec.either(Codec.STRING.listOf(), Codec.STRING)
.xmap({ e -> e.map({ it }, { listOf(it) }) }, { Either.left(it) })
}
@@ -0,0 +1,40 @@
/*
* 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.audio
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.resources.ResourceLocation
import net.minecraft.util.ExtraCodecs
/**
* An entry added to the target events, like an `"type": "event"` entry in `sounds.json`.
*
* @property sound Sound event id (from a `sounds.json`) to play. Must not itself be a target.
* @property weight Weight against the target's other entries while conditions match; 0 otherwise. Default 1.
* @property conditions Conditions for this entry only.
*/
data class ConditionalSoundEntry(val sound: ResourceLocation, val weight: Int, val conditions: List<AudioCondition>) {
companion object {
private val FULL_CODEC: Codec<ConditionalSoundEntry> = RecordCodecBuilder.create {
it.group(
ResourceLocation.CODEC.fieldOf("sound").forGetter(ConditionalSoundEntry::sound),
ExtraCodecs.POSITIVE_INT.optionalFieldOf("weight", 1).forGetter(ConditionalSoundEntry::weight),
AudioCondition.LIST_CODEC.optionalFieldOf("conditions", emptyList())
.forGetter(ConditionalSoundEntry::conditions)
).apply(it, ::ConditionalSoundEntry)
}
val CODEC: Codec<ConditionalSoundEntry> = Codec.withAlternative(
FULL_CODEC,
ResourceLocation.CODEC.xmap({ ConditionalSoundEntry(it, 1, emptyList()) }, ConditionalSoundEntry::sound)
)
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.util.ExtraCodecs
/**
* One file in `assets/<namespace>/conditional_sounds/`: extra entries added to existing sound events (from any
* `sounds.json`), each only eligible while its conditions match. Vanilla still picks the event and does the weighted
* random pick; these entries just join that pick.
*
* @property targets Sound event ids to extend. An id ending in `*` matches every event with that prefix.
* @property conditions Conditions shared by every entry in this file.
* @property sounds The entries to add.
*/
data class ConditionalSounds(
val targets: List<String>,
val conditions: List<AudioCondition>,
val sounds: List<ConditionalSoundEntry>
) {
companion object {
val CODEC: Codec<ConditionalSounds> = RecordCodecBuilder.create {
it.group(
AudioCodecs.STRING_OR_LIST.fieldOf("targets").forGetter(ConditionalSounds::targets),
AudioCondition.LIST_CODEC.optionalFieldOf("conditions", emptyList())
.forGetter(ConditionalSounds::conditions),
ExtraCodecs.nonEmptyList(ConditionalSoundEntry.CODEC.listOf()).fieldOf("sounds")
.forGetter(ConditionalSounds::sounds)
).apply(it, ::ConditionalSounds)
}
}
}
@@ -0,0 +1,40 @@
/*
* 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.audio.condition
import com.mojang.serialization.Codec
/**
* A client-side check against the local player's situation, used to filter conditional sound entries.
* Each condition reads what it needs from [AudioContext] itself. [test] runs on the client thread.
*/
interface AudioCondition {
fun test(ctx: AudioContext): Boolean
fun type(): ConditionType<*>
companion object {
val CODEC: Codec<AudioCondition> = Codec.lazyInitialized {
ConditionType.CODEC.dispatch("type", AudioCondition::type) { it.codec }
}
val LIST_CODEC: Codec<List<AudioCondition>> = CODEC.listOf()
fun all(conditions: List<AudioCondition>, ctx: AudioContext): Boolean {
for (i in conditions.indices) if (!conditions[i].test(ctx)) return false
return true
}
fun any(conditions: List<AudioCondition>, ctx: AudioContext): Boolean {
for (i in conditions.indices) if (conditions[i].test(ctx)) return true
return false
}
}
}
@@ -0,0 +1,57 @@
/*
* 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.audio.condition
import net.minecraft.client.Minecraft
import net.minecraft.client.multiplayer.ClientLevel
import net.minecraft.client.player.LocalPlayer
import net.minecraft.core.BlockPos
import net.minecraft.util.Mth
/**
* A reusable snapshot of who and where the local player is, which [AudioCondition]s read from.
* Holds only the player, level and positions; each condition derives the rest itself.
*
* Not thread-safe: client thread only. Positions are mutable and reused, so copy them if you need to keep them.
*/
class AudioContext {
private var _player: LocalPlayer? = null
private var _level: ClientLevel? = null
private val feet = BlockPos.MutableBlockPos()
private val eye = BlockPos.MutableBlockPos()
val player: LocalPlayer get() = checkNotNull(_player) { "AudioContext not updated" }
val level: ClientLevel get() = checkNotNull(_level) { "AudioContext not updated" }
fun update(player: LocalPlayer, level: ClientLevel) {
_player = player
_level = level
feet.set(player.blockPosition())
eye.set(player.blockX, Mth.floor(player.eyeY), player.blockZ)
}
fun clear() {
_player = null
_level = null
}
fun feetPos(): BlockPos = feet
fun eyePos(): BlockPos = eye
companion object {
fun capture(): AudioContext? {
val mc = Minecraft.getInstance()
val player = mc.player ?: return null
val level = mc.level ?: return null
return AudioContext().also { it.update(player, level) }
}
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition
import com.cobblemon.mod.common.Cobblemon
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import com.mojang.serialization.MapCodec
import net.minecraft.resources.ResourceLocation
/**
* A registered kind of [AudioCondition].
*
* @property id The id written in JSON. Ids without a namespace resolve to `cobblemon`.
* @property codec Codec for the condition's other fields.
*/
data class ConditionType<T : AudioCondition>(val id: ResourceLocation, val codec: MapCodec<T>) {
companion object {
private val REGISTRY = HashMap<ResourceLocation, ConditionType<*>>()
fun <T : AudioCondition> register(id: ResourceLocation, codec: MapCodec<T>): ConditionType<T> {
val type = ConditionType(id, codec)
check(REGISTRY.putIfAbsent(id, type) == null) { "Duplicate audio condition type: $id" }
return type
}
fun get(id: ResourceLocation): ConditionType<*>? = REGISTRY[id]
val CODEC: Codec<ConditionType<*>> = Codec.STRING.comapFlatMap({ raw ->
val id = ResourceLocation.tryParse(if (':' in raw) raw else "${Cobblemon.MODID}:$raw")
val type = id?.let { REGISTRY[it] }
if (type != null) DataResult.success(type) else DataResult.error { "Unknown audio condition type '$raw'" }
}, { it.id.toString() })
}
}
@@ -0,0 +1,59 @@
/*
* 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.audio.condition
import com.cobblemon.mod.common.api.audio.AudioCodecs
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import net.minecraft.core.Holder
import net.minecraft.core.Registry
import net.minecraft.resources.ResourceKey
import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.TagKey
/**
* Matches registry entries by id or tag. Parsed from a string or list of strings, where a `#` prefix means a tag.
* Ids and tags are resolved once when decoded, so matching does no parsing or registry lookups.
*/
class KeyMatcher<T> private constructor(
val keys: Set<ResourceKey<T>>,
val tags: List<TagKey<T>>
) {
fun matches(holder: Holder<T>): Boolean {
if (holder is Holder.Reference<T> && holder.key() in keys) return true
for (i in tags.indices) if (holder.`is`(tags[i])) return true
return false
}
fun matches(key: ResourceKey<T>): Boolean = key in keys
companion object {
fun <T> codec(registry: ResourceKey<out Registry<T>>, allowTags: Boolean): Codec<KeyMatcher<T>> =
AudioCodecs.STRING_OR_LIST.flatXmap({ strings -> parse(registry, allowTags, strings) }, { m ->
DataResult.success(m.keys.map { it.location().toString() } + m.tags.map { "#${it.location}" })
})
private fun <T> parse(
registry: ResourceKey<out Registry<T>>,
allowTags: Boolean,
strings: List<String>
): DataResult<KeyMatcher<T>> {
val keys = HashSet<ResourceKey<T>>()
val tags = ArrayList<TagKey<T>>()
for (s in strings) {
val isTag = s.startsWith("#")
if (isTag && !allowTags) return DataResult.error { "Tags are not supported here: '$s'" }
val id = ResourceLocation.read(if (isTag) s.substring(1) else s).result().orElse(null)
?: return DataResult.error { "Invalid id '$s'" }
if (isTag) tags += TagKey.create(registry, id) else keys += ResourceKey.create(registry, id)
}
return DataResult.success(KeyMatcher(keys, tags))
}
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.MapCodec
/** Every nested condition passes. */
data class AllOfCondition(val conditions: List<AudioCondition>) : AudioCondition {
override fun test(ctx: AudioContext) = AudioCondition.all(conditions, ctx)
override fun type() = BuiltinConditions.ALL_OF
companion object {
val CODEC: MapCodec<AllOfCondition> =
AudioCondition.LIST_CODEC.fieldOf("conditions").xmap(::AllOfCondition, AllOfCondition::conditions)
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.MapCodec
/** At least one nested condition passes. */
data class AnyOfCondition(val conditions: List<AudioCondition>) : AudioCondition {
override fun test(ctx: AudioContext) = AudioCondition.any(conditions, ctx)
override fun type() = BuiltinConditions.ANY_OF
companion object {
val CODEC: MapCodec<AnyOfCondition> =
AudioCondition.LIST_CODEC.fieldOf("conditions").xmap(::AnyOfCondition, AnyOfCondition::conditions)
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.cobblemon.mod.common.api.audio.condition.KeyMatcher
import com.mojang.serialization.MapCodec
import net.minecraft.core.registries.Registries
import net.minecraft.world.level.biome.Biome
/** Biome at the player's feet matches an id or `#tag`. */
data class BiomeCondition(val biomes: KeyMatcher<Biome>) : AudioCondition {
override fun test(ctx: AudioContext) = biomes.matches(ctx.level.getBiome(ctx.feetPos()))
override fun type() = BuiltinConditions.BIOME
companion object {
val CODEC: MapCodec<BiomeCondition> =
KeyMatcher.codec(Registries.BIOME, true).fieldOf("biomes").xmap(::BiomeCondition, BiomeCondition::biomes)
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.ConditionType
import com.cobblemon.mod.common.util.cobblemonResource
import com.mojang.serialization.MapCodec
/** The built-in [AudioCondition] types. Ids are in the `cobblemon` namespace, so JSON can write just `"biome"`. */
object BuiltinConditions {
val BIOME = register("biome", BiomeCondition.CODEC)
val DIMENSION = register("dimension", DimensionCondition.CODEC)
val TIME_OF_DAY = register("time_of_day", TimeOfDayCondition.CODEC)
val SKY_ACCESS = register("sky_access", SkyAccessCondition.CODEC)
val UNDERGROUND = register("underground", UndergroundCondition.CODEC)
val LIGHT_LEVEL = register("light_level", LightLevelCondition.CODEC)
val Y_LEVEL = register("y_level", YLevelCondition.CODEC)
val WEATHER = register("weather", WeatherCondition.CODEC)
val UNDERWATER = register("underwater", UnderwaterCondition.CODEC)
val ALL_OF = register("all_of", AllOfCondition.CODEC)
val ANY_OF = register("any_of", AnyOfCondition.CODEC)
val NOT = register("not", NotCondition.CODEC)
fun bootstrap() {}
private fun <T : AudioCondition> register(name: String, codec: MapCodec<T>) =
ConditionType.register(cobblemonResource(name), codec)
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.cobblemon.mod.common.api.audio.condition.KeyMatcher
import com.mojang.serialization.MapCodec
import net.minecraft.core.registries.Registries
import net.minecraft.world.level.Level
/** Current dimension matches one of the ids. Tags are not supported for dimensions. */
data class DimensionCondition(val dimensions: KeyMatcher<Level>) : AudioCondition {
override fun test(ctx: AudioContext) = dimensions.matches(ctx.level.dimension())
override fun type() = BuiltinConditions.DIMENSION
companion object {
val CODEC: MapCodec<DimensionCondition> = KeyMatcher.codec(Registries.DIMENSION, false).fieldOf("dimensions")
.xmap(::DimensionCondition, DimensionCondition::dimensions)
}
}
@@ -0,0 +1,57 @@
/*
* 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.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.util.StringRepresentable
import net.minecraft.world.level.LightLayer
/** Light at the player's eyes is within an inclusive range. */
data class LightLevelCondition(val min: Int, val max: Int, val source: LightSource) : AudioCondition {
override fun test(ctx: AudioContext) = source.read(ctx) in min..max
override fun type() = BuiltinConditions.LIGHT_LEVEL
companion object {
private val LIGHT = Codec.intRange(0, 15)
val CODEC: MapCodec<LightLevelCondition> = RecordCodecBuilder.mapCodec<LightLevelCondition> {
it.group(
LIGHT.optionalFieldOf("min", 0).forGetter(LightLevelCondition::min),
LIGHT.optionalFieldOf("max", 15).forGetter(LightLevelCondition::max),
LightSource.CODEC.optionalFieldOf("source", LightSource.COMBINED).forGetter(LightLevelCondition::source)
).apply(it, ::LightLevelCondition)
}
.validate { if (it.min <= it.max) DataResult.success(it) else DataResult.error { "light_level: min must be <= max" } }
}
}
enum class LightSource : StringRepresentable {
BLOCK {
override fun read(ctx: AudioContext) = ctx.level.getBrightness(LightLayer.BLOCK, ctx.eyePos())
},
SKY {
override fun read(ctx: AudioContext) = ctx.level.getBrightness(LightLayer.SKY, ctx.eyePos())
},
COMBINED {
override fun read(ctx: AudioContext) = ctx.level.getMaxLocalRawBrightness(ctx.eyePos())
};
abstract fun read(ctx: AudioContext): Int
override fun getSerializedName() = name.lowercase()
companion object {
val CODEC: Codec<LightSource> = StringRepresentable.fromEnum(::values)
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.MapCodec
/** The nested condition fails. */
data class NotCondition(val condition: AudioCondition) : AudioCondition {
override fun test(ctx: AudioContext) = !condition.test(ctx)
override fun type() = BuiltinConditions.NOT
companion object {
val CODEC: MapCodec<NotCondition> =
AudioCondition.CODEC.fieldOf("condition").xmap(::NotCondition, NotCondition::condition)
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
/** Sky is (or is not) visible straight up from the player's eyes. */
data class SkyAccessCondition(val value: Boolean) : AudioCondition {
override fun test(ctx: AudioContext) = ctx.level.canSeeSky(ctx.eyePos()) == value
override fun type() = BuiltinConditions.SKY_ACCESS
companion object {
val CODEC: MapCodec<SkyAccessCondition> =
Codec.BOOL.optionalFieldOf("value", true).xmap(::SkyAccessCondition, SkyAccessCondition::value)
}
}
@@ -0,0 +1,69 @@
/*
* 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.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.util.StringRepresentable
import java.util.*
/** Time of day (0 to 23999) is within an inclusive tick range; `min > max` wraps past midnight (e.g. 22000 to 2000). */
data class TimeOfDayCondition(val period: TimePeriod?, val min: Int, val max: Int) : AudioCondition {
override fun test(ctx: AudioContext): Boolean {
val t = Math.floorMod(ctx.level.dayTime, 24000L).toInt()
return if (min <= max) t in min..max else t !in (max + 1)..<min
}
override fun type() = BuiltinConditions.TIME_OF_DAY
companion object {
private val TICK = Codec.intRange(0, 23999)
val CODEC: MapCodec<TimeOfDayCondition> =
RecordCodecBuilder.mapCodec<Triple<Optional<TimePeriod>, Optional<Int>, Optional<Int>>> {
it.group(
TimePeriod.CODEC.optionalFieldOf("period").forGetter { t -> t.first },
TICK.optionalFieldOf("min").forGetter { t -> t.second },
TICK.optionalFieldOf("max").forGetter { t -> t.third }
).apply(it, ::Triple)
}.flatXmap({ (period, min, max) ->
when {
period.isPresent && (min.isPresent || max.isPresent) -> DataResult.error { "time_of_day: use either 'period' or 'min'+'max', not both" }
period.isPresent -> DataResult.success(
TimeOfDayCondition(
period.get(),
period.get().min,
period.get().max
)
)
min.isPresent && max.isPresent -> DataResult.success(TimeOfDayCondition(null, min.get(), max.get()))
else -> DataResult.error { "time_of_day: needs 'period' or both 'min' and 'max'" }
}
}, { c ->
DataResult.success(
if (c.period != null) Triple(Optional.of(c.period), Optional.empty(), Optional.empty())
else Triple(Optional.empty(), Optional.of(c.min), Optional.of(c.max))
)
})
}
}
enum class TimePeriod(val min: Int, val max: Int) : StringRepresentable {
DAWN(23000, 999), DAY(1000, 11999), DUSK(12000, 12999), NIGHT(13000, 22999);
override fun getSerializedName() = name.lowercase()
companion object {
val CODEC: Codec<TimePeriod> = StringRepresentable.fromEnum(::values)
}
}
@@ -0,0 +1,43 @@
/*
* 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.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.world.level.levelgen.Heightmap
/**
* Underground means no sky access AND at least [minDepth] blocks below the surface, so tree cover does not count.
* Depth is measured from the WORLD_SURFACE heightmap (synced to clients) to the player's eyes.
*/
data class UndergroundCondition(val value: Boolean, val minDepth: Int) : AudioCondition {
override fun test(ctx: AudioContext): Boolean {
val eye = ctx.eyePos()
val underground = !ctx.level.canSeeSky(eye) && ctx.level.getHeight(
Heightmap.Types.WORLD_SURFACE,
eye.x,
eye.z
) - eye.y >= minDepth
return underground == value
}
override fun type() = BuiltinConditions.UNDERGROUND
companion object {
val CODEC: MapCodec<UndergroundCondition> = RecordCodecBuilder.mapCodec {
it.group(
Codec.BOOL.optionalFieldOf("value", true).forGetter(UndergroundCondition::value),
Codec.INT.optionalFieldOf("min_depth", 8).forGetter(UndergroundCondition::minDepth)
).apply(it, ::UndergroundCondition)
}
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
/** Player's eyes are (or are not) under water. */
data class UnderwaterCondition(val value: Boolean) : AudioCondition {
override fun test(ctx: AudioContext) = ctx.player.isUnderWater == value
override fun type() = BuiltinConditions.UNDERWATER
companion object {
val CODEC: MapCodec<UnderwaterCondition> =
Codec.BOOL.optionalFieldOf("value", true).xmap(::UnderwaterCondition, UnderwaterCondition::value)
}
}
@@ -0,0 +1,46 @@
/*
* 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.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
import net.minecraft.util.StringRepresentable
import net.minecraft.world.level.Level
/** Current level weather (not biome-aware: it also "rains" in deserts). */
data class WeatherCondition(val weather: Weather) : AudioCondition {
override fun test(ctx: AudioContext) = weather.matches(ctx.level)
override fun type() = BuiltinConditions.WEATHER
companion object {
val CODEC: MapCodec<WeatherCondition> =
Weather.CODEC.fieldOf("weather").xmap(::WeatherCondition, WeatherCondition::weather)
}
}
enum class Weather : StringRepresentable {
CLEAR {
override fun matches(level: Level) = !level.isRaining
},
RAIN {
override fun matches(level: Level) = level.isRaining
},
THUNDER {
override fun matches(level: Level) = level.isThundering
};
abstract fun matches(level: Level): Boolean
override fun getSerializedName() = name.lowercase()
companion object {
val CODEC: Codec<Weather> = StringRepresentable.fromEnum(::values)
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.audio.condition.builtin
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
/** Player's feet Y is within an inclusive range; either bound may be omitted. */
data class YLevelCondition(val min: Int, val max: Int) : AudioCondition {
override fun test(ctx: AudioContext) = ctx.feetPos().y in min..max
override fun type() = BuiltinConditions.Y_LEVEL
companion object {
val CODEC: MapCodec<YLevelCondition> = RecordCodecBuilder.mapCodec<YLevelCondition> {
it.group(
Codec.INT.optionalFieldOf("min", Int.MIN_VALUE).forGetter(YLevelCondition::min),
Codec.INT.optionalFieldOf("max", Int.MAX_VALUE).forGetter(YLevelCondition::max)
).apply(it, ::YLevelCondition)
}
.validate { if (it.min <= it.max) DataResult.success(it) else DataResult.error { "y_level: min must be <= max" } }
}
}
@@ -27,10 +27,8 @@ import com.cobblemon.mod.common.net.messages.client.storage.RemoveClientPokemonP
import com.cobblemon.mod.common.net.messages.client.storage.SwapClientPokemonPacket
import com.cobblemon.mod.common.net.messages.client.storage.pc.InitializePCPacket
import com.cobblemon.mod.common.net.messages.client.storage.pc.MoveClientPCPokemonPacket
import com.cobblemon.mod.common.net.messages.client.storage.pc.SetPCBoxPacket
import com.cobblemon.mod.common.net.messages.client.storage.pc.SetPCPokemonPacket
import com.cobblemon.mod.common.net.messages.client.storage.pc.wallpaper.UnlockPCBoxWallpaperPacket
import com.cobblemon.mod.common.net.messages.server.storage.pc.MovePCPokemonBatchPacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.asTranslated
@@ -68,12 +66,6 @@ open class PCStore(
) : PokemonStore<PCPosition>() {
constructor(uuid: UUID): this(uuid, lang("your_pc"))
data class PCPokemonMove(
val pokemonID: UUID,
val oldPosition: PCPosition,
val newPosition: PCPosition
)
val boxes = mutableListOf<PCBox>()
protected var lockedSize = false
val backupStore = BottomlessStore(UUID(0L, 0L))
@@ -278,43 +270,6 @@ open class PCStore(
}
}
fun validateMoves(moves: List<PCPokemonMove>): Boolean {
if (moves.isEmpty() || moves.size > MovePCPokemonBatchPacket.MAX_MOVES) return false
if (moves.map { it.oldPosition }.toSet().size != moves.size ||
moves.map { it.newPosition }.toSet().size != moves.size ||
moves.map { it.pokemonID }.toSet().size != moves.size
) return false
if (moves.any { (_, source, target) -> !isValidPosition(source) || !isValidPosition(target) }) return false
val sourcePositions = moves.mapTo(mutableSetOf()) { it.oldPosition }
val pokemonMoves = moves.map { move ->
val pokemon = get(move.oldPosition)?.takeIf { it.uuid == move.pokemonID } ?: return false
move to pokemon
}
return !pokemonMoves.any { (move, _) -> get(move.newPosition) != null && move.newPosition !in sourcePositions }
}
fun moveBatch(moves: List<PCPokemonMove>): Boolean {
if (!validateMoves(moves)) return false
val pokemonMoves = moves.map { move ->
val pokemon = get(move.oldPosition)?.takeIf { it.uuid == move.pokemonID } ?: return false
move to pokemon
}
pokemonMoves.forEach { (move, _) -> setAtPosition(move.oldPosition, null) }
pokemonMoves.forEach { (move, pokemon) -> setAtPosition(move.newPosition, pokemon) }
val affectedBoxes = pokemonMoves
.flatMap { (move, _) -> listOf(move.oldPosition.box, move.newPosition.box) }
.distinct()
.map { boxes[it] }
affectedBoxes.forEach { sendPacketToObservers(SetPCBoxPacket(it)) }
pcChangeObservable.emit(Unit)
return true
}
override fun loadPositionFromNBT(nbt: CompoundTag): StoreCoordinates<PCPosition> {
return StoreCoordinates(this, PCPosition(nbt.getShort(DataKeys.STORE_BOX).toInt(), nbt.getByte(DataKeys.STORE_SLOT).toInt()))
}
@@ -111,7 +111,6 @@ object CobblemonClient {
val battleOverlay: BattleOverlay by lazy { BattleOverlay() }
val pokedexUsageContext: PokedexUsageContext by lazy { PokedexUsageContext() }
val rideControlsOverlay: RideControlsOverlay by lazy { RideControlsOverlay() }
var pcHealthToggle: Boolean = false
fun onLogin() {
clientPlayerData = ClientGeneralPlayerData()
@@ -29,7 +29,7 @@ class BoxStorageSlot(
val grabbedSlot = parent.grabbedSlot
return if (grabbedSlot == null) {
getPokemon().let { it == null || !parent.isInMultiSelection(it, position) }
true
} else {
grabbedSlot.getPokemon() != getPokemon()
}
@@ -50,8 +50,6 @@ import net.minecraft.network.chat.Component
import net.minecraft.sounds.SoundEvent
import kotlin.isInitialized
import net.minecraft.resources.ResourceLocation
import net.minecraft.util.FastColor
import org.lwjgl.glfw.GLFW
class PCGUI(
val pc: ClientPC,
@@ -100,8 +98,6 @@ class PCGUI(
private val buttonWallpaperResource = cobblemonResource("textures/gui/pc/pc_button_set_wallpaper.png")
private val buttonInfoArrow = cobblemonResource("textures/gui/pc/info_arrow.png")
private val buttonHealthToggleResource = cobblemonResource("textures/gui/pc/pc_button_toggle_health.png")
private val topSpacerResource = cobblemonResource("textures/gui/pc/pc_spacer_top.png")
private val bottomSpacerResource = cobblemonResource("textures/gui/pc/pc_spacer_bottom.png")
private val rightSpacerResource = cobblemonResource("textures/gui/pc/pc_spacer_right.png")
@@ -133,55 +129,6 @@ class PCGUI(
var selectPointerOffsetIncrement = false
var displayOptions = false
private var dragStartX: Int? = null
private var dragStartY: Int? = null
private var dragEndX: Int? = null
private var dragEndY: Int? = null
private var selectionDragActive = false
data class SelectionArea(val left: Int, val top: Int, val right: Int, val bottom: Int)
private data class BoxGridBounds(val left: Int, val top: Int, val right: Int, val bottom: Int) {
fun contains(x: Int, y: Int) = x in left..< right && y >= top && y < bottom
}
private fun getBoxGridBounds(): BoxGridBounds {
val left = storageWidget.x
val top = storageWidget.y
return BoxGridBounds(
left,
top,
left + StorageWidget.SCREEN_WIDTH,
top + StorageWidget.SCREEN_HEIGHT
)
}
fun getSelectionArea(): SelectionArea? {
if (!selectionDragActive) return null
val startX = dragStartX ?: return null
val startY = dragStartY ?: return null
val endX = dragEndX ?: return null
val endY = dragEndY ?: return null
val bounds = getBoxGridBounds()
if (!bounds.contains(startX, startY)) return null
val columns = 6
val rows = 5
val slotPitch = StorageSlot.SIZE + StorageWidget.BOX_SLOT_PADDING
val gridLeft = bounds.left + StorageWidget.BOX_SLOT_START_OFFSET_X
val gridTop = bounds.top + StorageWidget.BOX_SLOT_START_OFFSET_Y + if (displayOptions) 5 else 0
val startColumn = ((startX - gridLeft) / slotPitch).coerceIn(0, columns - 1)
val endColumn = (((endX.coerceIn(bounds.left, bounds.right - 1)) - gridLeft) / slotPitch).coerceIn(0, columns - 1)
val startRow = ((startY - gridTop) / slotPitch).coerceIn(0, rows - 1)
val endRow = (((endY.coerceIn(bounds.top, bounds.bottom - 1)) - gridTop) / slotPitch).coerceIn(0, rows - 1)
return SelectionArea(
gridLeft + minOf(startColumn, endColumn) * slotPitch, // left
gridTop + minOf(startRow, endRow) * slotPitch, // top
gridLeft + (maxOf(startColumn, endColumn) * slotPitch) + StorageSlot.SIZE, // right
gridTop + (maxOf(startRow, endRow) * slotPitch) + StorageSlot.SIZE // bottom
)
}
override fun renderBlurredBackground(delta: Float) {}
override fun renderMenuBackground(context: GuiGraphics) {}
@@ -272,6 +219,7 @@ class PCGUI(
storageWidget.setupStorageSlots()
for (button in optionButtons) {
button.visible = displayOptions
button.highlighted = false
}
}.also { it.highlighted = displayOptions }
)
@@ -302,28 +250,12 @@ class PCGUI(
configuration.showParty = isVisible
wallpaperWidget.visible = !isVisible
(it as IconButton).highlighted = !isVisible
if (unseenWallpapers.isNotEmpty()) MarkPCBoxWallpapersSeenPacket(unseenWallpapers).sendToServer()
if (!unseenWallpapers.isEmpty()) MarkPCBoxWallpapersSeenPacket(unseenWallpapers).sendToServer()
}.also {
it.visible = displayOptions
optionButtons.add(it)
})
val healthButton = this.addRenderableWidget(IconButton(
pX = x + 230,
pY = y + 31,
buttonWidth = 20,
buttonHeight = 20,
resource = buttonHealthToggleResource,
label = "toggle_health_bars",
) {
CobblemonClient.pcHealthToggle = !CobblemonClient.pcHealthToggle
(it as IconButton).highlighted = CobblemonClient.pcHealthToggle
}.also {
it.visible = displayOptions
optionButtons.add(it)
})
healthButton.highlighted = CobblemonClient.pcHealthToggle
PokemonSortMode.entries.forEachIndexed { index, sortType ->
val typeName = sortType.name.lowercase()
this.addRenderableWidget(IconButton(
@@ -383,20 +315,6 @@ class PCGUI(
super.init()
}
private fun renderSelectionBox(context: GuiGraphics, area: SelectionArea) {
context.pose().pushPose()
context.pose().translate(0.0, 0.0, 1500.0)
val borderColor = FastColor.ARGB32.color(255, 205, 212, 255)
val bgColor = FastColor.ARGB32.color(75, 133, 183, 230)
val thickness = 1
context.fill(area.left, area.top, area.right, area.bottom, bgColor)
context.fill(area.left, area.top, area.right, area.top + thickness, borderColor)
context.fill(area.left, area.bottom - thickness, area.right, area.bottom, borderColor)
context.fill(area.left, area.top, area.left + thickness, area.bottom, borderColor)
context.fill(area.right - thickness, area.top, area.right, area.bottom, borderColor)
context.pose().popPose()
}
override fun render(context: GuiGraphics, mouseX: Int, mouseY: Int, delta: Float) {
val matrices = context.pose()
renderBackground(context, mouseX, mouseY, delta)
@@ -537,20 +455,6 @@ class PCGUI(
shadow = true
)
// var dexNo = pokemon.species.nationalPokedexNumber.toString()
// while (dexNo.length < 4) {
// dexNo = "0$dexNo"
// }
// drawScaledText(
// context = context,
// font = CobblemonResources.DEFAULT_LARGE,
// text = Component.literal(dexNo).bold(),
// x = x + 38,
// y = y + 1.5,
// shadow = true,
// scale = 0.85f
// )
drawScaledText(
context = context,
font = CobblemonResources.DEFAULT_LARGE,
@@ -781,14 +685,12 @@ class PCGUI(
scale = SCALE
)
if (optionButtons.isNotEmpty() && displayOptions) {
if (!optionButtons.isEmpty() && displayOptions) {
for (button in optionButtons) button.showAlt = hasShiftDown()
}
super.render(context, mouseX, mouseY, delta)
getSelectionArea()?.let { renderSelectionBox(context, it) }
// Item Tooltip
if (pokemon != null) {
val displayedItem = if (showCosmeticItem) pokemon.cosmeticItem else pokemon.heldItemNoCopy()
@@ -810,20 +712,6 @@ class PCGUI(
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
storageWidget.clearPendingStorageSlotClick()
selectionDragActive = false
val clickX = mouseX.toInt()
val clickY = mouseY.toInt()
if (storageWidget.multiSelection == null && button == 0 &&
getBoxGridBounds().contains(clickX, clickY) &&
storageWidget.pastureWidget == null) {
dragStartX = clickX
dragStartY = clickY
} else {
dragStartX = null
dragStartY = null
}
// Trigger child component function as they will need to check the entire screen click area
if (::boxNameWidget.isInitialized) boxNameWidget.mouseClicked(mouseX, mouseY, button)
return super.mouseClicked(mouseX, mouseY, button)
@@ -852,43 +740,9 @@ class PCGUI(
storageWidget.pastureWidget?.let { pasture ->
if (pasture.pastureScrollList.isHovered) pasture.pastureScrollList.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
if (button == 0 && storageWidget.pastureWidget == null) {
val startX = dragStartX
val startY = dragStartY
if (startX != null && startY != null) {
val offsetX = mouseX - startX
val offsetY = mouseY - startY
if (offsetX * offsetX + offsetY * offsetY >= 25.0) {
selectionDragActive = true
storageWidget.clearPendingStorageSlotClick()
dragEndX = mouseX.toInt()
dragEndY = mouseY.toInt()
}
}
}
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
override fun mouseReleased(mouseX: Double, mouseY: Double, button: Int): Boolean {
val handled = super.mouseReleased(mouseX, mouseY, button)
if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT) {
if (selectionDragActive) {
dragEndX = mouseX.toInt()
dragEndY = mouseY.toInt()
storageWidget.updateSelection()
storageWidget.clearPendingStorageSlotClick()
} else {
storageWidget.completePendingStorageSlotClick(mouseX, mouseY)
}
}
dragStartX = null
dragStartY = null
dragEndX = null
dragEndY = null
selectionDragActive = false
return handled
}
override fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean {
val boxNameFocused = this::boxNameWidget.isInitialized && boxNameWidget.isFocused
val filterFocused = this::filterWidget.isInitialized && filterWidget.isFocused
@@ -1,37 +0,0 @@
package com.cobblemon.mod.common.client.gui.pc
import com.cobblemon.mod.common.pokemon.Pokemon
data class PCMultiSelection(
private val grid: MutableList<MutableList<Pokemon?>> = mutableListOf(),
val sourceBox: Int = 0,
val sourceColumn: Int = 0,
val sourceRow: Int = 0
) {
fun getHorizontalSize(): Int = grid.firstOrNull()?.size ?: 0
fun getVerticalSize(): Int = grid.size
constructor(horizontalSize: Int, verticalSize: Int, sourceBox: Int, sourceColumn: Int, sourceRow: Int) : this(
MutableList(verticalSize) { MutableList<Pokemon?>(horizontalSize) { null } },
sourceBox,
sourceColumn,
sourceRow
)
fun getPokemon(x: Int, y: Int): Pokemon? {
return grid[y][x]
}
fun setPokemon(x: Int, y: Int, pokemon: Pokemon?) {
grid[y][x] = pokemon
}
fun pokemonEntries(): List<Triple<Int, Int, Pokemon>> {
return grid.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, pokemon -> pokemon?.let { Triple(x, y, it) } }
}
}
fun getPokemonCount(): Int = pokemonEntries().size
}
@@ -45,13 +45,11 @@ class ReleaseButton(
vOffset = if (isHovered(mouseX.toDouble(), mouseY.toDouble())) HEIGHT else 0,
textureHeight = HEIGHT * 2
)
val pokemonCount = parent.multiSelection?.getPokemonCount() ?: 0
drawScaledText(
context = context,
font = CobblemonResources.DEFAULT_LARGE,
text = if (pokemonCount > 1)
{ lang("ui.pc.release_all").bold() } else { lang("ui.pc.release").bold() },
text = lang("ui.pc.release").bold(),
x = x + (WIDTH / 2),
y = y + 3.5,
centered = true,
@@ -10,11 +10,10 @@ package com.cobblemon.mod.common.client.gui.pc
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
import com.cobblemon.mod.common.client.gui.PokemonGUIAnimationStyle
import com.cobblemon.mod.common.client.gui.drawProfilePokemon
import com.cobblemon.mod.common.client.gui.pasture.PasturePCGUIConfiguration
import com.cobblemon.mod.common.client.gui.PokemonGUIAnimationStyle
import com.cobblemon.mod.common.client.render.drawScaledText
import com.cobblemon.mod.common.client.render.models.blockbench.FloatingState
import com.cobblemon.mod.common.client.render.renderScaledGuiItemIcon
@@ -23,19 +22,13 @@ import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.math.fromEulerXYZDegrees
import juuxel.adorn.util.Colors
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.Button
import net.minecraft.client.renderer.RenderType
import net.minecraft.client.sounds.SoundManager
import net.minecraft.network.chat.Component
import net.minecraft.util.Mth
import org.joml.Quaternionf
import org.joml.Vector3f
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
open class StorageSlot(
x: Int, y: Int,
@@ -61,17 +54,9 @@ open class StorageSlot(
}
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, delta: Float) {
val selectionArea = parent.pcGui.getSelectionArea()
if (selectionArea != null && parent.getSelectedPokemon(selectionArea).contains(this)) {
val highlightColor = 0x40FFFFFF
context.fill(x + 1, y, x + (SIZE - 1), y + SIZE, highlightColor)
context.fill(x, y + 1, x + 1, y + (SIZE - 1), highlightColor)
context.fill(x + SIZE - 1, y + 1, x + SIZE, y + (SIZE - 1), highlightColor)
}
if (shouldRender()) {
renderSlot(context, x, y, delta)
}
}
fun renderSlot(context: GuiGraphics, posX: Int, posY: Int, partialTicks: Float) {
@@ -145,23 +130,6 @@ open class StorageSlot(
matrixStack = matrices
)
}
// Pokemon health
// Taken from vanilla durability rendering
val currentHealth = pokemon.currentHealth
val maxHealth = pokemon.maxHealth.toFloat()
if (currentHealth < maxHealth && CobblemonClient.pcHealthToggle) {
val damageValue = maxHealth - currentHealth
val f = max(0.0f, (maxHealth - (maxHealth - currentHealth)) / maxHealth)
val color = Mth.hsvToRgb(f / 3.0f, 1.0f, 1.0f)
val totalWidth = 12
val width = (totalWidth - damageValue * totalWidth / pokemon.maxHealth.toFloat()).roundToInt();
val k = posX + 1
val l = posY + 6
val bgColor = if (this is PartyStorageSlot) Colors.BLACK else 0xFF3E3E3E.toInt()
context.fill(RenderType.guiOverlay(), k, l, k + totalWidth, l + 1, bgColor)
context.fill(RenderType.guiOverlay(), k, l, k + width, l + 1, color or bgColor)
}
matrices.popPose()
}
@@ -11,9 +11,9 @@ package com.cobblemon.mod.common.client.gui.pc
import com.cobblemon.mod.common.CobblemonNetwork
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.storage.StorePosition
import com.cobblemon.mod.common.api.storage.party.PartyPosition
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.bold
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.CobblemonResources
@@ -39,8 +39,8 @@ import net.minecraft.client.gui.components.Button
import net.minecraft.client.gui.screens.Screen
import net.minecraft.client.resources.sounds.SimpleSoundInstance
import net.minecraft.network.chat.Component
import net.minecraft.resources.ResourceLocation
import net.minecraft.sounds.SoundEvent
import java.util.UUID
class StorageWidget(
pX: Int, pY: Int,
@@ -77,15 +77,9 @@ class StorageWidget(
var displayConfirmRelease = false
var screenLoaded = false
var selectedPosition: PartyPosition? = null
var selectedPosition: StorePosition? = null
var grabbedSlot: GrabbedStorageSlot? = null
var multiSelection: PCMultiSelection? = null
private val multiGrabbedSlots = mutableMapOf<UUID, GrabbedStorageSlot>()
private var pendingStorageSlotClick: Button? = null
private var movePending = false
private var movePendingSince = 0L
var box = 0
set(value) {
field =
@@ -119,24 +113,19 @@ class StorageWidget(
subKey = "ui.generic.yes",
onPress = {
if (canDeleteSelected() && displayConfirmRelease) {
val selection = multiSelection
if (selection != null) {
selection.pokemonEntries().forEach { (column, row, pokemon) ->
val position = PCPosition(
selection.sourceBox,
(selection.sourceRow + row) * 6 + selection.sourceColumn + column
)
CobblemonNetwork.sendToServer(ReleasePCPokemonPacket(pokemon.uuid, position))
}
} else {
val position = selectedPosition ?: return@ReleaseConfirmButton
val pokemon = getSelectedPokemon() ?: return@ReleaseConfirmButton
val position = selectedPosition ?: return@ReleaseConfirmButton
val pokemon = getSelectedPokemon() ?: return@ReleaseConfirmButton
CobblemonNetwork.sendToServer(ReleasePartyPokemonPacket(pokemon.uuid, position))
val packet = when (position) {
is PartyPosition -> ReleasePartyPokemonPacket(pokemon.uuid, position)
is PCPosition -> ReleasePCPokemonPacket(pokemon.uuid, position)
else -> return@ReleaseConfirmButton
}
CobblemonNetwork.sendToServer(packet)
playSound(CobblemonSounds.PC_RELEASE)
resetSelected()
displayConfirmRelease = false
}
}
)
@@ -160,8 +149,9 @@ class StorageWidget(
}
fun canDeleteSelected(): Boolean {
multiSelection?.let { return it.pokemonEntries().isNotEmpty() }
return party.filterNotNull().size > 1 && selectedPosition != null && grabbedSlot != null
return !(selectedPosition is PartyPosition && party.filterNotNull().size <= 1)
&& selectedPosition != null
&& grabbedSlot != null
}
fun setupStorageSlots() {
@@ -180,7 +170,7 @@ class StorageWidget(
parent = this,
pc = pc,
position = PCPosition(box, index),
onPress = { pendingStorageSlotClick = it }
onPress = { this.onStorageSlotClicked(it) }
).also { widget ->
this.addWidget(widget)
this.boxSlots.add(widget)
@@ -210,7 +200,7 @@ class StorageWidget(
parent = this,
party = party,
position = PartyPosition(partyIndex),
onPress = { pendingStorageSlotClick = it }
onPress = { this.onStorageSlotClicked(it) }
).also { widget ->
this.addWidget(widget)
this.partySlots.add(widget)
@@ -220,118 +210,14 @@ class StorageWidget(
private fun getSelectedPokemon(): Pokemon? {
val selectedPosition = this.selectedPosition ?: return null
return party.get(selectedPosition)
}
fun getSelectedPokemon(area: PCGUI.SelectionArea): List<BoxStorageSlot> {
return boxSlots.filter { slot ->
slot.x < area.right && slot.x + StorageSlot.SIZE > area.left &&
slot.y < area.bottom && slot.y + StorageSlot.SIZE > area.top &&
slot.getPokemon()?.let(pcGui.search::passes) == true
return when (selectedPosition) {
is PCPosition -> pc.get(selectedPosition)
is PartyPosition -> party.get(selectedPosition)
else -> null
}
}
fun clearPendingStorageSlotClick() {
pendingStorageSlotClick = null
}
fun completePendingStorageSlotClick(mouseX: Double, mouseY: Double) {
val button = pendingStorageSlotClick ?: return
pendingStorageSlotClick = null
if (button.isMouseOver(mouseX, mouseY)) {
onStorageSlotClicked(button)
}
}
fun updateSelection() {
val area = pcGui.getSelectionArea()
if (area == null) {
multiSelection = null
return
}
selectedPosition = null
grabbedSlot = null
pcGui.setPreviewPokemon(null)
val selectedSlots = getSelectedPokemon(area)
if (selectedSlots.isEmpty()) {
multiSelection = null
return
}
val minColumn = selectedSlots.minOf { it.position.slot % 6 }
val maxColumn = selectedSlots.maxOf { it.position.slot % 6 }
val minRow = selectedSlots.minOf { it.position.slot / 6 }
val maxRow = selectedSlots.maxOf { it.position.slot / 6 }
val selection = PCMultiSelection(maxColumn - minColumn + 1, maxRow - minRow + 1, box, minColumn, minRow)
selectedSlots.forEach { slot ->
val pokemon = slot.getPokemon() ?: return@forEach
val slotIndex = slot.position.slot
val column = slotIndex % 6
val row = slotIndex / 6
if (column in minColumn..maxColumn && row in minRow..maxRow) {
selection.setPokemon(column - minColumn, row - minRow, pokemon)
}
}
playSound(CobblemonSounds.PC_GRAB)
multiSelection = selection
}
private fun moveMultiSelectionTo(destination: PCPosition): Boolean {
val selection = multiSelection ?: return false
val width = selection.getHorizontalSize()
val height = selection.getVerticalSize()
val destinationColumn = destination.slot % 6
val destinationRow = destination.slot / 6
if (destinationColumn + width > 6 || destinationRow + height > 5) return false
val moves = mutableListOf<PCStore.PCPokemonMove>()
val selectedSources = mutableSetOf<PCPosition>()
repeat(height) { row ->
repeat(width) { column ->
val pokemon = selection.getPokemon(column, row) ?: return@repeat
val source = PCPosition(selection.sourceBox, (selection.sourceRow + row) * 6 + selection.sourceColumn + column)
val target = PCPosition(destination.box, (destinationRow + row) * 6 + destinationColumn + column)
selectedSources.add(source)
moves.add(PCStore.PCPokemonMove(pokemon.uuid, source, target))
}
}
if (moves.isEmpty()) return false
repeat(height) { row ->
repeat(width) { column ->
if (selection.getPokemon(column, row) == null) return@repeat
val target = PCPosition(destination.box, (destinationRow + row) * 6 + destinationColumn + column)
val displacedPokemon = pc.get(target) ?: return@repeat
if (target in selectedSources) return@repeat
val displacedSource = PCPosition(
selection.sourceBox,
(selection.sourceRow + row) * 6 + selection.sourceColumn + column
)
if (pc.get(displacedSource) != null && displacedSource !in selectedSources) return false
moves.add(PCStore.PCPokemonMove(displacedPokemon.uuid, target, displacedSource))
}
}
if (moves.map { it.newPosition }.toSet().size != moves.size) return false
MovePCPokemonBatchPacket(moves).sendToServer()
return true
}
fun isInMultiSelection(pokemon: Pokemon, position: PCPosition): Boolean {
val selection = multiSelection ?: return false
return selection.sourceBox == position.box && selection.pokemonEntries().any { it.third == pokemon }
}
override fun renderWidget(context: GuiGraphics, mouseX: Int, mouseY: Int, delta: Float) {
updatePendingMove()
val matrices = context.pose()
// Party Label
if (pcGui.configuration.showParty) {
@@ -354,14 +240,11 @@ class StorageWidget(
shadow = true
)
val pokemonCount = multiSelection?.getPokemonCount() ?: 0
if (canDeleteSelected() && displayConfirmRelease) {
drawScaledText(
context = context,
font = CobblemonResources.DEFAULT_LARGE,
text = if (pokemonCount > 1)
{ lang("ui.pc.release_all").bold() } else { lang("ui.pc.release").bold() },
text = lang("ui.pc.release").bold(),
x = x + 223,
y = y + 119,
centered = true
@@ -425,7 +308,6 @@ class StorageWidget(
slot.render(context, mouseX, mouseY, delta)
val pokemon = slot.getPokemon()
if (grabbedSlot == null && slot.isHovered(mouseX, mouseY)
&& multiSelection == null
&& pokemon != null && pokemon != pcGui.previewPokemon
) {
pcGui.setPreviewPokemon(pokemon, pcGui.isPreviewInParty ?: false)
@@ -442,7 +324,6 @@ class StorageWidget(
slot.render(context, mouseX, mouseY, delta)
val pokemon = slot.getPokemon()
if (grabbedSlot == null && slot.isHovered(mouseX, mouseY)
&& multiSelection == null
&& pokemon != null && pokemon != pcGui.previewPokemon
) {
pcGui.setPreviewPokemon(pokemon, pcGui.isPreviewInParty ?: true)
@@ -454,32 +335,10 @@ class StorageWidget(
pastureWidget?.render(context, mouseX, mouseY, delta)
matrices.pushPose()
matrices.translate(0.0, 0.0, 1000.0)
renderSelectedPokemon(context, mouseX, mouseY, delta)
grabbedSlot?.render(context, mouseX, mouseY, delta)
matrices.popPose()
}
private fun renderSelectedPokemon(context: GuiGraphics, mouseX: Int, mouseY: Int, delta: Float) {
if (movePending) return
val selection = multiSelection
if (selection == null) {
grabbedSlot?.render(context, mouseX, mouseY, delta)
return
}
val slotOffset = StorageSlot.SIZE + BOX_SLOT_PADDING
selection.pokemonEntries().forEach { (column, row, pokemon) ->
val grabbed = multiGrabbedSlots.getOrPut(pokemon.uuid) {
GrabbedStorageSlot(0, 0, this, pokemon)
}
grabbed.render(
context,
mouseX + column * slotOffset,
mouseY + row * slotOffset,
delta
)
}
}
override fun mouseClicked(pMouseX: Double, pMouseY: Double, pButton: Int): Boolean {
if (displayConfirmRelease) {
if (releaseYesButton.isHovered(pMouseX, pMouseY)) releaseYesButton.mouseClicked(pMouseX, pMouseY, pButton)
@@ -512,55 +371,23 @@ class StorageWidget(
else -> return
}
val clickedPokemon = when (clickedPosition) {
is PCPosition -> pc.get(clickedPosition)
is PartyPosition -> party.get(clickedPosition)
else -> null
}
multiSelection?.let { selection ->
when (clickedPosition) {
is PCPosition -> {
if (clickedPosition.box == selection.sourceBox &&
clickedPosition.slot == selection.sourceRow * 6 + selection.sourceColumn
) {
resetSelected()
} else if (moveMultiSelectionTo(clickedPosition)) {
playSound(CobblemonSounds.PC_DROP)
movePending = true
}
}
is PartyPosition -> {
val selectedPokemon = selection.pokemonEntries().singleOrNull() ?: return
val (column, row, pokemon) = selectedPokemon
val source = PCPosition(
selection.sourceBox,
(selection.sourceRow + row) * 6 + selection.sourceColumn + column
)
if (pc.get(source) !== pokemon) return
val packet = clickedPokemon?.let {
SwapPCPartyPokemonPacket(it.uuid, clickedPosition, pokemon.uuid, source)
} ?: MovePCPokemonToPartyPacket(pokemon.uuid, source, clickedPosition)
packet.sendToServer()
playSound(CobblemonSounds.PC_DROP)
movePending = true
}
else -> Unit
}
return
}
// Reset release confirmation
displayConfirmRelease = false
// Clicking on itself, so unselect position
if (selectedPosition == clickedPosition) {
if (this.selectedPosition != null && this.selectedPosition == clickedPosition) {
if (grabbedSlot != null) playSound(CobblemonSounds.PC_DROP)
resetSelected()
return
}
// Check for selecting a Pokémon
val clickedPokemon = when(button) {
is BoxStorageSlot -> pc.get(clickedPosition as PCPosition)
is PartyStorageSlot -> party.get(clickedPosition as PartyPosition)
else -> null
}
val selectOverride = pcGui.configuration.selectOverride
if (selectOverride != null) {
selectOverride(pcGui, clickedPosition, clickedPokemon)
@@ -593,47 +420,59 @@ class StorageWidget(
}
}
if (clickedPosition is PCPosition) {
val column = clickedPosition.slot % 6
val row = clickedPosition.slot / 6
multiSelection = PCMultiSelection(1, 1, clickedPosition.box, column, row).also {
it.setPokemon(0, 0, clickedPokemon)
}
playSound(CobblemonSounds.PC_GRAB)
return
} else if (clickedPosition is PartyPosition) {
this.selectedPosition = clickedPosition
this.pcGui.setPreviewPokemon(clickedPokemon, pcGui.isPreviewInParty ?: false)
grabbedSlot = GrabbedStorageSlot(
x = button.x,
y = button.y,
parent = this,
pokemon = clickedPokemon
)
playSound(CobblemonSounds.PC_GRAB)
}
this.selectedPosition = clickedPosition
this.pcGui.setPreviewPokemon(clickedPokemon, pcGui.isPreviewInParty ?: false)
grabbedSlot = GrabbedStorageSlot(
x = button.x,
y = button.y,
parent = this,
pokemon = clickedPokemon
)
playSound(CobblemonSounds.PC_GRAB)
}
} else {
val sourcePosition = selectedPosition ?: return
val selectedPokemon = party.get(sourcePosition) ?: return
// Handle movement within the Box
val selectedPokemon = when(this.selectedPosition) {
is PCPosition -> pc.get(this.selectedPosition as PCPosition)
is PartyPosition -> party.get(this.selectedPosition as PartyPosition)
else -> null
} ?: return
// Box to Box
if (this.selectedPosition is PCPosition && clickedPosition is PCPosition) {
val packet = clickedPokemon?.let { SwapPCPokemonPacket(it.uuid, clickedPosition, selectedPokemon.uuid, this.selectedPosition as PCPosition) }
?: MovePCPokemonPacket(selectedPokemon.uuid, selectedPosition as PCPosition, clickedPosition)
packet.sendToServer()
playSound(CobblemonSounds.PC_DROP)
resetSelected()
}
// Box to Party
else if (this.selectedPosition is PCPosition && clickedPosition is PartyPosition) {
val packet = clickedPokemon?.let { SwapPCPartyPokemonPacket(clickedPokemon.uuid, clickedPosition, selectedPokemon.uuid, this.selectedPosition as PCPosition) }
?: MovePCPokemonToPartyPacket(selectedPokemon.uuid, this.selectedPosition as PCPosition, clickedPosition)
packet.sendToServer()
playSound(CobblemonSounds.PC_DROP)
resetSelected()
}
// Party to Box
if (clickedPosition is PCPosition) {
else if (this.selectedPosition is PartyPosition && clickedPosition is PCPosition) {
if (ServerSettings.preventCompletePartyDeposit && this.party.filterNotNull().size == 1 && clickedPokemon == null) {
return
}
val packet = clickedPokemon?.let { SwapPCPartyPokemonPacket(selectedPokemon.uuid, sourcePosition, clickedPokemon.uuid, clickedPosition) }
?: MovePartyPokemonToPCPacket(selectedPokemon.uuid, sourcePosition, clickedPosition)
val packet = clickedPokemon?.let { SwapPCPartyPokemonPacket(selectedPokemon.uuid, this.selectedPosition as PartyPosition, clickedPokemon.uuid, clickedPosition) }
?: MovePartyPokemonToPCPacket(selectedPokemon.uuid, this.selectedPosition as PartyPosition, clickedPosition)
packet.sendToServer()
playSound(CobblemonSounds.PC_DROP)
movePending = true
resetSelected()
}
// Party to Party
else if (clickedPosition is PartyPosition) {
val packet = clickedPokemon?.let { SwapPartyPokemonPacket(it.uuid, clickedPosition, selectedPokemon.uuid, sourcePosition) }
?: MovePartyPokemonPacket(selectedPokemon.uuid, sourcePosition, clickedPosition)
else if (this.selectedPosition is PartyPosition && clickedPosition is PartyPosition) {
val packet = clickedPokemon?.let { SwapPartyPokemonPacket(it.uuid, clickedPosition, selectedPokemon.uuid, this.selectedPosition as PartyPosition) }
?: MovePartyPokemonPacket(selectedPokemon.uuid, selectedPosition as PartyPosition, clickedPosition)
packet.sendToServer()
playSound(CobblemonSounds.PC_DROP)
movePending = true
resetSelected()
}
}
}
@@ -641,37 +480,6 @@ class StorageWidget(
fun resetSelected() {
selectedPosition = null
grabbedSlot = null
multiSelection = null
multiGrabbedSlots.clear()
displayConfirmRelease = false
pcGui.setPreviewPokemon(null)
}
// annoyingly complex solution, but server/client desync causes flashing when moving pokemon. this should fix it
// if you can think of a simpler solution, feel free to implement it
private fun updatePendingMove() {
if (!movePending) return
val selection = multiSelection
if (selection != null) {
val updated = selection.pokemonEntries().any { (column, row, pokemon) ->
val source = PCPosition(selection.sourceBox, (selection.sourceRow + row) * 6 + selection.sourceColumn + column)
pc.get(source)?.uuid != pokemon.uuid
}
if (updated) {
movePending = false
resetSelected()
}
return
}
val source = selectedPosition
val pokemon = grabbedSlot?.getPokemon()
if (source != null && pokemon != null) {
if (party.get(source)?.uuid != pokemon.uuid) {
movePending = false
resetSelected()
}
}
}
}
@@ -6,23 +6,59 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.client.gui.summary.widgets.screens.moves
package com.cobblemon.mod.common.client.gui.summary
import com.cobblemon.mod.common.client.gui.CobblemonRenderable
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.ObjectSelectionList
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.util.Mth
class MoveDescriptionScrollList(
class ScrollableTextBoxEntry(
var line : MutableComponent
) :
ObjectSelectionList.Entry<ScrollableTextBoxEntry>() {
override fun render(
context: GuiGraphics,
index: Int,
rowTop: Int,
rowLeft: Int,
rowWidth: Int,
rowHeight: Int,
mouseX: Int,
mouseY: Int,
isHovered: Boolean,
partialTicks: Float
) {
drawScaledText(
context = context,
text = line,
x = rowLeft + 82,
y = rowTop,
scale = 0.5F,
shadow = true
)
}
override fun getNarration(): Component {
return line
}
}
class ScrollableTextBox(
private val listX: Int,
private val listY: Int,
height: Int,
width: Int,
slotHeight: Int
) : ObjectSelectionList<MoveDescriptionEntry>(
) : ObjectSelectionList<ScrollableTextBoxEntry>(
Minecraft.getInstance(),
60, // width
30, // height
width, // width
height, // height
0, // top
slotHeight
), CobblemonRenderable {
@@ -38,8 +74,31 @@ class MoveDescriptionScrollList(
return x + width - 3
}
override fun getMaxPosition(): Int {
return super.getMaxPosition() + 3 // add bottom padding
}
// we do our own scrollbar rendering, and this being true renders the vanilla one
override fun scrollbarVisible() = false
override fun renderWidget(context: GuiGraphics, pMouseX: Int, pMouseY: Int, f: Float) {
isHovered = pMouseX >= x && pMouseY >= y && pMouseX < x + width && pMouseY < y + height
if (maxScroll > 0) {
val right = x + width
val bottom = y + height
val darkGray = 0xFF5B595B.toInt()
val lightGray = 0xFF8C8C8C.toInt()
context.fill(right - 2, y + 2, right - 4, bottom - 2, darkGray)
// vanilla scrollbar mumbo jumbo
var scrollHeight = ((height * height).toFloat() / maxPosition.toFloat()).toInt()
scrollHeight = Mth.clamp(scrollHeight, 32, height - 8)
var scrollY = scrollAmount.toInt() * (height - scrollHeight + 2) / maxScroll + y - 1
if (scrollY < y) { scrollY = y }
context.fill(right - 2, scrollY + 2, right - 4, scrollY + scrollHeight - 3, lightGray)
}
context.enableScissor(
x,
y,
@@ -79,7 +138,7 @@ class MoveDescriptionScrollList(
&& mouseY < bottom
}
fun setMoveDescription(moveDescription: MutableComponent) {
fun setText(moveDescription: MutableComponent) {
clearEntries()
val splitWidth = 100
val text = moveDescription.string
@@ -103,7 +162,8 @@ class MoveDescriptionScrollList(
}
for (part in splitText) {
addEntry(MoveDescriptionEntry(Component.literal(part)))
addEntry(ScrollableTextBoxEntry(Component.literal(part)))
}
scrollAmount = 0.0
}
}
@@ -13,6 +13,7 @@ import com.cobblemon.mod.common.api.gui.MultiLineLabelK
import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.text.*
import com.cobblemon.mod.common.client.CobblemonResources
import com.cobblemon.mod.common.client.gui.summary.ScrollableTextBox
import com.cobblemon.mod.common.client.gui.summary.widgets.SoundlessWidget
import com.cobblemon.mod.common.client.gui.summary.widgets.common.reformatNatureTextIfMinted
import com.cobblemon.mod.common.client.gui.summary.widgets.screens.stats.StatWidget.Companion.SCALE
@@ -27,6 +28,7 @@ import net.minecraft.client.Minecraft
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
class InfoWidget(
pX: Int,
@@ -45,6 +47,25 @@ class InfoWidget(
private val infoBaseResource = cobblemonResource("textures/gui/summary/summary_info_base.png")
}
private var metDataWidget: ScrollableTextBox = ScrollableTextBox(x + 5, y + 123, 20, 61, 5)
init {
pokemon.metData?.let { metData ->
val biome = ResourceLocation.parse(metData.biome.registeredName)
val biomeName = Component.translatable("biome.${biome.namespace}.${biome.path}")
metDataWidget.setText(lang("ui.info.met_data.${metData.variant.serializedName}",
biomeName,
metData.date.monthValue,
metData.date.dayOfMonth,
metData.date.year,
metData.level
))
} ?: run {
metDataWidget.setText(lang("ui.info.met_data.unavailable"))
}
addWidget(metDataWidget)
}
override fun renderWidget(context: GuiGraphics, pMouseX: Int, pMouseY: Int, pPartialTicks: Float) {
val matrices = context.pose()
// Base texture
@@ -163,6 +184,8 @@ class InfoWidget(
)
matrices.popPose()
metDataWidget.render(context, pMouseX, pMouseY, pPartialTicks)
drawScaledText(
context = context,
text = lang("ui.info.experience_points"),
@@ -1,47 +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.summary.widgets.screens.moves
import com.cobblemon.mod.common.client.render.drawScaledText
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.components.ObjectSelectionList
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
class MoveDescriptionEntry(
var line : MutableComponent
) :
ObjectSelectionList.Entry<MoveDescriptionEntry>() {
override fun render(
context: GuiGraphics,
index: Int,
rowTop: Int,
rowLeft: Int,
rowWidth: Int,
rowHeight: Int,
mouseX: Int,
mouseY: Int,
isHovered: Boolean,
partialTicks: Float
) {
drawScaledText(
context = context,
text = line,
x = rowLeft + 82,
y = rowTop,
scale = 0.5F,
shadow = true
)
}
override fun getNarration(): Component {
return line
}
}
@@ -13,6 +13,7 @@ import com.cobblemon.mod.common.api.gui.blitk
import com.cobblemon.mod.common.api.moves.Move
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.client.CobblemonClient
import com.cobblemon.mod.common.client.gui.summary.ScrollableTextBox
import com.cobblemon.mod.common.client.gui.summary.Summary
import com.cobblemon.mod.common.client.gui.summary.widgets.SoundlessWidget
import com.cobblemon.mod.common.client.render.drawScaledText
@@ -70,9 +71,11 @@ class MovesWidget(
addWidget(it)
}
private var descriptionScrollList = MoveDescriptionScrollList(
x + 69,
private var descriptionScrollList = ScrollableTextBox(
x + 68,
y + 113,
30,
61,
5
)
@@ -215,7 +218,7 @@ class MovesWidget(
fun selectMove(move: Move?) {
selectedMove = if (selectedMove == move || move == null) null else move
descriptionScrollList.setMoveDescription(selectedMove?.description ?: "".text())
descriptionScrollList.setText(selectedMove?.description ?: "".text())
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
@@ -0,0 +1,45 @@
/*
* 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.sound.conditional
import com.cobblemon.mod.common.api.audio.condition.AudioContext
import com.cobblemon.mod.common.client.sound.conditional.ConditionalSoundContext.ctx
import net.minecraft.client.Minecraft
import net.minecraft.client.multiplayer.ClientLevel
/** One shared [AudioContext], refreshed at most once per game tick. */
object ConditionalSoundContext {
private val ctx = AudioContext()
private var level: ClientLevel? = null
private var time = 0L
/** Bumped whenever [ctx] is refreshed. */
var version = 0
private set
fun current(): AudioContext? {
val mc = Minecraft.getInstance() ?: return null
val player = mc.player
val level = mc.level
if (player == null || level == null) {
if (this.level != null) {
this.level = null
ctx.clear()
}
return null
}
if (level !== this.level || level.gameTime != time) {
this.level = level
time = level.gameTime
ctx.update(player, level)
version++
}
return ctx
}
}
@@ -0,0 +1,128 @@
/*
* 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.sound.conditional
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.api.audio.ConditionalSounds
import com.cobblemon.mod.common.api.audio.condition.builtin.BuiltinConditions
import com.cobblemon.mod.common.api.data.DataRegistry
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.util.cobblemonResource
import com.google.gson.JsonParser
import com.mojang.serialization.JsonOps
import net.minecraft.client.Minecraft
import net.minecraft.client.sounds.SoundManager
import net.minecraft.resources.FileToIdConverter
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.server.packs.PackType
import net.minecraft.server.packs.resources.ResourceManager
/**
* Client-only registry of `assets/<ns>/conditional_sounds/` files. On reload it also adds a [ConditionalWeightedSound] per
* entry to each target sound event.
*
* Not registered with CobblemonDataProvider on purpose: its client reloader has no ordering against SoundManager,
* and the entries must be added to the sound registry SoundManager just rebuilt. So SoundManagerMixin reloads this
* at the end of SoundManager#apply (client thread).
*/
object ConditionalSoundsRegistry : DataRegistry {
override val id = cobblemonResource("conditional_sounds")
override val type = PackType.CLIENT_RESOURCES
override val observable = SimpleObservable<ConditionalSoundsRegistry>()
private val files = FileToIdConverter.json("conditional_sounds")
private var definitions: Map<ResourceLocation, ConditionalSounds> = emptyMap()
fun all(): Map<ResourceLocation, ConditionalSounds> = definitions
fun get(id: ResourceLocation): ConditionalSounds? = definitions[id]
override fun sync(player: ServerPlayer) {}
override fun reload(manager: ResourceManager) {
BuiltinConditions.bootstrap()
val loaded = sortedMapOf<ResourceLocation, ConditionalSounds>()
for ((path, resource) in files.listMatchingResources(manager)) {
val id = files.fileToId(path)
try {
val json = resource.openAsReader().use(JsonParser::parseReader)
val result = ConditionalSounds.CODEC.parse(JsonOps.INSTANCE, json)
result.result().ifPresentOrElse({ loaded[id] = it }) {
LOGGER.error("Skipping conditional sounds {}: {}", id, result.error().get().message())
}
} catch (e: Exception) {
LOGGER.error("Skipping conditional sounds {}", id, e)
}
}
definitions = loaded
addToSoundEvents(Minecraft.getInstance().soundManager)
observable.emit(this)
}
private fun addToSoundEvents(soundManager: SoundManager) {
val targetsByFile = definitions.mapValues { (id, def) -> resolveTargets(id, def.targets, soundManager) }
val allTargets = targetsByFile.values.flatten().toSet()
var added = 0
for ((id, def) in definitions) {
val targets = targetsByFile.getValue(id)
for (entry in def.sounds) {
if (entry.sound in allTargets) {
LOGGER.error(
"Conditional sounds {}: {} is also a target, which would loop; skipped",
id,
entry.sound
)
continue
}
val delegate = soundManager.getSoundEvent(entry.sound)
if (delegate == null) {
LOGGER.warn(
"Conditional sounds {}: sound event {} is not defined in any sounds.json; skipped",
id,
entry.sound
)
continue
}
val sound = ConditionalWeightedSound(def.conditions, entry.conditions, entry.weight, delegate)
targets.forEach { soundManager.getSoundEvent(it)!!.addSound(sound) }
added += targets.size
}
}
LOGGER.info("Loaded {} conditional sounds files, added {} entries", definitions.size, added)
}
private fun resolveTargets(
file: ResourceLocation,
targets: List<String>,
soundManager: SoundManager
): List<ResourceLocation> {
val out = LinkedHashSet<ResourceLocation>()
for (target in targets) {
if (target.endsWith("*")) {
val prefix = target.dropLast(1)
val matches = soundManager.availableSounds.filter { it.toString().startsWith(prefix) }
if (matches.isEmpty()) LOGGER.warn(
"Conditional sounds {}: target {} matches no sound events",
file,
target
)
out += matches
continue
}
val id = ResourceLocation.tryParse(target)
if (id == null || soundManager.getSoundEvent(id) == null) {
LOGGER.warn("Conditional sounds {}: target {} is not a defined sound event", file, target)
} else {
out += id
}
}
return out.toList()
}
}
@@ -0,0 +1,47 @@
/*
* 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.sound.conditional
import com.cobblemon.mod.common.api.audio.condition.AudioCondition
import net.minecraft.client.resources.sounds.Sound
import net.minecraft.client.sounds.SoundEngine
import net.minecraft.client.sounds.WeighedSoundEvents
import net.minecraft.client.sounds.Weighted
import net.minecraft.util.RandomSource
/**
* An entry added to a vanilla [WeighedSoundEvents]. Its weight is 0 while its conditions fail, so vanilla's
* own weighted pick (WeighedSoundEvents#getSound) simply skips it. Client thread only.
*/
class ConditionalWeightedSound(
private val gate: List<AudioCondition>,
private val conditions: List<AudioCondition>,
private val weight: Int,
private val delegate: WeighedSoundEvents
) : Weighted<Sound> {
private val unconditional = gate.isEmpty() && conditions.isEmpty()
private var version = -1
private var matched = false
override fun getWeight(): Int = if (matches()) weight else 0
override fun getSound(random: RandomSource): Sound = delegate.getSound(random)
override fun preloadIfRequired(engine: SoundEngine) {}
private fun matches(): Boolean {
if (unconditional) return true
val ctx = ConditionalSoundContext.current() ?: return false
if (version != ConditionalSoundContext.version) {
version = ConditionalSoundContext.version
matched = AudioCondition.all(gate, ctx) && AudioCondition.all(conditions, ctx)
}
return matched
}
}
@@ -47,6 +47,7 @@ import com.cobblemon.mod.common.net.messages.client.battle.BattleCaptureStartPac
import com.cobblemon.mod.common.net.messages.client.effect.SpawnSnowstormEntityParticlePacket
import com.cobblemon.mod.common.net.messages.client.spawn.SpawnPokeballPacket
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.pokemon.PokemonMetData
import com.cobblemon.mod.common.pokemon.ai.PokemonBrain
import com.cobblemon.mod.common.pokemon.properties.UncatchableProperty
import com.cobblemon.mod.common.util.*
@@ -357,6 +358,7 @@ class EmptyPokeBallEntity : ThrowableItemProjectile, PosableEntity, WaterDragMod
val party = player.party()
pokemon.pokemon.caughtBall = pokeBall
pokeBall.effects.forEach { effect -> effect.apply(player, pokemon.pokemon) }
pokemon.pokemon.metData = PokemonMetData.create(player, pokemon.pokemon)
party.add(pokemon.pokemon)
val leashHolder = pokemon.leashHolder
@@ -1,48 +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://www.mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.net.messages.server.storage.pc
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.storage.pc.PCStore
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.readPCPosition
import com.cobblemon.mod.common.util.writePCPosition
import net.minecraft.network.RegistryFriendlyByteBuf
class MovePCPokemonBatchPacket(val moves: List<PCStore.PCPokemonMove>) : NetworkPacket<MovePCPokemonBatchPacket> {
override val id = ID
override fun encode(buffer: RegistryFriendlyByteBuf) {
buffer.writeVarInt(moves.size)
moves.forEach { move ->
buffer.writeUUID(move.pokemonID)
buffer.writePCPosition(move.oldPosition)
buffer.writePCPosition(move.newPosition)
}
}
companion object {
val ID = cobblemonResource("move_pc_pokemon_batch")
const val MAX_MOVES = 60
fun decode(buffer: RegistryFriendlyByteBuf): MovePCPokemonBatchPacket {
val size = buffer.readVarInt()
require(size in 1..MAX_MOVES) { "Invalid batch PC move size: $size" }
return MovePCPokemonBatchPacket(
List(size) {
PCStore.PCPokemonMove(
pokemonID = buffer.readUUID(),
oldPosition = buffer.readPCPosition(),
newPosition = buffer.readPCPosition()
)
}
)
}
}
}
@@ -1,24 +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://www.mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.net.serverhandling.storage.pc
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.api.storage.pc.PCStore
import com.cobblemon.mod.common.api.storage.pc.link.PCLinkManager
import com.cobblemon.mod.common.net.messages.client.storage.pc.ClosePCPacket
import com.cobblemon.mod.common.net.messages.server.storage.pc.MovePCPokemonBatchPacket
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerPlayer
object MovePCPokemonBatchHandler : ServerNetworkPacketHandler<MovePCPokemonBatchPacket> {
override fun handle(packet: MovePCPokemonBatchPacket, server: MinecraftServer, player: ServerPlayer) {
val pc = PCLinkManager.getPC(player) ?: return run { ClosePCPacket(null).sendToPlayer(player) }
pc.moveBatch(packet.moves.map { PCStore.PCPokemonMove(it.pokemonID, it.oldPosition, it.newPosition) })
}
}
@@ -550,6 +550,8 @@ open class Pokemon : ShowdownIdentifiable {
onChange(OriginalTrainerUpdatePacket({ this }, value))
}
var metData: PokemonMetData? = null
/**
* Cache friendship on trade for OT
*/
@@ -1527,6 +1529,7 @@ open class Pokemon : ShowdownIdentifiable {
this.potentialMarks.clear()
this.potentialMarks += other.marks
this.markings = other.markings
this.metData = other.metData
this.recalculateCharacteristic()
this.updateAspects()
this.refreshOriginalTrainer()
@@ -0,0 +1,89 @@
/*
* 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.pokemon
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.core.Holder
import net.minecraft.util.StringRepresentable
import net.minecraft.world.entity.player.Player
import net.minecraft.world.level.biome.Biome
import java.time.LocalDate
import java.time.ZoneId
enum class PokemonMetDataVariant(private val string: String) : StringRepresentable {
STANDARD("standard"),
STARTER("starter");
override fun getSerializedName(): String {
return string
}
companion object {
fun getFromName(name: String): PokemonMetDataVariant? {
return entries.firstOrNull { it.string == name }
}
}
}
/**
* Stores information about the circumstances of a player's meeting with a [Pokemon]
*
* @param biome A [Holder] for the [Biome] the [Pokemon] was caught in
* @param date A [LocalDate] of the real life date the [Pokemon] was caught
* @param level The level the [Pokemon] was when caught
* @param variant The text variant to display. Defaults to [PokemonMetDataVariant.STANDARD]
*/
@ConsistentCopyVisibility
data class PokemonMetData private constructor(
val biome: Holder<Biome>,
val date: LocalDate,
val level: Int,
val variant: PokemonMetDataVariant = PokemonMetDataVariant.STANDARD
) {
companion object {
private val LOCAL_DATE_CODEC: Codec<LocalDate> = Codec.STRING.xmap(
LocalDate::parse,
LocalDate::toString
)
fun create(player: Player, pokemon: Pokemon, variant: PokemonMetDataVariant = PokemonMetDataVariant.STANDARD): PokemonMetData {
return PokemonMetData(
player.level().getBiome(player.blockPosition()),
LocalDate.now(ZoneId.systemDefault()),
pokemon.level, variant
)
}
val CODEC: Codec<PokemonMetData> = RecordCodecBuilder.create { instance ->
instance.group(
Biome.CODEC
.fieldOf("biome")
.forGetter { it.biome },
LOCAL_DATE_CODEC
.fieldOf("date")
.forGetter { it.date },
Codec.INT
.fieldOf("level")
.forGetter { it.level },
Codec.STRING
.fieldOf("variant")
.forGetter { it.variant.serializedName }
).apply(instance) { biome, date, level, variant ->
PokemonMetData(
biome = biome,
date = date,
level = level,
variant = PokemonMetDataVariant.getFromName(variant) ?: PokemonMetDataVariant.STANDARD
)
}
}
}
}
@@ -12,17 +12,17 @@ import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.advancement.CobblemonCriteria
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.starter.StarterChosenEvent
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.starter.StarterHandler
import com.cobblemon.mod.common.api.storage.player.PlayerInstancedDataStoreTypes
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.config.starter.StarterCategory
import com.cobblemon.mod.common.data.StarterDataLoader
import com.cobblemon.mod.common.net.messages.client.starter.OpenStarterUIPacket
import com.cobblemon.mod.common.pokemon.PokemonMetData
import com.cobblemon.mod.common.pokemon.PokemonMetDataVariant
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules
import net.minecraft.server.level.ServerPlayer
import kotlin.random.Random
open class CobblemonStarterHandler : StarterHandler {
@@ -73,6 +73,7 @@ open class CobblemonStarterHandler : StarterHandler {
it.pokemon.also {
playerData.starterSelected = true
playerData.starterUUID = it.uuid
pokemon.metData = PokemonMetData.create(player, pokemon, PokemonMetDataVariant.STARTER)
if (player.level().gameRules.getBoolean(CobblemonGameRules.SHINY_STARTERS)) { pokemon.shiny = true }
}
)
@@ -86,6 +86,7 @@ object DataKeys {
const val POKEMON_ORIGINAL_TRAINER_NAME = "PokemonOriginalTrainerName"
const val POKEMON_ORIGINAL_TRAINER_TYPE = "PokemonOriginalTrainerType"
const val POKEMON_ORIGINAL_TRAINER_FRIENDSHIP = "PokemonOriginalTrainerFriendship"
const val POKEMON_MET_DATA = "PokemonMetData"
const val POKEMON_PROPERTIES_MOVES = "Moves"
const val POKEMON_PROPERTIES_HELDITEM = "HeldItem"
@@ -8,25 +8,23 @@
package com.cobblemon.mod.common.util.codec.internal
import com.cobblemon.mod.common.api.mark.Marks
import com.cobblemon.mod.common.api.riding.stats.RidingStat
import com.cobblemon.mod.common.client.settings.ServerSettings
import com.cobblemon.mod.common.pokemon.OriginalTrainerType
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.PokemonMetData
import com.cobblemon.mod.common.util.DataKeys
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.ItemStack
import java.util.*
internal data class ClientPokemonP4(
val originalTrainerFriendship: Optional<Int>
val originalTrainerFriendship: Optional<Int>,
val pokemonMetData: Optional<PokemonMetData>
) : Partial<Pokemon> {
override fun into(other: Pokemon): Pokemon {
this.originalTrainerFriendship.ifPresent { other.originalTrainerFriendship = it }
other.metData = this.pokemonMetData.orElse(null)
return other
}
@@ -36,12 +34,18 @@ internal data class ClientPokemonP4(
*/
internal val CODEC: MapCodec<ClientPokemonP4> = RecordCodecBuilder.mapCodec { instance ->
instance.group(
Codec.INT.optionalFieldOf(DataKeys.POKEMON_ORIGINAL_TRAINER_FRIENDSHIP).forGetter(ClientPokemonP4::originalTrainerFriendship)
).apply(instance, ::ClientPokemonP4)
Codec.INT.optionalFieldOf(DataKeys.POKEMON_ORIGINAL_TRAINER_FRIENDSHIP).forGetter(ClientPokemonP4::originalTrainerFriendship),
PokemonMetData.CODEC.optionalFieldOf(DataKeys.POKEMON_MET_DATA).forGetter(ClientPokemonP4::pokemonMetData)
).apply(instance) {
originalTrainerFriendship, pokemonMetData -> ClientPokemonP4(
originalTrainerFriendship, pokemonMetData
)
}
}
internal fun from(pokemon: Pokemon): ClientPokemonP4 = ClientPokemonP4(
Optional.ofNullable(pokemon.originalTrainerFriendship)
Optional.ofNullable(pokemon.originalTrainerFriendship),
Optional.ofNullable(pokemon.metData)
)
}
}
@@ -9,6 +9,7 @@
package com.cobblemon.mod.common.util.codec.internal
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.PokemonMetData
import com.cobblemon.mod.common.util.DataKeys
import com.mojang.serialization.Codec
import com.mojang.serialization.MapCodec
@@ -16,28 +17,32 @@ import com.mojang.serialization.codecs.RecordCodecBuilder
import java.util.*
internal data class PokemonP4(
val originalTrainerFriendship: Optional<Int>
val originalTrainerFriendship: Optional<Int>,
val pokemonMetData: Optional<PokemonMetData>
) : Partial<Pokemon> {
override fun into(other: Pokemon): Pokemon {
this.originalTrainerFriendship.ifPresent { other.originalTrainerFriendship = it }
other.refreshOriginalTrainer()
other.metData = this.pokemonMetData.orElse(null)
return other
}
companion object {
internal val CODEC: MapCodec<PokemonP4> = RecordCodecBuilder.mapCodec { instance ->
instance.group(
Codec.INT.optionalFieldOf(DataKeys.POKEMON_ORIGINAL_TRAINER_FRIENDSHIP).forGetter(PokemonP4::originalTrainerFriendship)
Codec.INT.optionalFieldOf(DataKeys.POKEMON_ORIGINAL_TRAINER_FRIENDSHIP).forGetter(PokemonP4::originalTrainerFriendship),
PokemonMetData.CODEC.optionalFieldOf(DataKeys.POKEMON_MET_DATA).forGetter(PokemonP4::pokemonMetData)
).apply(instance) {
originalTrainerFriendship -> PokemonP4(
originalTrainerFriendship
originalTrainerFriendship, pokemonMetData -> PokemonP4(
originalTrainerFriendship, pokemonMetData
)
}
}
internal fun from(pokemon: Pokemon): PokemonP4 = PokemonP4(
Optional.ofNullable(pokemon.originalTrainerFriendship)
Optional.ofNullable(pokemon.originalTrainerFriendship),
Optional.ofNullable(pokemon.metData)
)
}
}
@@ -0,0 +1,20 @@
{
"targets": [
"cobblemon:battle.pvw.default"
],
"sounds": [
{
"sound": "cobblemon:music.cobblemon.plains",
"conditions": [
{
"type": "biome",
"biomes": "#cobblemon:is_plains"
},
{
"type": "underground",
"value": false
}
]
}
]
}
@@ -1267,6 +1267,9 @@
"cobblemon.ui.info.ability": "Ability",
"cobblemon.ui.info.experience_points": "Exp. Points",
"cobblemon.ui.info.to_next_level": "To Next Lv.",
"cobblemon.ui.info.met_data.standard": "Met in %1$s on %2$s/%3$s/%4$s at Lv.%5$s.",
"cobblemon.ui.info.met_data.starter": "Met in %1$s on %2$s/%3$s/%4$s at Lv.%5$s as your first partner Pokémon!",
"cobblemon.ui.info.met_data.unavailable": "Met a long time ago...",
"cobblemon.ui.trade": "Trade",
"cobblemon.trade.expired.sender": "Your request to trade with %1$s has timed out!",
"cobblemon.trade.expired.receiver": "The trade request from %1$s has timed out!",
@@ -1299,7 +1302,6 @@
"cobblemon.ui.pc.filter.tooltip": "Format: pikachu shiny held_item lvl=1...",
"cobblemon.ui.pc.options": "Options",
"cobblemon.ui.pc.release": "Release",
"cobblemon.ui.pc.release_all": "Release All",
"cobblemon.ui.sort.name": "Sort by name",
"cobblemon.ui.sort.level": "Sort by level",
"cobblemon.ui.sort.pokedex_number": "Sort by Pokédex number",
@@ -8,6 +8,9 @@
"battle.pvw.default": {
"sounds": []
},
"music.cobblemon.plains": {
"sounds": [ { "name": "cobblemon:music/cobblemon_plains", "volume": 0.6, "stream": true } ]
},
"entity.npc.gibber.generic": {
"sounds": [ { "name": "cobblemon:entity/npc/gibber/gibber_generic", "volume": 0.1 } ]
},
Binary file not shown.

Before

Width:  |  Height:  |  Size: 548 B