Add resource patch labels to the web map

Group nearby resource tiles of the same type into patches, and label
them on the map, e.g. "Iron ore / 2.4M", or "Crude oil / 12 wells".

- events-library: ResourcePatch model, shared by the server and map.
- events-server-web: ResourcePatchService reads the map-chunk-resource
  topic from the beginning (read_committed) into memory, and on request
  groups tiles into connected patches (join distance 2 tiles for ore,
  12 for infinite resources, whose wells are spread out). Results are
  cached until new data arrives.
  New endpoint: GET .../servers/{id}/map/resources/s{surface}/patches
- web-map: toggleable "Resource patches" overlay with labels at each
  patch centre and a hover tooltip, refreshed every minute. Patches
  under 10 tiles are hidden. (Surface 1 only, like the rest of the map.)
- events-mod: mark resources infinite based on the prototype's
  infinite_resource. Entity initial_amount is nil for e.g. crude oil, so
  oil fields were treated as hundreds of tiny ore patches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lazzexus 2026-10-13 07:07:23 +02:00
parent d5f722b998
commit 3d8673fe03
10 changed files with 388 additions and 5 deletions

View file

@ -0,0 +1,28 @@
package dev.adamko.kafkatorio.schema.common
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* A group of nearby resource tiles of the same type (an ore field, or an oil field), as shown on
* the in-game map.
*/
@Serializable
@SerialName("kafkatorio.resource.ResourcePatch")
data class ResourcePatch(
val protoId: PrototypeId,
val surfaceIndex: SurfaceIndex,
/**
* The total remaining amount. For infinite resources (e.g. crude oil) this is the sum of the
* current yields, so it's only meaningful relative to [tileCount].
*/
val totalAmount: Long,
/** The number of resource entities (ore tiles, or oil wells) in the patch. */
val tileCount: Int,
/** Infinite resources (e.g. crude oil) never deplete, and are counted by wells, not amount. */
val isInfinite: Boolean,
val centre: MapEntityPosition,
val leftTop: MapEntityPosition,
val rightBottom: MapEntityPosition,
)

View file

@ -198,10 +198,13 @@ export class EntityUpdatesHandler {
data.amounts[`${entity.position.x}`] ??= {}
data.amounts[`${entity.position.x}`][`${entity.position.y}`] = entity.amount
if (entity.initial_amount != null) {
// initial_amount can be nil even for infinite resources (e.g. crude oil), so also
// check the prototype. An initial amount marks the resource as infinite.
if (entity.prototype.infinite_resource) {
data.initialAmounts ??= {}
data.initialAmounts[`${entity.position.x}`] ??= {}
data.initialAmounts[`${entity.position.x}`][`${entity.position.y}`] = entity.initial_amount
data.initialAmounts[`${entity.position.x}`][`${entity.position.y}`] =
entity.initial_amount ?? entity.prototype.normal_resource_amount ?? 0
}
}
}

View file

@ -4,6 +4,7 @@ import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.processor.core.launchTopology
import dev.adamko.kafkatorio.server.processor.topology.broadcastToWebsocket
import dev.adamko.kafkatorio.server.processor.topology.saveMapTiles
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@ -17,6 +18,7 @@ internal val appProps = ApplicationProperties.load()
suspend fun main(): Unit = coroutineScope {
val wsServer = WebmapWebsocketServer()
val resourcePatchService = ResourcePatchService(appProps)
launch {
websocketBroadcaster(wsServer)
@ -30,10 +32,15 @@ suspend fun main(): Unit = coroutineScope {
saveTiles(appProps)
}
launch {
resourcePatchService.consume()
}
launch {
startWebServer(
appProps = appProps,
wsServer = wsServer,
resourcePatchService = resourcePatchService,
)
}
}

View file

@ -0,0 +1,227 @@
package dev.adamko.kafkatorio.server.web.resources
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.config.jsonMapper
import dev.adamko.kafkatorio.processor.config.topicName
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.MapChunkPosition
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
import dev.adamko.kafkatorio.schema.common.PrototypeId
import dev.adamko.kafkatorio.schema.common.ResourcePatch
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
import dev.adamko.kafkatorio.schema.packets.KafkatorioPacket
import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate
import java.time.Duration
import java.util.Properties
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.floor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.serialization.StringDeserializer
/**
* Keeps the latest amount of every resource tile in memory, and groups nearby tiles of the same
* resource into [ResourcePatch]es.
*
* Resource data is small, so instead of a Kafka Streams state store, the whole
* [MapChunkResourceUpdate] topic is read from the beginning on startup, and then followed.
*/
class ResourcePatchService(
private val appProps: ApplicationProperties,
) {
private data class ChunkKey(
val serverId: FactorioServerId,
val protoId: PrototypeId,
val surfaceIndex: SurfaceIndex,
val chunkPosition: MapChunkPosition,
)
private class ChunkResources(
val amounts: MutableMap<MapEntityPosition, UInt> = mutableMapOf(),
var isInfinite: Boolean = false,
)
private val chunks = ConcurrentHashMap<ChunkKey, ChunkResources>()
/** Incremented on every update, so cached patches can be invalidated. */
private val version = AtomicLong(0)
private data class CachedPatches(val version: Long, val patches: List<ResourcePatch>)
private val patchCache = ConcurrentHashMap<Pair<FactorioServerId, SurfaceIndex>, CachedPatches>()
/** Read all resource updates from the beginning of the topic, and keep following it. */
suspend fun consume(): Unit = withContext(Dispatchers.IO) {
val topic = MapChunkResourceUpdate::class.topicName
KafkaConsumer(consumerProperties(), StringDeserializer(), StringDeserializer()).use { consumer ->
val partitions = consumer.partitionsFor(topic).map { TopicPartition(it.topic(), it.partition()) }
consumer.assign(partitions)
consumer.seekToBeginning(partitions)
println("[ResourcePatchService] consuming $topic, partitions: ${partitions.size}")
while (isActive) {
val records = runInterruptible { consumer.poll(Duration.ofSeconds(1)) }
for (record in records) {
runCatching { handleRecord(record.key(), record.value()) }
.onFailure { println("[ResourcePatchService] failed to read record: $it") }
}
}
}
}
private fun consumerProperties() = Properties().apply {
putAll(appProps.kafkaStreamsConfig.filterKeys { it == ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG })
// Kafkatorio processors write transactionally - only read committed data
put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed")
put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
put(ConsumerConfig.CLIENT_ID_CONFIG, "kafkatorio.events-server-web.resource-patches")
}
private fun handleRecord(key: String?, value: String?) {
if (key == null || value == null) return
val serverId = jsonMapper.decodeFromString(FactorioServerId.serializer(), key)
val update = jsonMapper.decodeFromString(KafkatorioPacket.serializer(), value).data
as? MapChunkResourceUpdate ?: return
val chunkKey = ChunkKey(
serverId = serverId,
protoId = update.key.protoId,
surfaceIndex = update.key.surfaceIndex,
chunkPosition = update.key.chunkPosition,
)
val chunk = chunks.computeIfAbsent(chunkKey) { ChunkResources() }
synchronized(chunk) {
// Updates contain the current amount of the tiles that were (re-)scanned, so merge them.
// Note: depleted tiles aren't reported by the mod, so they keep their last known amount.
update.amounts.forEach { (position, amount) -> chunk.amounts[position] = amount }
if (update.initialAmounts.any()) chunk.isInfinite = true
}
version.incrementAndGet()
}
fun patches(serverId: FactorioServerId, surfaceIndex: SurfaceIndex): List<ResourcePatch> {
val currentVersion = version.get()
val cacheKey = serverId to surfaceIndex
patchCache[cacheKey]?.let { cached ->
if (cached.version == currentVersion) return cached.patches
}
val patches = computePatches(serverId, surfaceIndex)
patchCache[cacheKey] = CachedPatches(currentVersion, patches)
return patches
}
private fun computePatches(
serverId: FactorioServerId,
surfaceIndex: SurfaceIndex,
): List<ResourcePatch> {
// collect all tiles per resource prototype
val tilesByProto = mutableMapOf<PrototypeId, MutableMap<Long, UInt>>()
val infiniteProtos = mutableSetOf<PrototypeId>()
chunks.forEach { (key, chunk) ->
if (key.serverId != serverId || key.surfaceIndex != surfaceIndex) return@forEach
val tiles = tilesByProto.getOrPut(key.protoId) { mutableMapOf() }
synchronized(chunk) {
if (chunk.isInfinite) infiniteProtos += key.protoId
chunk.amounts.forEach { (position, amount) ->
tiles[packTile(floor(position.x).toInt(), floor(position.y).toInt())] = amount
}
}
}
return tilesByProto.flatMap { (protoId, tiles) ->
val isInfinite = protoId in infiniteProtos
// Ore tiles in a patch are (nearly) contiguous, but oil wells are spread out.
val joinDistance = if (isInfinite) INFINITE_RESOURCE_JOIN_DISTANCE else ORE_JOIN_DISTANCE
groupIntoPatches(tiles, joinDistance).map { patchTiles ->
createPatch(protoId, surfaceIndex, isInfinite, patchTiles, tiles)
}
}.sortedByDescending { it.tileCount }
}
/** Group tiles into connected components, where tiles within [joinDistance] are connected. */
private fun groupIntoPatches(tiles: Map<Long, UInt>, joinDistance: Int): List<List<Long>> {
val unvisited = tiles.keys.toMutableSet()
val patches = mutableListOf<List<Long>>()
while (unvisited.isNotEmpty()) {
val start = unvisited.first()
unvisited.remove(start)
val patch = mutableListOf(start)
val queue = ArrayDeque(listOf(start))
while (queue.isNotEmpty()) {
val tile = queue.removeFirst()
val x = unpackX(tile)
val y = unpackY(tile)
for (dx in -joinDistance..joinDistance) {
for (dy in -joinDistance..joinDistance) {
val neighbour = packTile(x + dx, y + dy)
if (unvisited.remove(neighbour)) {
patch += neighbour
queue += neighbour
}
}
}
}
patches += patch
}
return patches
}
private fun createPatch(
protoId: PrototypeId,
surfaceIndex: SurfaceIndex,
isInfinite: Boolean,
patchTiles: List<Long>,
amounts: Map<Long, UInt>,
): ResourcePatch {
val xs = patchTiles.map { unpackX(it) }
val ys = patchTiles.map { unpackY(it) }
return ResourcePatch(
protoId = protoId,
surfaceIndex = surfaceIndex,
totalAmount = patchTiles.sumOf { amounts.getValue(it).toLong() },
tileCount = patchTiles.size,
isInfinite = isInfinite,
// +0.5: the centre of the tile
centre = MapEntityPosition(xs.average() + 0.5, ys.average() + 0.5),
leftTop = MapEntityPosition(xs.min().toDouble(), ys.min().toDouble()),
rightBottom = MapEntityPosition(xs.max() + 1.0, ys.max() + 1.0),
)
}
companion object {
private const val ORE_JOIN_DISTANCE = 2
private const val INFINITE_RESOURCE_JOIN_DISTANCE = 12
/** Pack a tile coordinate into a single Long, for fast set lookups. */
private fun packTile(x: Int, y: Int): Long = (x.toLong() shl 32) or (y.toLong() and 0xFFFFFFFFL)
private fun unpackX(packed: Long): Int = (packed shr 32).toInt()
private fun unpackY(packed: Long): Int = packed.toInt()
}
}

View file

@ -7,6 +7,9 @@ import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.config.jsonMapper
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.schema.common.ResourcePatch
import kotlinx.serialization.builtins.ListSerializer
import io.ktor.http.HttpStatusCode
import io.ktor.http.content.EntityTagVersion
import io.ktor.http.content.versions
@ -27,6 +30,7 @@ import kotlinx.serialization.json.encodeToJsonElement
internal fun Routing.factorioServersRoutes(
appProps: ApplicationProperties,
resourcePatchService: ResourcePatchService,
) {
get<FactorioServers> {
@ -38,6 +42,11 @@ internal fun Routing.factorioServersRoutes(
get<FactorioServer.MapData.Tile> { tile ->
handleTileRequest(tile, appProps)
}
get<FactorioServer.MapData.ResourcePatches> { request ->
val patches = resourcePatchService.patches(request.mapData.server.factorioServerId, request.surfaceIndex)
call.respond(jsonMapper.encodeToJsonElement(ListSerializer(ResourcePatch.serializer()), patches))
}
}
@ -101,6 +110,13 @@ data class FactorioServer(
val chunkY: Int,
)
@Serializable
@Resource("resources/s{surfaceIndex}/patches")
data class ResourcePatches(
val mapData: MapData,
val surfaceIndex: SurfaceIndex,
)
@Serializable
@Resource("buildings/s{surfaceIndex}")
data class Buildings(

View file

@ -1,6 +1,7 @@
package dev.adamko.kafkatorio.server.web.rest
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.isSuccess
@ -22,7 +23,10 @@ import io.ktor.server.response.respondText
import io.ktor.server.routing.routing
internal fun Application.webmapTileServer(appProps: ApplicationProperties) {
internal fun Application.webmapTileServer(
appProps: ApplicationProperties,
resourcePatchService: ResourcePatchService,
) {
install(AutoHeadResponse)
install(CallLogging) {
@ -51,6 +55,6 @@ internal fun Application.webmapTileServer(appProps: ApplicationProperties) {
}
routing {
factorioServersRoutes(appProps)
factorioServersRoutes(appProps, resourcePatchService)
}
}

View file

@ -2,6 +2,7 @@ package dev.adamko.kafkatorio.server.web
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.rest.webmapTileServer
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
import dev.adamko.kafkatorio.server.web.websocket.webmapWebsocketServer
@ -13,6 +14,7 @@ import kotlinx.coroutines.coroutineScope
internal suspend fun startWebServer(
appProps: ApplicationProperties,
wsServer: WebmapWebsocketServer,
resourcePatchService: ResourcePatchService,
): Unit = coroutineScope {
embeddedServer(
@ -22,7 +24,7 @@ internal suspend fun startWebServer(
webmapWebsocketServer(wsServer)
webmapTileServer(appProps)
webmapTileServer(appProps, resourcePatchService)
}.start(wait = true)
}

View file

@ -1,12 +1,15 @@
package dev.adamko.kafkatorio.webmap
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.ResourcePatch
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.tileOnLoad
import dev.adamko.kafkatorio.webmap.services.EventsServerClient
import dev.adamko.kafkatorio.webmap.services.WebsocketService
import dev.adamko.kafkatorio.webmap.services.latLng
import io.kvision.maps.Maps
import io.kvision.maps.Maps.Companion.L
import io.kvision.maps.externals.leaflet.DoneCallback
@ -27,6 +30,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.await
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@ -39,6 +43,7 @@ import org.w3c.fetch.RELOAD
import org.w3c.fetch.RequestCache
import org.w3c.fetch.RequestInit
import org.w3c.fetch.RequestMode
import kotlin.time.Duration.Companion.seconds
class FactorioMap(
@ -65,6 +70,8 @@ class FactorioMap(
val playerIconsLayer: LayerGroup = LayerGroup()
private val resourcePatchesLayer: LayerGroup = LayerGroup()
init {
val baseLayers: Control.LayersObject = jso {
@ -73,6 +80,7 @@ class FactorioMap(
val overlays: Control.LayersObject = jso {
set("Players", playerIconsLayer)
set("Resource patches", resourcePatchesLayer)
set("Resources", resourcesTileLayer)
set("Buildings", buildingsTileLayer)
}
@ -104,6 +112,15 @@ class FactorioMap(
buildingsTileLayer.addTo(this)
playerIconsLayer.addTo(this)
resourcePatchesLayer.addTo(this)
}
coroutineScope.launch {
while (true) {
runCatching { refreshResourcePatches() }
.onFailure { println("[FactorioMap] failed to refresh resource patches: $it") }
delay(60.seconds)
}
}
@ -147,6 +164,24 @@ class FactorioMap(
}
private suspend fun refreshResourcePatches() {
// TODO the map only shows surface 1 (Nauvis) for now
val patches = EventsServerClient.resourcePatches(serverId, surfaceIndex = 1)
.filter { it.isInfinite || it.tileCount >= MIN_RESOURCE_PATCH_TILES }
resourcePatchesLayer.clearLayers()
patches.forEach { patch ->
val label = L.divIcon {
className = "resource-patch-label"
html = "<span>${patch.displayName()}<br>${patch.displayAmount()}</span>"
}
L.marker(patch.centre.latLng()) {
icon = label
}.bindTooltip(patch.tooltip()).addTo(resourcePatchesLayer)
}
}
private fun createServerTileLayer(
layer: ServerMapTileLayer
): TileLayer<TileLayer.TileLayerOptions> {
@ -191,5 +226,35 @@ class FactorioMap(
companion object {
/** Add this attribute to `<img>` tiles that need to be dynamically refreshed. */
const val DYNAMIC_RELOAD_ATT = "dynamic-reload"
/** Hide stray resource tiles that aren't really a patch */
private const val MIN_RESOURCE_PATCH_TILES = 10
}
}
/** e.g. `iron-ore` -> `Iron ore` */
private fun ResourcePatch.displayName(): String =
protoId.name.toString().replace('-', ' ').replaceFirstChar { it.uppercase() }
/** e.g. `2.4M`, or `12 wells` for infinite resources */
private fun ResourcePatch.displayAmount(): String =
if (isInfinite) "$tileCount wells" else formatAmount(totalAmount)
private fun ResourcePatch.tooltip(): String = buildString {
append("${displayName()}: ")
append(if (isInfinite) "$tileCount wells" else "${formatAmount(totalAmount)} in $tileCount tiles")
val width = (rightBottom.x - leftTop.x).toInt()
val height = (rightBottom.y - leftTop.y).toInt()
append(" (${width}x$height, centre [${centre.x.toInt()}, ${centre.y.toInt()}])")
}
private fun formatAmount(amount: Long): String = when {
amount >= 1_000_000_000 -> "${(amount / 100_000_000) / 10.0}B"
amount >= 1_000_000 -> "${(amount / 100_000) / 10.0}M"
amount >= 1_000 -> "${(amount / 100) / 10.0}k"
else -> "$amount"
}

View file

@ -1,6 +1,9 @@
package dev.adamko.kafkatorio.webmap.services
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.ResourcePatch
import dev.adamko.kafkatorio.webmap.config.jsonMapper
import kotlinx.serialization.builtins.ListSerializer
import io.kvision.rest.RestClient
import io.kvision.rest.call
import kotlinx.browser.window
@ -22,4 +25,12 @@ object EventsServerClient :
.await()
/** 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"
val json = window.fetch(url).await().text().await()
return jsonMapper.decodeFromString(ListSerializer(ResourcePatch.serializer()), json)
}
}

View file

@ -11,3 +11,23 @@
/* make the Leaflet map background transparent, so it matches the site theme */
background-color: rgba(255, 0, 0, 0.0) !important;
}
/* resource patch labels, e.g. 'Iron ore / 2.4M' - centred on the patch, readable on any terrain */
.resource-patch-label {
width: auto !important;
height: auto !important;
background: none;
border: none;
}
.resource-patch-label span {
display: block;
transform: translate(-50%, -50%);
white-space: nowrap;
text-align: center;
font-size: 12px;
font-weight: bold;
line-height: 1.2;
color: #fff;
text-shadow: 0 0 3px #000, 0 0 3px #000, 0 0 2px #000;
}