feat(game): add a chat command system with /help, /pos, /testbattle and /catch (#125)

This commit is contained in:
Fiereu authored and GitHub committed 2026-08-09 09:11:19 +02:00
1 parent abce0d6eb4
commit 70c746fdc6
24 files changed
+662 -142

No files matched your search

@@ -0,0 +1,8 @@
package de.fiereu.openmmo.common
object CharacterPermissions {
// The codec sends only the low byte, so bits above 0xFF never reach the client.
const val DEVELOPER = 0x100
}
fun CharacterInfo.hasPermission(permission: Int): Boolean = permissions and permission == permission
@@ -102,9 +102,11 @@ private class ConcurrentAttributes : SessionAttributes {
@Suppress("UNCHECKED_CAST")
override fun <T : Any> remove(key: SessionAttribute<T>): T? = map.remove(key) as T?
// Not getOrPut. That is a get then a put, so racing threads each build one and the loser's
// value is dropped while still in use.
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getOrPut(key: SessionAttribute<T>, default: () -> T): T =
map.getOrPut(key) { default() } as T
map.computeIfAbsent(key) { default() } as T
override fun contains(key: SessionAttribute<*>): Boolean = map.containsKey(key)
}
@@ -12,6 +12,9 @@ import io.kotest.matchers.shouldBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
private data class Ping(val n: Int)
@@ -121,6 +124,35 @@ class TypedProtocolHandlerTest :
session.attributes.contains(key) shouldBe true
}
test("getOrPut builds one value however many threads race for it") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
val session = channel.attr(SESSION_KEY).get()
val key = SessionAttribute.of<Any>("scope")
val built = AtomicInteger()
val threads = 16
val start = CountDownLatch(1)
val pool = Executors.newFixedThreadPool(threads)
val results =
(1..threads)
.map {
pool.submit<Any> {
start.await()
session.attributes.getOrPut(key) {
built.incrementAndGet()
Any()
}
}
}
.also { start.countDown() }
.map { it.get() }
pool.shutdown()
built.get() shouldBe 1
results.all { it === results.first() } shouldBe true
}
test("OutgoingPacket goes through ProtocolHandler.write") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
@@ -1,6 +1,7 @@
package de.fiereu.openmmo.net.game.codecs
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.CharacterPermissions
import de.fiereu.openmmo.common.test.decodeBytes
import de.fiereu.openmmo.common.test.encodeToBytes
import io.kotest.core.spec.style.FunSpec
@@ -56,4 +57,38 @@ class CharacterInfoCodecTest :
)
CharacterInfoCodecShort.decodeBytes(bytes) shouldBe info
}
test("permission bits above the low byte are not sent") {
val timestamp = LocalDateTime.of(2024, 1, 2, 3, 4, 5)
val info =
CharacterInfo(
id = 123,
name = "Uno",
userId = 2,
rivalSex = 1,
lastLogin = timestamp,
createdAt = timestamp,
money = 30000,
permissions = CharacterPermissions.DEVELOPER or 8,
remainingSafariSteps = 0,
remainingSafariBalls = 0,
pcExtraSlots = 0,
battleBoxExtraSlots = 0,
templateAmount = 0,
positionRegionId = 2,
positionBankId = 133.toByte(),
positionMapId = 1,
positionX = 782,
positionY = 749,
repelLeft = 0,
repelItemId = 0,
lureLeft = 0,
lureItemId = 0,
)
val decoded =
CharacterInfoCodecShort.decodeBytes(CharacterInfoCodecShort.encodeToBytes(info))
decoded.permissions shouldBe 8
}
})
@@ -1,12 +1,9 @@
package de.fiereu.openmmo.server.game.battle
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.utils.hexToBytes
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket
import de.fiereu.openmmo.net.game.packets.EntityPresencePacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
@@ -28,6 +25,7 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket
import de.fiereu.openmmo.net.game.packets.battle.Experience
import de.fiereu.openmmo.net.game.packets.battle.MoveSlots
import de.fiereu.openmmo.net.game.packets.battle.OpposingSide
import de.fiereu.openmmo.server.game.services.notice
import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.typechart.TypeChart
import javax.inject.Inject
@@ -334,11 +332,3 @@ private fun statOrder(hp: Int, atk: Int, def: Int, spd: Int, spAtk: Int, spDef:
internal fun ComputedStats.asWireList(): List<Short> = statOrder(hp, atk, def, spd, spAtk, spDef)
private fun EVs.asWireList(): List<Short> = statOrder(hp, atk, def, spd, spAtk, spDef)
fun notice(message: String): ChatMessagePacket =
ChatMessagePacket(
type = ChatType.GAME_NOTIFICATIONS,
language = Language.EN,
message = message,
sender = "",
)
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.server.game.di
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoSet
import de.fiereu.openmmo.server.game.services.command.CatchCommand
import de.fiereu.openmmo.server.game.services.command.ChatCommand
import de.fiereu.openmmo.server.game.services.command.HelpCommand
import de.fiereu.openmmo.server.game.services.command.PosCommand
import de.fiereu.openmmo.server.game.services.command.TestBattleCommand
/**
* A name must not start with a client side command. The client resolves those itself and never
* sends them, which is why there is a /pos and no /where, which /w would have swallowed.
*/
@Module
interface ChatCommandModule {
@Binds @IntoSet fun helpCommand(command: HelpCommand): ChatCommand
@Binds @IntoSet fun posCommand(command: PosCommand): ChatCommand
@Binds @IntoSet fun testBattleCommand(command: TestBattleCommand): ChatCommand
@Binds @IntoSet fun catchCommand(command: CatchCommand): ChatCommand
}
@@ -12,7 +12,7 @@ import javax.inject.Provider
import javax.inject.Singleton
@Singleton
@Component(modules = [GameServerModule::class])
@Component(modules = [GameServerModule::class, ChatCommandModule::class])
interface GameServerComponent {
fun server(): GameServer
@@ -69,6 +69,7 @@ import de.fiereu.openmmo.server.game.services.MovementService
import de.fiereu.openmmo.server.game.services.MultiplayerService
import de.fiereu.openmmo.server.game.services.PresenceService
import de.fiereu.openmmo.server.game.services.SocialService
import de.fiereu.openmmo.server.game.services.command.ChatCommandService
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.SCRIPT_SCOPE
import de.fiereu.openmmo.server.game.session.SessionRegistry
@@ -92,6 +93,7 @@ constructor(
private val socialService: SocialService,
private val guildService: GuildService,
private val battleService: BattleService,
private val chatCommandService: ChatCommandService,
private val sessionRegistry: SessionRegistry,
private val characterStore: CharacterStore,
scope: CoroutineScope,
@@ -158,7 +160,11 @@ constructor(
on<NullPacket> {}
on<KeepAlivePacket> { event -> event.session.send(event.packet) }
on<ChatMessagePacket> { event -> onChatMessage(event) }
on<ChatMessageSendPacket> { event -> battleService.onChatSend(event) }
// What the client sends when the player types. The text rides in target unless the mode
// carries a message of its own.
on<ChatMessageSendPacket> { event ->
chatCommandService.tryHandle(event.session, event.packet.message ?: event.packet.target)
}
}
override fun onInactive() {
@@ -191,8 +197,8 @@ constructor(
return
}
val charId = state.characterId ?: return
val sender = characterStore.getCharacter(charId)?.info?.name ?: "Unknown"
val msg = event.packet
val sender = characterStore.getCharacter(charId)?.info?.name ?: "Unknown"
log.info { "Chat [${msg.type}] $sender: ${msg.message}" }
multiplayerService.broadcastMessage(
ChatMessagePacket(
@@ -8,7 +8,6 @@ import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket
import de.fiereu.openmmo.net.game.packets.MapLoadedAckPacket
import de.fiereu.openmmo.net.game.packets.SocialListEntryAddPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket
@@ -30,7 +29,6 @@ import de.fiereu.openmmo.server.game.battle.StatCalculator
import de.fiereu.openmmo.server.game.battle.TurnEngine
import de.fiereu.openmmo.server.game.battle.WildMonFactory
import de.fiereu.openmmo.server.game.battle.acquiredMonsterDelta
import de.fiereu.openmmo.server.game.battle.notice
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.interest.InterestManager
@@ -44,16 +42,6 @@ import javax.inject.Singleton
private val log = KotlinLogging.logger {}
private const val TEST_BATTLE_COMMAND = "/testbattle"
// The bag is populated in the join flow, so /catch drives the catch sequence directly for testing
// even though a ball can now be thrown from the UI.
private const val CATCH_COMMAND = "/catch"
private const val DEFAULT_WILD_DEX = 19
private const val DEFAULT_WILD_LEVEL = 3
private const val MIN_WILD_LEVEL = 2
private const val MAX_WILD_LEVEL = 100
private const val POKE_BALL_ITEM: Short = 5004
/**
@@ -142,23 +130,11 @@ constructor(
event.session.send(emitter.moveSlotsDelta(reply.entityId, moves.map { it.id to it.pp }, 0))
}
fun onChatSend(event: PacketEvent<ChatMessageSendPacket>) {
val session = event.session
val text = (event.packet.message ?: event.packet.target).trim()
val parts = text.split(Regex("\\s+"))
when {
parts[0].equals(TEST_BATTLE_COMMAND, ignoreCase = true) -> {
val dexId = parts.getOrNull(1)?.toIntOrNull() ?: DEFAULT_WILD_DEX
val level =
(parts.getOrNull(2)?.toIntOrNull() ?: DEFAULT_WILD_LEVEL).coerceIn(
MIN_WILD_LEVEL, MAX_WILD_LEVEL)
startWildBattle(session, dexId, level)
}
text.equals(CATCH_COMMAND, ignoreCase = true) -> {
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return
battles.byChar(charId)?.let { catchWild(it) }
}
}
/** Throws a ball at the monster. False when the character is not in a battle. */
fun catchActiveWild(charId: Long): Boolean {
val battle = battles.byChar(charId) ?: return false
catchWild(battle)
return true
}
/** Ends a running battle when the player disconnects, keeping the last hp and pp state. */
@@ -7,9 +7,7 @@ import de.fiereu.openmmo.common.auth.SessionTokenVerifier
import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.common.utils.hexToBytes
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.codecs.SkinSet
import de.fiereu.openmmo.net.game.packets.CharacterEntry
@@ -20,19 +18,16 @@ import de.fiereu.openmmo.net.game.packets.DeleteCharacterPacket
import de.fiereu.openmmo.net.game.packets.DeleteCharacterResultPacket
import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.JoinResponsePacket
import de.fiereu.openmmo.net.game.packets.LocalPlayerStatePacket
import de.fiereu.openmmo.net.game.packets.MenuPagePayloadPacket
import de.fiereu.openmmo.net.game.packets.NewAuthData
import de.fiereu.openmmo.net.game.packets.ObjectiveProgressBulkPacket
import de.fiereu.openmmo.net.game.packets.PokedexSpeciesResetPacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.net.game.packets.RequestCharactersPacket
import de.fiereu.openmmo.net.game.packets.RequestPlayerPacket
import de.fiereu.openmmo.net.game.packets.SelectCharacterPacket
import de.fiereu.openmmo.net.game.packets.SelectedCharacterPacket
import de.fiereu.openmmo.net.game.packets.ViewScalePacket
import de.fiereu.openmmo.net.game.packets.WorldFlagTableResetPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleRatingBulkPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleStateBytePacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
@@ -40,7 +35,6 @@ import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.session.SessionRegistry
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.StoredCharacter
import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime
import javax.inject.Inject
@@ -48,18 +42,6 @@ import javax.inject.Singleton
private val log = KotlinLogging.logger {}
// The world-flag table the client loads on join. Groups one to three are zlib streams that each
// decompress to a 67-byte flag block, the fourth is empty. The client reads real flag state while
// building the follower and party, so empty groups leave a lookup null and crash it.
private val WORLD_FLAG_GROUPS =
listOf(
"789c637060a00434a8b0320000133900ea",
"789c637060a00434303032000012c500c2",
"789c637060a00434303032000012c500c2",
"",
)
.map(String::hexToBytes)
private const val DELETE_SUCCESS = 0
private const val DELETE_REJECTED = 1
@@ -77,6 +59,7 @@ constructor(
private val presenceService: PresenceService,
private val mapScriptService: MapScriptService,
private val tokenVerifier: SessionTokenVerifier,
private val worldStateService: WorldStateService,
) {
fun onJoinGame(event: PacketEvent<JoinPacket>) {
@@ -215,50 +198,13 @@ constructor(
sessionRegistry.bindCharacter(ctx, charId)
log.info { "Player selected character '${stored.info.name}' (id=$charId)" }
// Initialise the client world-flag table before any monster or follower is built. Without it
// the table stays null and the client crashes constructing a party monster that reads a flag.
// Restore persisted story state after resetting client flags.
ctx.send(WorldFlagTableResetPacket(WORLD_FLAG_GROUPS))
ctx.send(buildLocalPlayerState(stored))
StoryClientState.flags(stored.info.positionRegionId, stored.storyFlags).forEach { ctx.send(it) }
worldStateService.send(ctx, stored)
val info = stored.info
val now = LocalDateTime.now()
val updatedInfo = info.copy(lastLogin = now)
characterStore.updateCharacter(updatedInfo)
val containers =
mapOf(
PokemonContainer.PARTY to stored.pokemon,
PokemonContainer.PC to stored.pcStorage,
PokemonContainer.BATTLE_BOX_1 to emptyList(),
PokemonContainer.BATTLE_BOX_2 to emptyList(),
PokemonContainer.DAYCARE to emptyList(),
)
for ((container, pokemon) in containers) {
ctx.send(
PokemonContainerPacket(
container = container,
hasChange = true,
delete = false,
pokemon = pokemon,
))
}
listOf(PokemonContainer.UNKNOWN_13, PokemonContainer.UNKNOWN_14).forEach { container ->
ctx.send(
PokemonContainerPacket(
container = container,
hasChange = true,
delete = false,
pokemon = emptyList(),
))
}
// The bag item stacks (opcode 0x40). The real server sends these during join, interleaved with
// the container packets, so the client has the items before entering the world.
ctx.send(storyItemStacksPacket(stored.items))
ctx.send(SelectedCharacterPacket(info))
sendJoinState(ctx)
ctx.send(
@@ -272,33 +218,6 @@ constructor(
preloadMapAndJoin(ctx, state, info)
}
// The full local-player state snapshot the client loads on login. Missing it leaves player state
// uninitialised and the client crashes reading it (for example when opening the battle bag).
private fun buildLocalPlayerState(stored: StoredCharacter): LocalPlayerStatePacket {
val info = stored.info
val partyDex = stored.pokemon.map { it.dexId.toShort() }
return LocalPlayerStatePacket(
region = info.positionRegionId,
mapId = info.positionMapId.toShort(),
moveSpeed = 0.05f,
x = info.positionX,
y = info.positionY,
z = 0,
money = info.money,
gender = info.rivalSex,
skinTone = 0,
hairColor = 0,
playtime = 0.0,
flags = 0,
partyDex = partyDex,
partyForms = partyDex.map { 0.toByte() },
pokedexSeen = emptyList(),
pokedexCaught = emptyList(),
badges = emptyList(),
variables = StoryClientState.variables(info.positionRegionId, stored.storyVars),
)
}
// Small state packets the real server sends in the join flow. The battle-state byte and menu
// payloads initialise state the battle bag reads, so without them opening the bag crashes.
private fun sendJoinState(ctx: SessionContext) {
@@ -0,0 +1,13 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
fun notice(message: String): ChatMessagePacket =
ChatMessagePacket(
type = ChatType.GAME_NOTIFICATIONS,
language = Language.EN,
message = message,
sender = "",
)
@@ -26,6 +26,18 @@ internal object StoryClientState {
}
.sortedBy { it.key.toInt() and 0xff }
/**
* Every var in the GBA range, zeros included. A var back at 0 is stored as absent, so sending
* only what is stored would leave the client holding the old value. There is no var equivalent of
* [de.fiereu.openmmo.net.game.packets.WorldFlagTableResetPacket] to clear it first.
*/
fun allVariables(regionId: Byte, vars: Map<String, Int>): List<PlayerVariableEntry> {
val byId = variables(regionId, vars).associate { it.key.toInt() and 0xff to it.value }
return (0..(GBA_VARS_END - GBA_VARS_START)).map {
PlayerVariableEntry(it.toByte(), byId[it] ?: 0)
}
}
private fun flagId(regionId: Byte, key: String): Int? =
when (regionId.toInt()) {
KANTO_REGION -> KantoFlags.numericId(key)
@@ -0,0 +1,99 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.utils.hexToBytes
import de.fiereu.openmmo.net.game.packets.LocalPlayerStatePacket
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.WorldFlagTableResetPacket
import de.fiereu.openmmo.server.game.storage.StoredCharacter
import javax.inject.Inject
import javax.inject.Singleton
// The world-flag table the client loads on join. Groups one to three are zlib streams that each
// decompress to a 67-byte flag block, the fourth is empty. The client reads real flag state while
// building the follower and party, so empty groups leave a lookup null and crash it.
private val WORLD_FLAG_GROUPS =
listOf(
"789c637060a00434a8b0320000133900ea",
"789c637060a00434303032000012c500c2",
"789c637060a00434303032000012c500c2",
"",
)
.map(String::hexToBytes)
/**
* Sends the client its story, party and bag state. Story vars have no incremental packet, so
* anything that rewrites them has to send this whole block again.
*/
@Singleton
class WorldStateService @Inject constructor() {
/**
* Set [fullVars] when this is a resync rather than a login, so vars that dropped back to 0 are
* sent as 0 instead of being left off and read as their old value.
*/
fun send(ctx: SessionContext, stored: StoredCharacter, fullVars: Boolean = false) {
// The table must land before any monster or follower is built. Without it the table stays null
// and the client crashes constructing a party monster that reads a flag.
ctx.send(WorldFlagTableResetPacket(WORLD_FLAG_GROUPS))
ctx.send(localPlayerState(stored, fullVars))
StoryClientState.flags(stored.info.positionRegionId, stored.storyFlags).forEach { ctx.send(it) }
val containers =
mapOf(
PokemonContainer.PARTY to stored.pokemon,
PokemonContainer.PC to stored.pcStorage,
PokemonContainer.BATTLE_BOX_1 to emptyList(),
PokemonContainer.BATTLE_BOX_2 to emptyList(),
PokemonContainer.DAYCARE to emptyList(),
PokemonContainer.UNKNOWN_13 to emptyList(),
PokemonContainer.UNKNOWN_14 to emptyList(),
)
for ((container, pokemon) in containers) {
ctx.send(
PokemonContainerPacket(
container = container,
hasChange = true,
delete = false,
pokemon = pokemon,
))
}
// The real server sends the bag stacks interleaved with the containers, so the client has the
// items before entering the world.
ctx.send(storyItemStacksPacket(stored.items))
}
// Missing it leaves player state uninitialised and the client crashes reading it, for example
// when opening the battle bag.
private fun localPlayerState(
stored: StoredCharacter,
fullVars: Boolean,
): LocalPlayerStatePacket {
val info = stored.info
val partyDex = stored.pokemon.map { it.dexId.toShort() }
return LocalPlayerStatePacket(
region = info.positionRegionId,
mapId = info.positionMapId.toShort(),
moveSpeed = 0.05f,
x = info.positionX,
y = info.positionY,
z = 0,
money = info.money,
gender = info.rivalSex,
skinTone = 0,
hairColor = 0,
playtime = 0.0,
flags = 0,
partyDex = partyDex,
partyForms = partyDex.map { 0.toByte() },
pokedexSeen = emptyList(),
pokedexCaught = emptyList(),
badges = emptyList(),
variables =
if (fullVars) StoryClientState.allVariables(info.positionRegionId, stored.storyVars)
else StoryClientState.variables(info.positionRegionId, stored.storyVars),
)
}
}
@@ -0,0 +1,20 @@
package de.fiereu.openmmo.server.game.services.command
import de.fiereu.openmmo.common.CharacterPermissions
import de.fiereu.openmmo.server.game.services.BattleService
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class CatchCommand @Inject constructor(private val battleService: BattleService) : ChatCommand {
override val name = "catch"
override val usage = "/catch"
override val description = "throws a ball at the monster you are fighting"
override val permission = CharacterPermissions.DEVELOPER
override fun run(ctx: CommandContext) {
if (!battleService.catchActiveWild(ctx.characterId)) {
ctx.reply("You are not in a battle.")
}
}
}
@@ -0,0 +1,36 @@
package de.fiereu.openmmo.server.game.services.command
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.server.game.services.notice
import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.storage.StoredCharacter
/** One chat command, matched on [name] without the slash and without case. */
interface ChatCommand {
val name: String
val usage: String
val description: String
val permission: Int
get() = 0
// Runs on the thread the packet arrived on. Anything that waits for the client needs its own
// scope first.
fun run(ctx: CommandContext)
}
class CommandContext(
val session: SessionContext,
val state: PlayerState,
val character: StoredCharacter,
val args: List<String>,
/** Already filtered to what this caller may run. */
val commands: List<ChatCommand>,
) {
val characterId: Long
get() = character.info.id
fun reply(message: String) {
session.send(notice(message))
}
}
@@ -0,0 +1,71 @@
package de.fiereu.openmmo.server.game.services.command
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.hasPermission
import de.fiereu.openmmo.server.game.services.notice
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import javax.inject.Singleton
private val log = KotlinLogging.logger {}
private const val PREFIX = '/'
@Singleton
class ChatCommandService
@Inject
constructor(
private val characterStore: CharacterStore,
registered: Set<@JvmSuppressWildcards ChatCommand>,
) {
private val commands = registered.associateBy { it.name.lowercase() }
/** Handles a chat line. Returns false when it is ordinary chat the caller should broadcast. */
fun tryHandle(session: SessionContext, message: String): Boolean {
val text = message.trim()
if (!text.startsWith(PREFIX)) return false
// TODO: Support quoted arguments, for a command that takes a name with a space in it.
val parts = text.drop(1).split(Regex("\\s+")).filter { it.isNotEmpty() }
val name = parts.firstOrNull()?.lowercase()
if (name == null) {
session.send(notice("Type /help to see what you can run."))
return true
}
val state = session.attributes[PLAYER_STATE]
val character = state?.characterId?.let(characterStore::getCharacter)
if (state == null || character == null) {
session.send(notice("You are not in the world yet."))
return true
}
val command = commands[name]
if (command == null || !character.info.hasPermission(command.permission)) {
if (command != null) {
log.info { "char=${character.info.id} may not run /$name" }
}
session.send(notice("Unknown command: $name. Try /help."))
return true
}
val ctx =
CommandContext(
session = session,
state = state,
character = character,
args = parts.drop(1),
commands = commands.values.filter { character.info.hasPermission(it.permission) },
)
try {
command.run(ctx)
} catch (e: Exception) {
log.error(e) { "/$name failed for char=${character.info.id}" }
ctx.reply("/$name failed.")
}
return true
}
}
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.server.game.services.command
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HelpCommand @Inject constructor() : ChatCommand {
override val name = "help"
override val usage = "/help"
override val description = "lists the commands you can run"
override fun run(ctx: CommandContext) {
ctx.commands.sortedBy { it.name }.forEach { ctx.reply("${it.usage} - ${it.description}") }
}
}
@@ -0,0 +1,18 @@
package de.fiereu.openmmo.server.game.services.command
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PosCommand @Inject constructor() : ChatCommand {
override val name = "pos"
override val usage = "/pos"
override val description = "shows the map and tile you are standing on"
override fun run(ctx: CommandContext) {
val s = ctx.state
ctx.reply(
"region ${s.regionId} bank ${s.bankId} map ${s.mapId} " +
"(${s.x}, ${s.y}) z ${s.elevation} facing ${s.facingDirection}")
}
}
@@ -0,0 +1,28 @@
package de.fiereu.openmmo.server.game.services.command
import de.fiereu.openmmo.common.CharacterPermissions
import de.fiereu.openmmo.server.game.services.BattleService
import javax.inject.Inject
import javax.inject.Singleton
private const val DEFAULT_WILD_DEX = 19
private const val DEFAULT_WILD_LEVEL = 3
private const val MIN_WILD_LEVEL = 2
private const val MAX_WILD_LEVEL = 100
@Singleton
class TestBattleCommand @Inject constructor(private val battleService: BattleService) :
ChatCommand {
override val name = "testbattle"
override val usage = "/testbattle [dexId] [level]"
override val description = "starts a wild battle against the given species"
override val permission = CharacterPermissions.DEVELOPER
override fun run(ctx: CommandContext) {
val dexId = ctx.args.getOrNull(0)?.toIntOrNull() ?: DEFAULT_WILD_DEX
val level =
(ctx.args.getOrNull(1)?.toIntOrNull() ?: DEFAULT_WILD_LEVEL).coerceIn(
MIN_WILD_LEVEL, MAX_WILD_LEVEL)
battleService.startWildBattle(ctx.session, dexId, level)
}
}
@@ -291,6 +291,26 @@ constructor(
markDirty(characterId)
}
/** Replaces the whole party, bag and story state at once, for a dev jump to a story point. */
fun replaceProgress(
characterId: Long,
party: List<Pokemon>,
items: Map<Int, Int>,
storyFlags: Set<String>,
storyVars: Map<String, Int>,
) {
val stored = characters[characterId] ?: return
characters[characterId] =
stored.copy(
pokemon = party.toMutableList(),
items = items.toMutableMap(),
storyFlags = storyFlags.toMutableSet(),
// A var of 0 is the default, so it is stored as absent everywhere else too.
storyVars = storyVars.filterValues { it != 0 }.toMutableMap(),
)
markDirty(characterId)
}
fun startPeriodicFlush() {
periodicJob =
flushScope.launch {
@@ -1,20 +1,22 @@
-- One character per dev account, each with a Bulbasaur and Rattata party. The species
-- registry only covers Gen 1 to 3, so the party must stay inside that range.
-- Only applied when db.seedDev is enabled, never in production.
-- Ids are fixed low values with the kind tag in the low 16 bits. Runtime ids from
-- EntityIdService carry a timestamp head, so they can never collide with these.
-- Fixed low ids, so they never collide with EntityIdService ids, which carry a timestamp head.
-- Party dex ids must stay in Gen 1 to 3, the only range the species registry covers.
-- The delete cascades, so re-seeding drops whatever these characters caught, carried or unlocked.
DELETE FROM characters WHERE id IN (102400, 364544);
INSERT INTO characters (
id, user_id, name, name_prefix, rival_sex, last_login, created_at, money, permissions,
remaining_safari_steps, remaining_safari_balls, pc_extra_slots, battle_box_extra_slots,
template_amount, position_region_id, position_bank_id, position_map_id, position_x,
position_y, repel_left, repel_item_id, lure_left, lure_item_id
)
-- 264 is the 8 these characters already carried plus CharacterPermissions.DEVELOPER, 0x100.
VALUES
(102400, 1, 'Test', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 30000, 8,
(102400, 1, 'Test', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 30000, 264,
0, 0, 0, 0, 0, 1, 51, 3, 4, 4, 0, 0, 0, 0),
(364544, 2, 'Test2', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 30000, 8,
0, 0, 0, 0, 0, 1, 51, 3, 4, 4, 0, 0, 0, 0)
ON CONFLICT (id) DO NOTHING;
(364544, 2, 'Test2', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 30000, 264,
0, 0, 0, 0, 0, 1, 51, 3, 4, 4, 0, 0, 0, 0);
INSERT INTO pokemon (
id, owner_id, container, container_slot, dex_id, seed, ot, pokemon_level, hp, xp,
@@ -24,5 +26,7 @@ VALUES
(180224, 102400, 'PARTY', 0, 1, 0, 'Test', 5, 19, 135, 33, 35, 45, 40, CURRENT_TIMESTAMP),
(311296, 102400, 'PARTY', 1, 19, 0, 'Test', 3, 14, 27, 33, 35, 39, 30, CURRENT_TIMESTAMP),
(442368, 364544, 'PARTY', 0, 1, 0, 'Test2', 5, 19, 135, 33, 35, 45, 40, CURRENT_TIMESTAMP),
(507904, 364544, 'PARTY', 1, 19, 0, 'Test2', 3, 14, 27, 33, 35, 39, 30, CURRENT_TIMESTAMP)
ON CONFLICT (id) DO NOTHING;
(507904, 364544, 'PARTY', 1, 19, 0, 'Test2', 3, 14, 27, 33, 35, 39, 30, CURRENT_TIMESTAMP);
-- Gives the developer bit to characters made through the client, on the dev accounts only.
UPDATE characters SET permissions = permissions | 256 WHERE user_id IN (1, 2);
@@ -10,7 +10,6 @@ import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket
import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket
import de.fiereu.openmmo.net.game.packets.EntityPresencePacket
import de.fiereu.openmmo.net.game.packets.MapLoadedAckPacket
@@ -113,8 +112,8 @@ private class Fixture(scope: CoroutineScope) {
}
}
private fun FakeSession.startBattle(service: BattleService, command: String = "/testbattle 19 2") {
service.onChatSend(PacketEvent(ChatMessageSendPacket(0, "", command), this))
private fun FakeSession.startBattle(service: BattleService, dexId: Int = 19, level: Int = 2) {
service.startWildBattle(this, dexId, level)
}
private fun FakeSession.act(service: BattleService, action: BattleAction, value: Short = 0) {
@@ -157,7 +156,7 @@ class BattleServiceTest :
val fx = Fixture(backgroundScope)
val (session, charId) = fx.playerWithParty()
session.startBattle(fx.service, "/testbattle 9999 5")
session.startBattle(fx.service, dexId = 9999, level = 5)
fx.registry.byChar(charId).shouldBeNull()
session.sent.none { it is BattleFieldStatePacket }.shouldBeTrue()
@@ -185,7 +184,7 @@ class BattleServiceTest :
val fx = Fixture(backgroundScope)
// A bulky matchup, so neither side can faint inside one turn.
val (session, charId) = fx.playerWithParty(level = 30, hp = 999)
session.startBattle(fx.service, "/testbattle 143 10")
session.startBattle(fx.service, dexId = 143, level = 10)
session.sent.clear()
session.act(fx.service, BattleAction.MOVE, TACKLE)
@@ -0,0 +1,28 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.story.generated.kanto.KantoVars
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private const val KANTO: Byte = 0
class StoryClientStateVarsTest :
FunSpec({
test("a stored var is left out of the sparse list once it is back at zero") {
val set = StoryClientState.variables(KANTO, mapOf(KantoVars.VAR_STARTER_MON to 2))
val cleared = StoryClientState.variables(KANTO, emptyMap())
set.size shouldBe 1
cleared shouldBe emptyList()
}
test("the full list carries every var in the range, cleared ones as zero") {
val full = StoryClientState.allVariables(KANTO, mapOf(KantoVars.VAR_STARTER_MON to 2))
full.size shouldBe 256
full.map { it.key.toInt() and 0xff } shouldBe (0..255).toList()
val starter = StoryClientState.variables(KANTO, mapOf(KantoVars.VAR_STARTER_MON to 2))
full.single { it.key == starter.single().key }.value shouldBe 2
full.filter { it.key != starter.single().key }.all { it.value.toInt() == 0 } shouldBe true
}
})
@@ -0,0 +1,164 @@
package de.fiereu.openmmo.server.game.services.command
import de.fiereu.openmmo.common.CharacterPermissions
import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldContain
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
private class RecordingCommand(
override val permission: Int = 0,
private val fail: Boolean = false,
) : ChatCommand {
override val name = "secret"
override val usage = "/secret"
override val description = "only for developers"
var ran = false
override fun run(ctx: CommandContext) {
ran = true
if (fail) error("boom")
}
}
@OptIn(ExperimentalCoroutinesApi::class)
class ChatCommandServiceTest :
FunSpec({
fun FakeSession.replies() = sent.filterIsInstance<ChatMessagePacket>().map { it.message }
test("ordinary chat is left alone") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand()))
service.tryHandle(session, "hello there") shouldBe false
session.sent shouldBe emptyList()
}
}
test("pos reports the tile the player stands on") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId, regionId = 0, bankId = 4, mapId = 3)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand()))
service.tryHandle(session, "/pos") shouldBe true
session.replies().single() shouldContain "region 0 bank 4 map 3"
}
}
test("a command name is matched without case and around stray spaces") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand()))
service.tryHandle(session, " /PoS ") shouldBe true
session.replies().single() shouldContain "region"
}
}
test("help lists only the commands the caller may run") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val gated = RecordingCommand(CharacterPermissions.DEVELOPER)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand(), gated))
service.tryHandle(session, "/help") shouldBe true
session.replies().any { it.startsWith("/secret") } shouldBe false
session.replies().any { it.startsWith("/pos") } shouldBe true
}
}
test("an unknown command is answered without echoing the rest of the line") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand()))
service.tryHandle(session, "/nonsense hunter2") shouldBe true
val reply = session.replies().single()
reply shouldContain "Unknown command: nonsense"
reply.contains("hunter2") shouldBe false
}
}
test("a gated command needs its permission bit") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val gated = RecordingCommand(CharacterPermissions.DEVELOPER)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand(), gated))
service.tryHandle(session, "/secret") shouldBe true
gated.ran shouldBe false
session.replies().single() shouldContain "Unknown command"
val info = store.getCharacter(charId)!!.info
store.updateCharacter(
info.copy(permissions = info.permissions or CharacterPermissions.DEVELOPER))
session.sent.clear()
service.tryHandle(session, "/secret") shouldBe true
gated.ran shouldBe true
session.sent shouldBe emptyList()
}
}
test("a command that throws answers instead of killing the connection") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val service =
ChatCommandService(store, setOf(RecordingCommand(permission = 0, fail = true)))
service.tryHandle(session, "/secret") shouldBe true
session.replies().single() shouldContain "/secret failed."
}
}
test("a bare slash points at help") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Red", CharacterGender.MALE, Region.KANTO).info.id
val session = FakeSession(characterId = charId)
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand()))
service.tryHandle(session, "/ ") shouldBe true
session.replies().single() shouldContain "/help"
}
}
test("a command from a session with no character is refused") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val session = FakeSession()
val service = ChatCommandService(store, setOf(HelpCommand(), PosCommand()))
service.tryHandle(session, "/pos") shouldBe true
session.replies().single() shouldContain "not in the world"
}
}
})