feat(game): basic script implementations (#65)

* feat(game): open the wired dialog line when a player interacts with an npc or sign

* feat(game): run npc and sign interactions through a generated script layer

* chore(style): spotlessApply

* fix(codegen): generate dialog enums without a rom so ci can compile

* docs: add a guide for writing overworld scripts

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Fiereuandgithub-actions[bot] authored and GitHub committed 2026-07-26 00:12:30 +02:00
1 parent 6695daabd8
commit 300bc52531
691 files changed
+56022 -44

No files matched your search

+18
View File
@@ -71,3 +71,21 @@ jteCodegen {
))
}
}
// One shot bootstrap of the overworld script stubs into server.game. Run by hand with
// `gradlew :codegen:generateScriptStubs`. Deliberately not wired into the build, the emitted files
// are committed source so hand written ports are never overwritten on a normal build.
tasks.register<JavaExec>("generateScriptStubs") {
group = "codegen"
description = "Bootstrap overworld script stubs into server.game (manual, not part of the build)"
val fireredDir = rootProject.layout.projectDirectory.dir("decomp/pokefirered")
val serverGameSrc = rootProject.layout.projectDirectory.dir("server.game/src/main/kotlin")
classpath = sourceSets["generator"].runtimeClasspath
mainClass.set("de.fiereu.openmmo.codegen.script.Main")
args(
serverGameSrc.asFile.absolutePath,
romsDir.asFile.absolutePath,
"hoenn|BPEE|${sourceDecompDir.asFile.absolutePath}",
"kanto|BPRE|${fireredDir.asFile.absolutePath}",
)
}
@@ -7,11 +7,13 @@
@param List<DialogEntry> entries
package ${pkg}
import de.fiereu.openmmo.common.dialog.DialogLine
/**
* Overworld dialog lines for this location, generated from the decomp text. Each [textId] is
* 0x10000000 or the string's retail ROM offset, ready to send in a DialogAction packet.
*/
enum class ${enumName}(val textId: Int) {
enum class ${enumName}(override val textId: Int) : DialogLine {
@for(DialogEntry e : entries)
${RenderUtil.INSTANCE.entry(e)}
@endfor
@@ -33,15 +33,21 @@ private fun generateRegion(
) {
val renderer = DialogRenderer(region, templatesDir, outputDir, classCacheDir)
val rom = RomIndex.find(romsDir, gameCode)
val texts = TextParser(decompDir).parseAll()
println("[dialog] $region: parsed ${texts.size} text labels from $decompDir")
// Without a ROM we cannot resolve textIds, but the enums must still exist so code that
// references them compiles (for example in CI, where ROMs are never present). Emit every
// label with a placeholder textId so the build works, just without real dialog ids.
if (rom == null) {
println("[dialog] no $gameCode ROM found in $romsDir, generating empty $region")
renderer.render(emptyList())
println(
"[dialog] no $gameCode ROM found in $romsDir, generating $region labels without textIds")
renderer.render(texts.map { DialogLine(it.label, 0, RenderUtil.preview(it.content)) })
return
}
val charmap = Charmap.load(File(decompDir, "charmap.txt"))
val texts = TextParser(decompDir).parseAll()
println("[dialog] $region: parsed ${texts.size} text labels from $decompDir")
var unencodable = 0
var notFound = 0
@@ -0,0 +1,38 @@
package de.fiereu.openmmo.codegen.script
import de.fiereu.openmmo.codegen.dialog.Charmap
import de.fiereu.openmmo.codegen.dialog.RenderUtil
import de.fiereu.openmmo.codegen.dialog.RomIndex
import de.fiereu.openmmo.codegen.dialog.TextParser
import java.io.File
/**
* Maps a decomp text label to the generated dialog enum entry it became, mirroring the dialog
* generator so a script can reference the same entry. Only labels that resolved to a real ROM
* offset are present, and only the first label to claim an entry name in a location, since the
* dialog enum keeps one entry per name.
*/
object DialogRefIndex {
fun build(decompDir: File, romsDir: File, gameCode: String): Map<String, DialogRef> {
val rom = RomIndex.find(romsDir, gameCode) ?: return emptyMap()
val charmap = Charmap.load(File(decompDir, "charmap.txt"))
val resolved =
TextParser(decompDir).parseAll().mapNotNull { text ->
val bytes = charmap.encode(text.content) ?: return@mapNotNull null
if (rom.offsetOf(bytes) < 0) null else text.label
}
val refs = HashMap<String, DialogRef>()
resolved
.groupBy { RenderUtil.location(it) }
.forEach { (location, labels) ->
val className = RenderUtil.className(location).trim('`')
val takenNames = HashSet<String>()
for (label in labels) {
val entry = RenderUtil.entryName(label)
if (takenNames.add(entry)) refs[label] = DialogRef(className, entry)
}
}
return refs
}
}
@@ -0,0 +1,58 @@
@file:JvmName("Main")
package de.fiereu.openmmo.codegen.script
import java.io.File
/**
* One shot bootstrap of the overworld script stubs. Run by hand, the output is committed source and
* is never regenerated on build, so hand written ports are safe. Args are the server.game kotlin
* source root, the roms folder, then one `region|gameCode|decompDir` per region.
*/
fun main(args: Array<String>) {
require(args.size >= 3) {
"Usage: <server-game-kotlin-src> <roms-dir> <region|gameCode|decomp>... got ${args.toList()}"
}
val outputDir = File(args[0])
val romsDir = File(args[1])
val assigned = mutableSetOf<String>()
val mapValues = mutableListOf<String>()
for (spec in args.drop(2)) {
val (region, gameCode, decomp) = spec.split("|")
mapValues +=
ScriptGenerator(region, outputDir).generate(File(decomp), romsDir, gameCode, assigned)
}
writeRegistry(outputDir, mapValues)
println("[script] wrote registry over ${mapValues.size} maps, ${assigned.size} scripts")
}
private fun writeRegistry(outputDir: File, mapValues: List<String>) {
val pkg = "de.fiereu.openmmo.server.game.script.generated"
val chunks = mapValues.chunked(40)
val sb = StringBuilder()
sb.append("package ").append(pkg).append("\n\n")
sb.append("import de.fiereu.openmmo.server.game.script.Script\n\n")
sb.append("/**\n")
sb.append(
" * Every ported script keyed by its decomp label. Bootstrapped once from the decomp then\n")
sb.append(
" * edited by hand, so this file is committed source and is not regenerated on build.\n")
sb.append(" */\n")
sb.append("internal object GeneratedScripts {\n")
sb.append(" val byLabel: Map<String, Script> =\n")
sb.append(" HashMap<String, Script>().apply {\n")
for (i in chunks.indices) sb.append(" chunk").append(i).append("()\n")
sb.append(" }\n\n")
for ((i, chunk) in chunks.withIndex()) {
sb.append(" private fun MutableMap<String, Script>.chunk").append(i).append("() {\n")
for (value in chunk) sb.append(" putAll(").append(value).append(")\n")
sb.append(" }\n\n")
}
sb.append("}\n")
val file = File(outputDir, pkg.replace('.', '/') + "/GeneratedScripts.kt")
file.parentFile.mkdirs()
file.writeText(sb.toString())
}
@@ -0,0 +1,53 @@
package de.fiereu.openmmo.codegen.script
import java.io.File
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
/**
* The interactable script labels each map references, grouped by the owning map (the map folder
* name). Only npc (object event) and sign (bg event) scripts are collected, since those are the
* entry points a player can trigger.
*/
class MapEventIndex private constructor(val byMap: Map<String, List<String>>) {
companion object {
private val json = Json { ignoreUnknownKeys = true }
fun build(decompDir: File): MapEventIndex {
val mapsDir = File(decompDir, "data/maps")
val out = LinkedHashMap<String, List<String>>()
if (mapsDir.isDirectory) {
mapsDir
.listFiles { f -> f.isDirectory }
?.sortedBy { it.name }
?.forEach { dir ->
val mapJson = File(dir, "map.json")
if (mapJson.isFile) {
val labels = parse(mapJson)
if (labels.isNotEmpty()) out[dir.name] = labels
}
}
}
return MapEventIndex(out)
}
private fun parse(mapJson: File): List<String> {
val root = json.parseToJsonElement(mapJson.readText()).jsonObject
val labels = LinkedHashSet<String>()
for (key in listOf("object_events", "bg_events")) {
val arr = root[key]?.jsonArray ?: continue
for (event in arr) {
val script = event.jsonObject["script"]?.jsonPrimitive?.content
if (script != null && isLabel(script)) labels.add(script)
}
}
return labels.toList()
}
private fun isLabel(value: String): Boolean =
value.isNotBlank() && value != "0x0" && value != "NULL" && value.first().isLetter()
}
}
@@ -0,0 +1,138 @@
package de.fiereu.openmmo.codegen.script
import java.io.File
/**
* Emits one Kotlin file per map holding the [de.fiereu.openmmo.server.game.script.Script] objects
* for that map's npcs and signs. Single msgbox scripts are filled in, anything with branching or
* extra commands is left as a TODO stub with the decomp body in a comment. Returns the fully
* qualified per map map values so the caller can build the registry.
*/
class ScriptGenerator(
private val region: String,
private val outputDir: File,
) {
private val basePackage = "de.fiereu.openmmo.server.game.script.generated.$region"
private val dialogPackage = "de.fiereu.openmmo.dialog.generated.$region"
fun generate(
decompDir: File,
romsDir: File,
gameCode: String,
assigned: MutableSet<String>,
): List<String> {
val scripts = ScriptIndex.build(decompDir)
val events = MapEventIndex.build(decompDir)
val dialogRefs = DialogRefIndex.build(decompDir, romsDir, gameCode)
val packageDir = File(outputDir, basePackage.replace('.', '/'))
if (packageDir.exists()) packageDir.deleteRecursively()
packageDir.mkdirs()
val mapValues = mutableListOf<String>()
var simple = 0
var todo = 0
for ((mapName, labels) in events.byMap) {
val stubs = labels.filter { assigned.add(it) }.map { toStub(it, scripts, dialogRefs) }
if (stubs.isEmpty()) continue
File(packageDir, "$mapName.kt").writeText(renderMapFile(mapName, stubs))
mapValues.add("$basePackage.${mapName}Scripts")
simple += stubs.count { it.kind != ScriptKind.TODO }
todo += stubs.count { it.kind == ScriptKind.TODO }
}
println("[script] $region: ${mapValues.size} maps, $simple filled, $todo todo stubs")
return mapValues
}
private fun toStub(
label: String,
scripts: ScriptIndex,
dialogRefs: Map<String, DialogRef>,
): ScriptStub {
val commands =
scripts.commandsFor(label)
?: return ScriptStub(label, ScriptKind.TODO, null, listOf("script body not found"))
val msgbox = singleMsgbox(commands) ?: return ScriptStub(label, ScriptKind.TODO, null, commands)
val ref =
dialogRefs[msgbox.textLabel] ?: return ScriptStub(label, ScriptKind.TODO, null, commands)
val kind = if (msgbox.type == "MSGBOX_SIGN") ScriptKind.SIGN else ScriptKind.SAY
return ScriptStub(label, kind, ref, emptyList())
}
private data class Msgbox(val textLabel: String, val type: String)
/** The single meaningful command is a msgbox, ignoring cosmetic framing around it. */
private fun singleMsgbox(commands: List<String>): Msgbox? {
val meaningful = commands.filter { opcode(it) !in FRAMING }
if (meaningful.size != 1) return null
val cmd = meaningful.single()
if (opcode(cmd) != "msgbox") return null
val args = cmd.removePrefix("msgbox").substringBefore('@').trim().split(",")
val textLabel = args[0].trim()
if (textLabel.isEmpty() || !textLabel.first().isLetter()) return null
val type = args.getOrNull(1)?.trim().takeUnless { it.isNullOrEmpty() } ?: "MSGBOX_DEFAULT"
return Msgbox(textLabel, type)
}
private fun opcode(command: String): String =
command.substringBefore(' ').substringBefore('\t').trim()
private fun renderMapFile(mapName: String, stubs: List<ScriptStub>): String {
val imports = sortedSetOf<String>()
stubs.forEach { it.dialogRef?.let { ref -> imports.add("$dialogPackage.${ref.className}") } }
val sb = StringBuilder()
sb.append("package ").append(basePackage).append("\n\n")
imports.forEach { sb.append("import ").append(it).append('\n') }
sb.append("import de.fiereu.openmmo.server.game.script.Script\n")
sb.append("import de.fiereu.openmmo.server.game.script.ScriptContext\n\n")
for (stub in stubs) renderStub(sb, stub)
sb.append("internal val ").append(mapName).append("Scripts: Map<String, Script> =\n")
sb.append(" mapOf(\n")
for (stub in stubs) {
sb.append(" \"").append(stub.label).append("\" to ").append(stub.label).append(",\n")
}
sb.append(" )\n")
return sb.toString()
}
private fun renderStub(sb: StringBuilder, stub: ScriptStub) {
when (stub.kind) {
ScriptKind.SIGN -> renderBody(sb, stub.label, "ctx.sign(${stub.dialogRef!!.reference})")
ScriptKind.SAY -> renderBody(sb, stub.label, "ctx.say(${stub.dialogRef!!.reference})")
ScriptKind.TODO -> {
sb.append("/**\n * Not ported yet. Decomp body:\n * ```\n")
for (line in stub.decompLines) {
sb.append(" * ").append(line.replace("*/", "* /")).append('\n')
}
sb.append(" * ```\n */\n")
renderBody(sb, stub.label, "TODO(\"port ${stub.label}\")")
}
}
}
private fun renderBody(sb: StringBuilder, label: String, body: String) {
sb.append("internal object ").append(label).append(" : Script {\n")
sb.append(" override suspend fun run(ctx: ScriptContext) = ").append(body).append("\n")
sb.append("}\n\n")
}
private companion object {
// Cosmetic commands that wrap a plain message and do not change what is shown.
val FRAMING =
setOf(
"lock",
"lockall",
"faceplayer",
"release",
"releaseall",
"closemessage",
"waitmessage",
"waitbuttonpress",
"end",
"return",
)
}
}
@@ -0,0 +1,58 @@
package de.fiereu.openmmo.codegen.script
import java.io.File
/**
* Every executable script in the decomp keyed by its label, with the command lines that make up its
* body. Scripts live in the map scripts and in the shared script files. A label ending in `::`
* opens a script, a label ending in a single `:` opens data such as text and ends the current
* script.
*/
class ScriptIndex private constructor(private val commands: Map<String, List<String>>) {
fun commandsFor(label: String): List<String>? = commands[label]
companion object {
private val labelLine = Regex("^(\\w+)::?\\s*$")
fun build(decompDir: File): ScriptIndex {
val roots = listOf(File(decompDir, "data/maps"), File(decompDir, "data/scripts"))
val out = LinkedHashMap<String, MutableList<String>>()
for (root in roots) {
if (!root.isDirectory) continue
root
.walkTopDown()
.filter { it.isFile && it.extension == "inc" }
.forEach { parseFile(it, out) }
}
return ScriptIndex(out)
}
private fun parseFile(file: File, out: MutableMap<String, MutableList<String>>) {
// Labels stacked with no commands between them are aliases for the same body.
val pending = mutableListOf<String>()
for (raw in file.readLines()) {
val line = raw.trim()
val match = labelLine.matchEntire(line)
if (match != null) {
if (line.endsWith("::")) {
val label = match.groupValues[1]
out.getOrPut(label) { mutableListOf() }
pending.add(label)
} else {
// A data label ends the current script body.
pending.clear()
}
continue
}
if (line.isEmpty()) {
// A blank line separates one script from the next.
pending.clear()
continue
}
if (line.startsWith("@")) continue
for (label in pending) out.getValue(label).add(line)
}
}
}
}
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.codegen.script
/** How a ported script shows its line: a sign box, a spoken box, or not ported yet. */
enum class ScriptKind {
SIGN,
SAY,
TODO,
}
/** A reference to a generated dialog enum entry, for example `LittlerootTown.TownSign`. */
data class DialogRef(val className: String, val entryName: String) {
val reference: String
get() = "$className.$entryName"
}
/**
* One generated script object. [label] is the decomp script label and also the Kotlin object name.
* SIGN and SAY carry a [dialogRef], TODO carries the [decompLines] so the port can be filled in.
*/
data class ScriptStub(
val label: String,
val kind: ScriptKind,
val dialogRef: DialogRef?,
val decompLines: List<String>,
)