Show building rotation, recipes and other surfaces on the web map
The mod now sends each building's direction and recipe (furnaces: the last recipe, since they only have one while working). - Rotated buildings are drawn at their real footprint. - Crafting machines show their recipe icon, like Factorio's alt mode, and the hover tooltip includes the recipe. The web map has a surface drop-down (e.g. Space Exploration planets and orbits), backed by a new surfaces endpoint. Every layer, the resource labels and the player markers follow the chosen surface. Resource labels use the in-game names (e.g. "Iridite" instead of "Se iridium ore"). export_building_icons.py also exports recipe icons, plus recipe and resource names. The three in-memory views in events-server-web now share one helper for following a Kafka topic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7ef4918a5c
commit
b9adb9ea83
20 changed files with 482 additions and 139 deletions
|
|
@ -9,6 +9,7 @@ import io.kvision.maps.externals.leaflet.geo.LatLng
|
|||
import io.kvision.maps.externals.leaflet.layer.Layer
|
||||
import io.kvision.maps.externals.leaflet.map.LeafletMap
|
||||
import js.core.jso
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
|
@ -47,8 +48,22 @@ class BuildingIconsLayer(
|
|||
/** [buildingInfo], once loaded (for use outside of coroutines) */
|
||||
private var loadedBuildingInfo: Map<String, BuildingInfo> = emptyMap()
|
||||
|
||||
/** Recipe display names, by recipe name */
|
||||
private val recipeNames: Deferred<Map<String, String>> = coroutineScope.async {
|
||||
runCatching { EventsServerClient.recipeNames() }
|
||||
.onFailure { println("[BuildingIconsLayer] failed to load recipe names: $it") }
|
||||
.getOrDefault(emptyMap())
|
||||
.also { loadedRecipeNames = it }
|
||||
}
|
||||
|
||||
/** [recipeNames], once loaded (for use outside of coroutines) */
|
||||
private var loadedRecipeNames: Map<String, String> = emptyMap()
|
||||
|
||||
private val icons = mutableMapOf<String, Deferred<Image?>>()
|
||||
|
||||
/** The surface that's shown. Nauvis is surface 1. */
|
||||
private var surfaceIndex: Int = 1
|
||||
|
||||
/** The buildings on loaded tiles, by [cellKey], for finding the hovered building. */
|
||||
private val hoverIndex = mutableMapOf<String, MutableMap<String, MapBuilding>>()
|
||||
|
||||
|
|
@ -89,6 +104,14 @@ class BuildingIconsLayer(
|
|||
}
|
||||
|
||||
|
||||
/** Switch to another surface, and re-draw all tiles */
|
||||
fun showSurface(index: Int) {
|
||||
surfaceIndex = index
|
||||
hoverIndex.clear()
|
||||
layer.asDynamic().redraw()
|
||||
}
|
||||
|
||||
|
||||
/** Show a tooltip for the building under the mouse */
|
||||
fun onMouseMove(map: LeafletMap, latLng: LatLng) {
|
||||
if (!map.hasLayer(layer) || map.getZoom().toDouble() < MIN_ZOOM) {
|
||||
|
|
@ -105,17 +128,19 @@ class BuildingIconsLayer(
|
|||
hoverIndex[cellKey(x + dx * CELL_SIZE, y + dy * CELL_SIZE)]
|
||||
}
|
||||
}.flatMap { it.values }
|
||||
.firstOrNull { building ->
|
||||
val half = building.iconSize(info) / 2.0
|
||||
x >= building.position.x - half && x < building.position.x + half
|
||||
&& y >= building.position.y - half && y < building.position.y + half
|
||||
.filter { building ->
|
||||
val (w, h) = building.footprint(info)
|
||||
x >= building.position.x - w / 2.0 && x < building.position.x + w / 2.0
|
||||
&& y >= building.position.y - h / 2.0 && y < building.position.y + h / 2.0
|
||||
}
|
||||
// prefer small buildings, e.g. an inserter next to an assembler
|
||||
.minByOrNull { it.iconSize(info) }
|
||||
|
||||
if (hovered == null) {
|
||||
map.closeTooltip(hoverTooltip)
|
||||
} else {
|
||||
hoverTooltip.setLatLng(latLng)
|
||||
hoverTooltip.setContent(hovered.tooltip(info))
|
||||
hoverTooltip.setContent(hovered.tooltip(info, loadedRecipeNames))
|
||||
if (!map.hasLayer(hoverTooltip)) map.openTooltip(hoverTooltip)
|
||||
}
|
||||
}
|
||||
|
|
@ -133,52 +158,81 @@ class BuildingIconsLayer(
|
|||
val left = tileX * tileSizeInMap
|
||||
val top = tileY * tileSizeInMap
|
||||
|
||||
val surface = surfaceIndex
|
||||
// also get buildings that are centred on a neighbouring tile, but overlap this one
|
||||
val buildings = EventsServerClient.buildings(
|
||||
serverId,
|
||||
surfaceIndex = 1, // TODO the map only shows surface 1 (Nauvis) for now
|
||||
surfaceIndex = surface,
|
||||
left = left - MAX_BUILDING_SIZE,
|
||||
top = top - MAX_BUILDING_SIZE,
|
||||
right = left + tileSizeInMap + MAX_BUILDING_SIZE,
|
||||
bottom = top + tileSizeInMap + MAX_BUILDING_SIZE,
|
||||
)
|
||||
val info = buildingInfo.await()
|
||||
val recipes = recipeNames.await()
|
||||
|
||||
// the surface might have changed while fetching
|
||||
if (surface != surfaceIndex) return
|
||||
|
||||
updateHoverIndex(left, top, left + tileSizeInMap, top + tileSizeInMap, buildings)
|
||||
|
||||
// load the icons before drawing, so the canvas is updated in one go
|
||||
val buildingIcons = buildings.associateWith { icon(it.protoId.name.toString(), info) }
|
||||
.mapValues { (_, icon) -> icon?.await() }
|
||||
val buildingIcons = buildings.associateWith { building ->
|
||||
building.protoId.name.toString().takeIf { it in info }?.let { icon("entity", it) }
|
||||
}.mapValues { (_, icon) -> icon?.await() }
|
||||
|
||||
// like Factorio's 'alt mode', show the recipe on crafting machines, if it's big enough to see
|
||||
val showRecipes = zoom >= RECIPE_MIN_ZOOM
|
||||
val recipeIcons = if (!showRecipes) emptyMap() else buildings.associateWith { building ->
|
||||
building.recipe?.takeIf { it in recipes }?.let { icon("recipe", it) }
|
||||
}.mapValues { (_, icon) -> icon?.await() }
|
||||
|
||||
val ctx = canvas.getContext("2d") as CanvasRenderingContext2D
|
||||
ctx.clearRect(0.0, 0.0, TILE_SIZE.toDouble(), TILE_SIZE.toDouble())
|
||||
|
||||
// draw big buildings first, so small ones (like inserters) are on top
|
||||
buildings.sortedByDescending { it.iconSize(info) }.forEach { building ->
|
||||
val size = building.iconSize(info) * scale
|
||||
val px = (building.position.x - left) * scale - size / 2
|
||||
val py = (building.position.y - top) * scale - size / 2
|
||||
val centreX = (building.position.x - left) * scale
|
||||
val centreY = (building.position.y - top) * scale
|
||||
|
||||
// icons are square, so show the real footprint of rectangular buildings underneath
|
||||
val (w, h) = building.footprint(info)
|
||||
if (w != h) {
|
||||
ctx.fillStyle = "rgba(0, 0, 0, 0.35)"
|
||||
ctx.fillRect(centreX - w * scale / 2, centreY - h * scale / 2, w * scale, h * scale)
|
||||
}
|
||||
|
||||
val size = building.iconSize(info) * scale
|
||||
val icon = buildingIcons[building]
|
||||
if (icon != null) {
|
||||
ctx.drawImage(icon, px, py, size, size)
|
||||
ctx.drawImage(icon, centreX - size / 2, centreY - size / 2, size, size)
|
||||
} else {
|
||||
// no icon - show the outline of the building
|
||||
ctx.fillStyle = "rgba(160, 160, 160, 0.6)"
|
||||
ctx.fillRect(px, py, size, size)
|
||||
ctx.fillRect(centreX - size / 2, centreY - size / 2, size, size)
|
||||
}
|
||||
|
||||
val recipeIcon = recipeIcons[building]
|
||||
if (recipeIcon != null) {
|
||||
val recipeSize = size * 0.6
|
||||
ctx.fillStyle = "rgba(0, 0, 0, 0.6)"
|
||||
ctx.beginPath()
|
||||
ctx.arc(centreX, centreY, recipeSize * 0.6, 0.0, 2 * PI)
|
||||
ctx.fill()
|
||||
ctx.drawImage(recipeIcon, centreX - recipeSize / 2, centreY - recipeSize / 2, recipeSize, recipeSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun icon(name: String, info: Map<String, BuildingInfo>): Deferred<Image?>? {
|
||||
if (name !in info) return null
|
||||
return icons.getOrPut(name) {
|
||||
/** Load an icon from `/kafkatorio/icons/{type}/{name}.png` */
|
||||
private fun icon(type: String, name: String): Deferred<Image?> {
|
||||
return icons.getOrPut("$type/$name") {
|
||||
val deferred = CompletableDeferred<Image?>()
|
||||
val img = Image()
|
||||
img.onload = { deferred.complete(img) }
|
||||
img.onerror = { _, _, _, _, _ -> deferred.complete(null) }
|
||||
img.src = "/kafkatorio/icons/entity/$name.png"
|
||||
img.src = "/kafkatorio/icons/$type/$name.png"
|
||||
deferred
|
||||
}
|
||||
}
|
||||
|
|
@ -211,6 +265,9 @@ class BuildingIconsLayer(
|
|||
/** At lower zoom levels icons are too small to see. (At zoom 2, 1 Factorio tile is 4 pixels.) */
|
||||
private const val MIN_ZOOM = 2
|
||||
|
||||
/** Recipe icons are too small to see at lower zoom levels */
|
||||
private const val RECIPE_MIN_ZOOM = 4
|
||||
|
||||
/** The largest building, in tiles, so buildings that overlap tile edges are included */
|
||||
private const val MAX_BUILDING_SIZE = 16.0
|
||||
|
||||
|
|
@ -223,19 +280,32 @@ class BuildingIconsLayer(
|
|||
}
|
||||
|
||||
|
||||
/**
|
||||
* The icon is drawn as a square, because the mod doesn't send the direction of buildings, so
|
||||
* whether a building like a boiler (3x2) is rotated isn't known.
|
||||
*/
|
||||
/** Icons are drawn as squares, fitting inside the building. */
|
||||
private fun MapBuilding.iconSize(info: Map<String, BuildingInfo>): Int {
|
||||
val building = info[protoId.name.toString()] ?: return 1
|
||||
return max(1, min(building.w, building.h))
|
||||
val (w, h) = footprint(info)
|
||||
return max(1, min(w, h))
|
||||
}
|
||||
|
||||
|
||||
private fun MapBuilding.tooltip(info: Map<String, BuildingInfo>): String = buildString {
|
||||
/** The width and height in tiles, rotated if the building faces east or west */
|
||||
private fun MapBuilding.footprint(info: Map<String, BuildingInfo>): Pair<Int, Int> {
|
||||
val building = info[protoId.name.toString()] ?: return 1 to 1
|
||||
val isSideways = direction?.toInt() == DIRECTION_EAST || direction?.toInt() == DIRECTION_WEST
|
||||
return if (isSideways) building.h to building.w else building.w to building.h
|
||||
}
|
||||
|
||||
/** `defines.direction.east` - Factorio 2.0 has 16 directions, clockwise from north (0) */
|
||||
private const val DIRECTION_EAST = 4
|
||||
private const val DIRECTION_WEST = 12
|
||||
|
||||
|
||||
private fun MapBuilding.tooltip(
|
||||
info: Map<String, BuildingInfo>,
|
||||
recipeNames: Map<String, String>,
|
||||
): String = buildString {
|
||||
val name = protoId.name.toString()
|
||||
append("<b>${info[name]?.name ?: name}</b>")
|
||||
recipe?.let { append("<br>Recipe: ${recipeNames[it] ?: it}") }
|
||||
status?.let { append("<br>${it.name.lowercase().replace('_', ' ').replaceFirstChar(Char::uppercase)}") }
|
||||
health?.let { append("<br>Health: ${it.toInt()}") }
|
||||
append("<br>[${floor(position.x).toInt()}, ${floor(position.y).toInt()}]")
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import dev.adamko.kafkatorio.schema.common.ServerMapTileLayer
|
|||
import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename
|
||||
import dev.adamko.kafkatorio.schema.packets.EventServerPacket
|
||||
import dev.adamko.kafkatorio.webmap.externals.TileOnLoadFn
|
||||
import dev.adamko.kafkatorio.webmap.externals.leaflet
|
||||
import dev.adamko.kafkatorio.webmap.externals.tileOnLoad
|
||||
import dev.adamko.kafkatorio.webmap.services.EventsServerClient
|
||||
import dev.adamko.kafkatorio.webmap.services.WebsocketService
|
||||
|
|
@ -20,6 +21,8 @@ import io.kvision.maps.externals.leaflet.geo.CRS
|
|||
import io.kvision.maps.externals.leaflet.geo.LatLng
|
||||
import io.kvision.maps.externals.leaflet.layer.LayerGroup
|
||||
import io.kvision.maps.externals.leaflet.layer.tile.TileLayer
|
||||
import io.kvision.maps.externals.leaflet.layer.vector.CircleMarker
|
||||
import io.kvision.maps.externals.leaflet.map.LeafletMap
|
||||
import io.kvision.utils.px
|
||||
import js.core.jso
|
||||
import kotlinx.browser.document
|
||||
|
|
@ -36,6 +39,8 @@ import kotlinx.coroutines.flow.launchIn
|
|||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import org.w3c.dom.HTMLElement
|
||||
import org.w3c.dom.HTMLOptionElement
|
||||
import org.w3c.dom.HTMLSelectElement
|
||||
import org.w3c.dom.Image
|
||||
import org.w3c.dom.asList
|
||||
import org.w3c.fetch.NO_CORS
|
||||
|
|
@ -64,6 +69,9 @@ class FactorioMap(
|
|||
margin = 10.px
|
||||
}
|
||||
|
||||
/** The surface that's shown. Nauvis is surface 1. */
|
||||
private var surfaceIndex: Int = 1
|
||||
|
||||
private val terrainTileLayer: TileLayer<*> = createServerTileLayer(ServerMapTileLayer.TERRAIN)
|
||||
private val resourcesTileLayer: TileLayer<*> = createServerTileLayer(ServerMapTileLayer.RESOURCE)
|
||||
private val buildingsTileLayer: TileLayer<*> = createServerTileLayer(ServerMapTileLayer.BUILDING)
|
||||
|
|
@ -74,6 +82,14 @@ class FactorioMap(
|
|||
|
||||
private val buildingIconsLayer = BuildingIconsLayer(serverId, coroutineScope)
|
||||
|
||||
/** Resource display names (e.g. `se-iridium-ore` -> `Iridite`), if they've been exported */
|
||||
private var resourceNames: Map<String, String>? = null
|
||||
|
||||
/** Player markers, and the surface each player is on */
|
||||
private val playerMarkers = mutableMapOf<CircleMarker, Int?>()
|
||||
|
||||
private val surfaceSelect = document.createElement("select") as HTMLSelectElement
|
||||
|
||||
init {
|
||||
|
||||
val baseLayers: Control.LayersObject = jso {
|
||||
|
|
@ -109,6 +125,7 @@ class FactorioMap(
|
|||
options.zoomDelta = 0.1
|
||||
// options.fadeAnimation = false
|
||||
addControl(layersControl)
|
||||
addSurfaceControl(this)
|
||||
|
||||
terrainTileLayer.addTo(this)
|
||||
resourcesTileLayer.addTo(this)
|
||||
|
|
@ -139,6 +156,14 @@ class FactorioMap(
|
|||
}
|
||||
}
|
||||
|
||||
coroutineScope.launch {
|
||||
while (true) {
|
||||
runCatching { refreshSurfaces() }
|
||||
.onFailure { println("[FactorioMap] failed to refresh surfaces: $it") }
|
||||
delay(60.seconds)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
WebsocketService.packetsFlow
|
||||
.filterIsInstance<EventServerPacket.ChunkTileSaved>()
|
||||
|
|
@ -180,20 +205,109 @@ class FactorioMap(
|
|||
}
|
||||
|
||||
|
||||
/** Show a player's marker only if they're on the shown surface */
|
||||
fun updatePlayerMarker(previous: CircleMarker?, updated: CircleMarker?, surfaceIndex: Int?) {
|
||||
if (previous != null && previous != updated) {
|
||||
playerMarkers.remove(previous)
|
||||
playerIconsLayer.removeLayer(previous)
|
||||
}
|
||||
if (updated != null) {
|
||||
playerMarkers[updated] = surfaceIndex
|
||||
if (surfaceIndex == this.surfaceIndex) {
|
||||
if (!playerIconsLayer.hasLayer(updated)) playerIconsLayer.addLayer(updated)
|
||||
} else {
|
||||
playerIconsLayer.removeLayer(updated)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** A drop-down for choosing which surface (e.g. planet) is shown */
|
||||
private fun addSurfaceControl(map: LeafletMap) {
|
||||
val control = leaflet.control(jso<dynamic> { this.position = "topleft" })
|
||||
control.onAdd = { _: dynamic ->
|
||||
val container = document.createElement("div") as HTMLElement
|
||||
container.className = "leaflet-bar surface-select"
|
||||
container.appendChild(surfaceSelect)
|
||||
leaflet.DomEvent.disableClickPropagation(container)
|
||||
leaflet.DomEvent.disableScrollPropagation(container)
|
||||
container
|
||||
}
|
||||
control.addTo(map)
|
||||
|
||||
surfaceSelect.onchange = {
|
||||
surfaceSelect.value.toIntOrNull()?.let { showSurface(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private suspend fun refreshSurfaces() {
|
||||
val surfaces = EventsServerClient.surfaces(serverId)
|
||||
// e.g. `nauvis` -> `Nauvis`
|
||||
val options = surfaces.map { it.index.toString().toInt() to it.name.replaceFirstChar(Char::uppercase) }
|
||||
val current = (0 until surfaceSelect.options.length).map { i ->
|
||||
val option = surfaceSelect.options.item(i) as HTMLOptionElement
|
||||
option.value.toInt() to option.text
|
||||
}
|
||||
if (options == current) return
|
||||
|
||||
surfaceSelect.innerHTML = ""
|
||||
options.forEach { (index, name) ->
|
||||
val option = document.createElement("option") as HTMLOptionElement
|
||||
option.value = "$index"
|
||||
option.text = name
|
||||
surfaceSelect.appendChild(option)
|
||||
}
|
||||
surfaceSelect.value = "$surfaceIndex"
|
||||
}
|
||||
|
||||
|
||||
private fun showSurface(index: Int) {
|
||||
if (index == surfaceIndex) return
|
||||
println("[FactorioMap] showing surface $index")
|
||||
surfaceIndex = index
|
||||
|
||||
listOf(
|
||||
ServerMapTileLayer.TERRAIN to terrainTileLayer,
|
||||
ServerMapTileLayer.RESOURCE to resourcesTileLayer,
|
||||
ServerMapTileLayer.BUILDING to buildingsTileLayer,
|
||||
).forEach { (layer, tileLayer) ->
|
||||
tileLayer.setUrl(tileLayerUrlTemplate(layer), noRedraw = false)
|
||||
}
|
||||
|
||||
buildingIconsLayer.showSurface(index)
|
||||
|
||||
resourcePatchesLayer.clearLayers()
|
||||
coroutineScope.launch {
|
||||
runCatching { refreshResourcePatches() }
|
||||
.onFailure { println("[FactorioMap] failed to refresh resource patches: $it") }
|
||||
}
|
||||
|
||||
playerMarkers.forEach { (marker, surface) ->
|
||||
if (surface == index) playerIconsLayer.addLayer(marker) else playerIconsLayer.removeLayer(marker)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private suspend fun refreshResourcePatches() {
|
||||
// TODO the map only shows surface 1 (Nauvis) for now
|
||||
val patches = EventsServerClient.resourcePatches(serverId, surfaceIndex = 1)
|
||||
val surface = surfaceIndex
|
||||
val names = resourceNames
|
||||
?: runCatching { EventsServerClient.resourceNames() }.getOrDefault(emptyMap()).also { resourceNames = it }
|
||||
val patches = EventsServerClient.resourcePatches(serverId, surfaceIndex = surface)
|
||||
.filter { it.isInfinite || it.tileCount >= MIN_RESOURCE_PATCH_TILES }
|
||||
|
||||
// the surface might have changed while fetching
|
||||
if (surface != surfaceIndex) return
|
||||
|
||||
resourcePatchesLayer.clearLayers()
|
||||
patches.forEach { patch ->
|
||||
val label = L.divIcon {
|
||||
className = "resource-patch-label"
|
||||
html = "<span>${patch.displayName()}<br>${patch.displayAmount()}</span>"
|
||||
html = "<span>${patch.displayName(names)}<br>${patch.displayAmount()}</span>"
|
||||
}
|
||||
L.marker(patch.centre.latLng()) {
|
||||
icon = label
|
||||
}.bindTooltip(patch.tooltip()).addTo(resourcePatchesLayer)
|
||||
}.bindTooltip(patch.tooltip(names)).addTo(resourcePatchesLayer)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -237,7 +351,7 @@ class FactorioMap(
|
|||
}
|
||||
|
||||
private fun tileLayerUrlTemplate(layer: ServerMapTileLayer): String =
|
||||
"/kafkatorio/data/servers/${serverId.id}/map/layers/${layer.dir}/s1/z{z}/x{x}/y{y}.png"
|
||||
"/kafkatorio/data/servers/${serverId.id}/map/layers/${layer.dir}/s$surfaceIndex/z{z}/x{x}/y{y}.png"
|
||||
|
||||
companion object {
|
||||
/** Add this attribute to `<img>` tiles that need to be dynamically refreshed. */
|
||||
|
|
@ -249,9 +363,10 @@ class FactorioMap(
|
|||
}
|
||||
|
||||
|
||||
/** e.g. `iron-ore` -> `Iron ore` */
|
||||
private fun ResourcePatch.displayName(): String =
|
||||
protoId.name.toString().replace('-', ' ').replaceFirstChar { it.uppercase() }
|
||||
/** The in-game name, or e.g. `iron-ore` -> `Iron ore` if the names haven't been exported */
|
||||
private fun ResourcePatch.displayName(names: Map<String, String>): String =
|
||||
names[protoId.name.toString()]
|
||||
?: protoId.name.toString().replace('-', ' ').replaceFirstChar { it.uppercase() }
|
||||
|
||||
|
||||
/** e.g. `2.4M`, or `12 wells` for infinite resources */
|
||||
|
|
@ -262,8 +377,8 @@ private fun ResourcePatch.displayAmount(): String =
|
|||
private fun ResourcePatch.wells(): String = if (tileCount == 1) "1 well" else "$tileCount wells"
|
||||
|
||||
|
||||
private fun ResourcePatch.tooltip(): String = buildString {
|
||||
append("${displayName()}: ")
|
||||
private fun ResourcePatch.tooltip(names: Map<String, String>): String = buildString {
|
||||
append("${displayName(names)}: ")
|
||||
append(if (isInfinite) wells() else "${formatAmount(totalAmount)} in $tileCount tiles")
|
||||
val width = (rightBottom.x - leftTop.x).toInt()
|
||||
val height = (rightBottom.y - leftTop.y).toInt()
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package dev.adamko.kafkatorio.webmap.services
|
|||
|
||||
import dev.adamko.kafkatorio.schema.common.FactorioServerId
|
||||
import dev.adamko.kafkatorio.schema.common.MapBuilding
|
||||
import dev.adamko.kafkatorio.schema.common.MapSurface
|
||||
import dev.adamko.kafkatorio.schema.common.ResourcePatch
|
||||
import dev.adamko.kafkatorio.webmap.config.jsonMapper
|
||||
import kotlinx.serialization.Serializable
|
||||
|
|
@ -29,6 +30,14 @@ object EventsServerClient :
|
|||
.await()
|
||||
|
||||
|
||||
/** Fetch the surfaces that have a map. */
|
||||
suspend fun surfaces(serverId: FactorioServerId): List<MapSurface> {
|
||||
val url = "${window.location.origin}/kafkatorio/data/servers/${serverId.id}/map/surfaces"
|
||||
val json = window.fetch(url).await().text().await()
|
||||
return jsonMapper.decodeFromString(ListSerializer(MapSurface.serializer()), json)
|
||||
}
|
||||
|
||||
|
||||
/** Fetch the resource patches (ore fields, oil fields) on a surface. */
|
||||
suspend fun resourcePatches(serverId: FactorioServerId, surfaceIndex: Int): List<ResourcePatch> {
|
||||
val url = "${window.location.origin}/kafkatorio/data/servers/${serverId.id}/map/resources/s$surfaceIndex/patches"
|
||||
|
|
@ -65,6 +74,22 @@ object EventsServerClient :
|
|||
val json = response.text().await()
|
||||
return jsonMapper.decodeFromString(MapSerializer(String.serializer(), BuildingInfo.serializer()), json)
|
||||
}
|
||||
|
||||
|
||||
/** Fetch the display name of each recipe, by recipe name (exported like [buildingInfo]). */
|
||||
suspend fun recipeNames(): Map<String, String> = displayNames("recipes.json")
|
||||
|
||||
|
||||
/** Fetch the display name of each resource, by resource name (exported like [buildingInfo]). */
|
||||
suspend fun resourceNames(): Map<String, String> = displayNames("resources.json")
|
||||
|
||||
|
||||
private suspend fun displayNames(filename: String): Map<String, String> {
|
||||
val response = window.fetch("${window.location.origin}/kafkatorio/icons/$filename").await()
|
||||
if (!response.ok) return emptyMap()
|
||||
val json = response.text().await()
|
||||
return jsonMapper.decodeFromString(MapSerializer(String.serializer(), String.serializer()), json)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -31,16 +31,12 @@ private fun FactorioGameState.handlePlayerUpdate(
|
|||
|
||||
val updated = previous.update(update.tick, update.data)
|
||||
|
||||
if (previous.mapMarker != updated.mapMarker) {
|
||||
if (previous.mapMarker != null) {
|
||||
println("removing player icon ${previous.index}")
|
||||
playerIconsLayer.removeLayer(previous.mapMarker)
|
||||
}
|
||||
if (updated.mapMarker != null) {
|
||||
println("adding player icon ${updated.index}")
|
||||
playerIconsLayer.addLayer(updated.mapMarker)
|
||||
}
|
||||
}
|
||||
// only shown if the player is on the surface that the map shows
|
||||
map.updatePlayerMarker(
|
||||
previous = previous.mapMarker,
|
||||
updated = updated.mapMarker,
|
||||
surfaceIndex = updated.playerDetails.surfaceIndex?.toString()?.toInt(),
|
||||
)
|
||||
|
||||
val updatedPlayersState = players + (previous.index to updated)
|
||||
return copy(players = updatedPlayersState)
|
||||
|
|
|
|||
|
|
@ -31,3 +31,12 @@
|
|||
color: #fff;
|
||||
text-shadow: 0 0 3px #000, 0 0 3px #000, 0 0 2px #000;
|
||||
}
|
||||
|
||||
.surface-select select {
|
||||
border: none;
|
||||
padding: 4px 6px;
|
||||
font-size: 14px;
|
||||
background: #fff;
|
||||
color: #333;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue