feat(game): give monsters their real level up moveset (#85)

* feat(codegen): generate the level up learnsets from the decomp

* feat(game): give monsters their real level up moveset
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-05 10:38:55 +02:00
1 parent e24bc5518d
commit 1ecfabaed5
22 files changed
+485 -39

No files matched your search

+5
View File
@@ -52,6 +52,11 @@ jteCodegen {
inputDirs.from(sourceDecompDir)
extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath))
}
register("learnset") {
mainClass.set("de.fiereu.openmmo.codegen.learnset.Main")
inputDirs.from(sourceDecompDir)
extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath))
}
// 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
// GBA adapter that gives ported scripts readable keys.
@@ -0,0 +1,26 @@
@import java.util.List
@import de.fiereu.openmmo.codegen.learnset.ParsedLearnset
@import de.fiereu.openmmo.codegen.learnset.RenderUtil
@param List<List<ParsedLearnset>> chunks
package de.fiereu.openmmo.pokemon.generated
import de.fiereu.openmmo.pokemon.LearnsetRegistry
import de.fiereu.openmmo.pokemon.LevelUpMove
internal object GeneratedLearnsets {
fun loadInto(reg: LearnsetRegistry) {
@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: LearnsetRegistry) {
@for(ParsedLearnset l : chunks.get(c))
${RenderUtil.INSTANCE.learnset(l)}
@endfor
}
@endfor
}
@@ -0,0 +1,13 @@
package de.fiereu.openmmo.codegen
import java.io.File
/** Reads a `#define <prefix><name> <number>` block, keyed by the full constant name. */
fun defineTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap()
val regex = Regex("""^#define\s+($prefix\w+)\s+(\d+)\s*$""")
return file
.readLines()
.mapNotNull { regex.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
}
@@ -0,0 +1,67 @@
package de.fiereu.openmmo.codegen.learnset
import de.fiereu.openmmo.codegen.defineTable
import de.fiereu.openmmo.codegen.pokemon.NationalDex
import de.fiereu.openmmo.codegen.pokemon.SpeciesParser
import java.io.File
class LearnsetParser(private val rootDir: File) {
fun parseAll(): List<ParsedLearnset> {
val speciesIds = readDefineTable("include/constants/species.h", "SPECIES_")
val nationalDex = NationalDex.read(rootDir)
val moveIds = readDefineTable("include/constants/moves.h", "MOVE_")
val tables = readTables()
// The decomp keeps learnset pointers for placeholder species with no stats, drop those.
val known = SpeciesParser(rootDir).parseAll().mapTo(HashSet()) { it.id }
return readPointers()
.mapNotNull { (constant, symbol) ->
// Same as the species data, the client keys by national dex.
val dexId = speciesIds[constant]?.let { nationalDex[it] } ?: return@mapNotNull null
if (dexId !in known) return@mapNotNull null
val entries = tables[symbol] ?: return@mapNotNull null
val moves =
entries.mapNotNull { (level, move) ->
moveIds[move]?.let { ParsedLevelUpMove(level, it) }
}
if (moves.isEmpty()) null else ParsedLearnset(dexId, moves)
}
.sortedBy { it.dexId }
}
// static const u16 s<Name>LevelUpLearnset[] = { LEVEL_UP_MOVE(lvl, MOVE_X), ... };
private fun readTables(): Map<String, List<Pair<Int, String>>> {
val file = File(rootDir, "src/data/pokemon/level_up_learnsets.h")
require(file.exists()) {
"Decomp not initialized at $rootDir (missing ${file.path}). " +
"Run: git submodule update --init --recursive"
}
val table =
Regex(
"""static\s+const\s+u16\s+(\w+)\s*\[\s*]\s*=\s*\{(.*?)}""",
RegexOption.DOT_MATCHES_ALL,
)
val move = Regex("""LEVEL_UP_MOVE\(\s*(\d+)\s*,\s*(MOVE_\w+)\s*\)""")
return table.findAll(file.readText()).associate { match ->
match.groupValues[1] to
move
.findAll(match.groupValues[2])
.map { it.groupValues[1].toInt() to it.groupValues[2] }
.toList()
}
}
private fun readPointers(): Map<String, String> {
val file = File(rootDir, "src/data/pokemon/level_up_learnset_pointers.h")
require(file.exists()) { "Missing learnset pointer table at ${file.path}" }
val regex = Regex("""\[(SPECIES_\w+)]\s*=\s*(\w+)""")
return regex.findAll(file.readText()).associate { it.groupValues[1] to it.groupValues[2] }
}
private fun readDefineTable(path: String, prefix: String): Map<String, Int> {
val file = File(rootDir, path)
require(file.exists()) { "Missing $prefix table at ${file.path}" }
return defineTable(file, prefix)
}
}
@@ -0,0 +1,39 @@
package de.fiereu.openmmo.codegen.learnset
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.FileOutput
import gg.jte.resolve.DirectoryCodeResolver
import java.io.File
class LearnsetRenderer(
private val templatesDir: File,
private val outputDir: File,
private val classCacheDir: File,
private val registryChunkSize: Int = 50,
) {
fun render(learnsets: List<ParsedLearnset>) {
classCacheDir.mkdirs()
val engine =
TemplateEngine.create(
DirectoryCodeResolver(templatesDir.toPath()),
classCacheDir.toPath(),
ContentType.Plain,
)
val packageRoot = File(outputDir, BASE_PACKAGE.replace('.', '/'))
if (packageRoot.exists()) packageRoot.deleteRecursively()
val chunks = learnsets.sortedBy { it.dexId }.chunked(registryChunkSize)
val registry = File(outputDir, "${BASE_PACKAGE.replace('.', '/')}/GeneratedLearnsets.kt")
registry.parentFile.mkdirs()
FileOutput(registry.toPath()).use { out ->
engine.render("LearnsetRegistry.jte", mapOf("chunks" to chunks), out)
}
}
companion object {
private const val BASE_PACKAGE = "de.fiereu.openmmo.pokemon.generated"
}
}
@@ -0,0 +1,21 @@
@file:JvmName("Main")
package de.fiereu.openmmo.codegen.learnset
import java.io.File
fun main(args: Array<String>) {
require(args.size >= 4) {
"Usage: <output-dir> <templates-dir> <class-cache-dir> <decomp-dir> got ${args.toList()}"
}
val outputDir = File(args[0])
val templatesDir = File(args[1])
val classCacheDir = File(args[2])
val decompDir = File(args[3])
println("[learnset] parsing from $decompDir")
val learnsets = LearnsetParser(decompDir).parseAll()
println("[learnset] parsed ${learnsets.size} learnsets. writing to $outputDir")
LearnsetRenderer(templatesDir, outputDir, classCacheDir).render(learnsets)
println("[learnset] done")
}
@@ -0,0 +1,5 @@
package de.fiereu.openmmo.codegen.learnset
data class ParsedLearnset(val dexId: Int, val moves: List<ParsedLevelUpMove>)
data class ParsedLevelUpMove(val level: Int, val moveId: Int)
@@ -0,0 +1,9 @@
package de.fiereu.openmmo.codegen.learnset
object RenderUtil {
fun learnset(l: ParsedLearnset): String {
val moves = l.moves.joinToString(", ") { "LevelUpMove(${it.level}, ${it.moveId})" }
return "reg.register(${l.dexId}, listOf($moves))"
}
}
@@ -1,5 +1,6 @@
package de.fiereu.openmmo.codegen.move
import de.fiereu.openmmo.codegen.defineTable
import java.io.File
class MoveParser(private val rootDir: File) {
@@ -35,11 +36,7 @@ class MoveParser(private val rootDir: File) {
"Decomp not initialized at $rootDir (missing ${file.path}). " +
"Run: git submodule update --init --recursive"
}
val regex = Regex("""^#define\s+(MOVE_\w+)\s+(\d+)\s*$""")
return file
.readLines()
.mapNotNull { regex.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
return defineTable(file, "MOVE_")
}
private fun readMoveNames(): Map<String, String> {
@@ -1,5 +1,6 @@
package de.fiereu.openmmo.codegen.pokemon
import de.fiereu.openmmo.codegen.defineTable
import java.io.File
/**
@@ -10,23 +11,16 @@ import java.io.File
object NationalDex {
fun read(rootDir: File): Map<Int, Int> {
val internalBySuffix = defineTable(File(rootDir, "include/constants/species.h"), "SPECIES_")
val internalBySuffix =
defineTable(File(rootDir, "include/constants/species.h"), "SPECIES_").mapKeys {
it.key.removePrefix("SPECIES_")
}
val nationalBySuffix = enumTable(File(rootDir, "include/constants/pokedex.h"), "NATIONAL_DEX_")
return internalBySuffix
.mapNotNull { (suffix, internal) -> nationalBySuffix[suffix]?.let { internal to it } }
.toMap()
}
// #define SPECIES_<suffix> <n>
private fun defineTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap()
val re = Regex("""^#define\s+$prefix(\w+)\s+(\d+)\s*$""")
return file
.readLines()
.mapNotNull { re.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
}
// A plain enum where each NATIONAL_DEX_<suffix> takes the next value, starting at NONE = 0.
private fun enumTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap()
@@ -1,5 +1,6 @@
package de.fiereu.openmmo.codegen.pokemon
import de.fiereu.openmmo.codegen.defineTable
import java.io.File
class SpeciesParser(private val rootDir: File) {
@@ -86,11 +87,7 @@ class SpeciesParser(private val rootDir: File) {
private fun readDefineTable(path: String, prefix: String): Map<String, Int> {
val file = File(rootDir, path)
require(file.exists()) { "Missing $prefix table at ${file.path}" }
val regex = Regex("""^#define\s+($prefix\w+)\s+(\d+)\s*$""")
return file
.readLines()
.mapNotNull { regex.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
return defineTable(file, prefix)
}
private fun braceList(value: String): List<String> =
@@ -0,0 +1,46 @@
package de.fiereu.openmmo.pokemon
import de.fiereu.openmmo.common.MAX_MOVE_SLOTS
import de.fiereu.openmmo.pokemon.generated.GeneratedLearnsets
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
data class LevelUpMove(val level: Int, val moveId: Int)
/** The level up learnsets from the decomp, keyed by national dex id and sorted by level. */
@Singleton
class LearnsetRegistry @Inject constructor() {
private val learnsets = ConcurrentHashMap<Int, List<LevelUpMove>>()
init {
GeneratedLearnsets.loadInto(this)
}
fun register(dexId: Int, moves: List<LevelUpMove>) {
learnsets[dexId] = moves
}
fun get(dexId: Int): List<LevelUpMove> = learnsets[dexId] ?: emptyList()
fun movesAt(dexId: Int, level: Int): List<Int> =
get(dexId).filter { it.level == level }.map { it.moveId }
/**
* The moveset a monster generated at this level starts with. Like the games, the learnset is
* walked in order and a fifth move pushes out the oldest one.
*/
fun initialMoveset(dexId: Int, level: Int): List<Int> {
val slots = ArrayList<Int>(MAX_MOVE_SLOTS)
for (entry in get(dexId)) {
if (entry.level > level) break
if (entry.moveId in slots) continue
if (slots.size == MAX_MOVE_SLOTS) slots.removeAt(0)
slots += entry.moveId
}
return slots
}
fun size(): Int = learnsets.size
}
@@ -0,0 +1,79 @@
package de.fiereu.openmmo.pokemon
import de.fiereu.openmmo.common.MAX_MOVE_SLOTS
import de.fiereu.openmmo.moves.MoveRegistry
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.shouldBe
private const val TACKLE = 33
private const val GROWL = 45
private const val LEECH_SEED = 73
private const val VINE_WHIP = 22
private const val POISON_POWDER = 77
private const val SLEEP_POWDER = 79
private const val SWEET_SCENT = 230
private const val GROWTH = 74
private const val SYNTHESIS = 235
private const val SOLAR_BEAM = 76
class LearnsetRegistryTest :
FunSpec({
val learnsets = LearnsetRegistry()
test("every species with stats has a learnset") {
learnsets.size() shouldBe SpeciesRegistry().size()
}
test("a learnset is sorted by level") {
for (dexId in 1..learnsets.size()) {
val levels = learnsets.get(dexId).map { it.level }
levels shouldBe levels.sorted()
}
}
test("Bulbasaur learns the moves it does in the games") {
learnsets.get(1).take(4) shouldBe
listOf(
LevelUpMove(1, TACKLE),
LevelUpMove(4, GROWL),
LevelUpMove(7, LEECH_SEED),
LevelUpMove(10, VINE_WHIP),
)
}
test("two moves can share a level") {
learnsets.movesAt(1, 15) shouldBe listOf(POISON_POWDER, SLEEP_POWDER)
}
test("a level with no move learns nothing") { learnsets.movesAt(1, 2).shouldBeEmpty() }
test("the initial moveset stops at the given level") {
learnsets.initialMoveset(1, 1) shouldBe listOf(TACKLE)
learnsets.initialMoveset(1, 10) shouldBe listOf(TACKLE, GROWL, LEECH_SEED, VINE_WHIP)
}
test("a fifth move pushes out the oldest one") {
learnsets.initialMoveset(1, 100) shouldBe listOf(SWEET_SCENT, GROWTH, SYNTHESIS, SOLAR_BEAM)
}
test("no moveset is longer than four moves") {
for (dexId in 1..learnsets.size()) {
learnsets.initialMoveset(dexId, 100).size shouldBe
minOf(MAX_MOVE_SLOTS, learnsets.get(dexId).map { it.moveId }.distinct().size)
}
}
test("an unknown species has no learnset") {
learnsets.get(9999).shouldBeEmpty()
learnsets.initialMoveset(9999, 50).shouldBeEmpty()
}
test("every learned move is in the move registry") {
val moves = MoveRegistry()
val learned = (1..learnsets.size()).flatMap { learnsets.get(it) }
learned.size shouldBeGreaterThan 0
learned.filter { moves.get(it.moveId) == null }.shouldBeEmpty()
}
})