diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 640f74c4..5c3b8e61 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -89,7 +89,7 @@ import kotlin.reflect.typeOf private const val EXTERNAL_BUNDLE_FORMAT = "rylween.compiled.bundle" private const val EXTERNAL_BUNDLE_VERSION = 3 -private const val EXTERNAL_RUNTIME_SYSTEMS_VERSION = 14 +private const val EXTERNAL_RUNTIME_SYSTEMS_VERSION = 15 private const val GRID_CASTLE_KIND = "gridCastle" /** Serializes this game into the canonical strict JSON J1 artifact bytes. */ @@ -585,6 +585,8 @@ data class ExternalRuntimeRealm( val timeOfDay: List, /** Slug of the formula that prices a spell for its caster, or null when a spell costs its base cost. */ val spellCost: String?, + /** Slug of the formula for how many squares a party sees other parties, or null when parties never see each other. */ + val partySight: String?, ) /** One status-line time label exported for direct runtimes. */ @@ -1710,6 +1712,7 @@ private class ExternalBundleArtifactWriter { "camp" to campJson(realm.camp), "hunt" to realm.hunt?.let(::huntJson).orJsonNull(), "spellCost" to realm.spellCost?.let { formula -> JsonString(formula.slug) }.orJsonNull(), + "partySight" to realm.partySight?.let { formula -> JsonString(formula.slug) }.orJsonNull(), "timeOfDay" to JsonArray( realm.timeOfDay.map { band -> @@ -3815,6 +3818,7 @@ private class ExternalRuntimeSystemsReader( camp = requiredObject("camp").readCamp(), hunt = optional("hunt")?.takeUnless { it is JsonNull }?.asObject("hunt")?.readHunt(), spellCost = optional("spellCost")?.takeUnless { it is JsonNull }?.asString("spellCost"), + partySight = optional("partySight")?.takeUnless { it is JsonNull }?.asString("partySight"), timeOfDay = requiredArray("timeOfDay") .values diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index 78a98346..36aa9626 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -3521,6 +3521,9 @@ class FormulaBuilder( // The spell being cast, for the spell cost formula; the caster's stats are bound above. val spellBaseCost: IntExpr = v("spell_base_cost") + // The hour of the party's day, 0-23, for party sight. + val hour: IntExpr = v("hour") + // Upkeep and town entry: the party's living members and the gold it // carries, and the tax rate of the town it enters. val livingMembers: IntExpr = v("living_members") diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 49dd2d92..5292c9a4 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -325,7 +325,7 @@ fun validateFormulas(formulas: List) { check(formulas.map { it.id }.toSet().size == formulas.size) { "duplicate formula" } } -/** Validates that the hunt and castle trap chances, the spell cost and the battle arithmetic name authored formulas. */ +/** Validates that the hunt and castle trap chances, the spell cost, party sight and the battle arithmetic name authored formulas. */ private fun validateSystemFormulaReferences(content: GameModel) { val formulaIds = content.formulas.map { it.id }.toSet() content.realm.hunt?.let { hunt -> @@ -336,6 +336,9 @@ private fun validateSystemFormulaReferences(content: GameModel) { content.realm.spellCost?.let { spellCost -> check(spellCost in formulaIds) { "realm spell cost references missing formula ${spellCost.slug}" } } + content.realm.partySight?.let { partySight -> + check(partySight in formulaIds) { "realm party sight references missing formula ${partySight.slug}" } + } content.realm.upkeep.foodCost?.let { foodCost -> check(foodCost in formulaIds) { "realm upkeep food cost references missing formula ${foodCost.slug}" } } diff --git a/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt index d32aa562..91d7d8c4 100644 --- a/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt @@ -138,6 +138,12 @@ class RealmContentBuilder { /** What a spell costs its caster, mage spells in battle and priest spells alike; without it a spell costs its base cost. */ var spellCost: FormulaId? = null + /** + * How many squares away a party in the wilderness sees other players' parties on the same map; without it + * parties never see each other. + */ + var partySight: FormulaId? = null + fun baseResourceCapacity( resource: Resource, amount: Int, @@ -169,6 +175,7 @@ class RealmContentBuilder { hunt = hunt, timeOfDay = timeOfDayBands, spellCost = spellCost, + partySight = partySight, ) } diff --git a/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt index 27ba9b12..9761dc06 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt @@ -65,6 +65,7 @@ data class RealmContentModel( val hunt: HuntRulesModel? = null, val timeOfDay: List = defaultTimeOfDayBands(), val spellCost: FormulaId? = null, + val partySight: FormulaId? = null, ) /** Authored label for an inclusive hour span in the status line. */ diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index 01a69605..3b67286a 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -541,10 +541,11 @@ The system that uses a formula binds its variables: the member it is about (`weaponSkill`, `weaponDamage`, `hitPoints`, `armorClass`, `level`, `charisma`, `dexterity`), the monster (`monsterWeaponSkill`, `monsterHitPoints`, `monsterSpellPower`), the encounter, the party (`firstLevel`, `livingMembers`, -`gold`), a town's `taxPercent`, a shop item's `itemCost`, or a spell's -`spellBaseCost`. `atLeast` and `atMost` clamp a value, `whenValue(condition, a, b)` -picks one, and `random(lo..hi)` draws from the game's own random numbers. A -chance is a percentage the runtime rolls 0-99 against. +`gold`, and the `hour` of its day), a town's `taxPercent`, a shop item's +`itemCost`, or a spell's `spellBaseCost`. `atLeast` and `atMost` clamp a value, +`whenValue(condition, a, b)` picks one, and `random(lo..hi)` draws from the +game's own random numbers. A chance is a percentage the runtime rolls 0-99 +against. This game's rules that are formulas: what a spell costs (`realm { spellCost }`), a party member's and a monster's chance to hit and damage, a monster's chance to @@ -554,7 +555,9 @@ and the hit point range), battle experience and gold, level-up hit points, the food the party eats (`upkeep { foodCost }`), the town entry tax (`entryTax { amount }`; a party with less gold than the tax is shown the `entryTaxShortfall` prompt, with `TownText.taxShortfall`, and stays outside), -shop prices, the hunting and trap-disarm chances, and the haggle bonus. Inside a +shop prices, the hunting and trap-disarm chances, the haggle bonus, and how many +squares away players' parties see each other in the wilderness +(`realm { partySight }`; without it they never do). Inside a priest spell, `withCurrentCasterCost { caster, cost -> }` hands over the cost the formula works out; the spell's `baseCost` is declared once, in its `spell(...)` header. @@ -790,7 +793,7 @@ Use this placement rule during design review: A change to the shape of the `runtimeSystems` rows also bumps `EXTERNAL_RUNTIME_SYSTEMS_VERSION` in -`core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt` (14 today), so +`core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt` (15 today), so a runtime refuses a bundle written for another shape. If a rule mentions Rylween story content, item names, NPCs, mission prose, diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 10c95bca..cc56f9bc 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -398,6 +398,7 @@ val authoredRylween: RylweenModel = realm { baseResourceCapacity(Resource.Food, 150) spellCost = Formulas.spellCost + partySight = Formulas.partySight // Upkeep runs during wilderness turns. These fields control food // ticking, fatigue labels/drain, mana recovery, and starvation. upkeep { @@ -411,9 +412,9 @@ val authoredRylween: RylweenModel = line(UpkeepText.memberName, " starved to death!!!") } fatigueAt(0, literalText("You begin to feel tired"), statusLabel = "TIRED") - fatigueAt(-4, literalText("You are exhausted!!!"), drain = true, statusLabel = "EXHAUSTED") - fatigueAt(-8, flowText("You begin to feel weak from lack of sleep."), drain = true, statusLabel = "WEAK") - fatigueBelow(-8, flowText("You faint from lack of much-needed sleep."), drain = true, statusLabel = "FAINT") + fatigueAt(-6, literalText("You are exhausted!!!"), drain = true, statusLabel = "EXHAUSTED") + fatigueAt(-12, flowText("You begin to feel weak from lack of sleep."), drain = true, statusLabel = "WEAK") + fatigueBelow(-12, flowText("You faint from lack of much-needed sleep."), drain = true, statusLabel = "FAINT") } // Hunt is a reusable ranger action. The fields define chance, // move cost, food range, target prompts, and result text. @@ -450,7 +451,7 @@ val authoredRylween: RylweenModel = healthGain = 15 foodCostPerMember = 4 hoursAdvanced = 8 - hoursRestedReset = 14 + hoursRestedReset = 21 temperatureMax = 15 ambushChancePercent = 19 ambushTier = EncounterTiers.weak @@ -1217,7 +1218,7 @@ val authoredRylween: RylweenModel = torches = 5 food = 100 timeLeft = 200 - restedHours = 14 + restedHours = 21 } } @@ -1365,6 +1366,11 @@ val authoredRylween: RylweenModel = formula(Formulas.spellCost) { value = spellBaseCost + level } + // Players' parties see each other three squares away, and one + // square at night. + formula(Formulas.partySight) { + value = whenValue(hour lt 6, 1, 3) + } // Battle arithmetic. A chance is a percentage, rolled against // 0-99. A confused party fights at a third of its weapon skill, // and a member's own hit points add to the damage they deal. @@ -4317,7 +4323,7 @@ val authoredRylween: RylweenModel = ok = { writeText("You go to bed... {pause 1s}") playSound(Sounds.Explore.rest) - party.restedHours set 14 + party.restedHours set 21 writeText("Zzzz... {pause}") writeText( flowText( diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index ee3f7677..08149620 100644 --- a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt +++ b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt @@ -117,8 +117,9 @@ class RylweenCompiledGameLedgerTest { val externalBundleText = externalBundle.decodeToString() val runtimeSystems = externalBundle.readExternalRuntimeSystems() - check(runtimeSystems.schemaVersion == 14) + check(runtimeSystems.schemaVersion == 15) check(runtimeSystems.realm.spellCost == Formulas.spellCost.slug) + check(runtimeSystems.realm.partySight == Formulas.partySight.slug) check("\"dexterity\"" in externalBundleText) check(nextDsl.flags.size == 14) check(nextDsl.authoredFlags.size == 14) @@ -158,7 +159,7 @@ class RylweenCompiledGameLedgerTest { torches = 5, food = 100, timeLeft = 200, - restedHours = 14, + restedHours = 21, ), ) check(characterCreation.races.map { it.race } == listOf(Race.Human, Race.Dwarf, Race.Elf, Race.Halfling)) @@ -199,7 +200,7 @@ class RylweenCompiledGameLedgerTest { it.requiredStat == CharacterCreationStat.Dexterity && it.minimum == 50 }, ) - check(nextDsl.formulas.size == 22) + check(nextDsl.formulas.size == 23) check(nextDsl.rewards.size == 1) check( nextDsl.rewards @@ -1145,7 +1146,7 @@ class RylweenCompiledGameLedgerTest { check(nextDsl.realm.camp.healthGain == 15) check(nextDsl.realm.camp.foodCostPerMember == 4) check(nextDsl.realm.camp.hoursAdvanced == 8) - check(nextDsl.realm.camp.hoursRestedReset == 14) + check(nextDsl.realm.camp.hoursRestedReset == 21) check( nextDsl.realm.camp.temperatureBands == listOf( diff --git a/runtimes/runtime-bitmap-web/build.gradle.kts b/runtimes/runtime-bitmap-web/build.gradle.kts index 9aa7fb32..d50b69b2 100644 --- a/runtimes/runtime-bitmap-web/build.gradle.kts +++ b/runtimes/runtime-bitmap-web/build.gradle.kts @@ -142,6 +142,14 @@ val installRuntimeBitmapWeb: TaskProvider = } } +// The name Gradle's application plugin gives this task, for the project's default distribution. +tasks.register("installDist") { + group = "application" + description = "Installs the bitmap web runtime, the project's default distribution. Same as installRuntimeBitmapWeb." + + dependsOn(installRuntimeBitmapWeb) +} + val installBitmapSmokeBrowser: TaskProvider = tasks.register("installBitmapSmokeBrowser") { group = "verification" diff --git a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapPartyPresence.kt b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapPartyPresence.kt new file mode 100644 index 00000000..6731c212 --- /dev/null +++ b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapPartyPresence.kt @@ -0,0 +1,175 @@ +/** Players' parties seeing each other in the wilderness of the shared world. */ + +package rylween.bitmapweb + +import rylween.runtime.RuntimePartyPresence +import rylween.runtime.RuntimePresencePort +import java.io.IOException +import kotlin.math.abs +import kotlin.math.max + +/** How many horse colors the browser client has; players online at the same time get different ones while they last. */ +internal const val BITMAP_PARTY_COLORS = 8 + +/** Another player's party, as one player sees it: where it stands and the color its horse is drawn in. */ +internal data class BitmapSeenParty( + val name: String, + val x: Int, + val y: Int, + val color: Int, +) { + fun toJson(): String = + jsonObject( + "name" to name.json(), + "x" to x.toString(), + "y" to y.toString(), + "color" to color.toString(), + ) +} + +/** The message that tells a browser which other parties its player sees. */ +internal fun List.partiesMessage(): String = + jsonObject("type" to "parties".json(), "parties" to joinToString(prefix = "[", postfix = "]") { party -> party.toJson() }) + +/** + * Where every playing party is, shared by the sessions of one server. + * + * A party sees another when both are in the wilderness of the same map and the other is no more squares away than + * its own sight, in any direction, diagonals included. Sight is the seeing party's, so at night one party may see + * another that does not see it. Parties do not block each other, so any number may share a square; the list is sorted + * by square, then name, so the browser draws a crowded square the same way every time. + * + * Sessions publish from their own threads. A player's list is recomputed whenever anyone's presence changes, and + * [dispatch] runs the send, so a slow browser holds up only its own messages, never another player's move. Each send + * takes the newest list, so a player never ends on an older one. + */ +internal class BitmapPartyPresence( + private val dispatch: (Runnable) -> Unit, +) { + private val lock = Any() + + // Guarded by lock, and replaced rather than changed. + private var players: Map = emptyMap() + + /** Seats [account] while its browser is connected; [send] delivers a message to that browser. */ + fun join( + account: String, + send: (String) -> Unit, + ): Seat { + val viewer = Viewer(send) + synchronized(lock) { + check(account !in players) { "party presence: $account is already seated" } + players = players + (account to Player(freeColor(account), presence = null, viewer)) + } + return Seat(account, viewer) + } + + /** What [account] sees now. */ + fun seenBy(account: String): List = synchronized(lock) { seenBy(account, players) } + + // A session that outlived its socket must not move or remove the party of the account's next session. + private fun publish( + account: String, + viewer: Viewer, + presence: RuntimePartyPresence?, + ) = change { current -> + current[account] + ?.takeIf { player -> player.viewer === viewer } + ?.let { player -> current + (account to player.copy(presence = presence)) } + ?: current + } + + private fun remove( + account: String, + viewer: Viewer, + ) = change { current -> if (current[account]?.viewer === viewer) current - account else current } + + private fun change(next: (Map) -> Map) { + val changed = + synchronized(lock) { + players = next(players) + players.mapNotNull { (account, player) -> + player.viewer.takeIf { viewer -> viewer.see(seenBy(account, players)) } + } + } + changed.forEach { viewer -> dispatch(Runnable(viewer::flush)) } + } + + /** The account's preferred color, or the next one no one online has, or the preferred one when all are taken. */ + private fun freeColor(account: String): Int { + val preferred = Math.floorMod(account.hashCode(), BITMAP_PARTY_COLORS) + val taken = players.values.map(Player::color).toSet() + return (0 until BITMAP_PARTY_COLORS) + .map { offset -> (preferred + offset) % BITMAP_PARTY_COLORS } + .firstOrNull { color -> color !in taken } + ?: preferred + } + + private fun seenBy( + account: String, + players: Map, + ): List { + val own = players[account]?.presence?.takeIf { presence -> presence.inWilderness && presence.sight > 0 } ?: return emptyList() + return players + .filterKeys { other -> other != account } + .values + .mapNotNull { player -> player.presence?.takeIf { other -> own.sees(other) }?.let { other -> other to player.color } } + .map { (other, color) -> BitmapSeenParty(other.partyName, other.position.x, other.position.y, color) } + .sortedWith(compareBy(BitmapSeenParty::y, BitmapSeenParty::x, BitmapSeenParty::name)) + } + + private fun RuntimePartyPresence.sees(other: RuntimePartyPresence): Boolean = + other.inWilderness && + other.map == map && + max(abs(other.position.x - position.x), abs(other.position.y - position.y)) <= sight + + /** One browser's session: the runtime reports through it, and the server clears it when the party leaves play. */ + inner class Seat( + private val account: String, + private val viewer: Viewer, + ) : RuntimePresencePort { + override fun update(presence: RuntimePartyPresence) = publish(account, viewer, presence) + + /** Takes the party out of the world while its player is on the title screen. */ + fun hide() = publish(account, viewer, null) + + /** Takes the player off the server. */ + fun leave() = remove(account, viewer) + } + + private data class Player( + val color: Int, + val presence: RuntimePartyPresence?, + val viewer: Viewer, + ) + + class Viewer( + private val send: (String) -> Unit, + ) { + @Volatile + private var latest: List = emptyList() + + // Guarded by this viewer's monitor. + private var sent: List = emptyList() + + /** Records what the player sees now; true when that differs from the last list recorded. */ + fun see(parties: List): Boolean { + if (parties == latest) return false + latest = parties + return true + } + + fun flush() { + synchronized(this) { + val parties = latest + if (parties == sent) return + try { + send(parties.partiesMessage()) + sent = parties + } catch (_: IOException) { + // The browser has gone; its session takes it off the server when the socket closes. + } + } + } + } +} diff --git a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt index 28a7eed4..7a13d5e7 100644 --- a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt +++ b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt @@ -380,6 +380,7 @@ private class BitmapWebServer( }.associateBy { image -> image.id } private val audioCatalog = BitmapAudioCatalog.load(game.systems.audio, javaClass.classLoader) private val executor: ExecutorService = Executors.newCachedThreadPool() + private val partyPresence = BitmapPartyPresence(executor::execute) private val serverSocket = ServerSocket() private val clientIds = AtomicLong(0) @@ -988,6 +989,7 @@ private class BitmapWebServer( tileSize = config.tileSize, ) runtimeInput.textInputChanged = screen::setTextInput + val presenceSeat = partyPresence.join(account.slug, connection::sendText) val logFile = config.logFile(account) val saveFile = config.worldSaveFile val loadFile = sessionLoadFile(saveFile, account) @@ -1023,7 +1025,9 @@ private class BitmapWebServer( debugSecrets = config.debugSecrets, ), log = runtimeLog, + presence = presenceSeat, ) + presenceSeat.hide() runtimeLog.event("bitmap.session.end user=${account.slug} reason=${result.reason}") // Quitting goes back to the title screen, as in the original; the browser stays connected. if (result.reason != RuntimeSessionExitReason.Quit || !showTitleMenu) { @@ -1055,6 +1059,7 @@ private class BitmapWebServer( } finally { runtimeInput.close() runCatching { runtime.get(5, TimeUnit.SECONDS) } + presenceSeat.leave() activeUsers.remove(account.slug) } serverLog.event("bitmap.websocket.close id=$clientId user=${account.slug}") diff --git a/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts b/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts index eed9d996..95b63dec 100644 --- a/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts +++ b/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts @@ -290,6 +290,7 @@ const connectionDot = requireElement("connectionDot", HTMLElement); const connectionText = requireElement("connectionText", HTMLElement); let socket: WebSocket | null = null; let frame: BitmapFrame | null = null; +let seenParties: SeenParty[] = []; let currentCommands: BitmapCommand[] = []; let statusHotspots: StatusHotspot[] = []; let choiceTargets: ChoiceTarget[] = []; @@ -363,6 +364,20 @@ type MusicMessage = { id: string | null; }; +// Another player's party this player sees; color indexes seenPartyColors. +type SeenParty = { + name: string; + x: number; + y: number; + color: number; +}; + +// Sent whenever the parties this player sees change, sorted by square and then name. +type PartiesMessage = { + type: "parties"; + parties: SeenParty[]; +}; + type PlayingMusic = { id: string; source: AudioBufferSourceNode; @@ -1043,6 +1058,7 @@ function connect(): void { const protocol = location.protocol === "https:" ? "wss:" : "ws:"; socket = new WebSocket(protocol + "//" + location.host + "/ws/play"); socket.addEventListener("open", () => { + seenParties = []; connectionDot.classList.add("connected"); connectionText.textContent = "Connected"; refreshServerInfo().catch(() => undefined); @@ -1063,6 +1079,11 @@ function connect(): void { gameAudio.setMusic((message as unknown as MusicMessage).id); return; } + if (message.type === "parties") { + seenParties = (message as unknown as PartiesMessage).parties; + if (frame?.mode === "wilderness") requestPointerRedraw(); + return; + } const nextFrame = message as unknown as BitmapFrame; gameAudio.setMusic(nextFrame.music); syncMenuHighlight(nextFrame); @@ -2412,9 +2433,11 @@ function drawMap(map: BitmapMap): void { drawTile(rows[row][col], x + col * size, y + row * size, size, !transitionLayer); } } - if (!transitionLayer) return; - drawTerrainTransitions(rows, x, y, size); - drawWildernessMapMarkers(rows, x, y, size); + if (transitionLayer) { + drawTerrainTransitions(rows, x, y, size); + drawWildernessMapMarkers(rows, x, y, size); + } + if (frame?.mode === "wilderness") drawSeenParties(rows, x, y, size); } function drawPerspectiveMap(map: BitmapMap): boolean { @@ -3622,16 +3645,96 @@ function drawSettlementOverlay(settlement: string, x: number, y: number, size: n function drawPartyMarker(cx: number, cy: number, size: number): void { const marker = bitmapAssets.partyMarker; if (!marker.complete || marker.naturalWidth === 0) return; + drawMarkerImage(marker, cx, cy, size * 1.12); +} + +function drawMarkerImage(marker: CanvasImageSource, cx: number, cy: number, markerSize: number): void { ctx.save(); ctx.imageSmoothingEnabled = true; ctx.shadowColor = "rgba(0, 0, 0, 0.72)"; ctx.shadowBlur = 8; ctx.shadowOffsetY = 2; - const markerSize = size * 1.12; ctx.drawImage(marker, cx - markerSize / 2, cy - markerSize / 2, markerSize, markerSize); ctx.restore(); } +// Horse colors for other players' parties. The server gives players online together different ones while it can. +const seenPartyColors = ["#d8402c", "#2f7fe0", "#34343c", "#8a53e0", "#2fb46c", "#e85fa9", "#e8741c", "#2fc0c8"]; +const tintedPartyMarkers = new Map(); +// Small horses go in three corners of a square; the top right one holds a settlement's badge. +const seenPartyCorners: [number, number][] = [ + [0.27, 0.73], + [0.73, 0.73], + [0.27, 0.27], +]; + +// A party alone on a square is drawn full size. Beside this party's horse, or with other parties, each is drawn small +// in a corner, and when there are more than the corners hold, the last corner counts the rest ("+2"). +function drawSeenParties(rows: BitmapTile[][], startX: number, startY: number, size: number): void { + rows.forEach((row, rowIndex) => { + row.forEach((tile, colIndex) => { + const here = seenParties.filter((party) => party.x === tile.x && party.y === tile.y); + if (here.length === 0) return; + const x = startX + colIndex * size; + const y = startY + rowIndex * size; + if (here.length === 1 && !tile.center) { + drawSeenPartyMarker(here[0], x + size / 2, y + size / 2, size * 1.12); + return; + } + const crowded = here.length > seenPartyCorners.length; + const shown = crowded ? here.slice(0, seenPartyCorners.length - 1) : here; + shown.forEach((party, index) => { + const [cornerX, cornerY] = seenPartyCorners[index]; + drawSeenPartyMarker(party, x + size * cornerX, y + size * cornerY, size * 0.56); + }); + if (crowded) { + const [cornerX, cornerY] = seenPartyCorners[shown.length]; + drawSeenPartyCount(here.length - shown.length, x + size * cornerX, y + size * cornerY, size * 0.4); + } + }); + }); +} + +function drawSeenPartyMarker(party: SeenParty, cx: number, cy: number, markerSize: number): void { + const marker = tintedPartyMarker(party.color); + if (marker) drawMarkerImage(marker, cx, cy, markerSize); +} + +function tintedPartyMarker(color: number): HTMLCanvasElement | null { + const cached = tintedPartyMarkers.get(color); + if (cached) return cached; + const marker = bitmapAssets.partyMarker; + if (!marker.complete || marker.naturalWidth === 0) return null; + const tinted = document.createElement("canvas"); + tinted.width = marker.naturalWidth; + tinted.height = marker.naturalHeight; + const tint = tinted.getContext("2d"); + if (!tint) return null; + tint.drawImage(marker, 0, 0); + // The color covers only the rider's own pixels, and lets enough of the drawing through to read as a horse. + tint.globalCompositeOperation = "source-atop"; + tint.globalAlpha = 0.8; + tint.fillStyle = seenPartyColors[color % seenPartyColors.length]; + tint.fillRect(0, 0, tinted.width, tinted.height); + tintedPartyMarkers.set(color, tinted); + return tinted; +} + +function drawSeenPartyCount(count: number, cx: number, cy: number, badge: number): void { + ctx.save(); + ctx.fillStyle = "rgba(9, 7, 4, 0.82)"; + ctx.fillRect(cx - badge / 2, cy - badge / 2, badge, badge); + ctx.strokeStyle = "#f2e3a0"; + ctx.lineWidth = Math.max(1, Math.floor(badge * 0.06)); + ctx.strokeRect(cx - badge / 2 + 0.5, cy - badge / 2 + 0.5, badge - 1, badge - 1); + ctx.fillStyle = "#f2e3a0"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = "bold " + Math.floor(badge * 0.5) + "px Menlo, Monaco, Consolas, monospace"; + ctx.fillText("+" + count, cx, cy + 1); + ctx.restore(); +} + function terrainAtlasIndex(slug: string, settlement: string): TerrainAtlasIndex { if (settlement === "town") return {row: 3, col: 4}; if (settlement === "castle") return {row: 4, col: 4}; diff --git a/runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapPartyPresenceTest.kt b/runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapPartyPresenceTest.kt new file mode 100644 index 00000000..89ea97dd --- /dev/null +++ b/runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapPartyPresenceTest.kt @@ -0,0 +1,128 @@ +package rylween.bitmapweb + +import rylween.dsl.impl.GridPoint +import rylween.runtime.RuntimePartyPresence +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class BitmapPartyPresenceTest { + private val presence = BitmapPartyPresence(Runnable::run) + private val sent = mutableMapOf>() + + @Test + fun aPartySeesTheOthersWithinItsSightOnTheSameMap() { + val viewer = join("viewer") + val diagonal = join("diagonal") + val beyond = join("beyond") + val elsewhere = join("elsewhere") + val inTown = join("in-town") + + viewer.update(at("Viewer", 10, 10, sight = 3)) + diagonal.update(at("Diagonal", 13, 13)) + beyond.update(at("Beyond", 14, 10)) + elsewhere.update(at("Elsewhere", 10, 11).copy(map = "underworld")) + inTown.update(at("In town", 10, 10).copy(inWilderness = false)) + + assertEquals(listOf("Diagonal"), presence.seenBy("viewer").map(BitmapSeenParty::name)) + } + + @Test + fun sightIsTheSeeingPartys() { + val owl = join("owl") + val mole = join("mole") + + owl.update(at("Owl", 1, 1, sight = 3)) + mole.update(at("Mole", 3, 1, sight = 1)) + + assertEquals(listOf("Mole"), presence.seenBy("owl").map(BitmapSeenParty::name)) + assertEquals(emptyList(), presence.seenBy("mole")) + } + + @Test + fun partiesOnOneSquareAreAllSeenInTheSameOrderEveryTime() { + val viewer = join("viewer") + val others = listOf("Carol", "Alice", "Bob", "Dave").map { name -> join(name.lowercase()) to name } + + viewer.update(at("Viewer", 5, 5)) + others.forEach { (seat, name) -> seat.update(at(name, 5, 5)) } + join("zed").update(at("Zed", 4, 5)) + + assertEquals( + listOf("Zed" to GridPoint(4, 5)) + listOf("Alice", "Bob", "Carol", "Dave").map { name -> name to GridPoint(5, 5) }, + presence.seenBy("viewer").map { party -> party.name to GridPoint(party.x, party.y) }, + ) + } + + @Test + fun aPartyThatLeavesPlayIsNoLongerSeen() { + val viewer = join("viewer") + val other = join("other") + viewer.update(at("Viewer", 1, 1)) + other.update(at("Other", 2, 2)) + + other.hide() + assertEquals(emptyList(), presence.seenBy("viewer")) + + other.update(at("Other", 2, 2)) + other.leave() + assertEquals(emptyList(), presence.seenBy("viewer")) + } + + @Test + fun aSessionThatOutlivedItsSocketCannotMoveTheNextSessionsParty() { + val viewer = join("viewer") + viewer.update(at("Viewer", 1, 1)) + val stale = join("other") + stale.leave() + val current = join("other") + current.update(at("Other", 2, 2)) + + stale.update(at("Other", 9, 9)) + stale.leave() + + assertEquals(listOf(GridPoint(2, 2)), presence.seenBy("viewer").map { party -> GridPoint(party.x, party.y) }) + } + + @Test + fun playersOnlineTogetherHaveDifferentColorsWhileThereAreEnough() { + val viewer = join("viewer") + viewer.update(at("Viewer", 1, 1, sight = 9)) + (1 until BITMAP_PARTY_COLORS).forEach { index -> join("player-$index").update(at("Player $index", 2, 2)) } + + val colors = presence.seenBy("viewer").map(BitmapSeenParty::color) + assertEquals(BITMAP_PARTY_COLORS - 1, colors.toSet().size) + assertTrue(colors.all { color -> color in 0 until BITMAP_PARTY_COLORS }, "$colors") + } + + @Test + fun aBrowserIsSentWhatItsPlayerSeesOnlyWhenThatChanges() { + val viewer = join("viewer") + val other = join("other") + viewer.update(at("Viewer", 1, 1)) + other.update(at("Other", 2, 2)) + val color = presence.seenBy("viewer").single().color + other.update(at("Other", 2, 2)) + other.update(at("Other", 3, 3)) + other.update(at("Other", 9, 9)) + + assertEquals( + listOf( + """{"type":"parties", "parties":[{"name":"Other", "x":2, "y":2, "color":$color}]}""", + """{"type":"parties", "parties":[{"name":"Other", "x":3, "y":3, "color":$color}]}""", + """{"type":"parties", "parties":[]}""", + ), + sent.getValue("viewer"), + ) + } + + private fun join(account: String): BitmapPartyPresence.Seat = + presence.join(account) { message -> sent.getOrPut(account) { mutableListOf() } += message } + + private fun at( + name: String, + x: Int, + y: Int, + sight: Int = 3, + ): RuntimePartyPresence = RuntimePartyPresence(name, "wilderness", inWilderness = true, GridPoint(x, y), sight) +} diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt index 60af782a..62ab9857 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt @@ -120,7 +120,7 @@ internal class CastleRuntime( navigation.matches(RuntimeCommandActionId.MoveSouth, command) -> move(runtime, castle, dx = 0, dy = 1, castle.text.moveSouth) navigation.matches(RuntimeCommandActionId.MoveWest, command) -> move(runtime, castle, dx = -1, dy = 0, castle.text.moveWest) navigation.matches(RuntimeCommandActionId.MoveEast, command) -> move(runtime, castle, dx = 1, dy = 0, castle.text.moveEast) - navigation.matches(RuntimeCommandActionId.Save, command) -> runtime.also { saveRuntime(it) } + navigation.matches(RuntimeCommandActionId.Save, command) -> saveRuntime(runtime) navigation.matches(RuntimeCommandActionId.Help, command) -> runtime.also { showNavigationHelp(castle) } navigation.matches( RuntimeCommandActionId.ViewParty, @@ -437,9 +437,7 @@ internal class CastleRuntime( if (runtime.currentMode == RuntimeMode.Castle) screen.renderCastle(runtime, castle) } - private fun saveRuntime(runtime: RuntimeState) { - saveRuntimeForPlayer(runtime, content, systems, save, screen, log) - } + private fun saveRuntime(runtime: RuntimeState): RuntimeState = saveRuntimeForPlayer(runtime, content, systems, save, screen, log) private fun seedRooms( runtime: RuntimeState, diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt index ba2c2a5d..85d916c7 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt @@ -70,7 +70,7 @@ internal class DungeonRuntime( RuntimeCommandActionId.ViewParty, command, ) -> runtime.also(::showDungeonPageViews) - commands.matches(RuntimeCommandActionId.Save, command) -> runtime.also { saveRuntime(it) } + commands.matches(RuntimeCommandActionId.Save, command) -> saveRuntime(runtime) commands.matches(RuntimeCommandActionId.Drop, command) -> utility.drop(runtime).also(::redrawDungeonIfCurrent) commands.matches( RuntimeCommandActionId.RemoveArmor, @@ -254,9 +254,7 @@ internal class DungeonRuntime( if (runtime.currentMode == RuntimeMode.Dungeon) screen.renderDungeon(runtime) } - private fun saveRuntime(runtime: RuntimeState) { - saveRuntimeForPlayer(runtime, content, systems, save, screen, log) - } + private fun saveRuntime(runtime: RuntimeState): RuntimeState = saveRuntimeForPlayer(runtime, content, systems, save, screen, log) private fun eventByRef(ref: CompiledHandleRef): CompiledDungeonEvent = content.dungeonEvents.firstOrNull { event -> event.id == ref } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresence.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresence.kt new file mode 100644 index 00000000..5da13d7d --- /dev/null +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresence.kt @@ -0,0 +1,65 @@ +/** Where the active party is in the shared world, for hosts that show players each other's parties. */ + +package rylween.runtime + +import rylween.compiled.CompiledContentBundle +import rylween.compiled.ExternalRuntimeSystems +import rylween.dsl.impl.GridPoint +import rylween.dsl.impl.RuntimeMode + +/** Where the active party is, and how far it sees other parties. */ +data class RuntimePartyPresence( + val partyName: String, + /** Slug of the world map the party is on. */ + val map: String, + /** Whether the party is out in the wilderness. A party in a town, dungeon or castle is not seen and sees no one. */ + val inWilderness: Boolean, + val position: GridPoint, + /** How many squares away the party sees other parties, from the game's `realm { partySight }` formula. */ + val sight: Int, +) + +/** Told where the active party is whenever that changes, before the runtime waits for the next command. */ +fun interface RuntimePresencePort { + fun update(presence: RuntimePartyPresence) + + companion object { + /** For hosts that run one party alone. */ + val None = RuntimePresencePort { } + } +} + +/** Passes on only the updates that differ from the one before. */ +internal fun RuntimePresencePort.changesOnly(): RuntimePresencePort { + var last: RuntimePartyPresence? = null + return RuntimePresencePort { presence -> + if (presence != last) { + last = presence + update(presence) + } + } +} + +/** + * The active party's presence. Sight is 0 outside the wilderness or when the game declares no `partySight` formula. + * The formula sees the hour of the party's day. A random draw in it does not advance the party's random numbers, so + * showing parties to each other never changes how a game plays out. + */ +internal fun RuntimeState.presence( + content: CompiledContentBundle, + systems: ExternalRuntimeSystems, +): RuntimePartyPresence { + val inWilderness = currentMode == RuntimeMode.Wilderness + val sight = + systems.realm.partySight + ?.takeIf { inWilderness } + ?.let { formula -> content.evalFormula(formula, party, mapOf("hour" to hour.mod(24))).value.coerceAtLeast(0) } + ?: 0 + return RuntimePartyPresence( + partyName = party.name, + map = content.slug(currentMap), + inWilderness = inWilderness, + position = party.position, + sight = sight, + ) +} diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSession.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSession.kt index 340e1c2c..2ec278e0 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSession.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSession.kt @@ -16,12 +16,11 @@ internal data class RuntimeSaveContext( val userId: String, val hallOfHeroesCompletedBy: String?, ) { + /** Writes [runtime] and returns it with the world as saved, which may hold what other sessions saved. */ fun write( runtime: RuntimeState, content: CompiledContentBundle, - ) { - SaveFile.write(file, runtime, bundleContentHash, content, userId, hallOfHeroesCompletedBy) - } + ): RuntimeState = SaveFile.write(file, runtime, bundleContentHash, content, userId, hallOfHeroesCompletedBy) } internal data class RuntimeLoopContext( @@ -31,12 +30,14 @@ internal data class RuntimeLoopContext( val screen: RuntimeScreenPort, val save: RuntimeSaveContext, val log: RuntimeLog, + val presence: RuntimePresencePort = RuntimePresencePort.None, ) /** * Saves the game when the player asks to, in any mode: shows the authored saving text, writes the save, then shows * the done text, or the failed text when the write fails. A failed save is logged and play goes on. Players never - * see where the save is stored; the log records it. + * see where the save is stored; the log records it. Returns [runtime] with the world as saved, or unchanged when the + * save failed. */ internal fun saveRuntimeForPlayer( runtime: RuntimeState, @@ -45,28 +46,31 @@ internal fun saveRuntimeForPlayer( save: RuntimeSaveContext, screen: RuntimeScreenPort, log: RuntimeLog, -) { +): RuntimeState { val prompts = systems.prompts.save screen.writeText(prompts.saving.render({ null }, screen.textColumns)) val saved = persistRuntimeOrLogFailure(runtime, content, save, log, "command") - if (saved) RuntimeAudio(systems.audio, screen).cue(AudioCue.GameSaved) - screen.appendText((if (saved) prompts.done else prompts.failed).render({ null }, screen.textColumns)) + if (saved != null) RuntimeAudio(systems.audio, screen).cue(AudioCue.GameSaved) + screen.appendText((if (saved != null) prompts.done else prompts.failed).render({ null }, screen.textColumns)) + return saved ?: runtime } -/** Writes the save like [persistRuntime], but logs a failed write instead of throwing. Returns whether it worked. */ +/** + * Writes the save like [persistRuntime], but logs a failed write instead of throwing. Returns [runtime] with the world + * as saved, or null when the write failed. + */ internal fun persistRuntimeOrLogFailure( runtime: RuntimeState, content: CompiledContentBundle, save: RuntimeSaveContext, log: RuntimeLog, reason: String, -): Boolean = +): RuntimeState? = try { persistRuntime(runtime, content, save, log, reason) - true } catch (error: Exception) { log.failure("runtime.save.failed reason=$reason user=${save.userId} file=${save.file.path} mode=${runtime.currentMode}", error) - false + null } /** Programmatic configuration for one interactive runtime session. */ @@ -135,15 +139,18 @@ class RuntimeSessionFactory private constructor( log = log, ) + /** Runs a session through [input] and [screen], and tells [presence] where the party is as it plays. */ fun start( input: RuntimeInputPort, screen: RuntimeScreenPort, config: RuntimeSessionConfig, log: RuntimeLog, + presence: RuntimePresencePort = RuntimePresencePort.None, ): RuntimeSessionResult = runtime.runWilderness( input = input, screen = screen, + presence = presence.changesOnly(), userId = config.userId, stateSlug = config.stateSlug, loadFile = config.loadFile, diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt index 084a8bb5..a4fc744f 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt @@ -285,20 +285,24 @@ private fun RuntimeState.logPosition(): String = "${party.position.x},${party.po private fun logValue(value: String): String = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" -/** Writes [runtime] to the save and logs it, line by line. Throws when the write fails. */ +/** + * Writes [runtime] to the save and logs it, line by line. Returns [runtime] with the world as saved. Throws when the + * write fails. + */ internal fun persistRuntime( runtime: RuntimeState, content: CompiledContentBundle, save: RuntimeSaveContext, log: RuntimeLog, reason: String, -) { - save.write(runtime, content) +): RuntimeState { + val saved = save.write(runtime, content) log.event( "runtime.save reason=$reason user=${save.userId} file=${save.file.path} position=${runtime.logPosition()} " + "mode=${runtime.currentMode} lastPlayedDate=${runtime.lastPlayedDate ?: ""}", ) logSaveFileLines("runtime.save", save.file, log) + return saved } private fun logSaveFileLines( @@ -495,6 +499,7 @@ class GameRuntime private constructor( debugSecrets: Boolean = false, sessionDate: LocalDate = LocalDate.now(), log: RuntimeLog, + presence: RuntimePresencePort = RuntimePresencePort.None, ): RuntimeSessionResult { listOfNotNull(loadFile, saveFile).distinct().forEach { file -> SaveFile.savedBundleHash(file)?.takeIf { saved -> saved != bundleContentHash }?.let { saved -> @@ -527,7 +532,7 @@ class GameRuntime private constructor( flashLogSink.use { log.event("wilderness.boot state=$stateSlug position=${runtime.logPosition()} mode=${runtime.currentMode}") val saveContext = RuntimeSaveContext(saveFile, bundleContentHash, userId, systems.score.completedBy) - val loopContext = RuntimeLoopContext(content, systems, input, screen, saveContext, log) + val loopContext = RuntimeLoopContext(content, systems, input, screen, saveContext, log, presence) if (showTitleMenu || loadFile != null && !hasLoadUserSave) { runtime = runTitleMenu(runtime, stateSlug, seed, loopContext) @@ -538,6 +543,7 @@ class GameRuntime private constructor( runtime = runtime.materializeMissingNpcPlacements(world, log) runtime = runtime.applySessionDate(sessionDate, log) val sessionStartSaved = persistSessionStartIfChanged(sessionStartRuntime, runtime, saveContext, log) + runtime = sessionStartSaved ?: runtime logNpcPlacements(runtime, log) val commands = WildernessCommands.from(systems) val debugCommands = WildernessCommands.from(systems, RuntimeCommandGroupId.WildernessDebug) @@ -559,8 +565,9 @@ class GameRuntime private constructor( var wildernessTrack: String? = null screen.bootFrame() screen.renderWilderness(runtime, world) - if (!sessionStartSaved && !showSaveFailed(screen, input)) return input.exitResult() + if (sessionStartSaved == null && !showSaveFailed(screen, input)) return input.exitResult() while (true) { + presence.update(runtime.presence(content, systems)) when (runtime.currentMode) { RuntimeMode.Dungeon -> { wildernessTrack = null @@ -677,7 +684,7 @@ class GameRuntime private constructor( } commands.matches(RuntimeCommandActionId.Save, command) -> { - saveRuntimeForPlayer(runtime, content, systems, saveContext, screen, log) + runtime = saveRuntimeForPlayer(runtime, content, systems, saveContext, screen, log) false } @@ -1565,15 +1572,18 @@ class GameRuntime private constructor( return quitting } - /** Saves the session's starting state when it changed. Returns false when that save failed; the log has why. */ + /** + * Saves the session's starting state when it changed, and returns it with the world as saved. Null when that save + * failed; the log has why. + */ private fun persistSessionStartIfChanged( before: RuntimeState, after: RuntimeState, save: RuntimeSaveContext, log: RuntimeLog, - ): Boolean { + ): RuntimeState? { val hasUserSave = SaveFile.hasUserParty(save.file, save.userId) - if (before == after && save.file.isFile && hasUserSave) return true + if (before == after && save.file.isFile && hasUserSave) return after return persistRuntimeOrLogFailure(after, content, save, log, "session_start") } @@ -1602,7 +1612,7 @@ class GameRuntime private constructor( val screen = context.screen log.event("wilderness.enter position=${runtime.logPosition()}") val town = content.towns.firstOrNull { it.position == runtime.party.position } - if (town != null) return enterTown(runtime, world, input, screen, town, log) + if (town != null) return enterTown(runtime, world, input, screen, context.presence, town, log) val castle = systems.castleRows.firstOrNull { castle -> castle.entry == runtime.party.position } if (castle != null) { log.event("wilderness.enter_castle castle=${castle.id}") @@ -1628,6 +1638,7 @@ class GameRuntime private constructor( world: WorldMap, input: RuntimeInputPort, screen: RuntimeScreenPort, + presence: RuntimePresencePort, town: rylween.compiled.CompiledTown, log: RuntimeLog, ): RuntimeState { @@ -1658,6 +1669,7 @@ class GameRuntime private constructor( audio.cue(AudioCue.EnterTown) val taxResult = collectTownEntryTaxIfNeeded(current, world, input, screen, town, log) ?: return runtime current = taxResult.runtime + presence.update(current.presence(content, systems)) var menuNotice = taxResult.noticeLines fun menuLines(noticeLines: List): List = diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt index 1945e08c..1edb0d6a 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt @@ -34,6 +34,7 @@ private const val SAVE_MODEL = "shared-world" private const val PARTY_MEMBER_RECORD_COUNT = "party.members" private const val USERS_COUNT = "users.count" private const val HEROES_COUNT = "heroes.count" +private val clockKeys = listOf("realm.day", "realm.hour", "realm.minute") private val memberFieldKey = Regex("""^member\.(\d+)\.""") @@ -177,6 +178,11 @@ internal object SaveCodec { /** Reads and writes runtime shared-world saves. */ internal object SaveFile { + /** + * Writes the active user's party and the world into [file], and returns [runtime] with the world as written. + * Other sessions may have saved since this one read the file, so the world keeps the missions they completed and + * the NPC places they drew first. + */ fun write( file: File, runtime: RuntimeState, @@ -184,28 +190,35 @@ internal object SaveFile { content: CompiledContentBundle, userId: String, hallOfHeroesCompletedBy: String?, - ) = SaveFileStorage.update(file) { target -> - val activeUser = userId.normalizedSaveUser() - val existingValues = target.existingSaveValuesOrEmpty() - if (target.isFile) existingValues.requireReadableSave() - val preservedUsers = existingValues.userRecords().filterNot { record -> record.id == activeUser } - val userRecords = preservedUsers + UserSaveRecord(activeUser, runtime.userSaveValues(content)) - val scoreParties = - runtime.scoreParties - .filterNot { party -> party.userId == activeUser } + - runtime.party.toRuntimeScoreParty(activeUser) - val heroes = - existingValues - .heroEntries() - .withDerivedHeroes(scoreParties, hallOfHeroesCompletedBy, content) - val values = - buildMap { - putAll(runtime.worldSaveValues(bundleHash, content)) - putHeroEntries(heroes) - putUserRecords(userRecords) - } - SaveFileStorage.replace(target, SaveCodec.encodeValues(values)) - } + ): RuntimeState = + SaveFileStorage.update(file) { target -> + val activeUser = userId.normalizedSaveUser() + val existingValues = target.existingSaveValuesOrEmpty() + if (target.isFile) existingValues.requireReadableSave() + val world = runtime.withSavedWorld(existingValues, content) + val preservedUsers = + existingValues + .userRecords() + .filterNot { record -> record.id == activeUser } + .map { record -> record.withWorldClock(existingValues) } + val userRecords = preservedUsers + UserSaveRecord(activeUser, runtime.userSaveValues(content)) + val scoreParties = + runtime.scoreParties + .filterNot { party -> party.userId == activeUser } + + runtime.party.toRuntimeScoreParty(activeUser) + val heroes = + existingValues + .heroEntries() + .withDerivedHeroes(scoreParties, hallOfHeroesCompletedBy, content) + val values = + buildMap { + putAll(world.worldSaveValues(bundleHash, content)) + putHeroEntries(heroes) + putUserRecords(userRecords) + } + SaveFileStorage.replace(target, SaveCodec.encodeValues(values)) + world + } fun read( file: File, @@ -224,9 +237,10 @@ internal object SaveFile { val activeParty = userValues.readParty(baseState.party, content) val scoreParties = values.scoreParties(baseState.party, content, saveUser) return baseState.copy( - day = values.intOrDefault("realm.day", baseState.day), - hour = values.intOrDefault("realm.hour", baseState.hour), - minute = values.intOrDefault("realm.minute", baseState.minute), + // Each party keeps its own clock. Saves from before that kept one clock in the world rows. + day = userValues.optionalInt("realm.day") ?: values.intOrDefault("realm.day", baseState.day), + hour = userValues.optionalInt("realm.hour") ?: values.intOrDefault("realm.hour", baseState.hour), + minute = userValues.optionalInt("realm.minute") ?: values.intOrDefault("realm.minute", baseState.minute), currentMap = userValues.handleOrDefault("realm.currentMap", CompiledHandleKind.WorldMap, content, baseState.currentMap), currentMode = userValues.runtimeModeOrDefault("realm.currentMode", baseState.currentMode), currentTown = userValues.optionalHandle("realm.currentTown", CompiledHandleKind.Town, content) ?: baseState.currentTown, @@ -295,9 +309,6 @@ internal object SaveFile { put("saveModel", SAVE_MODEL) put("bundleHash", bundleHash) put("state", stateSlug) - put("realm.day", day.toString()) - put("realm.hour", hour.toString()) - put("realm.minute", minute.toString()) put("realm.lastPlayedDate", lastPlayedDate?.toString().orEmpty()) put("realm.partyMemberMax", partyMemberMax.toString()) put("missions.completed", completedMissions.joinToString(",") { mission -> content.slug(mission) }) @@ -305,8 +316,30 @@ internal object SaveFile { putNpcs(npcs, content) } + // A session reads the world once, when it starts. Completed missions only grow, and an NPC stays where the + // first save put it, so merging what other sessions saved since loses nothing of theirs. + private fun RuntimeState.withSavedWorld( + saved: Map, + content: CompiledContentBundle, + ): RuntimeState { + val savedNpcs = saved.readNpcs(emptyList(), content) + val savedNpcIds = savedNpcs.map(CompiledNpcPlacement::npc).toSet() + val savedMissions = saved.handleListOrDefault("missions.completed", CompiledHandleKind.Mission, content, emptyList()) + return copy( + npcs = savedNpcs + npcs.filterNot { placement -> placement.npc in savedNpcIds }, + completedMissions = (savedMissions + completedMissions).distinct(), + ) + } + + /** Gives a record saved before parties kept their own clock the one clock the world rows kept then. */ + private fun UserSaveRecord.withWorldClock(world: Map): UserSaveRecord = + copy(values = clockKeys.mapNotNull { key -> world[key]?.let { value -> key to value } }.toMap() + values) + private fun RuntimeState.userSaveValues(content: CompiledContentBundle): Map = buildMap { + put("realm.day", day.toString()) + put("realm.hour", hour.toString()) + put("realm.minute", minute.toString()) put("realm.currentMap", content.slug(currentMap)) put("realm.currentMode", currentMode.name) put("realm.currentTown", currentTown?.let(content::slug).orEmpty()) diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimePresenceTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimePresenceTest.kt new file mode 100644 index 00000000..5f53b143 --- /dev/null +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimePresenceTest.kt @@ -0,0 +1,109 @@ +package rylween.runtime + +import org.junit.jupiter.api.io.TempDir +import rylween.compiled.RuntimeCommandActionId +import rylween.compiled.RuntimeCommandGroupId +import rylween.compiled.readExternalCompiledBundleContentHash +import rylween.compiled.readExternalCompiledGameBundle +import rylween.compiled.readExternalRuntimeSystems +import rylween.dsl.impl.RuntimeMode +import java.io.File +import java.time.LocalDate +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The runtime tells its host where the party is, so other players can see it in the wilderness. */ +class RuntimePresenceTest { + private val bundleFile = File(requiredRuntimeTestProperty("rylween.runtime.bundle")) + + @TempDir + private lateinit var testTmp: File + private val bundle = bundleFile.readExternalCompiledGameBundle() + private val systems = bundleFile.readExternalRuntimeSystems() + private val content = bundle.content + private val factory = RuntimeSessionFactory.load(bundle, systems, bundleFile.readExternalCompiledBundleContentHash()) + private val town = content.towns.first() + private val fresh = RuntimeState.from(bundle.states.single { state -> content.slug(state.state) == "fresh-replay" }, content) + + @Test + fun aPartyIsSeenInTheWildernessButNotInsideATown() { + val wilderness = systems.commands.getValue(RuntimeCommandGroupId.Wilderness.id) + val enter = wilderness.key(RuntimeCommandActionId.Enter) + val leave = systems.commands.getValue(RuntimeCommandGroupId.Town.id).key(RuntimeCommandActionId.LeaveTown) + val redraw = wilderness.key(RuntimeCommandActionId.Redraw) + // Enter, pay the tax, leave, and redraw, which waits in the same place again and so reports nothing new. + val updates = playFromTown("${enter}P$leave$redraw", hour = 12) + + val outside = RuntimePartyPresence(fresh.party.name, content.slug(fresh.currentMap), true, town.position, sight = 3) + assertEquals(listOf(outside, outside.copy(inWilderness = false, sight = 0), outside), updates) + } + + @Test + fun partiesSeeLessFarAtNight() { + assertEquals(1, playFromTown("", hour = 2).single().sight) + assertEquals(3, fresh.copy(hour = 6).presence(content, systems).sight) + } + + @Test + fun aPartyOutsideTheWildernessSeesNoOne() { + val presence = fresh.copy(currentMode = RuntimeMode.Dungeon).presence(content, systems) + + assertEquals(false, presence.inWilderness) + assertEquals(0, presence.sight) + } + + /** Starts a party on the first town's square at [hour], plays [commands], and returns every presence update. */ + private fun playFromTown( + commands: String, + hour: Int, + ): List { + val saveFile = testTmp.resolve("presence.rsave").also(File::delete) + runSession(ScriptedInput(""), saveFile, loadFile = null) + val values = SaveCodec.decodeValues(saveFile.readLines()) + val prefix = values.localUserPrefix() + saveFile.writeText( + SaveCodec.encodeValues( + values + + mapOf( + "${prefix}party.x" to town.position.x.toString(), + "${prefix}party.y" to town.position.y.toString(), + "${prefix}party.gold" to "2000", + "${prefix}realm.hour" to hour.toString(), + ), + ), + ) + + val updates = mutableListOf() + runSession(ScriptedInput(commands), saveFile, loadFile = saveFile, presence = updates::add) + return updates.toList() + } + + private fun runSession( + input: RuntimeInputPort, + saveFile: File, + loadFile: File?, + presence: RuntimePresencePort = RuntimePresencePort.None, + ) { + RuntimeLog.open(testTmp.resolve("presence.log")).use { log -> + factory.start( + input = input, + screen = NoOpRuntimeScreen(), + config = + RuntimeSessionConfig( + userId = "local", + stateSlug = "fresh-replay", + loadFile = loadFile, + saveFile = saveFile, + sessionDate = LocalDate.of(2026, 5, 11), + ), + log = log, + presence = presence, + ) + } + } + + private fun Map.localUserPrefix(): String = + (1..getValue("users.count").toInt()) + .map { index -> "user.$index." } + .first { prefix -> get("${prefix}id") == "local" } +} diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/SharedWorldSaveTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/SharedWorldSaveTest.kt new file mode 100644 index 00000000..73158c14 --- /dev/null +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/SharedWorldSaveTest.kt @@ -0,0 +1,88 @@ +package rylween.runtime + +import org.junit.jupiter.api.io.TempDir +import rylween.compiled.CompiledNpcPlacement +import rylween.compiled.CompiledWorldPosition +import rylween.compiled.readExternalCompiledBundleContentHash +import rylween.compiled.readExternalCompiledGameBundle +import rylween.dsl.impl.GridPoint +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** Sessions read the shared world when they start, so a later save must not undo what another session saved since. */ +class SharedWorldSaveTest { + @TempDir + private lateinit var testTmp: File + private val bundleFile = File(requiredRuntimeTestProperty("rylween.runtime.bundle")) + private val bundle = bundleFile.readExternalCompiledGameBundle() + private val content = bundle.content + private val bundleHash = bundleFile.readExternalCompiledBundleContentHash() + private val state = bundle.states.single { content.slug(it.state) == "fresh-replay" } + private val initialRuntime = RuntimeState.from(state, content) + private val file get() = testTmp.resolve("world.rsave") + + @Test + fun aLaterSaveKeepsTheMissionsAnotherSessionCompleted() { + val (first, second) = content.missions.take(2).map { mission -> mission.id } + val alice = party("alice") + val bob = party("bob") + write(alice, "alice") + write(bob, "bob") + + write(alice.withCompletedMission(first), "alice") + val bobAfterSaving = write(bob.withCompletedMission(second), "bob") + + assertEquals(listOf(first, second), read("alice").completedMissions) + assertEquals(listOf(first, second), bobAfterSaving.completedMissions) + } + + @Test + fun anNpcStaysWhereTheFirstSaveReachingTheFilePutIt() { + val npc = content.characters.first().id + val placedFirst = CompiledNpcPlacement(npc, CompiledWorldPosition.Wilderness(GridPoint(3, 4))) + val placedLater = CompiledNpcPlacement(npc, CompiledWorldPosition.Wilderness(GridPoint(9, 9))) + + write(party("alice").copy(npcs = listOf(placedFirst)), "alice") + val bobAfterSaving = write(party("bob").copy(npcs = listOf(placedLater)), "bob") + + assertEquals(listOf(placedFirst), read("alice").npcs) + assertEquals(listOf(placedFirst), bobAfterSaving.npcs) + } + + @Test + fun eachPartyKeepsItsOwnClock() { + write(party("alice").copy(day = 2, hour = 3, minute = 15), "alice") + write(party("bob").copy(day = 5, hour = 20, minute = 45), "bob") + + assertEquals(Triple(2, 3, 15), read("alice").clock()) + assertEquals(Triple(5, 20, 45), read("bob").clock()) + } + + @Test + fun aPartySavedWhenTheWorldKeptOneClockKeepsThatClock() { + write(party("alice"), "alice") + val clockKeys = listOf("realm.day", "realm.hour", "realm.minute") + val withoutPartyClocks = + SaveCodec + .decodeValues(file.readLines()) + .filterKeys { key -> clockKeys.none { clockKey -> key.endsWith(".$clockKey") } } + file.writeText(SaveCodec.encodeValues(withoutPartyClocks + clockKeys.zip(listOf("4", "7", "30")))) + + write(party("bob").copy(hour = 22), "bob") + + assertEquals(Triple(4, 7, 30), read("alice").clock()) + assertEquals(22, read("bob").hour) + } + + private fun party(user: String): RuntimeState = initialRuntime.withParty(initialRuntime.party.copy(name = user)) + + private fun write( + runtime: RuntimeState, + user: String, + ): RuntimeState = SaveFile.write(file, runtime, bundleHash, content, user, null) + + private fun read(user: String): RuntimeState = SaveFile.read(file, content, { state }, user) + + private fun RuntimeState.clock(): Triple = Triple(day, hour, minute) +} diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/TownServiceHoursTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/TownServiceHoursTest.kt index 50c4741a..ba874a15 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/TownServiceHoursTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/TownServiceHoursTest.kt @@ -62,7 +62,7 @@ class TownServiceHoursTest { SaveCodec.encodeValues( values + mapOf( - "realm.hour" to hour.toString(), + "${prefix}realm.hour" to hour.toString(), "${prefix}party.x" to town.position.x.toString(), "${prefix}party.y" to town.position.y.toString(), ),