Merge branch 'render-refactor' into 'main'

Render refactor

See merge request cable-mc/cobblemon!537
This commit is contained in:
Hiroku committed 2023-07-09 23:48:57 +00:00
commit 5dcbb271a5
40 files changed
+362 -204

No files matched your search

+2
View File
@@ -212,6 +212,8 @@
- Fixed Shedinja not being able to recover naturally.
- Fixed different forms of Pokémon not being able to appear as different sizes.
- Fixed the Healing Machine soft locking you from using others when removed by non-players.
- Fixed animations being sped up when using the Replay Mod.
- Fixed particle animations not running when a Pokémon is off-screen.
### Developer
- Added SpawnEvent
@@ -175,7 +175,8 @@ fun drawPortraitPokemon(
matrixStack: MatrixStack,
scale: Float = 13F,
reversed: Boolean = false,
state: PoseableEntityState<PokemonEntity>? = null
state: PoseableEntityState<PokemonEntity>? = null,
partialTicks: Float
) {
val model = PokemonModelRepository.getPoser(species.resourceIdentifier, aspects)
val texture = PokemonModelRepository.getTexture(species.resourceIdentifier, aspects, state)
@@ -191,6 +192,7 @@ fun drawPortraitPokemon(
} else {
model.getPose(PoseType.PORTRAIT)?.let { state.setPose(it.poseName) }
state.timeEnteredPose = 0F
state.updatePartialTicks(partialTicks)
model.setupAnimStateful(null, state, 0F, 0F, 0F, 0F, 0F)
}
@@ -26,6 +26,10 @@ class ClientBallDisplay(val pokeBall: PokeBall, val aspects: Set<String>) : Poke
override val stateEmitter = SettableObservable(EmptyPokeBallEntity.CaptureState.FALL)
override val shakeEmitter = SimpleObservable<Unit>()
override fun updatePartialTicks(partialTicks: Float) {
this.currentPartialTicks += partialTicks
}
var scale = 1F
fun start() {
@@ -39,14 +43,4 @@ class ClientBallDisplay(val pokeBall: PokeBall, val aspects: Set<String>) : Poke
}
}
}
fun finish() {
lerp(seconds = 0.3F) { scale = 1 - it }
after(seconds = 0.3F) {
lerp(seconds = 0.3F) { scale = it }
after(seconds = 0.3F) {
}
}
}
}
@@ -21,7 +21,12 @@ class EmptyPokeBallClientDelegate : PokeBallPoseableState(), EntitySideDelegate<
override val stateEmitter: SettableObservable<CaptureState> = SettableObservable(NOT)
override val shakeEmitter = SimpleObservable<Unit>()
override fun updatePartialTicks(partialTicks: Float) {
this.currentPartialTicks = partialTicks
}
override fun initialize(entity: EmptyPokeBallEntity) {
age = entity.age
initSubscriptions()
entity.captureState.subscribe {
stateEmitter.set(CaptureState.values()[it.toInt()])
@@ -32,5 +37,6 @@ class EmptyPokeBallClientDelegate : PokeBallPoseableState(), EntitySideDelegate<
override fun tick(entity: EmptyPokeBallEntity) {
super.tick(entity)
updateLocatorPosition(entity.pos)
incrementAge(entity)
}
}
@@ -32,9 +32,11 @@ class PokemonClientDelegate : PoseableEntityState<PokemonEntity>(), PokemonSideD
var phaseTarget: Entity? = null
var entityScaleModifier = 1F
var animTick = 0F
var previousVerticalVelocity = 0F
override fun updatePartialTicks(partialTicks: Float) {
this.currentPartialTicks = partialTicks
}
var previousVerticalVelocity = 0F
var beamStartTime = System.currentTimeMillis()
val secondsSinceBeamEffectStarted: Float
@@ -103,6 +105,7 @@ class PokemonClientDelegate : PoseableEntityState<PokemonEntity>(), PokemonSideD
override fun initialize(entity: PokemonEntity) {
this.entity = entity
this.age = entity.age
}
override fun tick(entity: PokemonEntity) {
@@ -119,8 +122,9 @@ class PokemonClientDelegate : PoseableEntityState<PokemonEntity>(), PokemonSideD
}
updateLocatorPosition(entity.pos)
previousVerticalVelocity = entity.velocity.y.toFloat()
incrementAge(entity)
}
fun setPhaseTarget(targetId: Int) {
@@ -160,7 +160,7 @@ class PartyOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.ge
0.0
)
drawPortraitPokemon(pokemon.species, pokemon.aspects, matrices)
drawPortraitPokemon(pokemon.species, pokemon.aspects, matrices, partialTicks = partialDeltaTicks)
matrices.pop()
context.disableScissor()
}
@@ -29,14 +29,16 @@ fun drawProfilePokemon(
matrixStack: MatrixStack,
rotation: Quaternionf,
state: PoseableEntityState<PokemonEntity>?,
partialTicks: Float,
scale: Float = 20F
) = drawProfilePokemon(
renderablePokemon.species.resourceIdentifier,
renderablePokemon.aspects,
matrixStack,
rotation,
state,
scale
species = renderablePokemon.species.resourceIdentifier,
aspects = renderablePokemon.aspects,
matrixStack = matrixStack,
rotation = rotation,
state = state,
partialTicks = partialTicks,
scale = scale
)
fun drawProfilePokemon(
@@ -45,6 +47,7 @@ fun drawProfilePokemon(
matrixStack: MatrixStack,
rotation: Quaternionf,
state: PoseableEntityState<PokemonEntity>?,
partialTicks: Float,
scale: Float = 20F
) {
val model = PokemonModelRepository.getPoser(species, aspects)
@@ -58,6 +61,7 @@ fun drawProfilePokemon(
if (state != null) {
model.getPose(PoseType.PROFILE)?.let { state.setPose(it.poseName) }
state.timeEnteredPose = 0F
state.updatePartialTicks(partialTicks)
model.setupAnimStateful(null, state, 0F, 0F, 0F, 0F, 0F)
} else {
model.setupAnimStateless(PoseType.PROFILE)
@@ -145,7 +145,7 @@ class BattleGUI : Screen(battleLang("gui.title")) {
}
override fun charTyped(chr: Char, modifiers: Int): Boolean {
if (chr.toString() == PartySendBinding.boundKey().localizedText.string && CobblemonClient.battleOverlay.opacity == BattleOverlay.MAX_OPACITY && PartySendBinding.canAction()) {
if (chr.toString().equals(PartySendBinding.boundKey().localizedText.string, ignoreCase = true) && CobblemonClient.battleOverlay.opacity == BattleOverlay.MAX_OPACITY && PartySendBinding.canAction()) {
val battle = CobblemonClient.battle ?: return false
battle.minimised = !battle.minimised
PartySendBinding.actioned()
@@ -161,6 +161,7 @@ class BattleOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.g
context = context,
x = x,
y = y.toFloat(),
partialTicks = tickDelta,
reversed = !left,
species = battlePokemon.species,
level = battlePokemon.level,
@@ -182,6 +183,7 @@ class BattleOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.g
context: DrawContext,
x: Float,
y: Float,
partialTicks: Float,
reversed: Boolean,
species: Species,
level: Int,
@@ -227,6 +229,7 @@ class BattleOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.g
drawPokeBall(
state = ballState,
matrixStack = matrixStack,
partialTicks = partialTicks
)
} else {
matrixStack.push()
@@ -236,7 +239,8 @@ class BattleOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.g
matrixStack = matrixStack,
scale = 18F * (ballState?.scale ?: 1F),
reversed = reversed,
state = state
state = state,
partialTicks = partialTicks
)
matrixStack.pop()
}
@@ -379,6 +383,7 @@ class BattleOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.g
state: ClientBallDisplay,
matrixStack: MatrixStack,
scale: Float = 5F,
partialTicks: Float,
reversed: Boolean = false
) {
val model = PokeBallModelRepository.getPoser(state.pokeBall.name, state.aspects)
@@ -391,6 +396,7 @@ class BattleOverlay : InGameHud(MinecraftClient.getInstance(), MinecraftClient.g
model.getPose(PoseType.PORTRAIT)?.let { state.setPose(it.poseName) }
state.timeEnteredPose = 0F
state.updatePartialTicks(partialTicks)
model.setupAnimStateful(null, state, 0F, 0F, 0F, 0F, 0F)
matrixStack.scale(scale, scale, -scale)
@@ -72,7 +72,8 @@ class BattleSwitchPokemonSelection(
isFlatHealth = true,
state = null,
colour = null,
opacity = selection.opacity
opacity = selection.opacity,
partialTicks = deltaTicks
)
}
}
@@ -203,6 +203,7 @@ class PasturePokemonScrollList(
matrixStack = matrixStack,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = null,
partialTicks = partialTicks,
scale = 4.5F
)
matrixStack.pop()
@@ -19,18 +19,10 @@ class GrabbedStorageSlot(
) : StorageSlot(x, y, parent, {}) {
override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) {
renderSlot(context, mouseX - (width / 2), mouseY - (height / 2))
renderSlot(context = context, posX = mouseX - (width / 2), posY = mouseY - (height / 2), partialTicks = delta)
}
override fun isStationary(): Boolean {
return false
}
override fun getPokemon(): Pokemon? {
return pokemon
}
override fun isSelected(): Boolean {
return true
}
override fun isStationary() = false
override fun getPokemon() = pokemon
override fun isSelected() = true
}
@@ -48,11 +48,11 @@ open class StorageSlot(
override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) {
if (shouldRender()) {
renderSlot(context, x, y)
renderSlot(context, x, y, delta)
}
}
fun renderSlot(context: DrawContext, posX: Int, posY: Int) {
fun renderSlot(context: DrawContext, posX: Int, posY: Int, partialTicks: Float) {
val pokemon = getPokemon() ?: return
val matrices = context.matrices
context.enableScissor(
@@ -71,6 +71,7 @@ open class StorageSlot(
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = null,
partialTicks = partialTicks,
scale = 4.5F
)
matrices.pop()
@@ -70,7 +70,8 @@ class StarterRoundabout(
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(rotationVector),
state = null,
scale = 18F
scale = 18F,
partialTicks = delta
)
context.disableScissor()
@@ -140,7 +140,8 @@ class EvolutionSelectScreen(
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = null,
scale = 6F
scale = 6F,
partialTicks = partialTicks
)
matrices.pop()
}
@@ -32,18 +32,17 @@ class ModelWidget(
}
var state = PokemonFloatingState()
private val minecraft = MinecraftClient.getInstance()
val rotVec = Vector3f(13F, rotationY, 0F)
override fun renderButton(context: DrawContext, pMouseX: Int, pMouseY: Int, pPartialTicks: Float) {
override fun renderButton(context: DrawContext, pMouseX: Int, pMouseY: Int, partialTicks: Float) {
if (!render) {
return
}
hovered = pMouseX >= x && pMouseY >= y && pMouseX < x + width && pMouseY < y + height
renderPKM(context)
renderPKM(context, partialTicks)
}
private fun renderPKM(context: DrawContext) {
private fun renderPKM(context: DrawContext, partialTicks: Float) {
val matrices = context.matrices
matrices.push()
@@ -62,7 +61,8 @@ class ModelWidget(
renderablePokemon = pokemon,
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(rotVec),
state = state
state = state,
partialTicks = partialTicks
)
matrices.pop()
@@ -159,7 +159,8 @@ class PartySlotWidget(
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = null,
scale = 4.5F
scale = 4.5F,
partialTicks = delta
)
matrices.pop()
@@ -40,7 +40,8 @@ class ModelWidget(
renderablePokemon = pokemon,
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(rotVec),
state = state
state = state,
partialTicks = delta
)
matrices.pop()
@@ -75,7 +75,8 @@ open class PartySlot(
matrixStack = matrices,
rotation = Quaternionf().fromEulerXYZDegrees(Vector3f(13F, 35F, 0F)),
state = null,
scale = 4.5F
scale = 4.5F,
partialTicks = delta
)
matrices.pop()
@@ -21,8 +21,6 @@ object BattleCaptureEndHandler : ClientNetworkPacketHandler<BattleCaptureEndPack
val (_, activeBattlePokemon) = battle.getPokemonFromPNX(packet.targetPNX)
if (packet.succeeded) {
activeBattlePokemon.animations.add(MoveTileOffscreenAnimation().also { after(seconds = it.duration) { activeBattlePokemon.ballCapturing = null } })
} else {
activeBattlePokemon.ballCapturing?.finish()
}
activeBattlePokemon.ballCapturing = null
}
@@ -29,37 +29,39 @@ class PokemonOnShoulderRenderer<T : PlayerEntity>(renderLayerParent: FeatureRend
private val playerCache = hashMapOf<UUID, ShoulderCache>()
override fun render(
pMatrixStack: MatrixStack,
pBuffer: VertexConsumerProvider,
pPackedLight: Int,
pLivingEntity: T,
pLimbSwing: Float,
pLimbSwingAmount: Float,
pPartialTicks: Float,
pAgeInTicks: Float,
pNetHeadYaw: Float,
pHeadPitch: Float
matrixStack: MatrixStack,
buffer: VertexConsumerProvider,
packedLight: Int,
livingEntity: T,
limbSwing: Float,
limbSwingAmount: Float,
partialTicks: Float,
ageInTicks: Float,
netHeadYaw: Float,
headPitch: Float
) {
this.render(pMatrixStack, pBuffer, pPackedLight, pLivingEntity, pLimbSwing, pLimbSwingAmount, pNetHeadYaw, pHeadPitch, true)
this.render(pMatrixStack, pBuffer, pPackedLight, pLivingEntity, pLimbSwing, pLimbSwingAmount, pNetHeadYaw, pHeadPitch, false)
this.render(matrixStack, buffer, packedLight, livingEntity, limbSwing, limbSwingAmount, partialTicks, ageInTicks, netHeadYaw, headPitch, true)
this.render(matrixStack, buffer, packedLight, livingEntity, limbSwing, limbSwingAmount, partialTicks, ageInTicks, netHeadYaw, headPitch, false)
}
private fun render(
pMatrixStack: MatrixStack,
pBuffer: VertexConsumerProvider,
pPackedLight: Int,
pLivingEntity: T,
pLimbSwing: Float,
pLimbSwingAmount: Float,
pNetHeadYaw: Float,
pHeadPitch: Float,
matrixStack: MatrixStack,
buffer: VertexConsumerProvider,
packedLight: Int,
livingEntity: T,
limbSwing: Float,
limbSwingAmount: Float,
partialTicks: Float,
ageInTicks: Float,
netHeadYaw: Float,
headPitch: Float,
pLeftShoulder: Boolean
) {
val compoundTag = if (pLeftShoulder) pLivingEntity.shoulderEntityLeft else pLivingEntity.shoulderEntityRight
val compoundTag = if (pLeftShoulder) livingEntity.shoulderEntityLeft else livingEntity.shoulderEntityRight
if (compoundTag.isPokemonEntity()) {
pMatrixStack.push()
matrixStack.push()
val uuid = compoundTag.getCompound(DataKeys.POKEMON).getUuid(DataKeys.POKEMON_UUID)
val cache = this.playerCache.getOrPut(pLivingEntity.uuid) { ShoulderCache() }
val cache = this.playerCache.getOrPut(livingEntity.uuid) { ShoulderCache() }
val pokemon: Pokemon
if (pLeftShoulder && cache.lastKnownLeft?.uuid != uuid) {
pokemon = Pokemon().also { it.isClient = true }.loadFromNBT(compoundTag.getCompound(DataKeys.POKEMON))
@@ -76,17 +78,17 @@ class PokemonOnShoulderRenderer<T : PlayerEntity>(renderLayerParent: FeatureRend
val scale = pokemon.form.baseScale * pokemon.scaleModifier
val width = pokemon.form.hitbox.width
val offset = width / 2 - 0.7
pMatrixStack.translate(
matrixStack.translate(
if (pLeftShoulder) -offset else offset,
(if (pLivingEntity.isSneaking) -1.3 else -1.5) * scale,
(if (livingEntity.isSneaking) -1.3 else -1.5) * scale,
0.0
)
pMatrixStack.scale(scale, scale, scale)
matrixStack.scale(scale, scale, scale)
val model = PokemonModelRepository.getPoser(pokemon.species.resourceIdentifier, pokemon.aspects)
val state = PokemonFloatingState()
state.animationSeconds = pLivingEntity.age.toFloat() / 20F
val vertexConsumer = pBuffer.getBuffer(model.getLayer(PokemonModelRepository.getTexture(pokemon.species.resourceIdentifier, pokemon.aspects, state)))
val i = LivingEntityRenderer.getOverlay(pLivingEntity, 0.0f)
state.updatePartialTicks(livingEntity.age.toFloat() * 20 + partialTicks)
val vertexConsumer = buffer.getBuffer(model.getLayer(PokemonModelRepository.getTexture(pokemon.species.resourceIdentifier, pokemon.aspects, state)))
val i = LivingEntityRenderer.getOverlay(livingEntity, 0.0f)
val pose = model.poses.values
.firstOrNull { (if (pLeftShoulder) PoseType.SHOULDER_LEFT else PoseType.SHOULDER_RIGHT) in it.poseTypes }
@@ -96,17 +98,17 @@ class PokemonOnShoulderRenderer<T : PlayerEntity>(renderLayerParent: FeatureRend
model.setupAnimStateful(
entity = null,
state = state,
headYaw = pNetHeadYaw,
headPitch = pHeadPitch,
limbSwing = pLimbSwing,
limbSwingAmount = pLimbSwingAmount,
ageInTicks = pLivingEntity.age.toFloat()
headYaw = netHeadYaw,
headPitch = headPitch,
limbSwing = limbSwing,
limbSwingAmount = limbSwingAmount,
ageInTicks = livingEntity.age.toFloat()
)
model.render(pMatrixStack, vertexConsumer, pPackedLight, i, 1.0f, 1.0f, 1.0f, 1.0f)
model.withLayerContext(pBuffer, state, PokemonModelRepository.getLayers(pokemon.species.resourceIdentifier, pokemon.aspects)) {
model.render(pMatrixStack, vertexConsumer, pPackedLight, OverlayTexture.DEFAULT_UV, 1F, 1F, 1F, 1F)
model.render(matrixStack, vertexConsumer, packedLight, i, 1.0f, 1.0f, 1.0f, 1.0f)
model.withLayerContext(buffer, state, PokemonModelRepository.getLayers(pokemon.species.resourceIdentifier, pokemon.aspects)) {
model.render(matrixStack, vertexConsumer, packedLight, OverlayTexture.DEFAULT_UV, 1F, 1F, 1F, 1F)
}
pMatrixStack.pop();
matrixStack.pop();
}
}
@@ -256,11 +256,10 @@ abstract class PoseableEntityModel<T : Entity>(
alpha * a
)
val animationSeconds = currentState?.animationSeconds ?: 0F
val provider = bufferProvider
if (provider != null) {
for (layer in currentLayers) {
val texture = layer.texture?.invoke(animationSeconds) ?: continue
val texture = layer.texture?.invoke(currentState?.animationSeconds ?: 0F) ?: continue
val renderLayer = getLayer(texture, layer.emissive, layer.translucent)
val consumer = provider.getBuffer(renderLayer)
stack.push()
@@ -19,7 +19,6 @@ import com.cobblemon.mod.common.client.render.models.blockbench.pose.Pose
import com.cobblemon.mod.common.client.render.models.blockbench.quirk.ModelQuirk
import com.cobblemon.mod.common.client.render.models.blockbench.quirk.QuirkData
import java.util.concurrent.ConcurrentLinkedQueue
import net.minecraft.client.MinecraftClient
import net.minecraft.entity.Entity
import net.minecraft.util.math.Vec3d
@@ -37,17 +36,36 @@ abstract class PoseableEntityState<T : Entity> {
val statefulAnimations: MutableList<StatefulAnimation<T, *>> = mutableListOf()
val quirks = mutableMapOf<ModelQuirk<T, *>, QuirkData<T>>()
val additives: MutableList<PosedAdditiveAnimation<T>> = mutableListOf()
var timeEnteredPose = 0F
var previousAnimationSeconds = 0F
var animationSeconds = 0F
var deltaSeconds = 0F
var timeLastRendered = System.currentTimeMillis()
var wasPaused = false
val poseParticles = mutableListOf<BedrockParticleKeyframe>()
val runtime = MoLangRuntime().also {
it.environment.structs["query"] = it.environment.structs["variable"]
}
val allStatefulAnimations: List<StatefulAnimation<T, *>> get() = statefulAnimations + quirks.flatMap { it.value.animations }
protected var age = 0
protected var currentPartialTicks = 0F
fun getPartialTicks() = currentPartialTicks
open fun updateAge(age: Int) {
this.age = age
}
open fun incrementAge(entity: T) {
val previousAge = age
updateAge(age + 1)
runEffects(entity, previousAge, age)
}
abstract fun updatePartialTicks(partialTicks: Float)
open fun reset() {
updateAge(0)
}
val animationSeconds: Float get() = (age + getPartialTicks()) / 20F
var timeEnteredPose = 0F
val locatorStates = mutableMapOf<String, MatrixWrapper>()
val renderQueue = ConcurrentLinkedQueue<() -> Unit>()
@@ -56,26 +74,6 @@ abstract class PoseableEntityState<T : Entity> {
fun isNotPosedIn(vararg poses: Pose<T, in ModelFrame>) = poses.none { it.poseName == currentPose }
fun preRender() {
val now = System.currentTimeMillis()
var deltaMillis = now - timeLastRendered
if (wasPaused) {
deltaMillis = 0L
}
if (MinecraftClient.getInstance().isPaused) {
if (!wasPaused) {
wasPaused = true
}
} else if (wasPaused) {
wasPaused = false
}
timeLastRendered = now
deltaSeconds = deltaMillis / 1000F
previousAnimationSeconds = animationSeconds
animationSeconds += deltaSeconds
while (renderQueue.peek() != null) {
val action = renderQueue.poll()
action()
@@ -97,7 +95,6 @@ abstract class PoseableEntityState<T : Entity> {
val poseImpl = model.getPose(pose) ?: return
poseParticles.removeIf { it !in poseImpl.idleAnimations.filterIsInstance<BedrockStatelessAnimation<*>>().flatMap { it.particleKeyFrames } }
poseImpl.onTransitionedInto(this)
timeEnteredPose = animationSeconds
}
}
@@ -113,4 +110,15 @@ abstract class PoseableEntityState<T : Entity> {
fun updateLocatorPosition(position: Vec3d) {
locatorStates.values.toList().forEach { it.updatePosition(position) }
}
fun runEffects(entity: T, previousAge: Int, newAge: Int) {
val previousSeconds = previousAge / 20F
val currentSeconds = newAge / 20F
currentModel?.let { model ->
val pose = currentPose?.let(model::getPose)
allStatefulAnimations.forEach { it.applyEffects(entity, this, previousSeconds, currentSeconds) }
pose?.getApplicableIdleAnimations(entity, this)?.forEach { it.applyEffects(entity, this, previousSeconds, currentSeconds) }
}
}
}
@@ -41,4 +41,6 @@ interface StatefulAnimation<T : Entity, F : ModelFrame> {
headYaw: Float,
headPitch: Float
): Boolean
fun applyEffects(entity: T, state: PoseableEntityState<T>, previousSeconds: Float, newSeconds: Float) {}
}
@@ -28,4 +28,6 @@ abstract class StatelessAnimation<T : Entity, F : ModelFrame>(val frame: F) {
fun apply(entity: T?, model: PoseableEntityModel<T>, state: PoseableEntityState<T>?, limbSwing: Float, limbSwingAmount: Float, ageInTicks: Float, headYaw: Float, headPitch: Float) {
setAngles(entity, model, state, limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch)
}
open fun applyEffects(entity: T, state: PoseableEntityState<T>, previousSeconds: Float, newSeconds: Float) {}
}
@@ -10,9 +10,12 @@ package com.cobblemon.mod.common.client.render.models.blockbench.bedrock.animati
import com.bedrockk.molang.Expression
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.MoParams
import com.bedrockk.molang.runtime.MoScope
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.api.snowstorm.BedrockParticleEffect
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.client.particle.ParticleStorm
import com.cobblemon.mod.common.client.render.models.blockbench.PoseableEntityModel
import com.cobblemon.mod.common.client.render.models.blockbench.PoseableEntityState
@@ -21,8 +24,12 @@ import com.cobblemon.mod.common.util.math.geometry.toRadians
import com.cobblemon.mod.common.util.resolveDouble
import java.util.SortedMap
import net.minecraft.client.MinecraftClient
import net.minecraft.client.sound.PositionedSoundInstance
import net.minecraft.client.world.ClientWorld
import net.minecraft.entity.Entity
import net.minecraft.registry.RegistryKeys
import net.minecraft.sound.SoundCategory
import net.minecraft.util.Identifier
import net.minecraft.util.crash.CrashException
import net.minecraft.util.crash.CrashReport
import net.minecraft.util.math.Vec3d
@@ -32,70 +39,133 @@ data class BedrockAnimationGroup(
val animations: Map<String, BedrockAnimation>
)
data class BedrockParticleKeyframe(
val seconds: Float,
abstract class BedrockEffectKeyframe(val seconds: Float) {
abstract fun <T : Entity> run(entity: T, state: PoseableEntityState<T>)
}
class BedrockParticleKeyframe(
seconds: Float,
val effect: BedrockParticleEffect,
val locator: String,
val scripts: List<Expression>
)
) : BedrockEffectKeyframe(seconds) {
override fun <T : Entity> run(entity: T, state: PoseableEntityState<T>) {
val world = entity.world as ClientWorld
val matrixWrapper = state.locatorStates[locator] ?: state.locatorStates["root"]!!
val effect = effect
if (this in state.poseParticles) {
return
}
val storm = ParticleStorm(
effect = effect,
matrixWrapper = matrixWrapper,
world = world,
sourceVelocity = { entity.velocity },
sourceAlive = { !entity.isRemoved && this in state.poseParticles },
sourceVisible = { !entity.isInvisible }
)
state.poseParticles.add(this)
storm.runtime.execute(this.scripts)
storm.spawn()
}
}
class BedrockSoundKeyframe(
seconds: Float,
val sound: Identifier
): BedrockEffectKeyframe(seconds) {
override fun <T : Entity> run(entity: T, state: PoseableEntityState<T>) {
val registry = entity.world.registryManager.get(RegistryKeys.SOUND_EVENT)
val soundEvent = registry.get(sound)
if (soundEvent != null) {
MinecraftClient.getInstance().soundManager.play(
PositionedSoundInstance(
soundEvent,
SoundCategory.NEUTRAL,
1F,
1F,
entity.world.random,
entity.x,
entity.y,
entity.z
)
)
}
}
}
class BedrockInstructionKeyframe(
seconds: Float,
val expressions: List<Expression>
): BedrockEffectKeyframe(seconds) {
override fun <T : Entity> run(entity: T, state: PoseableEntityState<T>) {
expressions.forEach { expression -> BedrockAnimation.runInstruction(entity, state, expression) }
}
}
data class BedrockAnimation(
val shouldLoop: Boolean,
val animationLength: Double,
val particleEffects: List<BedrockParticleKeyframe>,
val effects: List<BedrockEffectKeyframe>,
val boneTimelines: Map<String, BedrockBoneTimeline>
) {
companion object {
val functionMappings = mutableMapOf<String, java.util.function.Function<MoParams, Any>>()
val sharedRuntime = MoLangRuntime().also {
it.environment.structs["query"] = it.environment.structs["variable"]
it.environment.structs["script"] = QueryStruct(functionMappings)
}
var context: InstructionContext? = null
inline fun <reified T : Entity> registerInstruction(name: String, crossinline function: (entity: T, state: PoseableEntityState<T>, params: MoParams) -> Any) {
functionMappings[name] = java.util.function.Function { args ->
val ctx = context ?: return@Function Unit
if (ctx.entity is T) {
val ret = function(ctx.entity, ctx.state as PoseableEntityState<T>, args)
if (ret is Unit) {
return@Function 0.0
} else {
return@Function ret
}
}
Unit
}
}
class InstructionContext(val entity: Entity, val state: PoseableEntityState<*>)
fun <T : Entity> runInstruction(entity: T, state: PoseableEntityState<T>, expression: Expression) {
val ctx = InstructionContext(entity, state)
context = ctx
expression.evaluate(MoScope(), sharedRuntime.environment)
context = null
}
init {
registerInstruction<Entity>("say") { entity, _, params ->
MinecraftClient.getInstance().player?.sendMessage(params.getString(0).text())
Unit
}
}
}
fun run(model: PoseableEntityModel<*>, entity: Entity?, state: PoseableEntityState<*>?, previousSecondsPassed: Double, secondsPassed: Double): Boolean {
var animationSeconds = secondsPassed
fun run(model: PoseableEntityModel<*>, state: PoseableEntityState<*>?, animationSeconds: Float): Boolean {
var animationSeconds = animationSeconds
if (shouldLoop) {
animationSeconds %= animationLength
animationSeconds %= animationLength.toFloat()
} else if (animationSeconds > animationLength && animationLength > 0) {
return false
}
if (entity != null && state != null) {
val particleEffectsToPlay = mutableListOf<BedrockParticleKeyframe>()
if (previousSecondsPassed > animationSeconds) {
particleEffectsToPlay.addAll(particleEffects.filter { it.seconds >= previousSecondsPassed || it.seconds <= animationSeconds })
} else {
particleEffectsToPlay.addAll(particleEffects.filter { it.seconds in previousSecondsPassed..animationSeconds })
}
for (particleEffect in particleEffectsToPlay) {
val world = entity.world as ClientWorld
val matrixWrapper = state.locatorStates[particleEffect.locator] ?: state.locatorStates["root"]!!
val effect = particleEffect.effect
if (particleEffect in state.poseParticles) {
continue
}
val storm = ParticleStorm(
effect = effect,
matrixWrapper = matrixWrapper,
world = world,
sourceVelocity = { entity.velocity },
sourceAlive = { !entity.isRemoved && particleEffect in state.poseParticles },
sourceVisible = { !entity.isInvisible }
)
state.poseParticles.add(particleEffect)
storm.runtime.execute(particleEffect.scripts)
storm.spawn()
}
}
boneTimelines.forEach { (boneName, timeline) ->
val part = model.relevantPartsByName[boneName]
if (part != null) {
if (!timeline.position.isEmpty()) {
val position = timeline.position.resolve(animationSeconds, state?.runtime ?: sharedRuntime).multiply(model.getChangeFactor(part.modelPart).toDouble())
val position = timeline.position.resolve(animationSeconds.toDouble(), state?.runtime ?: sharedRuntime).multiply(model.getChangeFactor(part.modelPart).toDouble())
part.modelPart.apply {
pivotX += position.x.toFloat()
pivotY += position.y.toFloat()
@@ -105,7 +175,7 @@ data class BedrockAnimation(
if (!timeline.rotation.isEmpty()) {
try {
val rotation = timeline.rotation.resolve(animationSeconds, state?.runtime ?: sharedRuntime).multiply(model.getChangeFactor(part.modelPart).toDouble())
val rotation = timeline.rotation.resolve(animationSeconds.toDouble(), state?.runtime ?: sharedRuntime).multiply(model.getChangeFactor(part.modelPart).toDouble())
part.modelPart.apply {
pitch += rotation.x.toFloat().toRadians()
yaw += rotation.y.toFloat().toRadians()
@@ -125,7 +195,7 @@ data class BedrockAnimation(
}
if (!timeline.scale.isEmpty()) {
var scale = timeline.scale.resolve(animationSeconds, state?.runtime ?: sharedRuntime)
var scale = timeline.scale.resolve(animationSeconds.toDouble(), state?.runtime ?: sharedRuntime)
val deviation = scale.multiply(-1.0).add(1.0, 1.0, 1.0).multiply(model.getChangeFactor(part.modelPart).toDouble())
scale = deviation.subtract(1.0, 1.0, 1.0).multiply(-1.0)
val mp = part.modelPart
@@ -137,6 +207,17 @@ data class BedrockAnimation(
}
return true
}
fun <T : Entity> applyEffects(entity: T, state: PoseableEntityState<T>, previousSeconds: Float, newSeconds: Float) {
val effectCondition: (effectKeyframe: BedrockEffectKeyframe) -> Boolean =
if (previousSeconds > newSeconds) {
{ it.seconds >= previousSeconds || it.seconds <= newSeconds }
} else {
{ it.seconds in previousSeconds..newSeconds }
}
effects.filter(effectCondition).forEach { it.run(entity, state) }
}
}
interface BedrockBoneValue {
@@ -164,7 +245,6 @@ class MolangBoneValue(
override fun isEmpty() = false
override fun resolve(time: Double, runtime: MoLangRuntime): Vec3d {
val environment = runtime.environment
val scope = MoScope()
environment.setSimpleVariable("anim_time", DoubleValue(time))
environment.setSimpleVariable("camera_rotation_x", DoubleValue(MinecraftClient.getInstance().gameRenderer.camera.rotation.x.toDouble()))
environment.setSimpleVariable("camera_rotation_y", DoubleValue(MinecraftClient.getInstance().gameRenderer.camera.rotation.y.toDouble()))
@@ -11,6 +11,7 @@ package com.cobblemon.mod.common.client.render.models.blockbench.bedrock.animati
import com.bedrockk.molang.MoLang
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.client.particle.BedrockParticleEffectRepository
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.google.gson.JsonArray
import com.google.gson.JsonDeserializationContext
@@ -32,7 +33,7 @@ object BedrockAnimationAdapter : JsonDeserializer<BedrockAnimation> {
val animationLength = json["animation_length"]?.asDouble ?: -1.0
val shouldLoop = animationLength > 0 && json["loop"]?.asBoolean == true
val boneTimelines = mutableMapOf<String, BedrockBoneTimeline>()
val particleEffects = mutableListOf<BedrockParticleKeyframe>()
val effects = mutableListOf<BedrockEffectKeyframe>()
json["bones"]?.asJsonObject?.entrySet()?.forEach { (boneName, timeline) ->
boneTimelines[boneName] = deserializeBoneTimeline(timeline.asJsonObject)
}
@@ -53,14 +54,46 @@ object BedrockAnimationAdapter : JsonDeserializer<BedrockAnimation> {
}
if (effectJson is JsonObject) {
particleEffects.add(resolveEffect(effectJson))
effects.add(resolveEffect(effectJson))
} else if (effectJson is JsonArray) {
for (effectJsonElement in effectJson) {
particleEffects.add(resolveEffect(effectJsonElement as JsonObject))
effects.add(resolveEffect(effectJsonElement as JsonObject))
}
}
}
return BedrockAnimation(shouldLoop, animationLength, particleEffects, boneTimelines)
json["sound_effects"]?.asJsonObject?.entrySet()?.forEach { (frame, effectJson) ->
fun resolveEffect(jsonObject: JsonObject): BedrockSoundKeyframe {
val effectId = jsonObject.get("effect").asString.asIdentifierDefaultingNamespace()
val seconds = frame.toFloat()
return BedrockSoundKeyframe(
seconds = seconds,
sound = effectId,
)
}
if (effectJson is JsonObject) {
effects.add(resolveEffect(effectJson))
} else if (effectJson is JsonArray) {
for (effectJsonElement in effectJson) {
effects.add(resolveEffect(effectJsonElement as JsonObject))
}
}
}
json["timeline"]?.asJsonObject?.entrySet()?.forEach { (frame, effectJson) ->
effects.add(
BedrockInstructionKeyframe(
seconds = frame.toFloat(),
expressions = if (effectJson is JsonArray) {
effectJson.asJsonArray.map { it.asString.let { if (it.endsWith(";")) it.substring(0, it.length - 1) else it }.asExpression() }
} else {
listOf(effectJson.asString.asExpression())
}
)
)
}
return BedrockAnimation(shouldLoop, animationLength, effects, boneTimelines)
}
else {
throw IllegalStateException("animation json could not be parsed")
@@ -31,7 +31,7 @@ open class BedrockStatefulAnimation<T : Entity>(
return this
}
var secondsPassed = 0F
var startedSeconds = -1F
var isTransformAnimation = false
private var afterAction: (T, PoseableEntityState<T>) -> Unit = { _, _ -> }
@@ -57,12 +57,20 @@ open class BedrockStatefulAnimation<T : Entity>(
headYaw: Float,
headPitch: Float
): Boolean {
val previousSeconds = secondsPassed
secondsPassed += state.deltaSeconds
return animation.run(model, entity, state, previousSeconds.toDouble(), secondsPassed.toDouble()).also {
if (startedSeconds == -1F) {
startedSeconds = state.animationSeconds
}
return animation.run(model, state, state.animationSeconds - startedSeconds).also {
if (!it && entity != null) {
afterAction(entity, state)
}
}
}
override fun applyEffects(entity: T, state: PoseableEntityState<T>, previousSeconds: Float, newSeconds: Float) {
val previousSecondsOffset = previousSeconds - startedSeconds
val currentSecondsOffset = newSeconds - startedSeconds
animation.applyEffects(entity, state, previousSecondsOffset, currentSecondsOffset)
}
}
@@ -12,6 +12,7 @@ import com.cobblemon.mod.common.client.render.models.blockbench.PoseableEntityMo
import com.cobblemon.mod.common.client.render.models.blockbench.PoseableEntityState
import com.cobblemon.mod.common.client.render.models.blockbench.animation.StatelessAnimation
import com.cobblemon.mod.common.client.render.models.blockbench.frame.ModelFrame
import com.cobblemon.mod.common.client.render.models.blockbench.pokemon.gen1.PikachuModel
import net.minecraft.entity.Entity
/**
@@ -26,18 +27,13 @@ import net.minecraft.entity.Entity
*/
class BedrockStatelessAnimation<T: Entity>(frame: ModelFrame, val animation: BedrockAnimation) : StatelessAnimation<T, ModelFrame>(frame) {
override val targetFrame: Class<ModelFrame> = ModelFrame::class.java
val particleKeyFrames = animation.particleEffects
var speed = 1F
fun setSpeed(speed: Float): BedrockStatelessAnimation<T> {
this.speed = speed
return this
}
val particleKeyFrames = animation.effects.filterIsInstance<BedrockParticleKeyframe>()
override fun setAngles(entity: T?, model: PoseableEntityModel<T>, state: PoseableEntityState<T>?, limbSwing: Float, limbSwingAmount: Float, ageInTicks: Float, headYaw: Float, headPitch: Float) {
val prev = if (state == null) 0F else (state.previousAnimationSeconds - state.timeEnteredPose)
val cur = if (state == null) 0F else (state.animationSeconds - state.timeEnteredPose)
animation.run(model, entity, state, prev * speed.toDouble(), cur * speed.toDouble())
animation.run(model, state, state?.animationSeconds ?: 0F)
}
override fun applyEffects(entity: T, state: PoseableEntityState<T>, previousSeconds: Float, newSeconds: Float) {
animation.applyEffects(entity, state, (previousSeconds % animation.animationLength).toFloat(), (newSeconds % animation.animationLength).toFloat())
}
}
@@ -12,11 +12,20 @@ import com.cobblemon.mod.common.client.render.models.blockbench.PoseableEntitySt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
/**
* A [PoseableEntityState] that exists even without an entity or other concrete state. This is
* for when a Pokémon needs to be continuously animated and there isn't an entity to attach state
* to.
* A [PoseableEntityState] that exists even without an entity or age-based state. This is
* for when a Pokémon needs to be continuously animated from GUIs and there isn't an entity
* to attach state to. It has no age, and updating the partial ticks will increment rather
* than replace.
*
* What to look out for: Don't run updatePartialTicks multiple times in a single frame. For
* other [PoseableEntityState] this is fine as it just replaces what was there before, but
* since this is incremental it would actually mess up the animation speeds.
*
* @author Hiroku
* @since May 1st, 2022
*/
class PokemonFloatingState : PoseableEntityState<PokemonEntity>()
class PokemonFloatingState : PoseableEntityState<PokemonEntity>() {
override fun updatePartialTicks(partialTicks: Float) {
this.currentPartialTicks += partialTicks
}
}
@@ -45,7 +45,7 @@ class ElectrodeModel(root: ModelPart) : PokemonPoseableModel() {
poseTypes = MOVING_POSES,
transformTicks = 0,
quirks = arrayOf(blink),
onTransitionedInto = { it?.animationSeconds = 0F },
onTransitionedInto = { it?.reset() },
idleAnimations = arrayOf(
bedrock("electrode", "ground_walk")
)
@@ -43,7 +43,7 @@ class VoltorbModel(root: ModelPart) : PokemonPoseableModel() {
walk = registerPose(
poseName = "walk",
poseTypes = MOVING_POSES,
onTransitionedInto = { it?.animationSeconds = 0F },
onTransitionedInto = { it?.reset() },
transformTicks = 0,
idleAnimations = arrayOf(
bedrock("voltorb", "ground_walk")
@@ -37,11 +37,13 @@ class Pose<T : Entity, F : ModelFrame>(
}
fun idleStateful(entity: T?, model: PoseableEntityModel<T>, state: PoseableEntityState<T>, limbSwing: Float, limbSwingAmount: Float, ageInTicks: Float, headYaw: Float, headPitch: Float) {
idleAnimations.forEach { idleAnimation ->
val allStatefuls = state.statefulAnimations + state.quirks.flatMap { it.value.animations }
if (allStatefuls.none { it.preventsIdle(entity, state, idleAnimation) }) {
idleAnimation.apply(entity, model, state, limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch)
}
getApplicableIdleAnimations(entity, state).forEach { idleAnimation ->
idleAnimation.apply(entity, model, state, limbSwing, limbSwingAmount, ageInTicks, headYaw, headPitch)
}
}
fun getApplicableIdleAnimations(entity: T?, state: PoseableEntityState<T>): List<StatelessAnimation<T, out F>> {
val allStatefulAnimations = state.allStatefulAnimations
return idleAnimations.filter { idle -> allStatefulAnimations.none { it.preventsIdle(entity, state, idle) } }
}
}
@@ -36,6 +36,7 @@ class PokeBallRenderer(context: EntityRendererFactory.Context) : EntityRenderer<
val vertexConsumer = ItemRenderer.getDirectItemGlintConsumer(buffer, model.getLayer(getTexture(entity)), false, false)
val state = entity.delegate as EmptyPokeBallClientDelegate
state.updatePartialTicks(partialTicks)
model.setLayerContext(buffer, state, PokemonModelRepository.getLayers(entity.pokeBall.name, entity.aspects.get()))
model.setAngles(entity, 0f, 0f, entity.age + partialTicks, 0F, 0F)
model.render(poseStack, vertexConsumer, packedLight, OverlayTexture.DEFAULT_UV, 1.0f, 1.0f, 1.0f, 1.0f)
@@ -106,6 +106,8 @@ class PokemonRenderer(
renderBeam(poseMatrix, partialTicks, entity, phaseTarget, lightColour, buffer)
}
clientDelegate.updatePartialTicks(partialTicks)
modelNow.setLayerContext(buffer, clientDelegate, PokemonModelRepository.getLayers(entity.pokemon.species.resourceIdentifier, entity.aspects.get()))
super.render(entity, entityYaw, partialTicks, poseMatrix, buffer, packedLight)
@@ -4,5 +4,5 @@
<modelVersion>4.0.0</modelVersion>
<groupId>local.com.bedrockk</groupId>
<artifactId>molang</artifactId>
<version>1.1.1</version>
<version>1.1.3</version>
</project>
+3 -3
View File
@@ -3,10 +3,10 @@
<groupId>local.com.bedrockk</groupId>
<artifactId>molang</artifactId>
<versioning>
<release>1.1.1</release>
<release>1.1.3</release>
<versions>
<version>1.1.1</version>
<version>1.1.3</version>
</versions>
<lastUpdated>20221939127979</lastUpdated>
<lastUpdated>20221939127989</lastUpdated>
</versioning>
</metadata>
@@ -25,22 +25,20 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
*/
@Mixin(InGameHud.class)
public class GuiMixin {
private Long lastTimeMillis = null;
@Inject(
method = "render",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/MinecraftClient;getProfiler()Lnet/minecraft/util/profiler/Profiler;",
target = "Lnet/minecraft/client/gui/hud/ChatHud;render(Lnet/minecraft/client/gui/DrawContext;III)V",
shift = At.Shift.BEFORE,
ordinal = 0
),
slice = @Slice(
from = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/gui/hud/InGameHud;renderScoreboardSidebar(Lnet/minecraft/client/gui/DrawContext;Lnet/minecraft/scoreboard/ScoreboardObjective;)V"
)
)
)
private void beforeChatHook(DrawContext context, float f, CallbackInfo ci) {
CobblemonClient.INSTANCE.beforeChatRender(context, f);
if (lastTimeMillis != null) {
CobblemonClient.INSTANCE.beforeChatRender(context, (System.currentTimeMillis() - lastTimeMillis) / 1000F * 20);
}
lastTimeMillis = System.currentTimeMillis();
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ versions:
# common
graal: 22.3.0
molang: 1.1.1
molang: 1.1.3
# test
junit: 5.9.0