feat(dialog): generate per-location gba dialog enums from the rom and drop the old script params (#64)

This commit is contained in:
Fiereu authored and GitHub committed 2026-07-25 21:26:43 +02:00
1 parent e89ae6e6df
commit 9c52eeb8c6
13 files changed
+419 -132

No files matched your search

@@ -0,0 +1,18 @@
@import java.util.List
@import de.fiereu.openmmo.codegen.dialog.DialogEntry
@import de.fiereu.openmmo.codegen.dialog.RenderUtil
@param String pkg
@param String enumName
@param List<DialogEntry> entries
package ${pkg}
/**
* 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) {
@for(DialogEntry e : entries)
${RenderUtil.INSTANCE.entry(e)}
@endfor
}
@@ -0,0 +1,78 @@
package de.fiereu.openmmo.codegen.dialog
import java.io.File
/**
* The GBA text encoder built from a pret decomp charmap.txt. It turns the literal content of a
* `.string` (letters, `\n`/`\l`/`\p` escapes, `{NAME}` placeholders, the `$` terminator) into the
* exact bytes the game stores in the ROM, so the encoded form can be located there.
*/
class Charmap
private constructor(
private val chars: Map<Char, ByteArray>,
private val escapes: Map<String, ByteArray>,
private val placeholders: Map<String, ByteArray>,
) {
/** Encodes [text], or returns null if it uses a symbol the charmap cannot represent. */
fun encode(text: String): ByteArray? {
val out = ArrayList<Byte>(text.length + 1)
var i = 0
while (i < text.length) {
val c = text[i]
when {
c == '\\' && i + 1 < text.length -> {
val esc = escapes["\\" + text[i + 1]] ?: return null
out.addAll(esc.toList())
i += 2
}
c == '{' -> {
val end = text.indexOf('}', i)
if (end < 0) return null
val bytes = placeholders[text.substring(i + 1, end)] ?: return null
out.addAll(bytes.toList())
i = end + 1
}
else -> {
val bytes = chars[c] ?: return null
out.addAll(bytes.toList())
i++
}
}
}
return out.toByteArray()
}
companion object {
// key = value where key may itself be the '=' char, value is one or more hex bytes, and an
// optional trailing "@ comment" follows whitespace.
private val entry = Regex("^(.*?)=\\s*([0-9A-Fa-f]{2}(?:\\s+[0-9A-Fa-f]{2})*)\\s*(?:@.*)?$")
fun load(charmapFile: File): Charmap {
val chars = HashMap<Char, ByteArray>()
val escapes = HashMap<String, ByteArray>()
val placeholders = HashMap<String, ByteArray>()
for (raw in charmapFile.readLines()) {
val line = raw.replace(Regex("\\s+@.*$"), "").trimEnd()
val m = entry.matchEntire(line) ?: continue
val key = m.groupValues[1].trim()
val bytes =
m.groupValues[2].split(Regex("\\s+")).map { it.toInt(16).toByte() }.toByteArray()
if (key.isEmpty() || bytes.isEmpty()) continue
if (key.length >= 2 && key.first() == '\'' && key.last() == '\'') {
when (val inner = key.substring(1, key.length - 1)) {
"\\n",
"\\l",
"\\p",
"\\r" -> escapes[inner] = bytes
"\\'" -> chars['\''] = bytes
else -> if (inner.length == 1) chars[inner[0]] = bytes
}
} else {
placeholders[key] = bytes
}
}
return Charmap(chars, escapes, placeholders)
}
}
}
@@ -0,0 +1,9 @@
package de.fiereu.openmmo.codegen.dialog
/**
* One dialog line resolved from the decomp: its full label, packed textId, and readable preview.
*/
data class DialogLine(val label: String, val textId: Int, val preview: String)
/** A single enum entry inside a location's dialog enum. */
data class DialogEntry(val name: String, val textId: Int, val preview: String)
@@ -0,0 +1,48 @@
package de.fiereu.openmmo.codegen.dialog
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.FileOutput
import gg.jte.resolve.DirectoryCodeResolver
import java.io.File
/** Emits one Kotlin file per location, each holding an enum of that location's dialog lines. */
class DialogRenderer(
region: String,
private val templatesDir: File,
private val outputDir: File,
private val classCacheDir: File,
) {
private val basePackage = "de.fiereu.openmmo.dialog.generated.$region"
fun render(lines: List<DialogLine>) {
classCacheDir.mkdirs()
val engine =
TemplateEngine.create(
DirectoryCodeResolver(templatesDir.toPath()),
classCacheDir.toPath(),
ContentType.Plain,
)
val packageRoot = File(outputDir, basePackage.replace('.', '/'))
if (packageRoot.exists()) packageRoot.deleteRecursively()
packageRoot.mkdirs()
lines
.groupBy { RenderUtil.location(it.label) }
.forEach { (location, group) ->
val className = RenderUtil.className(location)
val entries =
group
.map { DialogEntry(RenderUtil.entryName(it.label), it.textId, it.preview) }
.distinctBy { it.name }
.sortedBy { it.textId }
FileOutput(File(packageRoot, "${className.trim('`')}.kt").toPath()).use { out ->
engine.render(
"LocationDialog.jte",
mapOf("pkg" to basePackage, "enumName" to className, "entries" to entries),
out)
}
}
}
}
@@ -0,0 +1,66 @@
@file:JvmName("Main")
package de.fiereu.openmmo.codegen.dialog
import java.io.File
// GBA dialog ids carry the retail ROM file offset in the low bits with the mode-1 resolver on top.
private const val GBA_MODE = 0x10000000
fun main(args: Array<String>) {
require(args.size >= 5) {
"Usage: <output-dir> <templates-dir> <class-cache-dir> <roms-dir> <region|gameCode|decomp>... got ${args.toList()}"
}
val outputDir = File(args[0])
val templatesDir = File(args[1])
val classCacheDir = File(args[2])
val romsDir = File(args[3])
for (spec in args.drop(4)) {
val (region, gameCode, decomp) = spec.split("|")
generateRegion(region, gameCode, File(decomp), romsDir, outputDir, templatesDir, classCacheDir)
}
}
private fun generateRegion(
region: String,
gameCode: String,
decompDir: File,
romsDir: File,
outputDir: File,
templatesDir: File,
classCacheDir: File,
) {
val renderer = DialogRenderer(region, templatesDir, outputDir, classCacheDir)
val rom = RomIndex.find(romsDir, gameCode)
if (rom == null) {
println("[dialog] no $gameCode ROM found in $romsDir, generating empty $region")
renderer.render(emptyList())
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
val lines =
texts.mapNotNull { t ->
val bytes = charmap.encode(t.content)
if (bytes == null) {
unencodable++
return@mapNotNull null
}
val offset = rom.offsetOf(bytes)
if (offset < 0) {
notFound++
return@mapNotNull null
}
DialogLine(t.label, GBA_MODE or offset, RenderUtil.preview(t.content))
}
println(
"[dialog] $region: resolved ${lines.size} lines (skipped $unencodable unencodable, $notFound not in ROM)")
renderer.render(lines)
}
@@ -0,0 +1,66 @@
package de.fiereu.openmmo.codegen.dialog
object RenderUtil {
private val KEYWORDS =
setOf(
"as",
"break",
"class",
"continue",
"do",
"else",
"false",
"for",
"fun",
"if",
"in",
"interface",
"is",
"null",
"object",
"package",
"return",
"super",
"this",
"throw",
"true",
"try",
"typealias",
"typeof",
"val",
"var",
"when",
"while")
/** Location the label belongs to: everything before `_Text_`, or "Misc" when it has none. */
fun location(label: String): String =
if ("_Text_" in label) label.substringBefore("_Text_") else "Misc"
/** The enum entry name: the part after `_Text_`, or the whole label, made a valid identifier. */
fun entryName(label: String): String =
ident(if ("_Text_" in label) label.substringAfter("_Text_") else label)
fun className(location: String): String = ident(location)
private fun ident(s: String): String {
val safe = if (s.isNotEmpty() && s[0].isDigit()) "_$s" else s
return if (safe in KEYWORDS) "`$safe`" else safe
}
fun entry(e: DialogEntry): String = "/** ${e.preview} */ ${e.name}(0x${"%08X".format(e.textId)}),"
/** Turns raw `.string` content into a short single-line preview safe inside a KDoc comment. */
fun preview(content: String): String {
val text =
content
.replace("\\n", " ")
.replace("\\l", " ")
.replace("\\p", " ")
.replace("$", "")
.replace(Regex("\\s+"), " ")
.replace("*/", "* /")
.trim()
return if (text.length > 70) text.take(70) + "…" else text
}
}
@@ -0,0 +1,36 @@
package de.fiereu.openmmo.codegen.dialog
import java.io.File
/**
* A retail GBA ROM located by its header game code, used to resolve a text's file offset. The ROM
* is byte-identical to the pret decomp, so the offset of an encoded string is the value PokeMMO
* packs into a dialog textId.
*/
class RomIndex private constructor(private val latin1: String) {
/** The first offset of [bytes] in the ROM, or -1 if absent. */
fun offsetOf(bytes: ByteArray): Int = latin1.indexOf(String(bytes, Charsets.ISO_8859_1))
companion object {
private const val GAME_CODE_OFFSET = 0xAC
/** Finds the ROM in [romsDir] whose header game code equals [gameCode] (e.g. "BPEE"). */
fun find(romsDir: File, gameCode: String): RomIndex? {
val rom =
romsDir
.listFiles { f -> f.isFile }
?.firstOrNull { f ->
f.length() > GAME_CODE_OFFSET + 4 && readGameCode(f) == gameCode
} ?: return null
return RomIndex(String(rom.readBytes(), Charsets.ISO_8859_1))
}
private fun readGameCode(file: File): String =
file.inputStream().use { s ->
s.skip(GAME_CODE_OFFSET.toLong())
val b = ByteArray(4)
if (s.read(b) != 4) "" else String(b, Charsets.US_ASCII)
}
}
}
@@ -0,0 +1,72 @@
package de.fiereu.openmmo.codegen.dialog
import java.io.File
/** A `.string` text label found in the decomp: its label and the concatenated literal content. */
data class DecompText(val label: String, val content: String)
/**
* Collects every `.string` text label from the overworld data (map and shared scripts). A label is
* a text label when it is directly followed by one or more `.string` lines.
*/
class TextParser(private val decompDir: File) {
private val labelLine = Regex("^(\\w+):+\\s*$")
fun parseAll(): List<DecompText> {
val roots = listOf(File(decompDir, "data/maps"), File(decompDir, "data/scripts"))
val out = LinkedHashMap<String, String>()
for (root in roots) {
if (!root.isDirectory) continue
root
.walkTopDown()
.filter { it.isFile && it.extension == "inc" }
.forEach { file -> parseFile(file, out) }
}
return out.map { DecompText(it.key, it.value) }
}
private fun parseFile(file: File, out: MutableMap<String, String>) {
var pending: String? = null
var active: String? = null
val buffer = StringBuilder()
fun flush() {
val label = active
if (label != null && label !in out) out[label] = buffer.toString()
active = null
buffer.setLength(0)
}
for (raw in file.readLines()) {
val line = raw.trim()
val m = labelLine.matchEntire(line)
when {
m != null -> {
flush()
pending = m.groupValues[1]
}
line.startsWith(".string") -> {
val label = active ?: pending ?: continue
if (active == null) {
active = label
buffer.setLength(0)
}
buffer.append(stringLiteral(line))
}
line.isEmpty() -> {
flush()
pending = null
}
else -> {
flush()
pending = null
}
}
}
flush()
}
private fun stringLiteral(line: String): String {
val first = line.indexOf('"')
val last = line.lastIndexOf('"')
return if (first in 0 until last) line.substring(first + 1, last) else ""
}
}