feat(codegen): generate the decomp trainers and their parties (#115)

This commit is contained in:
Fiereu authored and GitHub committed 2026-08-08 21:06:24 +02:00
1 parent a6ee4bc91d
commit 457f21c17f
14 files changed
+429 -10

No files matched your search

+10
View File
@@ -57,6 +57,16 @@ jteCodegen {
inputDirs.from(sourceDecompDir) inputDirs.from(sourceDecompDir)
extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath)) extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath))
} }
// Trainers differ per game, so this is by region like maps rather than from the canonical decomp.
register("trainer") {
mainClass.set("de.fiereu.openmmo.codegen.trainer.Main")
inputDirs.from(
regionSources.values.map { rootProject.layout.projectDirectory.dir("decomp/$it") })
extraArgs.set(
regionSources.map { (region, decomp) ->
"$region|${rootProject.layout.projectDirectory.dir("decomp/$decomp").asFile.absolutePath}"
})
}
// Per region flag and var key constants for scripts. Names come from each decomp, so this is by // Per region flag and var key constants for scripts. Names come from each decomp, so this is by
// region like maps. The generic story store in server.game does not depend on these, they are the // region like maps. The generic story store in server.game does not depend on these, they are the
// GBA adapter that gives ported scripts readable keys. // GBA adapter that gives ported scripts readable keys.
@@ -0,0 +1,31 @@
@import java.util.List
@import de.fiereu.openmmo.codegen.trainer.ParsedTrainer
@import de.fiereu.openmmo.codegen.trainer.RenderUtil
@param String pkg
@param String objectName
@param String region
@param List<List<ParsedTrainer>> chunks
package ${pkg}
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.trainer.TrainerDef
import de.fiereu.openmmo.trainer.TrainerMon
import de.fiereu.openmmo.trainer.TrainerRegistry
internal object ${objectName} {
fun loadInto(reg: TrainerRegistry) {
@for(int i = 0; i < chunks.size(); i++)
registerChunk${i}(reg)
@endfor
}
@for(int c = 0; c < chunks.size(); c++)
private fun registerChunk${c}(reg: TrainerRegistry) {
@for(ParsedTrainer t : chunks.get(c))
${RenderUtil.INSTANCE.trainer(region, t)}
@endfor
}
@endfor
}
@@ -2,12 +2,18 @@ package de.fiereu.openmmo.codegen
import java.io.File import java.io.File
/** Reads a `#define <prefix><name> <number>` block, keyed by the full constant name. */ /**
* Reads a `#define <prefix><name> <number>` block, keyed by the full constant name. Emerald writes
* its trainer classes in hex, FireRed in decimal.
*/
fun defineTable(file: File, prefix: String): Map<String, Int> { fun defineTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap() if (!file.exists()) return emptyMap()
val regex = Regex("""^#define\s+($prefix\w+)\s+(\d+)\s*$""") val regex = Regex("""^#define\s+($prefix\w+)\s+(0[xX][0-9a-fA-F]+|\d+)\s*(?://.*)?$""")
return file return file
.readLines() .readLines()
.mapNotNull { regex.find(it.trim()) } .mapNotNull { regex.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() } .associate { it.groupValues[1] to parseNumber(it.groupValues[2]) }
} }
private fun parseNumber(text: String): Int =
if (text.startsWith("0x", ignoreCase = true)) text.substring(2).toInt(16) else text.toInt()
@@ -0,0 +1,22 @@
@file:JvmName("Main")
package de.fiereu.openmmo.codegen.trainer
import java.io.File
fun main(args: Array<String>) {
require(args.size >= 4) {
"Usage: <output-dir> <templates-dir> <class-cache-dir> <region|decomp>... got ${args.toList()}"
}
val outputDir = File(args[0])
val templatesDir = File(args[1])
val classCacheDir = File(args[2])
for (spec in args.drop(3)) {
val (region, decomp) = spec.split("|")
val trainers = TrainerParser(File(decomp)).parseAll()
println("[trainer] $region: parsed ${trainers.size} trainers from $decomp")
TrainerRenderer(region, templatesDir, outputDir, classCacheDir).render(trainers)
}
println("[trainer] done")
}
@@ -0,0 +1,18 @@
package de.fiereu.openmmo.codegen.trainer
/** A monster on a trainer's team. Empty [moveIds] means the level up moveset is used. */
data class ParsedTrainerMon(
val dexId: Int,
val level: Int,
val iv: Int,
val heldItem: Int,
val moveIds: List<Int>,
)
data class ParsedTrainer(
val id: Int,
val name: String,
val trainerClass: Int,
val doubleBattle: Boolean,
val party: List<ParsedTrainerMon>,
)
@@ -0,0 +1,17 @@
package de.fiereu.openmmo.codegen.trainer
object RenderUtil {
fun trainer(region: String, t: ParsedTrainer): String {
val party = t.party.joinToString(", ", "listOf(", ")") { mon(it) }
return "reg.register(Region.${region.uppercase()}, TrainerDef(${t.id}, \"${escape(t.name)}\", " +
"${t.trainerClass}, ${t.doubleBattle}, $party))"
}
private fun mon(m: ParsedTrainerMon): String {
val moves = m.moveIds.joinToString(", ", "listOf(", ")")
return "TrainerMon(${m.dexId}, ${m.level}, ${m.iv}, ${m.heldItem}, $moves)"
}
private fun escape(name: String) = name.replace("\\", "\\\\").replace("\"", "\\\"")
}
@@ -0,0 +1,137 @@
package de.fiereu.openmmo.codegen.trainer
import de.fiereu.openmmo.codegen.defineTable
import de.fiereu.openmmo.codegen.pokemon.NationalDex
import de.fiereu.openmmo.codegen.pokemon.SpeciesParser
import de.fiereu.openmmo.common.enums.MAX_IV
import java.io.File
class TrainerParser(private val rootDir: File) {
private val trainerIds = defines("include/constants/opponents.h", "TRAINER_")
private val classIds = defines("include/constants/trainers.h", "TRAINER_CLASS_")
private val speciesIds = defines("include/constants/species.h", "SPECIES_")
private val moveIds = defines("include/constants/moves.h", "MOVE_")
private val itemIds = defines("include/constants/items.h", "ITEM_")
private val nationalDex = NationalDex.read(rootDir)
private val knownDexIds = SpeciesParser(rootDir).parseAll().mapTo(HashSet()) { it.id }
fun parseAll(): List<ParsedTrainer> {
val parties = readParties()
return readTrainers()
.mapNotNull { entry ->
val id = trainerIds[entry.constant]
if (id == null) {
println("[trainer] skipped ${entry.constant}, it has no id in opponents.h")
return@mapNotNull null
}
val party = parties[entry.partySymbol]?.mapNotNull(::toMon).orEmpty()
// A trainer whose party stopped parsing would otherwise vanish without a trace.
if (party.isEmpty()) {
println(
"[trainer] skipped ${entry.constant}, ${entry.partySymbol} has no usable members")
return@mapNotNull null
}
ParsedTrainer(
id = id,
name = entry.name,
trainerClass = classIds[entry.trainerClass] ?: 0,
doubleBattle = entry.doubleBattle,
party = party,
)
}
.sortedBy { it.id }
}
private fun toMon(fields: Map<String, String>): ParsedTrainerMon? {
val dexId = speciesIds[fields["species"]]?.let { nationalDex[it] } ?: return null
if (dexId !in knownDexIds) return null
val level = fields["lvl"]?.toIntOrNull() ?: return null
val moves =
fields["moves"]
?.let { MOVE.findAll(it).mapNotNull { m -> moveIds[m.value] }.toList() }
?.filter { it != 0 }
.orEmpty()
// The decomp stores a 0 to 255 difficulty here and scales it to a real IV when it builds the
// party, so scale it once here rather than leaving a 255 that looks like an IV but is not.
val difficulty = fields["iv"]?.toIntOrNull() ?: 0
return ParsedTrainerMon(
dexId = dexId,
level = level,
iv = difficulty * MAX_IV / 255,
heldItem = itemIds[fields["heldItem"]] ?: 0,
moveIds = moves,
)
}
private data class TrainerEntry(
val constant: String,
val name: String,
val trainerClass: String,
val doubleBattle: Boolean,
val partySymbol: String,
)
// [TRAINER_X] = { .trainerClass = ..., .trainerName = _("NAME"), .party = MACRO(sParty_X), }
private fun readTrainers(): List<TrainerEntry> =
ENTRY.findAll(read("src/data/trainers.h"))
.mapNotNull { match ->
val body = match.groupValues[2]
val party = PARTY.find(body)?.groupValues?.get(1) ?: return@mapNotNull null
TrainerEntry(
constant = match.groupValues[1],
name = NAME.find(body)?.groupValues?.get(1).orEmpty(),
trainerClass = CLASS.find(body)?.groupValues?.get(1).orEmpty(),
doubleBattle = body.contains(".doubleBattle = TRUE"),
partySymbol = party,
)
}
.toList()
/**
* The party arrays keyed by symbol. The RS placeholder teams are written as bare macro names, so
* the macro bodies are read first and pasted in before the members are split out.
*/
private fun readParties(): Map<String, List<Map<String, String>>> {
val text = read("src/data/trainer_parties.h")
val macros =
MACRO.findAll(text).associate { it.groupValues[1] to it.groupValues[2].replace("\\", " ") }
return ARRAY.findAll(text).associate { match ->
val body =
macros.entries.fold(match.groupValues[2]) { acc, (name, b) -> acc.replace(name, b) }
match.groupValues[1] to MEMBER.findAll(body).map { fields(it.groupValues[1]) }.toList()
}
}
private fun fields(body: String): Map<String, String> =
FIELD.findAll(body).associate { it.groupValues[1] to it.groupValues[2].trim() }
private fun defines(path: String, prefix: String): Map<String, Int> =
defineTable(File(rootDir, path), prefix)
private fun read(path: String): String {
val file = File(rootDir, path)
require(file.exists()) {
"Decomp not initialized at $rootDir (missing ${file.path}). " +
"Run: git submodule update --init --recursive"
}
return file.readText()
}
private companion object {
val ENTRY = Regex("""\[(TRAINER_\w+)]\s*=\s*\{(.*?)\n\s*},""", RegexOption.DOT_MATCHES_ALL)
val NAME = Regex("""\.trainerName\s*=\s*_\("([^"]*)"\)""")
val CLASS = Regex("""\.trainerClass\s*=\s*(TRAINER_CLASS_\w+)""")
val PARTY = Regex("""\.party\s*=\s*\w+\(\s*(\w+)\s*\)""")
val MACRO = Regex("""#define\s+(DUMMY_\w+)\s+((?:.*\\\r?\n)*.*)""")
val ARRAY =
Regex(
"""static\s+const\s+struct\s+TrainerMon\w+\s+(\w+)\s*\[\s*]\s*=\s*\{(.*?)};""",
RegexOption.DOT_MATCHES_ALL,
)
// One member, allowing the single nested brace list that .moves brings.
val MEMBER = Regex("""\{((?:[^{}]|\{[^{}]*})*)}""", RegexOption.DOT_MATCHES_ALL)
val FIELD = Regex("""\.(\w+)\s*=\s*(\{[^}]*}|[^,}]+)""")
val MOVE = Regex("""MOVE_\w+""")
}
}
@@ -0,0 +1,47 @@
package de.fiereu.openmmo.codegen.trainer
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.FileOutput
import gg.jte.resolve.DirectoryCodeResolver
import java.io.File
/** Emits one object of trainer registrations per region, namespaced the same way story keys are. */
class TrainerRenderer(
private val region: String,
private val templatesDir: File,
private val outputDir: File,
private val classCacheDir: File,
private val chunkSize: Int = 25,
) {
fun render(trainers: List<ParsedTrainer>) {
classCacheDir.mkdirs()
val engine =
TemplateEngine.create(
DirectoryCodeResolver(templatesDir.toPath()),
classCacheDir.toPath(),
ContentType.Plain,
)
val objectName = "Generated${region.replaceFirstChar { it.uppercase() }}Trainers"
val file = File(outputDir, "${BASE_PACKAGE.replace('.', '/')}/$objectName.kt")
file.parentFile.mkdirs()
FileOutput(file.toPath()).use { out ->
engine.render(
"TrainerRegistry.jte",
mapOf(
"pkg" to BASE_PACKAGE,
"objectName" to objectName,
"region" to region,
"chunks" to trainers.chunked(chunkSize),
),
out,
)
}
}
companion object {
private const val BASE_PACKAGE = "de.fiereu.openmmo.trainer.generated"
}
}
@@ -0,0 +1,55 @@
package de.fiereu.openmmo.trainer
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.trainer.generated.GeneratedHoennTrainers
import de.fiereu.openmmo.trainer.generated.GeneratedKantoTrainers
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
/** A monster on a trainer's team. Empty [moveIds] means the level up moveset is used. */
data class TrainerMon(
val dexId: Int,
val level: Int,
val iv: Int,
val heldItem: Int,
val moveIds: List<Int>,
)
data class TrainerDef(
val id: Int,
val name: String,
val trainerClass: Int,
val doubleBattle: Boolean,
val party: List<TrainerMon>,
)
private data class TrainerKey(val region: Region, val id: Int)
/**
* The trainers from the decomp, keyed by region and trainer id. The two regions number their
* trainers from zero, so the region is part of the key.
*/
@Singleton
class TrainerRegistry @Inject constructor() {
private val trainers = ConcurrentHashMap<TrainerKey, TrainerDef>()
init {
GeneratedHoennTrainers.loadInto(this)
GeneratedKantoTrainers.loadInto(this)
}
fun register(region: Region, def: TrainerDef) {
val previous = trainers.put(TrainerKey(region, def.id), def)
// Generated data, so a clash means the parser produced two trainers for one id and the second
// would quietly replace the first.
check(previous == null) {
"Two $region trainers share id ${def.id}: ${previous?.name}, ${def.name}"
}
}
fun get(region: Region, id: Int): TrainerDef? = trainers[TrainerKey(region, id)]
fun size(): Int = trainers.size
}
@@ -0,0 +1,71 @@
package de.fiereu.openmmo.trainer
import de.fiereu.openmmo.common.MAX_MOVE_SLOTS
import de.fiereu.openmmo.common.MAX_PARTY_SIZE
import de.fiereu.openmmo.common.enums.MAX_IV
import de.fiereu.openmmo.common.enums.Region
import io.kotest.assertions.withClue
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.ints.shouldBeLessThanOrEqual
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
private const val BROCK = 414
private const val GEODUDE = 74
private const val ONIX = 95
private const val TACKLE = 33
private const val DEFENSE_CURL = 111
private const val BIND = 20
private const val ROCK_TOMB = 317
// Every [TRAINER_*] the two decomps declare, less TRAINER_NONE in each, which has no party.
private const val HOENN_TRAINERS = 854
private const val KANTO_TRAINERS = 742
class TrainerRegistryTest :
FunSpec({
val trainers = TrainerRegistry()
test("every decomp trainer with a party is registered") {
// An exact count, so a decomp update that breaks the party parser cannot pass unnoticed.
trainers.size() shouldBe HOENN_TRAINERS + KANTO_TRAINERS
trainers.get(Region.KANTO, BROCK).shouldNotBeNull()
trainers.get(Region.HOENN, 1).shouldNotBeNull()
}
test("a gym leader keeps its decomp party") {
val brock = trainers.get(Region.KANTO, BROCK).shouldNotBeNull()
brock.name shouldBe "BROCK"
brock.doubleBattle shouldBe false
brock.party shouldBe
listOf(
TrainerMon(GEODUDE, 12, 0, 0, listOf(TACKLE, DEFENSE_CURL)),
TrainerMon(ONIX, 14, 0, 0, listOf(TACKLE, BIND, ROCK_TOMB)),
)
}
test("the same id in the other region is a different trainer") {
trainers.get(Region.HOENN, BROCK) shouldNotBe trainers.get(Region.KANTO, BROCK)
}
test("every trainer has a usable party") {
for (region in Region.entries) {
for (id in 0..1000) {
val def = trainers.get(region, id) ?: continue
withClue("$region/$id") {
def.party.size shouldBeGreaterThan 0
def.party.size shouldBeLessThanOrEqual MAX_PARTY_SIZE
def.party.forEach {
it.level shouldBeGreaterThan 0
it.dexId shouldBeGreaterThan 0
it.moveIds.size shouldBeLessThanOrEqual MAX_MOVE_SLOTS
// The decomp field is a 0 to 255 difficulty, scaled to an IV when parsed.
it.iv shouldBeLessThanOrEqual MAX_IV
}
}
}
}
}
})
@@ -8,6 +8,8 @@ import java.time.LocalDateTime
const val MAX_MOVE_SLOTS = 4 const val MAX_MOVE_SLOTS = 4
const val MAX_PARTY_SIZE = 6
data class Pokemon( data class Pokemon(
val id: Long, val id: Long,
val ownerId: Long, val ownerId: Long,
@@ -52,7 +52,9 @@ open class PokemonStats(private val individualCap: Int, private val totalCap: In
class EVs : PokemonStats(252, 510) class EVs : PokemonStats(252, 510)
class IVs : PokemonStats(31, 186) const val MAX_IV = 31
class IVs : PokemonStats(MAX_IV, 186)
fun IVs.compress(): Int = fun IVs.compress(): Int =
(((hp and 31) shl 0) or (((hp and 31) shl 0) or
@@ -171,7 +171,7 @@ data class BattleBulkStatePacket(
val phase: Byte, val phase: Byte,
val firstGroup: List<BattleSerializedEntry>, val firstGroup: List<BattleSerializedEntry>,
val secondGroup: List<BattleSerializedEntry>, val secondGroup: List<BattleSerializedEntry>,
val valueA: Int, val prizeMoney: Int,
val valueB: Int, val valueB: Int,
val flag: Byte, val flag: Byte,
val thirdGroup: List<BattleSerializedEntry>, val thirdGroup: List<BattleSerializedEntry>,
@@ -185,7 +185,7 @@ data class BattleBulkStatePacket(
phase = 0, phase = 0,
firstGroup = listOf(NullSerializedEntry), firstGroup = listOf(NullSerializedEntry),
secondGroup = listOf(NullSerializedEntry), secondGroup = listOf(NullSerializedEntry),
valueA = 0, prizeMoney = 0,
valueB = 0, valueB = 0,
flag = 2, flag = 2,
thirdGroup = emptyList(), thirdGroup = emptyList(),
@@ -197,7 +197,7 @@ data class BattleBulkStatePacket(
phase = -1, phase = -1,
firstGroup = emptyList(), firstGroup = emptyList(),
secondGroup = emptyList(), secondGroup = emptyList(),
valueA = 0, prizeMoney = 0,
valueB = 0, valueB = 0,
flag = 2, flag = 2,
thirdGroup = emptyList(), thirdGroup = emptyList(),
@@ -210,10 +210,11 @@ object BattleBulkStatePacketCodec : PacketCodec<BattleBulkStatePacket>() {
val phase = field(S8) { it.phase } val phase = field(S8) { it.phase }
val firstGroup = field(BattleSerializedEntryCodec.listPrefixed(U8)) { it.firstGroup } val firstGroup = field(BattleSerializedEntryCodec.listPrefixed(U8)) { it.firstGroup }
val secondGroup = field(BattleSerializedEntryCodec.listPrefixed(U8)) { it.secondGroup } val secondGroup = field(BattleSerializedEntryCodec.listPrefixed(U8)) { it.secondGroup }
val valueA = field(S32LE) { it.valueA } val prizeMoney = field(S32LE) { it.prizeMoney }
val valueB = field(S32LE) { it.valueB } val valueB = field(S32LE) { it.valueB }
val flag = field(S8) { it.flag } val flag = field(S8) { it.flag }
val thirdGroup = field(BattleSerializedEntryCodec.listPrefixed(U8)) { it.thirdGroup } val thirdGroup = field(BattleSerializedEntryCodec.listPrefixed(U8)) { it.thirdGroup }
return BattleBulkStatePacket(phase, firstGroup, secondGroup, valueA, valueB, flag, thirdGroup) return BattleBulkStatePacket(
phase, firstGroup, secondGroup, prizeMoney, valueB, flag, thirdGroup)
} }
} }
@@ -1,6 +1,7 @@
package de.fiereu.openmmo.server.game.services package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.MAX_PARTY_SIZE
import de.fiereu.openmmo.common.Pokemon import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
@@ -103,7 +104,6 @@ constructor(
} + List((MAX_MOVES - moveIds.size).coerceAtLeast(0)) { PokemonMove(0, 0) } } + List((MAX_MOVES - moveIds.size).coerceAtLeast(0)) { PokemonMove(0, 0) }
private companion object { private companion object {
const val MAX_PARTY_SIZE = 6
const val MAX_MOVES = 4 const val MAX_MOVES = 4
} }
} }