feat(game): littleroot town intro with the truck and mom cutscene

This commit is contained in:
Fiereu committed 2026-07-26 14:36:07 +02:00
1 parent 41ff99ae4f
commit 9cda538a68
23 files changed
+368 -71

No files matched your search

@@ -16,6 +16,7 @@ import de.fiereu.openmmo.common.enums.MovementType
import de.fiereu.openmmo.common.enums.Weather import de.fiereu.openmmo.common.enums.Weather
import de.fiereu.openmmo.maps.BgEventDef import de.fiereu.openmmo.maps.BgEventDef
import de.fiereu.openmmo.maps.MapDef import de.fiereu.openmmo.maps.MapDef
import de.fiereu.openmmo.maps.MapFrameScript
import de.fiereu.openmmo.maps.NpcDef import de.fiereu.openmmo.maps.NpcDef
import de.fiereu.openmmo.maps.WarpTile import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.maps.WildEncounterSlot import de.fiereu.openmmo.maps.WildEncounterSlot
@@ -46,4 +47,5 @@ internal val ${objectName}: MapDef =
npcs = ${RenderUtil.INSTANCE.npcs(map.getVisibleNpcs())}, npcs = ${RenderUtil.INSTANCE.npcs(map.getVisibleNpcs())},
bgEvents = ${RenderUtil.INSTANCE.bgEvents(map.getBgEvents())}, bgEvents = ${RenderUtil.INSTANCE.bgEvents(map.getBgEvents())},
onTransitionScript = "${map.getOnTransitionScript()}", onTransitionScript = "${map.getOnTransitionScript()}",
onFrameScripts = ${RenderUtil.INSTANCE.frameScripts(map.getOnFrameScripts())},
) )
@@ -28,6 +28,14 @@ data class ParsedMap(
val bgEvents: List<ParsedBgEvent>, val bgEvents: List<ParsedBgEvent>,
// Decomp label of the map's ON_TRANSITION script, or "" when the map has none. // Decomp label of the map's ON_TRANSITION script, or "" when the map has none.
val onTransitionScript: String, val onTransitionScript: String,
// The map's ON_FRAME table: run the script once its var equals the value, on map entry.
val onFrameScripts: List<ParsedFrameScript>,
)
data class ParsedFrameScript(
val varKey: String,
val value: Int,
val script: String,
) )
data class ParsedConnection( data class ParsedConnection(
@@ -47,6 +55,7 @@ data class ParsedWarp(
val targetX: Int, val targetX: Int,
val targetY: Int, val targetY: Int,
val targetElevation: Int, val targetElevation: Int,
val dynamic: Boolean = false,
) )
data class ParsedNpc( data class ParsedNpc(
@@ -61,6 +70,8 @@ data class ParsedNpc(
val trainerType: Int, val trainerType: Int,
val facing: String, val facing: String,
val script: String, val script: String,
// Namespaced story flag that hides this npc by default, or "" when it is always shown.
val hideFlag: String,
) )
data class ParsedBgEvent( data class ParsedBgEvent(
@@ -193,6 +193,7 @@ class PretGbaParser(
visibleNpcs = parseNpcs(mapJson, mapDirName, ctx), visibleNpcs = parseNpcs(mapJson, mapDirName, ctx),
bgEvents = parseBgEvents(mapJson), bgEvents = parseBgEvents(mapJson),
onTransitionScript = parseOnTransitionScript(mapDirName), onTransitionScript = parseOnTransitionScript(mapDirName),
onFrameScripts = parseOnFrameScripts(mapDirName),
) )
} }
@@ -225,9 +226,25 @@ class PretGbaParser(
mapJson["warp_events"]?.jsonArrayOrNull()?.mapNotNull { warp -> mapJson["warp_events"]?.jsonArrayOrNull()?.mapNotNull { warp ->
val obj = warp.jsonObject val obj = warp.jsonObject
val destName = obj["dest_map"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null val destName = obj["dest_map"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val destAddr = ctx.addresses[destName] ?: return@mapNotNull null
val x = obj["x"]?.jsonPrimitive?.intOrNull ?: 0 val x = obj["x"]?.jsonPrimitive?.intOrNull ?: 0
val y = obj["y"]?.jsonPrimitive?.intOrNull ?: 0 val y = obj["y"]?.jsonPrimitive?.intOrNull ?: 0
// A MAP_DYNAMIC warp has no static destination, the runtime resolves it from the player's
// dynamic warp (setdynamicwarp). Emit the tile so it still triggers, with dynamic = true.
if (destName == "MAP_DYNAMIC") {
return@mapNotNull ParsedWarp(
x = x,
y = y,
elevation = ((obj["elevation"]?.jsonPrimitive?.intOrNull ?: 0) - 1).coerceAtLeast(0),
targetRegion = 0,
targetBank = 0,
targetMap = 0,
targetX = 0,
targetY = 0,
targetElevation = 0,
dynamic = true,
)
}
val destAddr = ctx.addresses[destName] ?: return@mapNotNull null
val srcElevation = (obj["elevation"]?.jsonPrimitive?.intOrNull ?: 0) val srcElevation = (obj["elevation"]?.jsonPrimitive?.intOrNull ?: 0)
val destWarpId = val destWarpId =
obj["dest_warp_id"]?.jsonPrimitive?.let { it.intOrNull ?: it.content.toIntOrNull() } obj["dest_warp_id"]?.jsonPrimitive?.let { it.intOrNull ?: it.content.toIntOrNull() }
@@ -249,15 +266,14 @@ class PretGbaParser(
) )
} ?: emptyList() } ?: emptyList()
// Every object event is emitted. A npc hidden by a story flag keeps the flag in hideFlag so the
// server can skip it at spawn and a script can show it later, the always-visible ones get "".
private fun parseNpcs(mapJson: JsonObject, mapDirName: String, ctx: Context): List<ParsedNpc> { private fun parseNpcs(mapJson: JsonObject, mapDirName: String, ctx: Context): List<ParsedNpc> {
val visibleOverride = region.defaultVisibleNpcs[mapDirName] val visibleOverride = region.defaultVisibleNpcs[mapDirName]
return mapJson["object_events"]?.jsonArrayOrNull().orEmpty().mapIndexedNotNull { idx, npcElement return mapJson["object_events"]?.jsonArrayOrNull().orEmpty().mapIndexed { idx, npcElement ->
->
val npc = npcElement.jsonObject val npc = npcElement.jsonObject
val isVisible = val flag = npc["flag"]?.jsonPrimitive?.contentOrNull ?: "0"
if (visibleOverride != null) idx in visibleOverride val shownByDefault = if (visibleOverride != null) idx in visibleOverride else flag == "0"
else npc["flag"]?.jsonPrimitive?.contentOrNull == "0"
if (!isVisible) return@mapIndexedNotNull null
val gfxName = npc["graphics_id"]?.jsonPrimitive?.contentOrNull ?: "OBJ_EVENT_GFX_BOY_1" val gfxName = npc["graphics_id"]?.jsonPrimitive?.contentOrNull ?: "OBJ_EVENT_GFX_BOY_1"
val movementName = npc["movement_type"]?.jsonPrimitive?.contentOrNull ?: "MOVEMENT_TYPE_NONE" val movementName = npc["movement_type"]?.jsonPrimitive?.contentOrNull ?: "MOVEMENT_TYPE_NONE"
ParsedNpc( ParsedNpc(
@@ -274,10 +290,41 @@ class PretGbaParser(
else 1, else 1,
facing = movementTypes.facingRef(movementName), facing = movementTypes.facingRef(movementName),
script = npc["script"]?.jsonPrimitive?.contentOrNull ?: "0x0", script = npc["script"]?.jsonPrimitive?.contentOrNull ?: "0x0",
hideFlag = if (shownByDefault) "" else "${region.name}/$flag",
) )
} }
} }
// Parses the map's ON_FRAME table: each map_script_2 runs its script once the var equals the
// value
// when the player enters the map. Values that are not plain integers (rare) are skipped.
private fun parseOnFrameScripts(mapDirName: String): List<ParsedFrameScript> {
val file = File(rootDir, "data/maps/$mapDirName/scripts.inc")
if (!file.exists()) return emptyList()
val text = file.readText()
val tableLabel =
Regex("""map_script\s+MAP_SCRIPT_ON_FRAME_TABLE\s*,\s*(\w+)""")
.find(text)
?.groupValues
?.get(1) ?: return emptyList()
val block =
Regex("""(?m)^$tableLabel:\s*\n(.*?)(?=\n\s*\.2byte)""", RegexOption.DOT_MATCHES_ALL)
.find(text)
?.groupValues
?.get(1) ?: return emptyList()
val entry = Regex("""map_script_2\s+(\w+)\s*,\s*(\d+)\s*,\s*(\w+)""")
return entry
.findAll(block)
.map {
ParsedFrameScript(
varKey = "${region.name}/${it.groupValues[1]}",
value = it.groupValues[2].toInt(),
script = it.groupValues[3],
)
}
.toList()
}
private fun parseBgEvents(mapJson: JsonObject): List<ParsedBgEvent> = private fun parseBgEvents(mapJson: JsonObject): List<ParsedBgEvent> =
mapJson["bg_events"]?.jsonArrayOrNull()?.map { be -> mapJson["bg_events"]?.jsonArrayOrNull()?.map { be ->
val obj = be.jsonObject val obj = be.jsonObject
@@ -31,7 +31,8 @@ object RenderUtil {
"WarpTile(x = ${it.x}, y = ${it.y}, elevation = ${it.elevation}," + "WarpTile(x = ${it.x}, y = ${it.y}, elevation = ${it.elevation}," +
" targetRegionId = ${it.targetRegion}, targetBankId = ${it.targetBank}," + " targetRegionId = ${it.targetRegion}, targetBankId = ${it.targetBank}," +
" targetMapId = ${it.targetMap}," + " targetMapId = ${it.targetMap}," +
" targetX = ${it.targetX}, targetY = ${it.targetY}, targetElevation = ${it.targetElevation})" " targetX = ${it.targetX}, targetY = ${it.targetY}, targetElevation = ${it.targetElevation}," +
" dynamic = ${it.dynamic})"
} }
} }
@@ -42,7 +43,16 @@ object RenderUtil {
" x = ${it.x}, y = ${it.y}, elevation = ${it.elevation}," + " x = ${it.x}, y = ${it.y}, elevation = ${it.elevation}," +
" movementType = ${it.movementType}, movementRangeX = ${it.movementRangeX}," + " movementType = ${it.movementType}, movementRangeX = ${it.movementRangeX}," +
" movementRangeY = ${it.movementRangeY}, trainerType = ${it.trainerType}," + " movementRangeY = ${it.movementRangeY}, trainerType = ${it.trainerType}," +
" facing = ${it.facing}, script = ${escapeString(it.script)})" " facing = ${it.facing}, script = ${escapeString(it.script)}," +
" hideFlag = ${escapeString(it.hideFlag)})"
}
}
fun frameScripts(scripts: List<ParsedFrameScript>): String {
if (scripts.isEmpty()) return EMPTY_LIST
return scripts.joinToString(LIST_SEP, LIST_OPEN, LIST_CLOSE) {
"MapFrameScript(varKey = ${escapeString(it.varKey)}, value = ${it.value}," +
" script = ${escapeString(it.script)})"
} }
} }
@@ -34,6 +34,8 @@ class MapDef(
val bgEvents: List<BgEventDef> = emptyList(), val bgEvents: List<BgEventDef> = emptyList(),
/** Decomp label of the script that runs when a player enters this map, or "" if none. */ /** Decomp label of the script that runs when a player enters this map, or "" if none. */
val onTransitionScript: String = "", val onTransitionScript: String = "",
/** Conditional entry scripts: run [MapFrameScript.script] when its var equals its value. */
val onFrameScripts: List<MapFrameScript> = emptyList(),
private val blockData: String = "", private val blockData: String = "",
private val behaviorData: String = "", private val behaviorData: String = "",
) { ) {
@@ -48,6 +50,13 @@ class MapDef(
wildEncounters.firstOrNull { it.method == method } wildEncounters.firstOrNull { it.method == method }
} }
/** One ON_FRAME entry: run [script] when the story var [varKey] currently equals [value]. */
data class MapFrameScript(
val varKey: String,
val value: Int,
val script: String,
)
private fun decodeBlockData(blockData: String, behaviorData: String): List<Tile2D> { private fun decodeBlockData(blockData: String, behaviorData: String): List<Tile2D> {
if (blockData.isEmpty()) return emptyList() if (blockData.isEmpty()) return emptyList()
val bytes = Base64.getDecoder().decode(blockData) val bytes = Base64.getDecoder().decode(blockData)
@@ -15,4 +15,6 @@ data class NpcDef(
val trainerType: Int, val trainerType: Int,
val facing: Direction, val facing: Direction,
val script: String = "0x0", val script: String = "0x0",
/** Story flag that hides this npc by default, or "" when it is always shown. */
val hideFlag: String = "",
) )
@@ -13,4 +13,12 @@ data class WarpTile(
val targetY: Int, val targetY: Int,
val targetElevation: Int = 0, val targetElevation: Int = 0,
val facingDirection: Direction? = null, val facingDirection: Direction? = null,
/** Direction the player faces after this warp, or null to infer it. */
val exitFacing: Direction? = null,
/**
* A MAP_DYNAMIC warp whose destination is not baked in but set at runtime (the decomp
* setdynamicwarp). The target fields are placeholders, the real destination comes from the
* player's stored dynamic warp when they step on it.
*/
val dynamic: Boolean = false,
) )
@@ -25,5 +25,7 @@ data class CharacterInfo(
val repelLeft: Short, val repelLeft: Short,
val repelItemId: Short, val repelItemId: Short,
val lureLeft: Short, val lureLeft: Short,
val lureItemId: Short val lureItemId: Short,
/** Runtime warp destination for MAP_DYNAMIC warps (setdynamicwarp), or null if none is set. */
val dynamicWarp: DynamicWarp? = null,
) )
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.common
import de.fiereu.openmmo.common.enums.Direction
/**
* A destination set at runtime by a script (the decomp setdynamicwarp) that a MAP_DYNAMIC warp tile
* resolves to when the player steps on it. Used for the intro truck exit.
*/
data class DynamicWarp(
val regionId: Byte,
val bankId: Byte,
val mapId: Byte,
val x: Short,
val y: Short,
val facing: Direction,
)
@@ -4,16 +4,19 @@ import de.fiereu.openmmo.common.enums.Direction
/** /**
* One step of an applymovement sequence: either a walk one tile in [direction] or a turn in place * One step of an applymovement sequence: either a walk one tile in [direction] or a turn in place
* to face [direction]. This is the small, game agnostic vocabulary scripts use, decomp movement * to face [direction]. [action] is the client movement-action byte (from packet captures: face
* templates are ported into lists of these. * 0x00-0x03, walk 0x10-0x13); a whole sequence of these is sent in one movement packet. This is the
* small game agnostic vocabulary scripts use.
*/ */
enum class MovementStep(val direction: Direction, val walks: Boolean) { enum class MovementStep(val direction: Direction, val walks: Boolean, val action: Int) {
WALK_UP(Direction.UP, true), FACE_DOWN(Direction.DOWN, false, 0x00),
WALK_DOWN(Direction.DOWN, true), FACE_UP(Direction.UP, false, 0x01),
WALK_LEFT(Direction.LEFT, true), FACE_LEFT(Direction.LEFT, false, 0x02),
WALK_RIGHT(Direction.RIGHT, true), FACE_RIGHT(Direction.RIGHT, false, 0x03),
FACE_UP(Direction.UP, false), WALK_DOWN(Direction.DOWN, true, 0x10),
FACE_DOWN(Direction.DOWN, false), WALK_UP(Direction.UP, true, 0x11),
FACE_LEFT(Direction.LEFT, false), WALK_LEFT(Direction.LEFT, true, 0x12),
FACE_RIGHT(Direction.RIGHT, false), WALK_RIGHT(Direction.RIGHT, true, 0x13),
// Hides the entity in place, used at the end of a walk into a door (decomp set_invisible).
SET_INVISIBLE(Direction.DOWN, false, 0x60),
} }
@@ -1,7 +1,9 @@
package de.fiereu.openmmo.server.game.script package de.fiereu.openmmo.server.game.script
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.dialog.DialogLine import de.fiereu.openmmo.common.dialog.DialogLine
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.server.game.services.DialogService import de.fiereu.openmmo.server.game.services.DialogService
import de.fiereu.openmmo.server.game.services.ScriptMovementService import de.fiereu.openmmo.server.game.services.ScriptMovementService
import de.fiereu.openmmo.server.game.services.StoryService import de.fiereu.openmmo.server.game.services.StoryService
@@ -56,6 +58,16 @@ internal constructor(
suspend fun moveSelf(vararg steps: MovementStep) = suspend fun moveSelf(vararg steps: MovementStep) =
movement.moveSelf(session, state, steps.toList()) movement.moveSelf(session, state, steps.toList())
/** Show a normally hidden map npc (its decomp local id) to this player, the decomp addobject. */
fun showNpc(localId: Int) = movement.showNpc(session, state, localId)
/** Set where a MAP_DYNAMIC warp sends this player (the decomp setdynamicwarp). */
fun setDynamicWarp(regionId: Int, bankId: Int, mapId: Int, x: Int, y: Int, facing: Direction) =
movement.setDynamicWarp(
state,
DynamicWarp(
regionId.toByte(), bankId.toByte(), mapId.toByte(), x.toShort(), y.toShort(), facing))
private companion object { private companion object {
// Sign boxes have no speaker, npc boxes point at the entity. // Sign boxes have no speaker, npc boxes point at the entity.
const val SIGN = 3 const val SIGN = 3
@@ -31,7 +31,20 @@ constructor(
private val storyService: StoryService, private val storyService: StoryService,
private val movementService: ScriptMovementService, private val movementService: ScriptMovementService,
) { ) {
fun run(session: SessionContext, state: PlayerState, script: Script, entityId: Long) { fun run(session: SessionContext, state: PlayerState, script: Script, entityId: Long) =
runAll(session, state, listOf(script), entityId)
/**
* Runs [scripts] in order on one coroutine so they share the dialog lock, for example a map's
* on-transition script followed by its matching on-frame cutscene.
*/
fun runAll(
session: SessionContext,
state: PlayerState,
scripts: List<Script>,
entityId: Long,
) {
if (scripts.isEmpty()) return
state.inDialog = true state.inDialog = true
val scope = val scope =
session.attributes.getOrPut(SCRIPT_SCOPE) { session.attributes.getOrPut(SCRIPT_SCOPE) {
@@ -40,7 +53,7 @@ constructor(
val ctx = ScriptContext(session, state, entityId, dialogService, storyService, movementService) val ctx = ScriptContext(session, state, entityId, dialogService, storyService, movementService)
scope.launch { scope.launch {
try { try {
script.run(ctx) for (script in scripts) script.run(ctx)
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
} catch (e: NotImplementedError) { } catch (e: NotImplementedError) {
@@ -1,9 +1,19 @@
package de.fiereu.openmmo.server.game.script.generated.hoenn package de.fiereu.openmmo.server.game.script.generated.hoenn
import de.fiereu.openmmo.dialog.generated.hoenn.LittlerootTown import de.fiereu.openmmo.dialog.generated.hoenn.LittlerootTown
import de.fiereu.openmmo.server.game.script.MovementStep.FACE_LEFT
import de.fiereu.openmmo.server.game.script.MovementStep.SET_INVISIBLE
import de.fiereu.openmmo.server.game.script.MovementStep.WALK_DOWN
import de.fiereu.openmmo.server.game.script.MovementStep.WALK_LEFT
import de.fiereu.openmmo.server.game.script.MovementStep.WALK_RIGHT
import de.fiereu.openmmo.server.game.script.MovementStep.WALK_UP
import de.fiereu.openmmo.server.game.script.Script import de.fiereu.openmmo.server.game.script.Script
import de.fiereu.openmmo.server.game.script.ScriptContext import de.fiereu.openmmo.server.game.script.ScriptContext
import de.fiereu.openmmo.story.generated.hoenn.HoennFlags import de.fiereu.openmmo.story.generated.hoenn.HoennFlags
import de.fiereu.openmmo.story.generated.hoenn.HoennVars
// Decomp local id of mom in this map's object events (LOCALID_LITTLEROOT_MOM).
private const val LOCALID_MOM = 3
/** /**
* Not ported yet. Decomp body: * Not ported yet. Decomp body:
@@ -39,6 +49,26 @@ internal object LittlerootTown_OnTransition : Script {
} }
} }
/**
* The intro cutscene, run from the on-frame table when VAR_LITTLEROOT_INTRO_STATE is 1 (the player
* just stepped off the truck). Lean port of LittlerootTown_EventScript_StepOffTruckMale plus
* GoInsideWithMom: mom comes out and greets the player, then the intro advances so it plays once.
*/
internal object LittlerootTown_EventScript_StepOffTruckMale : Script {
override suspend fun run(ctx: ScriptContext) {
ctx.showNpc(LOCALID_MOM)
ctx.moveNpc(LOCALID_MOM, WALK_DOWN, WALK_DOWN, WALK_LEFT, FACE_LEFT)
ctx.say(LittlerootTown.OurNewHomeLetsGoInside)
// Mom walks back to her door and steps inside (goes invisible).
ctx.moveNpc(LOCALID_MOM, WALK_RIGHT, WALK_UP, WALK_UP, SET_INVISIBLE)
ctx.setVar(HoennVars.VAR_LITTLEROOT_INTRO_STATE, 3)
// TODO Finish the Littleroot intro cutscene
// Port the rest of GoInsideWithMom: the player jumping off the truck, the door open/close
// animations, the player following mom into the house, and the warpsilent inside. These need
// door, hideplayer, warpsilent and sound-effect script verbs.
}
}
internal object LittlerootTown_EventScript_FatMan : Script { internal object LittlerootTown_EventScript_FatMan : Script {
override suspend fun run(ctx: ScriptContext) = ctx.say(LittlerootTown.CanUsePCToStoreItems) override suspend fun run(ctx: ScriptContext) = ctx.say(LittlerootTown.CanUsePCToStoreItems)
} }
@@ -116,6 +146,8 @@ internal object LittlerootTown_EventScript_MaysHouseSign : Script {
internal val LittlerootTownScripts: Map<String, Script> = internal val LittlerootTownScripts: Map<String, Script> =
mapOf( mapOf(
"LittlerootTown_OnTransition" to LittlerootTown_OnTransition, "LittlerootTown_OnTransition" to LittlerootTown_OnTransition,
"LittlerootTown_EventScript_StepOffTruckMale" to
LittlerootTown_EventScript_StepOffTruckMale,
"LittlerootTown_EventScript_Twin" to LittlerootTown_EventScript_Twin, "LittlerootTown_EventScript_Twin" to LittlerootTown_EventScript_Twin,
"LittlerootTown_EventScript_FatMan" to LittlerootTown_EventScript_FatMan, "LittlerootTown_EventScript_FatMan" to LittlerootTown_EventScript_FatMan,
"LittlerootTown_EventScript_Boy" to LittlerootTown_EventScript_Boy, "LittlerootTown_EventScript_Boy" to LittlerootTown_EventScript_Boy,
@@ -2,6 +2,7 @@ package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.maps.MapDef import de.fiereu.openmmo.maps.MapDef
import de.fiereu.openmmo.server.game.script.Script
import de.fiereu.openmmo.server.game.script.ScriptRegistry import de.fiereu.openmmo.server.game.script.ScriptRegistry
import de.fiereu.openmmo.server.game.script.ScriptRunner import de.fiereu.openmmo.server.game.script.ScriptRunner
import de.fiereu.openmmo.server.game.session.PlayerState import de.fiereu.openmmo.server.game.session.PlayerState
@@ -22,17 +23,29 @@ class MapScriptService
constructor( constructor(
private val scriptRegistry: ScriptRegistry, private val scriptRegistry: ScriptRegistry,
private val scriptRunner: ScriptRunner, private val scriptRunner: ScriptRunner,
private val storyService: StoryService,
) { ) {
fun onMapEnter(session: SessionContext, state: PlayerState, map: MapDef) { fun onMapEnter(session: SessionContext, state: PlayerState, map: MapDef) {
// A script is already running for this player, do not start a second one on top of it. // A script is already running for this player, do not start a second one on top of it.
if (state.inDialog) return if (state.inDialog) return
val label = map.onTransitionScript val charId = state.characterId
if (label.isEmpty()) return // The on-transition script runs on every entry, then the one on-frame script whose var matches.
val script = scriptRegistry.forLabel(label) val scripts = buildList {
if (script == null) { resolve(map.onTransitionScript)?.let { add(it) }
log.debug { "Map ${map.bankId}:${map.mapId} on-transition script $label is not ported yet" } if (charId != null) {
return map.onFrameScripts
.firstOrNull { storyService.getVar(charId, it.varKey) == it.value }
?.let { resolve(it.script) }
?.let { add(it) }
} }
scriptRunner.run(session, state, script, entityId = -1) }
if (scripts.isNotEmpty()) scriptRunner.runAll(session, state, scripts, entityId = -1)
}
private fun resolve(label: String): Script? {
if (label.isEmpty()) return null
val script = scriptRegistry.forLabel(label)
if (script == null) log.debug { "Map script $label is not ported yet" }
return script
} }
} }
@@ -5,6 +5,7 @@ import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.maps.MapDef import de.fiereu.openmmo.maps.MapDef
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.net.game.packets.EntityFaceTurnPacket import de.fiereu.openmmo.net.game.packets.EntityFaceTurnPacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket
@@ -12,6 +13,7 @@ import de.fiereu.openmmo.net.game.packets.MapData
import de.fiereu.openmmo.net.game.packets.MovementPacket import de.fiereu.openmmo.net.game.packets.MovementPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.StoredCharacter
import io.github.oshai.kotlinlogging.KotlinLogging import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@@ -103,7 +105,9 @@ constructor(
} }
if (warp != null) { if (warp != null) {
log.info { "WARP at ($toX, $toY) facing ${msg.direction}" } log.info { "WARP at ($toX, $toY) facing ${msg.direction}" }
warpService.executeWarp(ctx, charId, warp) // A MAP_DYNAMIC warp (the truck exit) resolves to the destination a script set on the player.
val resolved = if (warp.dynamic) resolveDynamicWarp(stored) else warp
if (resolved != null) warpService.executeWarp(ctx, charId, resolved)
return return
} }
@@ -126,6 +130,27 @@ constructor(
encounterService.onStep(ctx, charId, currentMap, toX, toY) encounterService.onStep(ctx, charId, currentMap, toX, toY)
} }
/**
* Builds the real warp for a MAP_DYNAMIC tile from the destination a script set on the player.
*/
private fun resolveDynamicWarp(stored: StoredCharacter): WarpTile? {
val d = stored.info.dynamicWarp
if (d == null) {
log.warn { "Dynamic warp tile stepped on but no dynamic warp is set for ${stored.info.id}" }
return null
}
return WarpTile(
x = 0,
y = 0,
targetRegionId = d.regionId,
targetBankId = d.bankId,
targetMapId = d.mapId,
targetX = d.x.toInt(),
targetY = d.y.toInt(),
exitFacing = d.facing,
)
}
/** Snap the client back to the position the server considers authoritative. */ /** Snap the client back to the position the server considers authoritative. */
private fun sendPositionReset( private fun sendPositionReset(
ctx: SessionContext, ctx: SessionContext,
@@ -3,6 +3,7 @@ package de.fiereu.openmmo.server.game.services
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.maps.NpcDef
import de.fiereu.openmmo.net.game.packets.NpcSpawnPacket import de.fiereu.openmmo.net.game.packets.NpcSpawnPacket
import io.github.oshai.kotlinlogging.KotlinLogging import io.github.oshai.kotlinlogging.KotlinLogging
import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicLong
@@ -87,8 +88,32 @@ constructor(
} }
for (npc in map.npcs) { for (npc in map.npcs) {
val key = "$bankId:$mapId:${npc.entityIdx}" // Npcs hidden by a story flag stay out of the world until a script shows them.
val entityId = npcEntityIds.getOrPut(key) { npcEntityIdCounter.incrementAndGet() } if (npc.hideFlag.isNotEmpty()) continue
ctx.send(buildSpawnPacket(npc, entityIdFor(bankId, mapId, npc.entityIdx), bankId, mapId))
}
}
/** Allocate (or return) the stable entity id for a map npc by its decomp local id. */
fun entityIdFor(bankId: Int, mapId: Int, entityIdx: Int): Long =
npcEntityIds.getOrPut("$bankId:$mapId:$entityIdx") { npcEntityIdCounter.incrementAndGet() }
/** Spawn a single npc (including a normally hidden one) for one player, for cutscenes. */
fun spawnNpc(ctx: SessionContext, bankId: Int, mapId: Int, localId: Int) {
val npc = mapManager.getMap(1, bankId, mapId)?.npcs?.firstOrNull { it.entityIdx == localId }
if (npc == null) {
log.warn { "spawnNpc: npc $localId not found on $bankId:$mapId" }
return
}
ctx.send(buildSpawnPacket(npc, entityIdFor(bankId, mapId, localId), bankId, mapId))
}
private fun buildSpawnPacket(
npc: NpcDef,
entityId: Long,
bankId: Int,
mapId: Int,
): NpcSpawnPacket {
val movementId = npc.movementType.forRegion(Region.HOENN).id val movementId = npc.movementType.forRegion(Region.HOENN).id
val unk3 = ((movementId and 0xFF) shl 8) or 0x02 val unk3 = ((movementId and 0xFF) shl 8) or 0x02
val unk4 = val unk4 =
@@ -97,8 +122,7 @@ constructor(
} else { } else {
0 0
} }
val spawnPacket = return NpcSpawnPacket(
NpcSpawnPacket(
entityId = entityId, entityId = entityId,
unk1 = 1, unk1 = 1,
unk2 = npc.graphicsId, unk2 = npc.graphicsId,
@@ -113,7 +137,5 @@ constructor(
unk5 = 2, unk5 = 2,
unk6 = 8, unk6 = 8,
) )
ctx.send(spawnPacket)
}
} }
} }
@@ -1,10 +1,10 @@
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.DynamicWarp
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.packets.EntityFaceTurnPacket import de.fiereu.openmmo.net.game.packets.DialogDataPacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.server.game.script.MovementStep import de.fiereu.openmmo.server.game.script.MovementStep
import de.fiereu.openmmo.server.game.session.PlayerState import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.storage.CharacterStore import de.fiereu.openmmo.server.game.storage.CharacterStore
@@ -18,8 +18,8 @@ import kotlinx.coroutines.delay
* which is exactly waitmovement. * which is exactly waitmovement.
* *
* Story cutscenes are per player, so the movement is sent to the acting player only and is not * Story cutscenes are per player, so the movement is sent to the acting player only and is not
* broadcast to other players who happen to share the map. It reuses [EntityMovePacket], the same * broadcast to other players who happen to share the map. The whole action sequence goes in one
* packet the server already uses to show other entities walking. * movement packet, matching what the real client expects (from packet captures).
*/ */
@Singleton @Singleton
class ScriptMovementService class ScriptMovementService
@@ -44,11 +44,25 @@ constructor(
mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId) ?: return mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId) ?: return
val npc = map.npcs.firstOrNull { it.entityIdx == localId } ?: return val npc = map.npcs.firstOrNull { it.entityIdx == localId } ?: return
val entityId = val entityId =
npcService.getNpcEntityId(info.positionBankId.toInt(), info.positionMapId.toInt(), localId) npcService.entityIdFor(info.positionBankId.toInt(), info.positionMapId.toInt(), localId)
?: return
drive(session, entityId, Pose(npc.x, npc.y, npc.facing), steps) drive(session, entityId, Pose(npc.x, npc.y, npc.facing), steps)
} }
/** Show a normally hidden map npc to the player for a cutscene (the decomp addobject). */
fun showNpc(session: SessionContext, state: PlayerState, localId: Int) {
val charId = state.characterId ?: return
val info = characterStore.getCharacter(charId)?.info ?: return
npcService.spawnNpc(session, info.positionBankId.toInt(), info.positionMapId.toInt(), localId)
}
/**
* Set the destination a MAP_DYNAMIC warp resolves to for this player (the decomp setdynamicwarp).
*/
fun setDynamicWarp(state: PlayerState, warp: DynamicWarp) {
val charId = state.characterId ?: return
characterStore.setDynamicWarp(charId, warp)
}
/** Walk the player's own avatar through [steps] and commit the final tile as authoritative. */ /** Walk the player's own avatar through [steps] and commit the final tile as authoritative. */
suspend fun moveSelf( suspend fun moveSelf(
session: SessionContext, session: SessionContext,
@@ -74,26 +88,25 @@ constructor(
start: Pose, start: Pose,
steps: List<MovementStep>, steps: List<MovementStep>,
): Pose { ): Pose {
if (steps.isEmpty()) return start
// The whole sequence goes in one movement packet (entityId, startIndex 0, count, action bytes).
// The client walks/turns the entity itself, so no coords are sent.
val actions = ByteArray(steps.size) { steps[it].action.toByte() }
session.send(DialogDataPacket(entityId, unk1 = 0, type = steps.size, data = actions))
// waitmovement: hold until the client has had time to play the sequence.
delay(steps.sumOf { if (it.walks) WALK_STEP_MS else FACE_STEP_MS })
var pose = start var pose = start
for (step in steps) { for (step in steps) {
pose = pose =
if (step.walks) { if (step.walks)
val nx = pose.x + step.direction.dx Pose(pose.x + step.direction.dx, pose.y + step.direction.dy, step.direction)
val ny = pose.y + step.direction.dy else pose.copy(facing = step.direction)
session.send(EntityMovePacket(entityId, nx, ny, step.direction))
delay(WALK_STEP_MS)
Pose(nx, ny, step.direction)
} else {
session.send(EntityFaceTurnPacket(entityId, step.direction.ordinal.toByte()))
delay(FACE_STEP_MS)
pose.copy(facing = step.direction)
}
} }
return pose return pose
} }
private companion object { private companion object {
// Rough GBA step timings, tune against the client if the animation and server drift apart. // Rough client step timings, tune if the animation and server drift apart.
const val WALK_STEP_MS = 250L const val WALK_STEP_MS = 250L
const val FACE_STEP_MS = 120L const val FACE_STEP_MS = 120L
} }
@@ -41,7 +41,8 @@ constructor(
WarpExitRules.getKnownOverride(sourceMap, destMap, warp.targetX, warp.targetY) WarpExitRules.getKnownOverride(sourceMap, destMap, warp.targetX, warp.targetY)
val warpFacing = val warpFacing =
knownOverride?.facing warp.exitFacing
?: knownOverride?.facing
?: WarpExitRules.inferExitFacing( ?: WarpExitRules.inferExitFacing(
destTileBehavior = null, destTileBehavior = null,
destMap = destMap, destMap = destMap,
@@ -1,8 +1,10 @@
package de.fiereu.openmmo.server.game.storage package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.DynamicWarp
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.Direction
import de.fiereu.openmmo.common.enums.EVs import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.IVs import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
@@ -160,6 +162,12 @@ constructor(
repelItemId = repelItemId, repelItemId = repelItemId,
lureLeft = lureLeft, lureLeft = lureLeft,
lureItemId = lureItemId, lureItemId = lureItemId,
dynamicWarpRegion = dynamicWarp?.regionId?.toShort(),
dynamicWarpBank = dynamicWarp?.bankId?.toShort(),
dynamicWarpMap = dynamicWarp?.mapId?.toShort(),
dynamicWarpX = dynamicWarp?.x,
dynamicWarpY = dynamicWarp?.y,
dynamicWarpFacing = dynamicWarp?.facing?.ordinal?.toShort(),
) )
private fun CharactersRecord.toInfo(): CharacterInfo = private fun CharactersRecord.toInfo(): CharacterInfo =
@@ -187,8 +195,26 @@ constructor(
repelItemId = repelItemId, repelItemId = repelItemId,
lureLeft = lureLeft, lureLeft = lureLeft,
lureItemId = lureItemId, lureItemId = lureItemId,
dynamicWarp = toDynamicWarp(),
) )
private fun CharactersRecord.toDynamicWarp(): DynamicWarp? {
val region = dynamicWarpRegion ?: return null
val bank = dynamicWarpBank ?: return null
val map = dynamicWarpMap ?: return null
val x = dynamicWarpX ?: return null
val y = dynamicWarpY ?: return null
val facing = dynamicWarpFacing ?: return null
return DynamicWarp(
regionId = region.toByte(),
bankId = bank.toByte(),
mapId = map.toByte(),
x = x,
y = y,
facing = Direction.entries[facing.toInt()],
)
}
private fun Pokemon.toRecord(): PokemonRecord = private fun Pokemon.toRecord(): PokemonRecord =
PokemonRecord( PokemonRecord(
id = id, id = id,
@@ -1,7 +1,10 @@
package de.fiereu.openmmo.server.game.storage package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.Pokemon import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.story.generated.hoenn.HoennVars
import io.github.oshai.kotlinlogging.KotlinLogging import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
@@ -80,17 +83,30 @@ constructor(
pcExtraSlots = 0, pcExtraSlots = 0,
battleBoxExtraSlots = 0, battleBoxExtraSlots = 0,
templateAmount = 0, templateAmount = 0,
// New characters start inside the moving truck (InsideOfTruck, bank 75 map 40). Walking
// out warps to Littleroot, where the intro var below drives the mom cutscene.
positionRegionId = 1, positionRegionId = 1,
positionBankId = 51, positionBankId = 75,
positionMapId = 3, positionMapId = 40,
positionX = 4, positionX = 2,
positionY = 4, positionY = 2,
repelLeft = 0, repelLeft = 0,
repelItemId = 0, repelItemId = 0,
lureLeft = 0, lureLeft = 0,
lureItemId = 0, lureItemId = 0,
// The truck's exit is a MAP_DYNAMIC warp. Point it at Littleroot Town for the intro,
// the
// same thing the decomp setdynamicwarp does at new game. Facing right off the truck.
dynamicWarp = DynamicWarp(1, 50, 9, 3, 10, Direction.RIGHT),
) )
val stored = StoredCharacter(info, mutableListOf(), mutableListOf(), mutableMapOf()) // Male intro path. Gender selection is not implemented yet, so everyone takes the male branch.
// TODO Support the female intro path
// Add character gender (checkplayergender) so new characters can take the female Littleroot
// intro (VAR_LITTLEROOT_INTRO_STATE = 2, May's house at 12,10) instead of always the male one.
val storyVars = mutableMapOf(HoennVars.VAR_LITTLEROOT_INTRO_STATE to 1)
val stored =
StoredCharacter(
info, mutableListOf(), mutableListOf(), mutableMapOf(), storyVars = storyVars)
repository.insertAggregate(stored) repository.insertAggregate(stored)
characters[id] = stored characters[id] = stored
charactersByUser.computeIfAbsent(userId) { CopyOnWriteArrayList() }.add(id) charactersByUser.computeIfAbsent(userId) { CopyOnWriteArrayList() }.add(id)
@@ -169,6 +185,13 @@ constructor(
markDirty(characterId) markDirty(characterId)
} }
/** Set (or clear with null) the runtime destination for MAP_DYNAMIC warps (setdynamicwarp). */
fun setDynamicWarp(characterId: Long, warp: DynamicWarp?) {
val stored = characters[characterId] ?: return
characters[characterId] = stored.copy(info = stored.info.copy(dynamicWarp = warp))
markDirty(characterId)
}
/** Set a story flag. Copies the set so flusher snapshots never see a half-updated collection. */ /** Set a story flag. Copies the set so flusher snapshots never see a half-updated collection. */
fun setStoryFlag(characterId: Long, flag: String) { fun setStoryFlag(characterId: Long, flag: String) {
val stored = characters[characterId] ?: return val stored = characters[characterId] ?: return
@@ -0,0 +1,10 @@
-- Runtime warp destination set by a script (the decomp setdynamicwarp). A MAP_DYNAMIC warp tile
-- resolves to this when the player steps on it. All null means no dynamic warp is set.
ALTER TABLE characters
ADD COLUMN dynamic_warp_region SMALLINT,
ADD COLUMN dynamic_warp_bank SMALLINT,
ADD COLUMN dynamic_warp_map SMALLINT,
ADD COLUMN dynamic_warp_x SMALLINT,
ADD COLUMN dynamic_warp_y SMALLINT,
ADD COLUMN dynamic_warp_facing SMALLINT;
@@ -2,8 +2,7 @@ package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.packets.EntityFaceTurnPacket import de.fiereu.openmmo.net.game.packets.DialogDataPacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.server.game.script.MovementStep import de.fiereu.openmmo.server.game.script.MovementStep
import de.fiereu.openmmo.server.game.storage.CharacterStore import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService import de.fiereu.openmmo.server.game.storage.EntityIdService
@@ -40,12 +39,8 @@ class ScriptMovementServiceTest :
) )
end shouldBe ScriptMovementService.Pose(4, 3, Direction.LEFT) end shouldBe ScriptMovementService.Pose(4, 3, Direction.LEFT)
session.sent shouldBe // One movement packet carrying walk_up, walk_up, walk_left (0x11, 0x11, 0x12).
listOf( session.sent shouldBe listOf(DialogDataPacket(42L, 0, 3, byteArrayOf(0x11, 0x11, 0x12)))
EntityMovePacket(42L, 5, 4, Direction.UP),
EntityMovePacket(42L, 5, 3, Direction.UP),
EntityMovePacket(42L, 4, 3, Direction.LEFT),
)
} }
} }
@@ -58,7 +53,8 @@ class ScriptMovementServiceTest :
val end = service(store).drive(session, 7L, start, listOf(MovementStep.FACE_RIGHT)) val end = service(store).drive(session, 7L, start, listOf(MovementStep.FACE_RIGHT))
end shouldBe ScriptMovementService.Pose(8, 2, Direction.RIGHT) end shouldBe ScriptMovementService.Pose(8, 2, Direction.RIGHT)
session.sent shouldBe listOf(EntityFaceTurnPacket(7L, Direction.RIGHT.ordinal.toByte())) // One movement packet carrying face_right (0x03).
session.sent shouldBe listOf(DialogDataPacket(7L, 0, 1, byteArrayOf(0x03)))
} }
} }
@@ -67,7 +67,8 @@ class StoryServiceTest :
store.flushAll() store.flushAll()
repo.saved[id]!!.storyFlags shouldBe setOf("hoenn/FLAG_ADVENTURE_STARTED") repo.saved[id]!!.storyFlags shouldBe setOf("hoenn/FLAG_ADVENTURE_STARTED")
repo.saved[id]!!.storyVars shouldBe mapOf("hoenn/VAR_LITTLEROOT_TOWN_STATE" to 4) // New characters are seeded with the intro var, so check the entry rather than the map.
repo.saved[id]!!.storyVars["hoenn/VAR_LITTLEROOT_TOWN_STATE"] shouldBe 4
} }
} }
}) })