diff --git a/docs/kafkatorio-platform/building-icons/export_building_icons.py b/docs/kafkatorio-platform/building-icons/export_building_icons.py index afc186c..1167aec 100644 --- a/docs/kafkatorio-platform/building-icons/export_building_icons.py +++ b/docs/kafkatorio-platform/building-icons/export_building_icons.py @@ -6,8 +6,8 @@ The icons belong to Wube and the mod authors, so they're not in this repo. Inste from a Factorio client that has the same mods as the server: factorio --dump-data # script-output/data-raw-dump.json - factorio --dump-prototype-locale # script-output/entity-locale.json - factorio --dump-icon-sprites # script-output/entity/*.png + factorio --dump-prototype-locale # script-output/entity-locale.json, recipe-locale.json + factorio --dump-icon-sprites # script-output/entity/*.png, recipe/*.png (For a Steam install, set `SteamAppId=427520` so that Steam doesn't relaunch the game.) @@ -20,6 +20,9 @@ and mount in the web-map container at /usr/share/nginx/icons. The output contains - buildings.json: {"": {"w": , "h": , "name": ""}} - entity/.png + - recipes.json: {"": ""} + - resources.json: {"": ""} + - recipe/.png """ import json @@ -62,7 +65,22 @@ def main(script_output: Path, output_dir: Path): shutil.copyfile(icon, output_dir / "entity" / f"{name}.png") (output_dir / "buildings.json").write_text(json.dumps(buildings, indent=1, sort_keys=True)) - print(f"exported {len(buildings)} buildings to {output_dir}") + + # recipes, shown on crafting machines + recipe_names = json.loads((script_output / "recipe-locale.json").read_text()).get("names", {}) + (output_dir / "recipe").mkdir(exist_ok=True) + recipes = {} + for icon in (script_output / "recipe").glob("*.png"): + recipes[icon.stem] = recipe_names.get(icon.stem, icon.stem) + shutil.copyfile(icon, output_dir / "recipe" / icon.name) + (output_dir / "recipes.json").write_text(json.dumps(recipes, indent=1, sort_keys=True)) + + # resource names, for the resource patch labels + resources = {name: names.get(name, name) for name in data_raw.get("resource", {})} + (output_dir / "resources.json").write_text(json.dumps(resources, indent=1, sort_keys=True)) + + print(f"exported {len(buildings)} buildings, {len(recipes)} recipes and {len(resources)} resources" + f" to {output_dir}") if __name__ == "__main__": diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/entities.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/entities.kt index 3b85517..86206aa 100644 --- a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/entities.kt +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/entities.kt @@ -30,6 +30,10 @@ sealed interface FactorioEntityData { val lastUser: UInt? = null, val status: Status? = null, val unitNumber: UnitNumber? = null, + /** @see FactorioEntityUpdateElement.Standard.direction */ + val direction: UByte? = null, + /** @see FactorioEntityUpdateElement.Standard.recipe */ + val recipe: String? = null, ) : FactorioEntityData @@ -273,6 +277,10 @@ sealed interface FactorioEntityUpdateElement { val isActive: Boolean = false, val isRotatable: Boolean = false, val lastUser: UInt? = null, + /** `defines.direction` - 0 (north) to 15, clockwise. Only set if the entity can be rotated. */ + val direction: UByte? = null, + /** The name of the recipe that a crafting machine is set to (or last used, for furnaces) */ + val recipe: String? = null, ) : FactorioEntityUpdateElement } diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt index 172eb88..d67370a 100644 --- a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt @@ -14,4 +14,8 @@ data class MapBuilding( val status: FactorioEntityData.Status? = null, val health: Float? = null, val unitNumber: UnitNumber? = null, + /** `defines.direction` - 0 (north) to 15, clockwise */ + val direction: UByte? = null, + /** The name of the recipe of a crafting machine */ + val recipe: String? = null, ) diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapSurfaces.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapSurfaces.kt new file mode 100644 index 0000000..834ef83 --- /dev/null +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapSurfaces.kt @@ -0,0 +1,13 @@ +package dev.adamko.kafkatorio.schema.common + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + + +/** A surface (e.g. Nauvis, or a Space Exploration planet or orbit) that has map data. */ +@Serializable +@SerialName("kafkatorio.surface.MapSurface") +data class MapSurface( + val index: SurfaceIndex, + val name: String, +) diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketKeyed.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketKeyed.kt index 7abb190..7921ba0 100644 --- a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketKeyed.kt +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketKeyed.kt @@ -174,7 +174,9 @@ data class MapChunkEntityUpdate( health = entity.health, isActive = entity.isActive, isRotatable = entity.isRotatable, - lastUser = entity.lastUser + lastUser = entity.lastUser, + direction = entity.direction, + recipe = entity.recipe, ) } } diff --git a/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts b/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts index c26833e..c504e84 100644 --- a/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts +++ b/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts @@ -306,6 +306,8 @@ export interface FactorioEntityUpdateElementStandard { isActive?: boolean; isRotatable?: boolean; lastUser?: UInt | null; + direction?: UByte | null; + recipe?: string | null; } export type MinedProduct = diff --git a/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts b/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts index 6f865a7..91a38b2 100644 --- a/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts +++ b/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts @@ -11,6 +11,7 @@ import EventDataCache from "../../emitting/EventDataCache"; import { BoundingBox, LuaEntity, + LuaRecipePrototype, LuaSurface, MapPosition, OldTileAndPosition, @@ -137,6 +138,8 @@ export class EntityUpdatesHandler { isRotatable: entity.rotatable, lastUser: entity.last_user?.index, status: Converters.entityStatus(entity.status), + direction: entity.supports_direction ? entity.direction : undefined, + recipe: EntityUpdatesHandler.recipeName(entity), } EventDataCache.throttle( @@ -156,6 +159,22 @@ export class EntityUpdatesHandler { } + /** The recipe of a crafting machine. Furnaces only have a recipe while working, so use the last one. */ + private static recipeName(entity: LuaEntity): string | undefined { + if (entity.type == "assembling-machine" || entity.type == "rocket-silo") { + const [recipe] = entity.get_recipe() + return recipe?.name + } else if (entity.type == "furnace") { + const [recipe] = entity.get_recipe() + if (recipe != undefined) return recipe.name + // documented as a prototype, but be lenient in case it's a name + const previous = entity.previous_recipe?.name as LuaRecipePrototype | string | undefined + return typeof previous == "string" ? previous : previous?.name + } + return undefined + } + + private static throttleResourcesUpdate( eventName: EventName, eventTick: Tick, diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt index 189ce6d..ff0e584 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt @@ -6,21 +6,10 @@ 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 dev.adamko.kafkatorio.server.web.kafka.followTopic 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 /** @@ -45,41 +34,16 @@ class BuildingService( /** 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") } - } - } - } + suspend fun consume(): Unit = followTopic( + appProps, + MapChunkEntityUpdate::class.topicName, + clientId = "kafkatorio.events-server-web.buildings", + ) { serverId, data -> + if (data is MapChunkEntityUpdate) handleUpdate(serverId, data) } - 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 - + private fun handleUpdate(serverId: FactorioServerId, update: MapChunkEntityUpdate) { // ghosts are planned buildings, not built ones if (update.key.protoId.type.toString() in IGNORED_TYPES) return @@ -105,6 +69,8 @@ class BuildingService( status = entity.status, health = entity.health, unitNumber = entity.unitNumber, + direction = entity.direction, + recipe = entity.recipe, ) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/kafka/followTopic.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/kafka/followTopic.kt new file mode 100644 index 0000000..bacc70d --- /dev/null +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/kafka/followTopic.kt @@ -0,0 +1,59 @@ +package dev.adamko.kafkatorio.server.web.kafka + +import dev.adamko.kafkatorio.processor.config.ApplicationProperties +import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.packets.KafkatorioPacket +import dev.adamko.kafkatorio.schema.packets.KafkatorioPacketData +import dev.adamko.kafkatorio.server.web.config.jsonMapper +import java.time.Duration +import java.util.Properties +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 + + +/** + * Read all packets from the beginning of a topic, and keep following it. + * + * This is for small in-memory views of the data. Unlike Kafka Streams there's no state store, so + * the whole topic is re-read on every startup. + */ +suspend fun followTopic( + appProps: ApplicationProperties, + topic: String, + clientId: String, + handle: (serverId: FactorioServerId, data: KafkatorioPacketData) -> Unit, +): Unit = withContext(Dispatchers.IO) { + val properties = 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, clientId) + } + + KafkaConsumer(properties, StringDeserializer(), StringDeserializer()).use { consumer -> + val partitions = consumer.partitionsFor(topic).map { TopicPartition(it.topic(), it.partition()) } + consumer.assign(partitions) + consumer.seekToBeginning(partitions) + println("[$clientId] consuming $topic, partitions: ${partitions.size}") + + while (isActive) { + val records = runInterruptible { consumer.poll(Duration.ofSeconds(1)) } + for (record in records) { + runCatching { + val key = record.key() ?: return@runCatching + val value = record.value() ?: return@runCatching + val serverId = jsonMapper.decodeFromString(FactorioServerId.serializer(), key) + val packet = jsonMapper.decodeFromString(KafkatorioPacket.serializer(), value) + handle(serverId, packet.data) + }.onFailure { println("[$clientId] failed to read record: $it") } + } + } + } +} diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt index d44c4a6..2c012ed 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt @@ -6,6 +6,7 @@ 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.surfaces.SurfaceService import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @@ -21,6 +22,7 @@ suspend fun main(): Unit = coroutineScope { val wsServer = WebmapWebsocketServer() val resourcePatchService = ResourcePatchService(appProps) val buildingService = BuildingService(appProps) + val surfaceService = SurfaceService(appProps) launch { websocketBroadcaster(wsServer) @@ -42,12 +44,17 @@ suspend fun main(): Unit = coroutineScope { buildingService.consume() } + launch { + surfaceService.consume() + } + launch { startWebServer( appProps = appProps, wsServer = wsServer, resourcePatchService = resourcePatchService, buildingService = buildingService, + surfaceService = surfaceService, ) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt index d23b656..2c87020 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt @@ -1,7 +1,6 @@ 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 @@ -9,21 +8,11 @@ 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 dev.adamko.kafkatorio.server.web.kafka.followTopic 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 /** @@ -60,42 +49,16 @@ class ResourcePatchService( /** 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") } - } - } - } + suspend fun consume(): Unit = followTopic( + appProps, + MapChunkResourceUpdate::class.topicName, + clientId = "kafkatorio.events-server-web.resource-patches", + ) { serverId, data -> + if (data is MapChunkResourceUpdate) handleUpdate(serverId, data) } - 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 - + private fun handleUpdate(serverId: FactorioServerId, update: MapChunkResourceUpdate) { val chunkKey = ChunkKey( serverId = serverId, protoId = update.key.protoId, diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt index dc2b9c9..8541911 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt @@ -9,6 +9,8 @@ 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.server.web.surfaces.SurfaceService +import dev.adamko.kafkatorio.schema.common.MapSurface import dev.adamko.kafkatorio.schema.common.MapBuilding import dev.adamko.kafkatorio.schema.common.MapEntityPosition import dev.adamko.kafkatorio.schema.common.ResourcePatch @@ -35,6 +37,7 @@ internal fun Routing.factorioServersRoutes( appProps: ApplicationProperties, resourcePatchService: ResourcePatchService, buildingService: BuildingService, + surfaceService: SurfaceService, ) { get { @@ -43,6 +46,11 @@ internal fun Routing.factorioServersRoutes( call.respond(serverIdsJson) } + get { request -> + val surfaces = surfaceService.surfaces(request.mapData.server.factorioServerId) + call.respond(jsonMapper.encodeToJsonElement(ListSerializer(MapSurface.serializer()), surfaces)) + } + get { tile -> handleTileRequest(tile, appProps) } @@ -124,6 +132,12 @@ data class FactorioServer( val chunkY: Int, ) + @Serializable + @Resource("surfaces") + data class Surfaces( + val mapData: MapData, + ) + @Serializable @Resource("resources/s{surfaceIndex}/patches") data class ResourcePatches( diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt index df63eb9..aa4924b 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt @@ -3,6 +3,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 dev.adamko.kafkatorio.server.web.surfaces.SurfaceService import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.isSuccess @@ -28,6 +29,7 @@ internal fun Application.webmapTileServer( appProps: ApplicationProperties, resourcePatchService: ResourcePatchService, buildingService: BuildingService, + surfaceService: SurfaceService, ) { install(AutoHeadResponse) @@ -57,6 +59,6 @@ internal fun Application.webmapTileServer( } routing { - factorioServersRoutes(appProps, resourcePatchService, buildingService) + factorioServersRoutes(appProps, resourcePatchService, buildingService, surfaceService) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/surfaces/SurfaceService.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/surfaces/SurfaceService.kt new file mode 100644 index 0000000..bceef9a --- /dev/null +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/surfaces/SurfaceService.kt @@ -0,0 +1,49 @@ +package dev.adamko.kafkatorio.server.web.surfaces + +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.MapSurface +import dev.adamko.kafkatorio.schema.common.ServerMapTileLayer +import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename +import dev.adamko.kafkatorio.schema.common.SurfaceIndex +import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate +import dev.adamko.kafkatorio.server.web.kafka.followTopic +import java.util.concurrent.ConcurrentHashMap +import kotlin.io.path.isDirectory + + +/** Keeps the names of the surfaces, so the web map can list them. */ +class SurfaceService( + private val appProps: ApplicationProperties, +) { + + private val surfaceNames = ConcurrentHashMap, String>() + + + /** The mod regularly sends the name of every surface. */ + suspend fun consume(): Unit = followTopic( + appProps, + SurfaceUpdate::class.topicName, + clientId = "kafkatorio.events-server-web.surfaces", + ) { serverId, data -> + if (data is SurfaceUpdate) surfaceNames[serverId to data.index] = data.name + } + + + /** The surfaces that have a map, sorted by index. */ + fun surfaces(serverId: FactorioServerId): List = + surfaceNames + .filterKeys { (id, index) -> id == serverId && hasTerrain(serverId, index) } + .map { (key, name) -> MapSurface(index = key.second, name = name) } + .sortedBy { it.index.toString().toInt() } + + + /** Surfaces without terrain tiles (e.g. surfaces that only exist for mod internals) can't be shown. */ + private fun hasTerrain(serverId: FactorioServerId, surfaceIndex: SurfaceIndex): Boolean { + // the tile files are in `.../s{surfaceIndex}/z{zoom}/x{x}/y{y}.png` + val tile = ServerMapTilePngFilename(serverId, ServerMapTileLayer.TERRAIN, surfaceIndex, 0, 0, 0) + val surfaceDir = appProps.serverDataDir.resolve(tile.value).parent.parent.parent + return surfaceDir.isDirectory() + } +} diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt index 8e149a7..a59b85f 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt @@ -4,6 +4,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.surfaces.SurfaceService import dev.adamko.kafkatorio.server.web.rest.webmapTileServer import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer import dev.adamko.kafkatorio.server.web.websocket.webmapWebsocketServer @@ -17,6 +18,7 @@ internal suspend fun startWebServer( wsServer: WebmapWebsocketServer, resourcePatchService: ResourcePatchService, buildingService: BuildingService, + surfaceService: SurfaceService, ): Unit = coroutineScope { embeddedServer( @@ -26,7 +28,7 @@ internal suspend fun startWebServer( webmapWebsocketServer(wsServer) - webmapTileServer(appProps, resourcePatchService, buildingService) + webmapTileServer(appProps, resourcePatchService, buildingService, surfaceService) }.start(wait = true) } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt index 3265b64..b899a84 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt @@ -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 = emptyMap() + /** Recipe display names, by recipe name */ + private val recipeNames: Deferred> = 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 = emptyMap() + private val icons = mutableMapOf>() + /** 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>() @@ -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): Deferred? { - 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 { + return icons.getOrPut("$type/$name") { val deferred = CompletableDeferred() 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): 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 = buildString { +/** The width and height in tiles, rotated if the building faces east or west */ +private fun MapBuilding.footprint(info: Map): Pair { + 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, + recipeNames: Map, +): String = buildString { val name = protoId.name.toString() append("${info[name]?.name ?: name}") + recipe?.let { append("
Recipe: ${recipeNames[it] ?: it}") } status?.let { append("
${it.name.lowercase().replace('_', ' ').replaceFirstChar(Char::uppercase)}") } health?.let { append("
Health: ${it.toInt()}") } append("
[${floor(position.x).toInt()}, ${floor(position.y).toInt()}]") diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt index 1cd2f30..6ee2981 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt @@ -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? = null + + /** Player markers, and the surface each player is on */ + private val playerMarkers = mutableMapOf() + + 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() @@ -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 { 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 = "${patch.displayName()}
${patch.displayAmount()}
" + html = "${patch.displayName(names)}
${patch.displayAmount()}
" } 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 `` 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 = + 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 = 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() diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt index d7a6679..9ee3959 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt @@ -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 { + 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 { 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 = displayNames("recipes.json") + + + /** Fetch the display name of each resource, by resource name (exported like [buildingInfo]). */ + suspend fun resourceNames(): Map = displayNames("resources.json") + + + private suspend fun displayNames(filename: String): Map { + 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) + } } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/FactorioGameState.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/FactorioGameState.kt index f4a0946..9448fc7 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/FactorioGameState.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/FactorioGameState.kt @@ -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) diff --git a/modules/web-map/src/main/resources/css/kafkatorio.css b/modules/web-map/src/main/resources/css/kafkatorio.css index 2806bd7..dc6fd81 100644 --- a/modules/web-map/src/main/resources/css/kafkatorio.css +++ b/modules/web-map/src/main/resources/css/kafkatorio.css @@ -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; +}