fix(game): stop running the warp arrival twice (#94)

* fix(game): use the npc's own region for map and sprite lookups

* fix(game): trigger warps by their tile behaviour

* fix(game): classify every warp metatile behaviour the decomp accepts

* fix(game): stop running the warp arrival twice

* fix(game): stop a failed warp from freezing the player and leaking its old map

* fix(game): give every warp a deadline and hand the map group over on arrival

* fix(game): check the warp target first and stop the deadline outliving the session
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-07 16:14:51 +02:00
1 parent 085407ccf1
commit b615b65334
8 files changed
+476 -55

No files matched your search

@@ -184,7 +184,7 @@ internal constructor(
regionId.toByte(), bankId.toByte(), mapId.toByte(), x.toShort(), y.toShort(), facing)) regionId.toByte(), bankId.toByte(), mapId.toByte(), x.toShort(), y.toShort(), facing))
/** Warps the player without door movement. */ /** Warps the player without door movement. */
fun warp(regionId: Int, bankId: Int, mapId: Int, x: Int, y: Int, facing: Direction) { suspend fun warp(regionId: Int, bankId: Int, mapId: Int, x: Int, y: Int, facing: Direction) {
checkNotNull(warp) { "Script warp service is unavailable" } checkNotNull(warp) { "Script warp service is unavailable" }
.warp( .warp(
session, session,
@@ -34,6 +34,7 @@ import de.fiereu.openmmo.net.game.packets.ViewScalePacket
import de.fiereu.openmmo.net.game.packets.WorldFlagTableResetPacket import de.fiereu.openmmo.net.game.packets.WorldFlagTableResetPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleRatingBulkPacket import de.fiereu.openmmo.net.game.packets.battle.BattleRatingBulkPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleStateBytePacket import de.fiereu.openmmo.net.game.packets.battle.BattleStateBytePacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.PlayerState import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.session.SessionRegistry import de.fiereu.openmmo.server.game.session.SessionRegistry
@@ -330,6 +331,11 @@ constructor(
log.warn { "RequestPlayer without active character" } log.warn { "RequestPlayer without active character" }
return return
} }
// The client asks for its player once a map transition is done, so the warp ends here. The
// waiter is only cleared at the end, so a throw in between leaves the deadline to rescue it.
state.justWarped = false
val pendingLoad = ctx.attributes[PENDING_MAP_LOAD]
val stored = characterStore.getCharacter(charId) val stored = characterStore.getCharacter(charId)
if (stored == null) { if (stored == null) {
log.warn { "RequestPlayer for unknown character $charId" } log.warn { "RequestPlayer for unknown character $charId" }
@@ -339,7 +345,8 @@ constructor(
log.info { "Sending LoadEntity for character '${info.name}'" } log.info { "Sending LoadEntity for character '${info.name}'" }
val facing = state.facingDirection val facing = state.facingDirection
val loadEntity = mapLoadService.createLoadEntity(info, facing, party = stored.pokemon) val loadEntity =
mapLoadService.createLoadEntity(info, facing, state.elevation, party = stored.pokemon)
ctx.send(loadEntity) ctx.send(loadEntity)
npcService.spawnNpcsForMap( npcService.spawnNpcsForMap(
@@ -358,15 +365,19 @@ constructor(
state.x = info.positionX state.x = info.positionX
state.y = info.positionY state.y = info.positionY
// The client dropped its entities with the map cache, so always re-exchange snapshots.
presenceService.enter(ctx) presenceService.enter(ctx)
ctx.send(RenderScreenPacket(true)) ctx.send(RenderScreenPacket(true))
// An entry script may fade back out, so it runs after the fade this arrival owns.
mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId)?.let { map -> mapManager.getMap(info.positionRegionId, info.positionBankId, info.positionMapId)?.let { map ->
mapScriptService.onMapEnter(ctx, state, map) mapScriptService.onMapEnter(ctx, state, map)
} }
socialService.sendFriendList(ctx) socialService.sendFriendList(ctx)
if (ctx.attributes[PENDING_MAP_LOAD] === pendingLoad) ctx.attributes.remove(PENDING_MAP_LOAD)
pendingLoad?.complete(Unit)
log.info { "Player $charId spawned in bank=$bankId map=$mapId" } log.info { "Player $charId spawned in bank=$bankId map=$mapId" }
} }
@@ -95,9 +95,9 @@ constructor(
val atServerTile = msg.x == fromX && msg.y == fromY val atServerTile = msg.x == fromX && msg.y == fromY
if (state.justWarped) { if (state.justWarped) {
// Drop movement packets sent before the warp completed. // Drop every step until the client asks for its player, else one left over from the old map
if (!atServerTile) return // can fire a second warp.
state.justWarped = false return
} else if (!atServerTile) { } else if (!atServerTile) {
log.debug { log.debug {
"DESYNC: char=$charId claims (${msg.x}, ${msg.y}), server has ($fromX, $fromY), resetting" "DESYNC: char=$charId claims (${msg.x}, ${msg.y}), server has ($fromX, $fromY), resetting"
@@ -7,10 +7,20 @@ import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionKind import de.fiereu.openmmo.net.game.packets.MapTransitionKind
import de.fiereu.openmmo.net.game.packets.MapTransitionPacket import de.fiereu.openmmo.net.game.packets.MapTransitionPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
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
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeoutOrNull
private val log = KotlinLogging.logger {}
// A cutscene must not hang if the client never answers the transition.
private val MAP_LOAD_TIMEOUT = 10.seconds
/** A direct, no-auto-step warp for cutscenes (the decomp's `warpsilent`). */ /** A direct, no-auto-step warp for cutscenes (the decomp's `warpsilent`). */
@Singleton @Singleton
@@ -21,17 +31,22 @@ constructor(
private val mapLoadService: MapLoadService, private val mapLoadService: MapLoadService,
private val characterStore: CharacterStore, private val characterStore: CharacterStore,
private val presenceService: PresenceService, private val presenceService: PresenceService,
private val npcService: NpcService,
) { ) {
fun warp( /** Warps and waits until the client has loaded the destination, so the script can go on. */
suspend fun warp(
session: SessionContext, session: SessionContext,
state: PlayerState, state: PlayerState,
destination: DynamicWarp, destination: DynamicWarp,
) { ) {
val characterId = state.characterId ?: return val characterId = state.characterId ?: return
val stored = characterStore.getCharacter(characterId) ?: return val stored = characterStore.getCharacter(characterId) ?: return
val map = val map = mapManager.getMap(destination.regionId, destination.bankId, destination.mapId)
mapManager.getMap(destination.regionId, destination.bankId, destination.mapId) ?: return if (map == null) {
log.warn {
"Map not found for scripted warp ${destination.regionId}:${destination.bankId}:${destination.mapId}"
}
return
}
val info = val info =
stored.info.copy( stored.info.copy(
positionRegionId = destination.regionId, positionRegionId = destination.regionId,
@@ -44,27 +59,40 @@ constructor(
characterStore.updateCharacter(info) characterStore.updateCharacter(info)
characterStore.flushCharacterAsync(characterId) characterStore.flushCharacterAsync(characterId)
state.justWarped = true state.justWarped = true
// Leave now, so the old map's observers do not keep a ghost for the whole transition.
presenceService.leave(session)
state.regionId = destination.regionId.toInt() state.regionId = destination.regionId.toInt()
state.bankId = destination.bankId.toInt() state.bankId = destination.bankId.toInt()
state.mapId = destination.mapId.toInt() state.mapId = destination.mapId.toInt()
state.x = destination.x state.x = destination.x
state.y = destination.y state.y = destination.y
state.elevation = map.tileAt(destination.x.toInt(), destination.y.toInt())?.elevation ?: 0
state.facingDirection = destination.facing state.facingDirection = destination.facing
val loaded = CompletableDeferred<Unit>()
session.attributes[PENDING_MAP_LOAD] = loaded
session.send(MapTransitionPacket()) session.send(MapTransitionPacket())
session.send(RenderScreenPacket(false)) session.send(RenderScreenPacket(false))
session.send(MapTransitionAckPacket(MapTransitionKind.WARP)) session.send(MapTransitionAckPacket(MapTransitionKind.WARP))
mapLoadService.resetClientCache(session, map) mapLoadService.resetClientCache(session, map)
session.send(mapManager.createLoadMapPacket(map, reloadPlayer = true, deleteCache = true)) session.send(mapManager.createLoadMapPacket(map, reloadPlayer = true, deleteCache = true))
mapLoadService.preloadConnectedMaps(session, map, depth = 1, reloadPlayer = true) mapLoadService.preloadConnectedMaps(session, map, depth = 1, reloadPlayer = true)
session.send(mapLoadService.createLoadEntity(info, destination.facing))
npcService.spawnNpcsForMap( try {
session, if (withTimeoutOrNull(MAP_LOAD_TIMEOUT) { loaded.await() } == null) {
destination.bankId.toInt(), log.warn {
destination.mapId.toInt(), "Character $characterId did not load ${destination.bankId}:${destination.mapId}"
destination.regionId.toInt(), }
) // No arrival will follow, so give the screen and the map group back here.
presenceService.refresh(session) state.justWarped = false
session.send(RenderScreenPacket(true)) session.send(RenderScreenPacket(true))
presenceService.enter(session)
}
} finally {
if (session.attributes[PENDING_MAP_LOAD] === loaded) {
session.attributes.remove(PENDING_MAP_LOAD)
}
}
} }
} }
@@ -8,15 +8,28 @@ import de.fiereu.openmmo.net.game.packets.MapTransitionAckPacket
import de.fiereu.openmmo.net.game.packets.MapTransitionKind import de.fiereu.openmmo.net.game.packets.MapTransitionKind
import de.fiereu.openmmo.net.game.packets.MapTransitionPacket import de.fiereu.openmmo.net.game.packets.MapTransitionPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.session.PlayerState
import de.fiereu.openmmo.server.game.session.SCRIPT_SCOPE
import de.fiereu.openmmo.server.game.storage.CharacterStore import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.WarpExitRules import de.fiereu.openmmo.server.game.world.WarpExitRules
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
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
private val log = KotlinLogging.logger {} private val log = KotlinLogging.logger {}
// A player must not stay gated if the client never answers the transition.
private val ARRIVAL_TIMEOUT = 10.seconds
@Singleton @Singleton
class WarpService class WarpService
@Inject @Inject
@@ -25,22 +38,32 @@ constructor(
private val mapManager: MapManager, private val mapManager: MapManager,
private val characterStore: CharacterStore, private val characterStore: CharacterStore,
private val presenceService: PresenceService, private val presenceService: PresenceService,
private val mapScriptService: MapScriptService,
) { ) {
fun executeWarp(ctx: SessionContext, charId: Long, warp: WarpTile) { fun executeWarp(ctx: SessionContext, charId: Long, warp: WarpTile) {
val state = ctx.attributes[PLAYER_STATE] val state = ctx.attributes[PLAYER_STATE]
state?.justWarped = true
val stored = characterStore.getCharacter(charId) ?: return val stored = characterStore.getCharacter(charId) ?: return
// Check the map first. Moving the player onto one we do not have would strand it there.
val destMap = mapManager.getMap(warp.targetRegionId, warp.targetBankId, warp.targetMapId) val destMap = mapManager.getMap(warp.targetRegionId, warp.targetBankId, warp.targetMapId)
if (destMap == null) {
log.warn {
"Map not found for warp target ${warp.targetRegionId}:${warp.targetBankId}:${warp.targetMapId}"
}
return
}
state?.justWarped = true
// Leave now, so the old map's observers do not keep a ghost for the whole transition.
presenceService.leave(ctx)
val sourceMap = val sourceMap =
mapManager.getMap( mapManager.getMap(
stored.info.positionRegionId, stored.info.positionBankId, stored.info.positionMapId) stored.info.positionRegionId, stored.info.positionBankId, stored.info.positionMapId)
val knownOverride = val knownOverride =
WarpExitRules.getKnownOverride(sourceMap, destMap, warp.targetX, warp.targetY) WarpExitRules.getKnownOverride(sourceMap, destMap, warp.targetX, warp.targetY)
val destBehavior = destMap?.tileAt(warp.targetX, warp.targetY)?.behavior val destBehavior = destMap.tileAt(warp.targetX, warp.targetY)?.behavior
val warpFacing = val warpFacing =
warp.exitFacing warp.exitFacing
@@ -65,7 +88,7 @@ constructor(
destMap = destMap, destMap = destMap,
destTileBehavior = destBehavior, destTileBehavior = destBehavior,
) )
if (shouldAutoStepOffWarp && destMap != null) { if (shouldAutoStepOffWarp) {
val destWarp = destMap.warps.find { it.x == offsetX && it.y == offsetY } val destWarp = destMap.warps.find { it.x == offsetX && it.y == offsetY }
if (destWarp != null) { if (destWarp != null) {
offsetX += offsetX +=
@@ -86,11 +109,11 @@ constructor(
} }
val playerZ = val playerZ =
destMap?.warps?.find { it.x == warp.targetX && it.y == warp.targetY }?.elevation destMap.warps.find { it.x == warp.targetX && it.y == warp.targetY }?.elevation
?: warp.targetElevation ?: warp.targetElevation
log.info { log.info {
"WARP EXIT: source=${sourceMap?.bankId}:${sourceMap?.mapId} dest=${destMap?.bankId}:${destMap?.mapId} target=(${warp.targetX},${warp.targetY}) final=($offsetX,$offsetY) z=$playerZ facing=$warpFacing autoStep=$shouldAutoStepOffWarp" "WARP EXIT: source=${sourceMap?.bankId}:${sourceMap?.mapId} dest=${destMap.bankId}:${destMap.mapId} target=(${warp.targetX},${warp.targetY}) final=($offsetX,$offsetY) z=$playerZ facing=$warpFacing autoStep=$shouldAutoStepOffWarp"
} }
val newInfo = val newInfo =
@@ -110,31 +133,44 @@ constructor(
state.mapId = warp.targetMapId.toInt() state.mapId = warp.targetMapId.toInt()
state.x = offsetX.toShort() state.x = offsetX.toShort()
state.y = offsetY.toShort() state.y = offsetY.toShort()
state.elevation = playerZ
} }
// Only fade out and send the map. onRequestPlayer does the arrival and fades back in.
ctx.send(MapTransitionPacket()) ctx.send(MapTransitionPacket())
ctx.send(RenderScreenPacket(false)) ctx.send(RenderScreenPacket(false))
ctx.send(MapTransitionAckPacket(MapTransitionKind.WARP)) ctx.send(MapTransitionAckPacket(MapTransitionKind.WARP))
if (destMap != null) { mapLoadService.resetClientCache(ctx, destMap)
mapLoadService.resetClientCache(ctx, destMap) ctx.send(mapManager.createLoadMapPacket(destMap, reloadPlayer = true, deleteCache = true))
ctx.send(mapManager.createLoadMapPacket(destMap, reloadPlayer = true, deleteCache = true)) mapLoadService.preloadConnectedMaps(ctx, destMap, depth = 1, reloadPlayer = true)
mapLoadService.preloadConnectedMaps(ctx, destMap, depth = 1, reloadPlayer = true) if (state != null) awaitArrival(ctx, state, charId)
} else {
log.warn {
"Map not found for warp target ${warp.targetRegionId}:${warp.targetBankId}:${warp.targetMapId}"
}
}
// Release the fade after loading the destination.
ctx.send(mapLoadService.createLoadEntity(newInfo, warpFacing, playerZ))
presenceService.refresh(ctx)
if (state != null && destMap != null) mapScriptService.onMapEnter(ctx, state, destMap)
ctx.send(RenderScreenPacket(true))
log.info { "Player $charId warped to bank=${warp.targetBankId} map=${warp.targetMapId}" } log.info { "Player $charId warped to bank=${warp.targetBankId} map=${warp.targetMapId}" }
} }
/**
* Releases the player if the client never asks for it. Without this a lost RequestPlayer leaves
* the player faded out and unable to move for the rest of the session.
*/
private fun awaitArrival(ctx: SessionContext, state: PlayerState, charId: Long) {
val loaded = CompletableDeferred<Unit>()
ctx.attributes[PENDING_MAP_LOAD] = loaded
// The session's own scope, so a disconnect cancels this instead of reviving a dead session.
val scope =
ctx.attributes.getOrPut(SCRIPT_SCOPE) {
CoroutineScope(SupervisorJob() + Dispatchers.Default)
}
scope.launch {
if (withTimeoutOrNull(ARRIVAL_TIMEOUT) { loaded.await() } != null) return@launch
// A newer warp owns the gate now, leave it to its own deadline.
if (ctx.attributes[PENDING_MAP_LOAD] !== loaded) return@launch
if (!ctx.channel.isActive) return@launch
ctx.attributes.remove(PENDING_MAP_LOAD)
log.warn { "Character $charId never asked for its player after a warp" }
state.justWarped = false
ctx.send(RenderScreenPacket(true))
presenceService.enter(ctx)
}
}
} }
@@ -1,24 +1,30 @@
package de.fiereu.openmmo.server.game.session package de.fiereu.openmmo.server.game.session
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import java.util.concurrent.ConcurrentHashMap
/**
* Per-session player state. Scripts run on their own coroutine while packets are answered on the
* mailbox coroutine, and both threads touch every field here, so all of them are volatile.
*/
data class PlayerState( data class PlayerState(
val userId: Int, val userId: Int,
var characterId: Long? = null, @field:Volatile var characterId: Long? = null,
var justWarped: Boolean = false, @field:Volatile var justWarped: Boolean = false,
var facingDirection: Direction = Direction.DOWN, @field:Volatile var facingDirection: Direction = Direction.DOWN,
var inDialog: Boolean = false, @field:Volatile var inDialog: Boolean = false,
var dialogNpcEntityId: Long = 0, @field:Volatile var dialogNpcEntityId: Long = 0,
var dialogSeqId: Int = 0, @field:Volatile var dialogSeqId: Int = 0,
var regionId: Int = 1, @field:Volatile var regionId: Int = 1,
var bankId: Int = 51, @field:Volatile var bankId: Int = 51,
var mapId: Int = 3, @field:Volatile var mapId: Int = 3,
var x: Short = 4, @field:Volatile var x: Short = 4,
var y: Short = 2, @field:Volatile var y: Short = 2,
@field:Volatile var elevation: Int = 0,
/** Trusts one source tile after scripted movement. */ /** Trusts one source tile after scripted movement. */
var acceptNextMoveSource: Boolean = false, @field:Volatile var acceptNextMoveSource: Boolean = false,
/** Maps the client already holds. A warp sends deleteCache, which empties this. */ /** Maps the client already holds. A warp sends deleteCache, which empties this. */
val loadedMaps: MutableSet<Int> = mutableSetOf(), val loadedMaps: MutableSet<Int> = ConcurrentHashMap.newKeySet(),
) )
/** Packs a map address into one key for [PlayerState.loadedMaps]. */ /** Packs a map address into one key for [PlayerState.loadedMaps]. */
@@ -14,5 +14,8 @@ val PENDING_DIALOG = SessionAttribute.of<CompletableDeferred<Unit>>("pendingDial
val PENDING_DIALOG_RESPONSE = val PENDING_DIALOG_RESPONSE =
SessionAttribute.of<CompletableDeferred<DialogActionResponsePacket>>("pendingDialogResponse") SessionAttribute.of<CompletableDeferred<DialogActionResponsePacket>>("pendingDialogResponse")
/** Completed when the client has asked for its player again, which ends a map transition. */
val PENDING_MAP_LOAD = SessionAttribute.of<CompletableDeferred<Unit>>("pendingMapLoad")
/** Scope the connection's scripts run in. Cancelled on disconnect so a waiting script unwinds. */ /** Scope the connection's scripts run in. Cancelled on disconnect so a waiting script unwinds. */
val SCRIPT_SCOPE = SessionAttribute.of<CoroutineScope>("scriptScope") val SCRIPT_SCOPE = SessionAttribute.of<CoroutineScope>("scriptScope")
@@ -0,0 +1,337 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.LoadMapPacket
import de.fiereu.openmmo.net.game.packets.RenderScreenPacket
import de.fiereu.openmmo.server.game.session.PENDING_MAP_LOAD
import de.fiereu.openmmo.server.game.session.SCRIPT_SCOPE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
// No map is registered here, so a warp aimed at it cannot complete.
private const val MISSING_BANK: Byte = 120
private const val MISSING_MAP: Byte = 120
// Longer than either warp service waits for the client.
private val ARRIVAL_DEADLINE_PASSED = 15.seconds
private fun littlerootTown() =
DynamicWarp(
regionId = 1,
bankId = 50,
mapId = 9,
x = 5,
y = 8,
facing = Direction.DOWN,
)
private fun warpTo(bankId: Byte, mapId: Byte) =
WarpTile(
x = 0,
y = 0,
targetRegionId = 1,
targetBankId = bankId,
targetMapId = mapId,
targetX = 5,
targetY = 8,
)
@OptIn(ExperimentalCoroutinesApi::class)
class WarpArrivalTest :
FunSpec({
/** Every service a warp touches, sharing one interest manager. */
class Fixture(store: CharacterStore) {
val mapManager = MapManager()
val mapLoad = MapLoadService(mapManager)
val presence =
PresenceService(InterestManager(), PassThroughInterestPolicy(), mapLoad, store)
val warps = WarpService(mapLoad, mapManager, store, presence)
val scriptWarps = ScriptWarpService(mapManager, mapLoad, store, presence)
}
/** The warp deadline runs on the session's scope, which a disconnect cancels. */
fun FakeSession.useScope(scope: CoroutineScope) = also { attributes[SCRIPT_SCOPE] = scope }
suspend fun CharacterStore.player(name: String = "May") =
createCharacter(1, name, CharacterGender.FEMALE, Region.HOENN).info.id
test("a warp gates movement until the client asks for its player") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
session.state().justWarped shouldBe true
session.sent.filterIsInstance<RenderScreenPacket>() shouldBe
listOf(RenderScreenPacket(false))
}
}
test("a warp the client never answers gives movement back") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
advanceTimeBy(ARRIVAL_DEADLINE_PASSED)
runCurrent()
session.state().justWarped shouldBe false
session.attributes[PENDING_MAP_LOAD] shouldBe null
session.sent.filterIsInstance<RenderScreenPacket>().last() shouldBe
RenderScreenPacket(true)
}
}
test("an arrival cancels the deadline of the warp it belongs to") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
// What onRequestPlayer does on arrival.
session.state().justWarped = false
session.attributes.remove(PENDING_MAP_LOAD)!!.complete(Unit)
advanceUntilIdle()
session.state().justWarped shouldBe false
session.sent.filterIsInstance<RenderScreenPacket>() shouldBe
listOf(RenderScreenPacket(false))
}
}
test("a second warp keeps the gate its predecessor's deadline would have opened") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
val first = session.attributes[PENDING_MAP_LOAD]
f.warps.executeWarp(session, charId, warpTo(51, 3))
runCurrent()
(session.attributes[PENDING_MAP_LOAD] === first) shouldBe false
// The second warp arrives, then the first one's deadline passes.
session.state().justWarped = false
session.attributes.remove(PENDING_MAP_LOAD)!!.complete(Unit)
session.sent.clear()
advanceTimeBy(ARRIVAL_DEADLINE_PASSED)
runCurrent()
session.sent shouldBe emptyList()
}
}
test("a warp to a map that is not loaded leaves the player where it was") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.mapManager.getMap(1, MISSING_BANK, MISSING_MAP) shouldBe null
val before = store.getCharacter(charId)!!.info
f.warps.executeWarp(session, charId, warpTo(MISSING_BANK, MISSING_MAP))
advanceUntilIdle()
session.state().justWarped shouldBe false
session.state().mapId shouldBe 3
store.getCharacter(charId)!!.info.positionMapId shouldBe before.positionMapId
session.sent shouldBe emptyList()
}
}
test("a warp for an unknown character does not gate movement") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val session = FakeSession(characterId = 404).useScope(backgroundScope)
val f = Fixture(store)
f.warps.executeWarp(session, 404, warpTo(50, 9))
advanceUntilIdle()
session.state().justWarped shouldBe false
session.sent shouldBe emptyList()
}
}
test("a disconnect during the transition cancels the deadline") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val scope = CoroutineScope(backgroundScope.coroutineContext + Job())
val session = FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(scope)
val f = Fixture(store)
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
// What onInactive does.
scope.cancel()
session.sent.clear()
advanceTimeBy(ARRIVAL_DEADLINE_PASSED)
runCurrent()
session.sent shouldBe emptyList()
}
}
test("a warp carries the elevation of its destination to the arrival") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
val stairs = f.mapManager.getMap(1, 51, 3)!!.warps.first()
f.warps.executeWarp(
session,
charId,
warpTo(51, 3).copy(targetX = stairs.x, targetY = stairs.y, targetElevation = 3),
)
runCurrent()
session.state().elevation shouldBe (stairs.elevation)
}
}
test("warping despawns the player from the map it left right away") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player("May")
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val watcher = FakeSession(characterId = store.player("Brendan"), bankId = 51, mapId = 3)
val f = Fixture(store)
f.presence.enter(session)
f.presence.enter(watcher)
watcher.sent.clear()
f.warps.executeWarp(session, charId, warpTo(50, 9))
runCurrent()
watcher.sent shouldBe listOf(EntityLeavePacket(charId))
}
}
test("arriving on the same map still re-exchanges entity snapshots") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player("May")
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val watcher = FakeSession(characterId = store.player("Brendan"), bankId = 51, mapId = 3)
val f = Fixture(store)
f.presence.enter(session)
f.presence.enter(watcher)
session.sent.clear()
// The arrival re-enters the map the player never really left.
f.presence.enter(session)
session.sent.map { it::class } shouldBe listOf(watcher.sent.first()::class)
}
}
test("a scripted warp resumes once the client has loaded the map") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
val cutscene = launch { f.scriptWarps.warp(session, session.state(), littlerootTown()) }
// Not advanceUntilIdle, that would run the clock past the load timeout.
runCurrent()
session.state().justWarped shouldBe true
session.sent.filterIsInstance<LoadMapPacket>().isEmpty() shouldBe false
session.attributes.remove(PENDING_MAP_LOAD)!!.complete(Unit)
runCurrent()
cutscene.join()
session.attributes[PENDING_MAP_LOAD] shouldBe null
session.sent.filterIsInstance<RenderScreenPacket>() shouldBe
listOf(RenderScreenPacket(false))
}
}
test("a scripted warp the client never answers gives movement back") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
val cutscene = launch { f.scriptWarps.warp(session, session.state(), littlerootTown()) }
advanceUntilIdle()
cutscene.join()
session.state().justWarped shouldBe false
session.attributes[PENDING_MAP_LOAD] shouldBe null
session.sent.filterIsInstance<RenderScreenPacket>().last() shouldBe
RenderScreenPacket(true)
}
}
test("a scripted warp to a map that is not loaded does nothing") {
runTest {
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.player()
val session =
FakeSession(characterId = charId, bankId = 51, mapId = 3).useScope(backgroundScope)
val f = Fixture(store)
f.scriptWarps.warp(
session,
session.state(),
littlerootTown().copy(bankId = MISSING_BANK, mapId = MISSING_MAP),
)
session.state().justWarped shouldBe false
session.sent shouldBe emptyList()
}
}
})