Compare commits

..
Author SHA1 Message Date
MeAlam1 9fd3c67717 fix: Cleaned up the Conditional Audio System 2026-12-05 01:33:53 +01:00
MeAlam1 d075837ddb feat: Works 2026-12-05 01:06:25 +01:00
26 changed files with 1006 additions and 0 deletions

No files matched your search

@@ -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;
@@ -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" } }
}
}
@@ -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
}
}
@@ -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
}
]
}
]
}
@@ -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 } ]
},