Add a building icon layer to the web map
events-server-web keeps the latest state of every building in memory (read from the map-chunk-entity topic, like the resource patches) and serves them per area. The web map draws the icons at their real size onto canvas tiles, so large bases stay fast, and shows each building's name, status and health on hover. Ghosts are ignored, and buildings are removed when they're mined. The icons belong to Wube and the mod authors, so they aren't in the repo. export_building_icons.py builds them from a Factorio client's --dump-data/--dump-prototype-locale/--dump-icon-sprites output, and the web-map nginx serves them from a mounted volume. Also label single-well oil fields "1 well". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c9206ba8d2
commit
7ef4918a5c
15 changed files with 615 additions and 5 deletions
|
|
@ -0,0 +1,155 @@
|
|||
package dev.adamko.kafkatorio.server.web.buildings
|
||||
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.processor.config.topicName
|
||||
import dev.adamko.kafkatorio.schema.common.FactorioServerId
|
||||
import dev.adamko.kafkatorio.schema.common.MapBuilding
|
||||
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
|
||||
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
|
||||
import dev.adamko.kafkatorio.schema.packets.KafkatorioPacket
|
||||
import dev.adamko.kafkatorio.schema.packets.MapChunkEntityUpdate
|
||||
import dev.adamko.kafkatorio.server.web.config.jsonMapper
|
||||
import java.time.Duration
|
||||
import java.util.Properties
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
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 state of every building in memory, so the web map can draw them as icons.
|
||||
*
|
||||
* Like [dev.adamko.kafkatorio.server.web.resources.ResourcePatchService], the whole
|
||||
* [MapChunkEntityUpdate] topic is read from the beginning on startup, and then followed.
|
||||
*/
|
||||
class BuildingService(
|
||||
private val appProps: ApplicationProperties,
|
||||
) {
|
||||
|
||||
private data class ChunkKey(
|
||||
val serverId: FactorioServerId,
|
||||
val surfaceIndex: SurfaceIndex,
|
||||
val chunkX: Int,
|
||||
val chunkY: Int,
|
||||
)
|
||||
|
||||
/** Buildings per chunk, by position */
|
||||
private val chunks = ConcurrentHashMap<ChunkKey, ConcurrentHashMap<MapEntityPosition, MapBuilding>>()
|
||||
|
||||
|
||||
/** Read all building updates from the beginning of the topic, and keep following it. */
|
||||
suspend fun consume(): Unit = withContext(Dispatchers.IO) {
|
||||
val topic = MapChunkEntityUpdate::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("[BuildingService] 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("[BuildingService] failed to read record: $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun consumerProperties() = Properties().apply {
|
||||
putAll(appProps.kafkaStreamsConfig.filterKeys { it == ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG })
|
||||
put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed")
|
||||
put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
|
||||
put(ConsumerConfig.CLIENT_ID_CONFIG, "kafkatorio.events-server-web.buildings")
|
||||
}
|
||||
|
||||
|
||||
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? MapChunkEntityUpdate ?: return
|
||||
|
||||
// ghosts are planned buildings, not built ones
|
||||
if (update.key.protoId.type.toString() in IGNORED_TYPES) return
|
||||
|
||||
// The mod groups updates per prototype and chunk, so an update only says which events
|
||||
// happened, not which event affected which building. If the buildings were only mined,
|
||||
// then they're gone. (If they were built and mined in the same update, then keep them.)
|
||||
val eventNames = update.events?.keys?.map { it.toString() }.orEmpty()
|
||||
val isRemoved = eventNames.isNotEmpty() && eventNames.all { it in REMOVAL_EVENTS }
|
||||
|
||||
update.entities().forEach { entity ->
|
||||
val chunkKey = ChunkKey(
|
||||
serverId = serverId,
|
||||
surfaceIndex = update.key.surfaceIndex,
|
||||
chunkX = floor(entity.position.x / CHUNK_SIZE).toInt(),
|
||||
chunkY = floor(entity.position.y / CHUNK_SIZE).toInt(),
|
||||
)
|
||||
if (isRemoved) {
|
||||
chunks[chunkKey]?.remove(entity.position)
|
||||
} else {
|
||||
chunks.computeIfAbsent(chunkKey) { ConcurrentHashMap() }[entity.position] = MapBuilding(
|
||||
protoId = entity.protoId,
|
||||
position = entity.position,
|
||||
status = entity.status,
|
||||
health = entity.health,
|
||||
unitNumber = entity.unitNumber,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Get the buildings whose centre is within an area (inclusive left/top, exclusive right/bottom). */
|
||||
fun buildings(
|
||||
serverId: FactorioServerId,
|
||||
surfaceIndex: SurfaceIndex,
|
||||
leftTop: MapEntityPosition,
|
||||
rightBottom: MapEntityPosition,
|
||||
): List<MapBuilding> {
|
||||
val chunkX0 = floor(leftTop.x / CHUNK_SIZE).toInt()
|
||||
val chunkY0 = floor(leftTop.y / CHUNK_SIZE).toInt()
|
||||
val chunkX1 = floor(rightBottom.x / CHUNK_SIZE).toInt()
|
||||
val chunkY1 = floor(rightBottom.y / CHUNK_SIZE).toInt()
|
||||
|
||||
val result = mutableListOf<MapBuilding>()
|
||||
for (chunkX in chunkX0..chunkX1) {
|
||||
for (chunkY in chunkY0..chunkY1) {
|
||||
val chunk = chunks[ChunkKey(serverId, surfaceIndex, chunkX, chunkY)] ?: continue
|
||||
chunk.values.filterTo(result) { building ->
|
||||
building.position.x >= leftTop.x && building.position.x < rightBottom.x
|
||||
&& building.position.y >= leftTop.y && building.position.y < rightBottom.y
|
||||
}
|
||||
if (result.size >= MAX_BUILDINGS) return result
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
companion object {
|
||||
private const val CHUNK_SIZE = 32.0
|
||||
|
||||
/** Limit the response size, if a client requests a huge area */
|
||||
private const val MAX_BUILDINGS = 50_000
|
||||
|
||||
private val IGNORED_TYPES = setOf("entity-ghost", "tile-ghost")
|
||||
|
||||
private val REMOVAL_EVENTS = setOf(
|
||||
"on_player_mined_entity",
|
||||
"on_robot_mined_entity",
|
||||
"on_entity_died",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -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.buildings.BuildingService
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
|
@ -19,6 +20,7 @@ internal val appProps = ApplicationProperties.load()
|
|||
suspend fun main(): Unit = coroutineScope {
|
||||
val wsServer = WebmapWebsocketServer()
|
||||
val resourcePatchService = ResourcePatchService(appProps)
|
||||
val buildingService = BuildingService(appProps)
|
||||
|
||||
launch {
|
||||
websocketBroadcaster(wsServer)
|
||||
|
|
@ -36,11 +38,16 @@ suspend fun main(): Unit = coroutineScope {
|
|||
resourcePatchService.consume()
|
||||
}
|
||||
|
||||
launch {
|
||||
buildingService.consume()
|
||||
}
|
||||
|
||||
launch {
|
||||
startWebServer(
|
||||
appProps = appProps,
|
||||
wsServer = wsServer,
|
||||
resourcePatchService = resourcePatchService,
|
||||
buildingService = buildingService,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,10 @@ 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.buildings.BuildingService
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import dev.adamko.kafkatorio.schema.common.MapBuilding
|
||||
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
|
||||
import dev.adamko.kafkatorio.schema.common.ResourcePatch
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import io.ktor.http.HttpStatusCode
|
||||
|
|
@ -31,6 +34,7 @@ import kotlinx.serialization.json.encodeToJsonElement
|
|||
internal fun Routing.factorioServersRoutes(
|
||||
appProps: ApplicationProperties,
|
||||
resourcePatchService: ResourcePatchService,
|
||||
buildingService: BuildingService,
|
||||
) {
|
||||
|
||||
get<FactorioServers> {
|
||||
|
|
@ -47,6 +51,16 @@ internal fun Routing.factorioServersRoutes(
|
|||
val patches = resourcePatchService.patches(request.mapData.server.factorioServerId, request.surfaceIndex)
|
||||
call.respond(jsonMapper.encodeToJsonElement(ListSerializer(ResourcePatch.serializer()), patches))
|
||||
}
|
||||
|
||||
get<FactorioServer.MapData.Buildings> { request ->
|
||||
val buildings = buildingService.buildings(
|
||||
serverId = request.mapData.server.factorioServerId,
|
||||
surfaceIndex = request.surfaceIndex,
|
||||
leftTop = MapEntityPosition(request.left, request.top),
|
||||
rightBottom = MapEntityPosition(request.right, request.bottom),
|
||||
)
|
||||
call.respond(jsonMapper.encodeToJsonElement(ListSerializer(MapBuilding.serializer()), buildings))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -122,7 +136,11 @@ data class FactorioServer(
|
|||
data class Buildings(
|
||||
val mapData: MapData,
|
||||
val surfaceIndex: SurfaceIndex,
|
||||
// a list of buildings... (Sealed interface, different types?)
|
||||
// the area, as query parameters
|
||||
val left: Double,
|
||||
val top: Double,
|
||||
val right: Double,
|
||||
val bottom: Double,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package dev.adamko.kafkatorio.server.web.rest
|
||||
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.server.web.buildings.BuildingService
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
|
|
@ -26,6 +27,7 @@ import io.ktor.server.routing.routing
|
|||
internal fun Application.webmapTileServer(
|
||||
appProps: ApplicationProperties,
|
||||
resourcePatchService: ResourcePatchService,
|
||||
buildingService: BuildingService,
|
||||
) {
|
||||
|
||||
install(AutoHeadResponse)
|
||||
|
|
@ -55,6 +57,6 @@ internal fun Application.webmapTileServer(
|
|||
}
|
||||
|
||||
routing {
|
||||
factorioServersRoutes(appProps, resourcePatchService)
|
||||
factorioServersRoutes(appProps, resourcePatchService, buildingService)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package dev.adamko.kafkatorio.server.web
|
|||
|
||||
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.server.web.buildings.BuildingService
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import dev.adamko.kafkatorio.server.web.rest.webmapTileServer
|
||||
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
|
||||
|
|
@ -15,6 +16,7 @@ internal suspend fun startWebServer(
|
|||
appProps: ApplicationProperties,
|
||||
wsServer: WebmapWebsocketServer,
|
||||
resourcePatchService: ResourcePatchService,
|
||||
buildingService: BuildingService,
|
||||
): Unit = coroutineScope {
|
||||
|
||||
embeddedServer(
|
||||
|
|
@ -24,7 +26,7 @@ internal suspend fun startWebServer(
|
|||
|
||||
webmapWebsocketServer(wsServer)
|
||||
|
||||
webmapTileServer(appProps, resourcePatchService)
|
||||
webmapTileServer(appProps, resourcePatchService, buildingService)
|
||||
|
||||
}.start(wait = true)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue