feat(battle): add the wild battle system with structured codecs (#58)

This commit is contained in:
Fiereu authored and GitHub committed 2026-07-25 17:28:48 +02:00
1 parent 214663531a
commit 651a1fbb67
30 files changed
+2429 -522

No files matched your search

@@ -113,7 +113,7 @@ object GameProtocol : Protocol() {
bidi<DialogOptionPacket>(0x26u, DialogOptionPacketCodec)
c2s<PlayerStopMovingPacket>(0x27u, PlayerStopMovingPacketCodec)
s2c<BattlePromptSwitchPacket>(0x27u, BattlePromptSwitchPacketCodec)
s2c<PcTogglePacket>(0x27u, PcTogglePacketCodec)
c2s<TypedBinaryDataPacket>(0x28u, TypedBinaryDataPacketCodec)
s2c<EntityInteractionFlagPacket>(0x28u, EntityInteractionFlagPacketCodec)
@@ -407,7 +407,7 @@ object GameProtocol : Protocol() {
s2c<EntityAppearanceSyncPacket>(0x94u, EntityAppearanceSyncPacketCodec)
c2s<MailComposeSendPacket>(0x95u, MailComposeSendPacketCodec)
s2c<BattleSwitchPromptTogglePacket>(0x95u, BattleSwitchPromptTogglePacketCodec)
s2c<MailTogglePacket>(0x95u, MailTogglePacketCodec)
c2s<TeamPreviewRevealPickPacket>(0x96u, TeamPreviewRevealPickPacketCodec)
s2c<BattleEndDisconnectPacket>(0x96u, BattleEndDisconnectPacketCodec)
@@ -36,12 +36,14 @@ internal val BattleMessageArgCodec: Codec<BattleMessageArg> =
}
val t = type.toInt()
val payload: BattleMessageArgPayload =
when {
t == 5 -> StringArgPayload(Utf16LeNullTerminated.read(buf))
t == 28 -> EmptyArgPayload
t == 30 -> LongArgPayload(S64LE.read(buf))
t == 9 || t == 10 || t == 17 -> IntArgPayload(S32LE.read(buf))
t == 18 -> StringArgPayload(Utf16LeNullTerminated.read(buf))
when (t) {
5 -> StringArgPayload(Utf16LeNullTerminated.read(buf))
28 -> EmptyArgPayload
30 -> LongArgPayload(S64LE.read(buf))
9,
10,
17 -> IntArgPayload(S32LE.read(buf))
18 -> StringArgPayload(Utf16LeNullTerminated.read(buf))
else -> {
val n = U8.read(buf)
ShortListArgPayload((0 until n).map { S16LE.read(buf) })
@@ -56,12 +58,14 @@ internal val BattleMessageArgCodec: Codec<BattleMessageArg> =
S8.write(buf, rawType)
if (value.hasExtra) S8.write(buf, value.extra)
val t = value.type.toInt()
when {
t == 5 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value)
t == 28 -> Unit
t == 30 -> S64LE.write(buf, (value.payload as LongArgPayload).value)
t == 9 || t == 10 || t == 17 -> S32LE.write(buf, (value.payload as IntArgPayload).value)
t == 18 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value)
when (t) {
5 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value)
28 -> Unit
30 -> S64LE.write(buf, (value.payload as LongArgPayload).value)
9,
10,
17 -> S32LE.write(buf, (value.payload as IntArgPayload).value)
18 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value)
else -> {
val values = (value.payload as ShortListArgPayload).values
U8.write(buf, values.size)
@@ -2,35 +2,152 @@ package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
data class BattleMoveDataEntry(
val entityId: Long,
val value: Short,
val actionCount: Int,
)
/** The body of a nested battle action event, selected by its [BattleEventType]. */
sealed interface BattleEventBody {
/** Event 0, BattleHpUpdate: the entity's resulting hp. */
data class HpUpdate(val currentHp: Short) : BattleEventBody
private val BattleMoveDataEntryCodec: Codec<BattleMoveDataEntry> =
object : PacketCodec<BattleMoveDataEntry>() {
override fun CodecScope<BattleMoveDataEntry>.body(): BattleMoveDataEntry {
val entityId = field(S64LE) { it.entityId }
val value = field(S16LE) { it.value }
val actionCount = field(U8) { it.actionCount }
return BattleMoveDataEntry(entityId, value, actionCount)
/**
* Event 1, BattleStatChange. [stat] is the wire stat id (1 atk, 2 def, 3 spd, ...) and
* [stageDelta] the signed number of stages (-1 down one, +2 up two). [changeType] is 0 for a
* normal stage change.
*/
data class StatChange(val stat: Byte, val stageDelta: Short, val changeType: Byte = 0) :
BattleEventBody
/** Event 5, BattlePokemonFainted. [playFaintAnimation] plays the faint-in-place animation. */
data class Faint(val playFaintAnimation: Boolean) : BattleEventBody
/**
* Event 4, BattleEffectivenessMessage. No body: the client derives the message from the types.
*/
data object EffectivenessMessage : BattleEventBody
/** Event 0x40, BattleMoveFailed. [moveId] names the move in the "it failed" message. */
data class MoveFailed(val moveId: Short) : BattleEventBody
}
private val HpUpdateBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody {
val currentHp = field(S16LE) { (it as BattleEventBody.HpUpdate).currentHp }
return BattleEventBody.HpUpdate(currentHp)
}
}
data class BattleEntityMoveEventPacket(
private val StatChangeBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody {
val changeType = field(S8) { (it as BattleEventBody.StatChange).changeType }
val stat = field(S8) { (it as BattleEventBody.StatChange).stat }
val stageDelta = field(S16LE) { (it as BattleEventBody.StatChange).stageDelta }
return BattleEventBody.StatChange(stat, stageDelta, changeType)
}
}
private val FaintBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody {
val playFaintAnimation = field(Bool) { (it as BattleEventBody.Faint).playFaintAnimation }
return BattleEventBody.Faint(playFaintAnimation)
}
}
private val EffectivenessMessageBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody =
BattleEventBody.EffectivenessMessage
}
private val MoveFailedBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody {
val moveId = field(S16LE) { (it as BattleEventBody.MoveFailed).moveId }
return BattleEventBody.MoveFailed(moveId)
}
}
/**
* A nested battle action event's type, the client's event id. Each type holds the codec for its
* body. The enum grows as we capture more of the client's event types.
*/
enum class BattleEventType(val id: Int, val codec: Codec<BattleEventBody>) {
HP_UPDATE(id = 0, codec = HpUpdateBodyCodec),
STAT_CHANGE(id = 1, codec = StatChangeBodyCodec),
EFFECTIVENESS_MESSAGE(id = 4, codec = EffectivenessMessageBodyCodec),
POKEMON_FAINTED(id = 5, codec = FaintBodyCodec),
MOVE_FAILED(id = 0x40, codec = MoveFailedBodyCodec);
companion object {
fun ofId(id: Int): BattleEventType = entries.first { it.id == id }
fun ofBody(body: BattleEventBody): BattleEventType =
when (body) {
is BattleEventBody.HpUpdate -> HP_UPDATE
is BattleEventBody.StatChange -> STAT_CHANGE
is BattleEventBody.EffectivenessMessage -> EFFECTIVENESS_MESSAGE
is BattleEventBody.Faint -> POKEMON_FAINTED
is BattleEventBody.MoveFailed -> MOVE_FAILED
}
}
}
private const val FLAG_ENTITY_A = 0x01
private const val FLAG_ENTITY_B = 0x02
/**
* One nested battle action event. The variable header is a type id, a presence-flags byte, then the
* entity ids the flags select. [entityA] and [entityB] are present only when their flag bit is set.
*/
data class BattleActionEvent(val entityA: Long?, val entityB: Long?, val body: BattleEventBody)
private val BattleActionEventCodec: Codec<BattleActionEvent> =
object : PacketCodec<BattleActionEvent>() {
override fun CodecScope<BattleActionEvent>.body(): BattleActionEvent {
val typeId = field(U8) { BattleEventType.ofBody(it.body).id }
val aux =
field(U8) {
var flags = 0
if (it.entityA != null) flags = flags or FLAG_ENTITY_A
if (it.entityB != null) flags = flags or FLAG_ENTITY_B
flags
}
val entityA = optionalField((aux and FLAG_ENTITY_A) != 0, S64LE) { it.entityA }
val entityB = optionalField((aux and FLAG_ENTITY_B) != 0, S64LE) { it.entityB }
val body = field(BattleEventType.ofId(typeId).codec) { it.body }
return BattleActionEvent(entityA, entityB, body)
}
}
/** One mon a move affected: its entity, its move short, and the events applied to it. */
data class BattleEffectTarget(
val entityId: Long,
val value: Short,
val targetMove: Short,
val subEvents: List<BattleActionEvent>,
)
object BattleEffectTargetCodec : PacketCodec<BattleEffectTarget>() {
override fun CodecScope<BattleEffectTarget>.body(): BattleEffectTarget {
val entityId = field(S64LE) { it.entityId }
val targetMove = field(S16LE) { it.targetMove }
val subEvents = field(BattleActionEventCodec.listPrefixed(U8)) { it.subEvents }
return BattleEffectTarget(entityId, targetMove, subEvents)
}
}
data class BattleEntityMoveEventPacket(
val sourceEntity: Long,
val sourceMove: Short,
val kind: Byte,
val entries: List<BattleMoveDataEntry>,
val targets: List<BattleEffectTarget>,
)
object BattleEntityMoveEventPacketCodec : PacketCodec<BattleEntityMoveEventPacket>() {
override fun CodecScope<BattleEntityMoveEventPacket>.body(): BattleEntityMoveEventPacket {
val entityId = field(S64LE) { it.entityId }
val value = field(S16LE) { it.value }
val sourceEntity = field(S64LE) { it.sourceEntity }
val sourceMove = field(S16LE) { it.sourceMove }
val kind = field(S8) { it.kind }
val entries = field(BattleMoveDataEntryCodec.listPrefixed(U8)) { it.entries }
return BattleEntityMoveEventPacket(entityId, value, kind, entries)
val targets = field(BattleEffectTargetCodec.listPrefixed(U8)) { it.targets }
return BattleEntityMoveEventPacket(sourceEntity, sourceMove, kind, targets)
}
}
@@ -2,146 +2,54 @@ package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
data class BattleFieldMon(
val entityId: Long,
val species: Short,
val hp: Short,
)
/**
* The field state for a wild encounter (opcode 0x30). Each side sends a monster count that sizes
* the client's slot array followed by that many monster blocks. A player block carries a
* per-species stat and move block with its hp and party slot filled in, so a benched monster goes
* in its own slot instead of overwriting the active one.
* the client's slot array followed by that many monster blocks. The player side closes with the
* active monster's detail, the wild side carries a single wild block.
*/
data class BattleFieldStatePacket(
val playerName: String,
val playerId: Long,
val playerParty: List<BattleFieldMon>,
val wildMon: BattleFieldMon,
val playerParty: List<BattleMonBlock>,
val activeSlot: Int,
val wildParty: List<BattleMonBlock>,
)
private fun seg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private val PREAMBLE = seg("02000000000000000000000000ff000000000016000000ff00200006")
private val AFTER_NAME = seg("00")
private val APPEARANCE = seg("ff00024c031aac0f00038001a400040000000000")
private val SIDE_HEADER = seg("01")
private val SIDE_MID = seg("00")
// A monster block starts with its slot index then a constant 01.
private val MON_CONST = seg("01")
private val ACTIVE_DETAIL = seg("0000ef010600000000000003ff000000006666666601060000000000")
private val WILD_DATA_A = seg("020000010000000e00")
private val WILD_DATA_B = seg("000000ff0300010000f8010200000000010003ff000000006666666600000000")
private const val WILD_COUNT = 1
// Per-species blocks captured from a real field state. The 9-byte stat segment is
// [prefix (7)][max hp][00] and the 17-byte move segment is [move body (16)][party slot]. Hp and
// slot are spliced in per monster.
private class SpeciesBlock(val statPrefix: ByteArray, val moveBody: ByteArray)
private val SPECIES_BLOCKS =
mapOf(
495 to SpeciesBlock(seg("06000000000000"), seg("000000ff0301410021002b0000000000")),
504 to SpeciesBlock(seg("02000001000000"), seg("000000ff030132002100000000000000")),
)
private val DEFAULT_SPECIES_BLOCK = SPECIES_BLOCKS.getValue(504)
private fun speciesBlock(species: Short): SpeciesBlock =
SPECIES_BLOCKS[species.toInt()] ?: DEFAULT_SPECIES_BLOCK
private val BattleFieldStateBody: Codec<BattleFieldStatePacket> =
object : Codec<BattleFieldStatePacket> {
override fun read(buf: ReadBuffer): BattleFieldStatePacket {
buf.readBytes(ByteArray(PREAMBLE.size))
val playerName = Utf16LeNullTerminated.read(buf)
buf.readBytes(ByteArray(AFTER_NAME.size))
val playerId = S64LE.read(buf)
buf.readBytes(ByteArray(APPEARANCE.size))
buf.readBytes(ByteArray(SIDE_HEADER.size))
val playerCount = U8.read(buf)
buf.readBytes(ByteArray(SIDE_MID.size))
val party = List(playerCount) { readMon(buf) }
buf.readBytes(ByteArray(ACTIVE_DETAIL.size))
buf.readBytes(ByteArray(SIDE_HEADER.size))
U8.read(buf) // opponent count
buf.readBytes(ByteArray(SIDE_MID.size))
val wild = readWild(buf)
return BattleFieldStatePacket(playerName, playerId, party, wild)
}
override fun write(buf: WriteBuffer, value: BattleFieldStatePacket) {
buf.writeBytes(PREAMBLE)
Utf16LeNullTerminated.write(buf, value.playerName)
buf.writeBytes(AFTER_NAME)
S64LE.write(buf, value.playerId)
buf.writeBytes(APPEARANCE)
buf.writeBytes(SIDE_HEADER)
U8.write(buf, value.playerParty.size)
buf.writeBytes(SIDE_MID)
value.playerParty.forEachIndexed { slot, mon -> writeMon(buf, slot, mon) }
buf.writeBytes(ACTIVE_DETAIL)
buf.writeBytes(SIDE_HEADER)
U8.write(buf, WILD_COUNT)
buf.writeBytes(SIDE_MID)
writeWild(buf, value.wildMon)
}
private fun readMon(buf: ReadBuffer): BattleFieldMon {
S8.read(buf) // slot index
buf.readBytes(ByteArray(MON_CONST.size))
val entityId = S64LE.read(buf)
val species = S16LE.read(buf)
val block = speciesBlock(species)
buf.readBytes(ByteArray(block.statPrefix.size))
S8.read(buf) // max hp
S8.read(buf) // stat tail
val hp = S16LE.read(buf)
buf.readBytes(ByteArray(block.moveBody.size))
S8.read(buf) // slot trailer
return BattleFieldMon(entityId, species, hp)
}
private fun writeMon(buf: WriteBuffer, slot: Int, mon: BattleFieldMon) {
S8.write(buf, slot.toByte())
buf.writeBytes(MON_CONST)
S64LE.write(buf, mon.entityId)
S16LE.write(buf, mon.species)
val block = speciesBlock(mon.species)
buf.writeBytes(block.statPrefix)
S8.write(buf, mon.hp.toByte()) // max hp
S8.write(buf, 0)
S16LE.write(buf, mon.hp)
buf.writeBytes(block.moveBody)
S8.write(buf, slot.toByte()) // slot trailer
}
private fun readWild(buf: ReadBuffer): BattleFieldMon {
S8.read(buf) // slot index
buf.readBytes(ByteArray(MON_CONST.size))
val entityId = S64LE.read(buf)
val species = S16LE.read(buf)
buf.readBytes(ByteArray(WILD_DATA_A.size))
val hp = S16LE.read(buf)
buf.readBytes(ByteArray(WILD_DATA_B.size))
return BattleFieldMon(entityId, species, hp)
}
private fun writeWild(buf: WriteBuffer, mon: BattleFieldMon) {
S8.write(buf, 0)
buf.writeBytes(MON_CONST)
S64LE.write(buf, mon.entityId)
S16LE.write(buf, mon.species)
buf.writeBytes(WILD_DATA_A)
S16LE.write(buf, mon.hp)
buf.writeBytes(WILD_DATA_B)
}
}
object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
override fun CodecScope<BattleFieldStatePacket>.body(): BattleFieldStatePacket {
return field(BattleFieldStateBody) { it }
constant(PREAMBLE)
val playerName = field(Utf16LeNullTerminated) { it.playerName }
reserved(0)
val playerId = field(S64LE) { it.playerId }
constant(APPEARANCE)
constant(1) // player side marker
val partyCount = field(U8) { it.playerParty.size }
reserved(0)
val party =
List(partyCount) { i ->
val block = field(BattleFullBlockCodec) { it.playerParty[i] }
// The trailing byte flags the last party block; 0 says another block follows.
field(S8) { if (i == it.playerParty.lastIndex) 1.toByte() else 0.toByte() }
block
}
val active =
field(BattleActiveDetailCodec) {
BattleActiveDetail.of(it.activeSlot, it.playerParty[it.activeSlot])
}
// Closes the player side after the active detail: [01][active level][00 x5].
constant(1)
field(S8) { it.playerParty[it.activeSlot].level }
padding(5)
constant(1) // wild side marker
val wildCount = field(U8) { it.wildParty.size }
reserved(0)
val wildParty = List(wildCount) { i -> field(BattleWildBlockCodec) { it.wildParty[i] } }
return BattleFieldStatePacket(playerName, playerId, party, active.slot, wildParty)
}
}
@@ -0,0 +1,114 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
/**
* One monster as the battle packets carry it, shared by the field state and the switch-in. The
* values are server computed and the client displays them as sent. A full block carries hp,
* ability, and moves. The 21-byte active detail names only species, level, and gender.
*
* [movesPresent] is the wire flag that guards the ability and move ids. The wild block clears it so
* the client never learns the enemy moveset.
*/
data class BattleMonBlock(
val slot: Int,
val entityId: Long,
val species: Short,
val level: Byte,
val gender: Byte,
val abilityId: Short,
val maxHp: Short,
val currentHp: Short,
val movesPresent: Boolean,
val moveIds: List<Short>,
) {
init {
require(moveIds.size == MOVE_SLOTS) { "A battle mon block carries exactly $MOVE_SLOTS moves" }
}
companion object {
const val MOVE_SLOTS = 4
}
}
private fun seg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
// Captured constant that precedes the moves-present flag, meaning still unknown.
private val MOVES_HEADER = seg("000000ff03")
// The wild block replaces the ability and move segment with this captured marker.
private val WILD_MOVES_SEGMENT = seg("000000ff030001")
private val ACTIVE_TAIL = seg("03ff0000000066666666")
private val NO_MOVES = List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
/** The active monster's detail block, naming only species, level, and gender. */
internal data class BattleActiveDetail(
val slot: Int,
val species: Short,
val level: Byte,
val gender: Byte,
) {
companion object {
fun of(slot: Int, mon: BattleMonBlock): BattleActiveDetail =
BattleActiveDetail(slot, mon.species, mon.level, mon.gender)
}
}
internal object BattleActiveDetailCodec : PacketCodec<BattleActiveDetail>() {
const val WIRE_SIZE = 21
override fun CodecScope<BattleActiveDetail>.body(): BattleActiveDetail {
reserved(0)
val slot = field(S8) { it.slot.toByte() }.toInt()
val species = field(S16LE) { it.species }
val level = field(S8) { it.level }
padding(4)
val gender = field(S8) { it.gender }
reserved(0)
constant(ACTIVE_TAIL)
return BattleActiveDetail(slot, species, level, gender)
}
}
internal object BattleFullBlockCodec : PacketCodec<BattleMonBlock>() {
override fun CodecScope<BattleMonBlock>.body(): BattleMonBlock {
val slot = field(S8) { it.slot.toByte() }.toInt()
constant(1)
val entityId = field(S64LE) { it.entityId }
val species = field(S16LE) { it.species }
val level = field(S8) { it.level }
padding(2)
val gender = field(S8) { it.gender }
padding(3)
val currentHp = field(S16LE) { it.currentHp }
val maxHp = field(S16LE) { it.maxHp }
constant(MOVES_HEADER)
val movesPresent = field(Bool) { it.movesPresent }
val abilityId = field(S16LE) { it.abilityId }
val moveIds = field(S16LE.repeat(BattleMonBlock.MOVE_SLOTS)) { it.moveIds }
return BattleMonBlock(
slot, entityId, species, level, gender, abilityId, maxHp, currentHp, movesPresent, moveIds)
}
}
/** The wild side's block. The decode fills ability and moves with zero. */
internal object BattleWildBlockCodec : PacketCodec<BattleMonBlock>() {
override fun CodecScope<BattleMonBlock>.body(): BattleMonBlock {
val slot = field(S8) { it.slot.toByte() }.toInt()
constant(1)
val entityId = field(S64LE) { it.entityId }
val species = field(S16LE) { it.species }
val level = field(S8) { it.level }
padding(2)
val gender = field(S8) { it.gender }
padding(3)
val currentHp = field(S16LE) { it.currentHp }
val maxHp = field(S16LE) { it.maxHp }
constant(WILD_MOVES_SEGMENT)
field(BattleActiveDetailCodec) { BattleActiveDetail.of(it.slot, it) }
padding(4)
return BattleMonBlock(
slot, entityId, species, level, gender, 0, maxHp, currentHp, false, NO_MOVES)
}
}
@@ -1,16 +0,0 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
data class BattlePromptSwitchPacket(
val enabled: Boolean,
)
object BattlePromptSwitchPacketCodec : PacketCodec<BattlePromptSwitchPacket>() {
override fun CodecScope<BattlePromptSwitchPacket>.body(): BattlePromptSwitchPacket {
val enabled = field(Bool) { it.enabled }
return BattlePromptSwitchPacket(enabled)
}
}
@@ -2,126 +2,64 @@ package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
data class BattleSwitchInMon(
val entityId: Long,
val species: Short,
val hp: Short,
)
/**
* Brings a monster onto the field after a switch (opcode 0x35). The header names the new and
* previous active party slots. A monster coming out for the first time carries its full block, the
* same layout as the field state. One already seen active is sent as just its 21-byte active
* detail. When [fullBlock] is false the incoming hp and entity id are left at zero on decode.
* detail. When [fullBlock] is false the decode fills only species, level, and gender.
*/
data class BattleSwitchInPacket(
val newSlot: Int,
val oldSlot: Int,
val mon: BattleSwitchInMon,
val mon: BattleMonBlock,
val fullBlock: Boolean,
)
private fun switchSeg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private val NO_MOVES = List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
private val SWITCH_HEADER = switchSeg("0000")
private val SWITCH_MON_CONST = switchSeg("01")
private data class SwitchInMon(val mon: BattleMonBlock, val fullBlock: Boolean)
// A species carries a full-block stat prefix and move body (as in the field state) plus a distinct
// active-detail stat used by the switch-in and active-mon segments.
private class SwitchSpeciesBlock(
val statPrefix: ByteArray,
val moveBody: ByteArray,
val activeStat: ByteArray,
)
private val SWITCH_SPECIES_BLOCKS =
mapOf(
495 to
SwitchSpeciesBlock(
switchSeg("06000000000000"),
switchSeg("000000ff0301410021002b0000000000"),
switchSeg("06000000000000"),
),
504 to
SwitchSpeciesBlock(
switchSeg("02000001000000"),
switchSeg("000000ff030132002100000000000000"),
switchSeg("02000000000100"),
),
)
private val DEFAULT_SWITCH_BLOCK = SWITCH_SPECIES_BLOCKS.getValue(504)
private fun switchBlock(species: Short): SwitchSpeciesBlock =
SWITCH_SPECIES_BLOCKS[species.toInt()] ?: DEFAULT_SWITCH_BLOCK
// [00][slot][species][active stat (7)] then this constant tail.
private val SWITCH_ACTIVE_TAIL = switchSeg("03ff0000000066666666")
private const val SWITCH_STAT_PREFIX_SIZE = 7
private const val SWITCH_MOVE_BODY_SIZE = 16
private const val SWITCH_ACTIVE_STAT_SIZE = 7
private const val SWITCH_ACTIVE_DETAIL_SIZE = 21
private val BattleSwitchInBody: Codec<BattleSwitchInPacket> =
object : Codec<BattleSwitchInPacket> {
override fun read(buf: ReadBuffer): BattleSwitchInPacket {
buf.readBytes(ByteArray(SWITCH_HEADER.size))
val newSlot = U8.read(buf)
val oldSlot = U8.read(buf)
val fullBlock = buf.remaining() > SWITCH_ACTIVE_DETAIL_SIZE
var entityId = 0L
var blockHp: Short = 0
var blockSpecies: Short = 0
if (fullBlock) {
S8.read(buf) // slot index
buf.readBytes(ByteArray(SWITCH_MON_CONST.size))
entityId = S64LE.read(buf)
blockSpecies = S16LE.read(buf)
buf.readBytes(ByteArray(SWITCH_STAT_PREFIX_SIZE))
S8.read(buf) // max hp
S8.read(buf) // stat tail
blockHp = S16LE.read(buf)
buf.readBytes(ByteArray(SWITCH_MOVE_BODY_SIZE))
S8.read(buf) // slot trailer
}
// active detail
S8.read(buf) // constant 00
S8.read(buf) // slot
val activeSpecies = S16LE.read(buf)
buf.readBytes(ByteArray(SWITCH_ACTIVE_STAT_SIZE))
buf.readBytes(ByteArray(SWITCH_ACTIVE_TAIL.size))
val species = if (fullBlock) blockSpecies else activeSpecies
return BattleSwitchInPacket(
newSlot, oldSlot, BattleSwitchInMon(entityId, species, blockHp), fullBlock)
// Whether the full block precedes the active detail is not flagged on the wire. Only the
// remaining length tells the two shapes apart, so this section cannot go through the scope.
private val SwitchInMonCodec: Codec<SwitchInMon> =
object : Codec<SwitchInMon> {
override fun read(buf: ReadBuffer): SwitchInMon {
val fullBlock = buf.remaining() > BattleActiveDetailCodec.WIRE_SIZE
val block = if (fullBlock) BattleFullBlockCodec.read(buf) else null
if (fullBlock) S8.read(buf) // last-block flag before the active detail
val active = BattleActiveDetailCodec.read(buf)
val mon =
block
?: BattleMonBlock(
slot = active.slot,
entityId = 0,
species = active.species,
level = active.level,
gender = active.gender,
abilityId = 0,
maxHp = 0,
currentHp = 0,
movesPresent = false,
moveIds = NO_MOVES,
)
return SwitchInMon(mon, fullBlock)
}
override fun write(buf: WriteBuffer, value: BattleSwitchInPacket) {
buf.writeBytes(SWITCH_HEADER)
U8.write(buf, value.newSlot)
U8.write(buf, value.oldSlot)
val block = switchBlock(value.mon.species)
override fun write(buf: WriteBuffer, value: SwitchInMon) {
if (value.fullBlock) {
S8.write(buf, value.newSlot.toByte())
buf.writeBytes(SWITCH_MON_CONST)
S64LE.write(buf, value.mon.entityId)
S16LE.write(buf, value.mon.species)
buf.writeBytes(block.statPrefix)
S8.write(buf, value.mon.hp.toByte()) // max hp
S8.write(buf, 0)
S16LE.write(buf, value.mon.hp)
buf.writeBytes(block.moveBody)
S8.write(buf, value.newSlot.toByte()) // slot trailer
BattleFullBlockCodec.write(buf, value.mon)
S8.write(buf, 1) // last-block flag before the active detail
}
S8.write(buf, 0)
S8.write(buf, value.newSlot.toByte())
S16LE.write(buf, value.mon.species)
buf.writeBytes(block.activeStat)
buf.writeBytes(SWITCH_ACTIVE_TAIL)
BattleActiveDetailCodec.write(buf, BattleActiveDetail.of(value.mon.slot, value.mon))
}
}
object BattleSwitchInPacketCodec : PacketCodec<BattleSwitchInPacket>() {
override fun CodecScope<BattleSwitchInPacket>.body(): BattleSwitchInPacket {
return field(BattleSwitchInBody) { it }
padding(2)
val newSlot = field(U8) { it.newSlot }
val oldSlot = field(U8) { it.oldSlot }
val section = field(SwitchInMonCodec) { SwitchInMon(it.mon, it.fullBlock) }
return BattleSwitchInPacket(newSlot, oldSlot, section.mon, section.fullBlock)
}
}
@@ -1,16 +0,0 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
data class BattleSwitchPromptTogglePacket(
val shown: Boolean,
)
object BattleSwitchPromptTogglePacketCodec : PacketCodec<BattleSwitchPromptTogglePacket>() {
override fun CodecScope<BattleSwitchPromptTogglePacket>.body(): BattleSwitchPromptTogglePacket {
val shown = field(Bool) { it.shown }
return BattleSwitchPromptTogglePacket(shown)
}
}
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
data class MailTogglePacket(
val shown: Boolean,
)
object MailTogglePacketCodec : PacketCodec<MailTogglePacket>() {
override fun CodecScope<MailTogglePacket>.body(): MailTogglePacket {
val shown = field(Bool) { it.shown }
return MailTogglePacket(shown)
}
}
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.Bool
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
data class PcTogglePacket(
val shown: Boolean,
)
object PcTogglePacketCodec : PacketCodec<PcTogglePacket>() {
override fun CodecScope<PcTogglePacket>.body(): PcTogglePacket {
val shown = field(Bool) { it.shown }
return PcTogglePacket(shown)
}
}
@@ -0,0 +1,40 @@
package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.net.game.packets.battle.BattleActionEvent
import de.fiereu.openmmo.net.game.packets.battle.BattleEffectTarget
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacketCodec
import de.fiereu.openmmo.net.game.packets.battle.BattleEventBody
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class BattleEntityMoveEventPacketTest :
FunSpec({
test("round-trips every body type and entity-flag combination") {
val packet =
BattleEntityMoveEventPacket(
sourceEntity = 0x1122334455667788L,
sourceMove = 0x0200,
kind = 1,
targets =
listOf(
BattleEffectTarget(
entityId = 10L,
targetMove = 0x0200,
subEvents =
listOf(
BattleActionEvent(null, null, BattleEventBody.HpUpdate(14)),
BattleActionEvent(20L, null, BattleEventBody.StatChange(1, -2)),
BattleActionEvent(null, 30L, BattleEventBody.Faint(true)),
BattleActionEvent(
40L, 50L, BattleEventBody.EffectivenessMessage),
BattleActionEvent(null, null, BattleEventBody.MoveFailed(33)))),
BattleEffectTarget(
entityId = 60L, targetMove = 0, subEvents = emptyList())))
val bytes = BattleEntityMoveEventPacketCodec.encodeToBytes(packet)
BattleEntityMoveEventPacketCodec.decodeBytes(bytes) shouldBe packet
}
})
@@ -2,14 +2,14 @@ package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacketCodec
import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.util.Base64
// A two-monster party wild encounter (Snivy active, Patrat benched), scrubbed of capture data. The
// player side carries a per-species stat and move block and a per-slot trailer, all reproduced by
// the codec.
// A two-monster party wild encounter (Snivy active, Patrat benched), scrubbed of capture data.
private const val CAPTURED_TWO_PARTY =
"AgAAAAAAAAAAAAAAAP8AAAAAABYAAAD/ACAABlQAZQBzAHQAAAAAAJABAAAAAAD/AAJMAxqsDwADgAGkAAQAAAAAAAECAAABAMABAAAAAADvAQYAAAAAAAAWABYAAAAA/wMBQQAhACsAAAAAAAABAQDAAgAAAAAA+AECAAABAAAADgAOAAAAAP8DATIAIQAAAAAAAAABAADvAQYAAAAAAAAD/wAAAABmZmZmAQYAAAAAAAEBAAABAMADAAAAAAD4AQIAAAEAAAAOAA4AAAAA/wMAAQAA+AECAAAAAAEAA/8AAAAAZmZmZgAAAAA="
@@ -20,9 +20,79 @@ class BattleFieldStatePacketTest :
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
decoded.playerName shouldBe "Test"
decoded.playerParty.size shouldBe 2
decoded.playerParty[0].species shouldBe 495.toShort()
decoded.playerParty[1].species shouldBe 504.toShort()
decoded.wildMon.species shouldBe 504.toShort()
decoded.activeSlot shouldBe 0
BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("decodes the structured mon fields from the capture") {
val bytes = Base64.getDecoder().decode(CAPTURED_TWO_PARTY)
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
val snivy = decoded.playerParty[0]
snivy.slot shouldBe 0
snivy.species shouldBe 495.toShort()
snivy.level shouldBe 6.toByte()
snivy.gender shouldBe 0.toByte()
snivy.abilityId shouldBe 65.toShort()
snivy.maxHp shouldBe 22.toShort()
snivy.currentHp shouldBe 22.toShort()
snivy.movesPresent shouldBe true
snivy.moveIds shouldBe listOf<Short>(33, 43, 0, 0)
val patrat = decoded.playerParty[1]
patrat.slot shouldBe 1
patrat.species shouldBe 504.toShort()
patrat.level shouldBe 2.toByte()
patrat.gender shouldBe 1.toByte()
patrat.abilityId shouldBe 50.toShort()
patrat.moveIds shouldBe listOf<Short>(33, 0, 0, 0)
val wild = decoded.wildParty.single()
wild.species shouldBe 504.toShort()
wild.level shouldBe 2.toByte()
wild.maxHp shouldBe 14.toShort()
wild.currentHp shouldBe 14.toShort()
wild.movesPresent shouldBe false
}
test("round-trips a synthetic field state for a species without a capture") {
val rattata =
BattleMonBlock(
slot = 0,
entityId = 0x123C000L,
species = 19,
level = 7,
gender = 1,
abilityId = 50,
maxHp = 21,
currentHp = 17,
movesPresent = true,
moveIds = listOf(33, 39, 45, 98),
)
val wild =
BattleMonBlock(
slot = 0,
entityId = 0x456C000L,
species = 74,
level = 9,
gender = 0,
abilityId = 0,
maxHp = 26,
currentHp = 26,
movesPresent = false,
moveIds = listOf(0, 0, 0, 0),
)
val packet =
BattleFieldStatePacket(
playerName = "Ash",
playerId = 0x19000L,
playerParty = listOf(rattata),
activeSlot = 0,
wildParty = listOf(wild),
)
val decoded =
BattleFieldStatePacketCodec.decodeBytes(
BattleFieldStatePacketCodec.encodeToBytes(packet))
decoded shouldBe packet
}
})
@@ -2,7 +2,7 @@ package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInMon
import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacketCodec
import io.kotest.core.spec.style.FunSpec
@@ -10,39 +10,59 @@ import io.kotest.matchers.shouldBe
private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }
private fun patrat(): BattleMonBlock =
BattleMonBlock(
slot = 1,
entityId = 0x000000000003C000L,
species = 504,
level = 2,
gender = 1,
abilityId = 50,
maxHp = 14,
currentHp = 14,
movesPresent = true,
moveIds = listOf(33, 0, 0, 0),
)
class BattleSwitchInPacketTest :
FunSpec({
// Switching back to an already-active monster sends only the 21-byte active detail.
// Reproduced
// byte for byte from a real capture (Snivy, slot 0, previous slot 1).
// Reproduced byte for byte from a real capture (Snivy, slot 0, previous slot 1).
test("encodes a return switch-in as just the active detail") {
val packet =
BattleSwitchInPacket(
newSlot = 0,
oldSlot = 1,
mon = BattleSwitchInMon(entityId = 0, species = 495, hp = 0),
mon =
BattleMonBlock(
slot = 0,
entityId = 0,
species = 495,
level = 6,
gender = 0,
abilityId = 0,
maxHp = 0,
currentHp = 0,
movesPresent = false,
moveIds = listOf(0, 0, 0, 0),
),
fullBlock = false,
)
val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet)
bytes.hex() shouldBe "000000010000ef010600000000000003ff0000000066666666"
}
// A benched monster coming out carries its full block then its active detail.
// A benched monster coming out carries its full block then its active detail. The block
// matches the captured Patrat bytes now built from structured fields.
test("round-trips a full-block switch-in") {
val packet =
BattleSwitchInPacket(
newSlot = 1,
oldSlot = 0,
mon = BattleSwitchInMon(entityId = 0x000000000003C000L, species = 504, hp = 14),
fullBlock = true,
)
BattleSwitchInPacket(newSlot = 1, oldSlot = 0, mon = patrat(), fullBlock = true)
val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet)
bytes.size shouldBe 65
val decoded = BattleSwitchInPacketCodec.decodeBytes(bytes)
decoded.newSlot shouldBe 1
decoded.oldSlot shouldBe 0
decoded.fullBlock shouldBe true
decoded.mon.species shouldBe 504.toShort()
decoded.mon.hp shouldBe 14.toShort()
decoded.mon shouldBe patrat()
}
})