Add a research page, and keep the topics that views are rebuilt from

The mod sends the research state of a force (researched technologies,
levels, current research, progress and queue) whenever research changes,
and every minute for the progress. events-server-web keeps the latest state
and serves it at /kafkatorio/data/servers/{id}/research.

The web map has a research page (/servers/{id}/research, linked from the
header), with:
- progress, the current research and the queue
- the science packs needed for everything that's left
- every technology, filterable by status, science pack and name, with its
  cost (including levelled technologies' count formulas)
- details: the total cost to reach a technology, its prerequisites, what it
  leads to and what it unlocks

The technology tree comes from export_building_icons.py, which now also
exports technologies.json, items.json and technology/science pack icons.

Kafka deleted data older than 7 days, but the building, resource and
research views are rebuilt by reading their topics from the beginning, so
buildings disappeared after a restart. These topics are now kept forever.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lazzexus 2026-11-03 10:46:09 +01:00
parent 4d02928081
commit e31971c58e
23 changed files with 1517 additions and 11 deletions

View file

@ -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, recipe-locale.json
factorio --dump-icon-sprites # script-output/entity/*.png, recipe/*.png
factorio --dump-prototype-locale # script-output/*-locale.json
factorio --dump-icon-sprites # script-output/entity/*.png, recipe/*.png, technology/*.png, ...
(For a Steam install, set `SteamAppId=427520` so that Steam doesn't relaunch the game.)
@ -23,6 +23,10 @@ The output contains
- recipes.json: {"<recipe name>": "<display name>"}
- resources.json: {"<resource name>": "<display name>"}
- recipe/<recipe name>.png
- technologies.json: the technology tree, for the research page
- technology/<technology name>.png
- items.json: {"<item name>": "<display name>"}, for science packs and research triggers
- item/<item name>.png (science packs, and items in research triggers)
"""
import json
@ -31,6 +35,14 @@ import shutil
import sys
from pathlib import Path
try:
from PIL import Image # optional, to shrink the (large) technology icons
except ImportError:
Image = None
# technology icons are 256px, but the research page shows them much smaller
TECHNOLOGY_ICON_SIZE = 128
def footprint(selection_box) -> tuple[int, int]:
"""The size in tiles, from a selection box like [[-1.5, -1.5], [1.5, 1.5]]"""
@ -79,8 +91,95 @@ def main(script_output: Path, output_dir: Path):
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}")
technologies, items = export_technologies(script_output, data_raw, output_dir)
print(f"exported {len(buildings)} buildings, {len(recipes)} recipes, {len(resources)} resources,"
f" {len(technologies)} technologies and {len(items)} items to {output_dir}")
def as_list(value) -> list:
"""Factorio dumps empty lists as empty objects, `{}`"""
return value if isinstance(value, list) else []
def copy_icon(source: Path, target: Path, max_size: int):
"""Copy an icon, shrinking it to max_size if Pillow is installed."""
if Image is None:
shutil.copyfile(source, target)
return
with Image.open(source) as image:
if image.width > max_size:
image = image.resize((max_size, max_size * image.height // image.width), Image.LANCZOS)
image.save(target, optimize=True)
def export_technologies(script_output: Path, data_raw: dict, output_dir: Path) -> tuple[dict, dict]:
"""The technology tree, with the cost of each technology, and icons."""
tech_names = json.loads((script_output / "technology-locale.json").read_text()).get("names", {})
item_names = json.loads((script_output / "item-locale.json").read_text()).get("names", {})
(output_dir / "technology").mkdir(exist_ok=True)
(output_dir / "item").mkdir(exist_ok=True)
technologies = {}
# science packs, and items needed by research triggers
item_icons = set()
for name, tech in data_raw.get("technology", {}).items():
if tech.get("hidden"):
continue
unit = tech.get("unit")
max_level = tech.get("max_level")
technology = {
"name": tech_names.get(name, name),
"prerequisites": as_list(tech.get("prerequisites")),
"order": tech.get("order", ""),
"unlocks": [e["recipe"] for e in as_list(tech.get("effects")) if e.get("type") == "unlock-recipe"],
}
if unit:
ingredients = [list(i.values()) if isinstance(i, dict) else i for i in as_list(unit.get("ingredients"))]
technology["cost"] = {
"count": unit.get("count"),
# e.g. "2^(L-6)*1000", for technologies with levels
"countFormula": unit.get("count_formula"),
"time": unit.get("time"),
"ingredients": [[pack, amount] for pack, amount in ingredients],
}
if tech.get("ignore_tech_cost_multiplier"):
technology["cost"]["ignoreMultiplier"] = True
item_icons.update(pack for pack, _ in ingredients)
trigger = tech.get("research_trigger")
if trigger:
technology["trigger"] = trigger
if "item" in trigger:
item_icons.add(trigger["item"] if isinstance(trigger["item"], str) else trigger["item"]["name"])
if max_level is not None:
technology["maxLevel"] = max_level # a number, or "infinite"
if tech.get("upgrade"):
technology["upgrade"] = True
# technologies with levels are split up (e.g. mining-productivity-1, -2, ...); the level of
# the first one is in its name
level = name.rsplit("-", 1)[-1]
if level.isdigit():
technology["level"] = int(level)
if tech.get("enabled") is False:
technology["disabled"] = True
technologies[name] = technology
icon = script_output / "technology" / f"{name}.png"
if icon.exists():
copy_icon(icon, output_dir / "technology" / icon.name, TECHNOLOGY_ICON_SIZE)
items = {}
for item in sorted(item_icons):
items[item] = item_names.get(item, item)
icon = script_output / "item" / f"{item}.png"
if icon.exists():
shutil.copyfile(icon, output_dir / "item" / icon.name)
(output_dir / "technologies.json").write_text(json.dumps(technologies, indent=1, sort_keys=True))
(output_dir / "items.json").write_text(json.dumps(items, indent=1, sort_keys=True))
return technologies, items
if __name__ == "__main__":

View file

@ -79,3 +79,26 @@ data class SurfaceUpdate(
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
/** The research state of a force: what's researched, and what's being researched. */
@Serializable
@SerialName("kafkatorio.packet.instant.ResearchUpdate")
data class ResearchUpdate(
val forceName: String,
/** The names of all researched technologies */
val researched: LuaJsonList<String>,
/**
* The level of technologies that can be researched more than once (e.g. infinite mining
* productivity). The level is the next one to research.
*/
val levels: Map<String, Int> = emptyMap(),
/** The technology that's being researched */
val current: String? = null,
/** Progress of [current], from 0 to 1 */
val progress: Double? = null,
/** The research queue, starting with [current] */
val queue: LuaJsonList<String> = LuaJsonList(emptyList()),
/** The map setting that multiplies the cost of all technologies */
val technologyPriceMultiplier: Double = 1.0,
) : KafkatorioInstantPacketData()

View file

@ -21,6 +21,7 @@ export type KafkatorioPacketData =
| KafkatorioPacketData.MapChunkTileUpdate
| KafkatorioPacketData.PlayerUpdate
| KafkatorioPacketData.PrototypesUpdate
| KafkatorioPacketData.ResearchUpdate
| KafkatorioPacketData.SurfaceUpdate;
export namespace KafkatorioPacketData {
@ -29,6 +30,7 @@ export namespace KafkatorioPacketData {
ConsoleChatUpdate = "kafkatorio.packet.instant.ConsoleChatUpdate",
ConsoleCommandUpdate = "kafkatorio.packet.instant.ConsoleCommandUpdate",
PrototypesUpdate = "kafkatorio.packet.instant.PrototypesUpdate",
ResearchUpdate = "kafkatorio.packet.instant.ResearchUpdate",
SurfaceUpdate = "kafkatorio.packet.instant.SurfaceUpdate",
EntityUpdate = "kafkatorio.packet.keyed.EntityUpdate",
MapChunkEntityUpdate = "kafkatorio.packet.keyed.MapChunkEntityUpdate",
@ -64,6 +66,17 @@ export namespace KafkatorioPacketData {
prototypes: FactorioPrototype[];
}
export interface ResearchUpdate {
type: KafkatorioPacketData.Type.ResearchUpdate;
forceName: string;
researched: string[];
levels?: { [key: string]: number };
current?: string | null;
progress?: Double | null;
queue?: string[];
technologyPriceMultiplier?: Double;
}
export interface SurfaceUpdate {
type: KafkatorioPacketData.Type.SurfaceUpdate;
index: SurfaceIndex;

View file

@ -1,6 +1,7 @@
import {isEventType} from "./eventTypeCheck";
import {Converters} from "./converters";
import {handleSurfaceUpdate} from "./surfaceUpdates";
import {handleResearchTick} from "./researchUpdates";
import EventCacheService from "../emitting/EventDataCache";
import MapChunkUpdate from "./handlers/MapChunkUpdateHandler";
import EntityUpdates from "./handlers/EntityUpdateHandler";
@ -18,6 +19,8 @@ script.on_event(defines.events.on_tick, (event: OnTickEvent) => {
}
}
handleResearchTick(event)
const kPacket: KafkatorioPacketData | null = KafkatorioPacketQueue.dequeue()
if (kPacket != null) {
PacketEmitter.emitInstantPacket(kPacket)

View file

@ -0,0 +1,99 @@
import PacketEmitter from "../emitting/PacketEmitter";
import {KafkatorioPacketData} from "../../generated/kafkatorio-schema";
import {LuaForce, OnTickEvent} from "factorio:runtime"
import Type = KafkatorioPacketData.Type;
/** Research progress changes constantly, so send it at most this often */
const PROGRESS_INTERVAL_TICKS = 60 * 60
/** Batch research events (e.g. queueing several technologies at once) */
const EVENT_DELAY_TICKS = 60
/** Ticks at which each force's research should be sent, by force name */
const pendingForces: Record<string, number> = {}
function scheduleResearchUpdate(force: LuaForce) {
const due = game.tick + EVENT_DELAY_TICKS
const pending = pendingForces[force.name]
if (pending == undefined || pending > due) {
pendingForces[force.name] = due
}
}
/** Send the research state of the 'player' force, and of any forces with research events */
export function handleResearchTick(event: OnTickEvent) {
if (event.tick % PROGRESS_INTERVAL_TICKS == 0) {
const player = game.forces["player"]
if (player != undefined) {
pendingForces[player.name] = event.tick
}
}
for (const [forceName, due] of pairs(pendingForces)) {
if (due <= event.tick) {
delete pendingForces[forceName]
const force = game.forces[forceName]
if (force != undefined) {
emitResearchUpdate(force)
}
}
}
}
function emitResearchUpdate(force: LuaForce) {
const researched: string[] = []
const levels: Record<string, number> = {}
for (const [name, technology] of pairs(force.technologies)) {
if (technology.researched) {
researched[researched.length] = name
}
if (technology.prototype.max_level > 1) {
levels[name] = technology.level
}
}
const queue: string[] = []
for (const technology of force.research_queue ?? []) {
queue[queue.length] = technology.name
}
const current = force.current_research
const update: KafkatorioPacketData.ResearchUpdate = {
type: Type.ResearchUpdate,
forceName: force.name,
researched: researched,
levels: levels,
current: current?.name,
progress: current != undefined ? force.research_progress : undefined,
queue: queue,
technologyPriceMultiplier: game.difficulty_settings.technology_price_multiplier,
}
PacketEmitter.emitInstantPacket(update)
}
script.on_event(
[
defines.events.on_research_started,
defines.events.on_research_finished,
defines.events.on_research_cancelled,
defines.events.on_research_reversed,
defines.events.on_research_queued,
defines.events.on_research_moved,
],
(event) => {
const e = event as unknown as { research?: { force: LuaForce }, force?: LuaForce }
const force = e.force ?? e.research?.force
if (force != undefined) {
scheduleResearchUpdate(force)
}
},
)

View file

@ -2,12 +2,17 @@ package dev.adamko.kafkatorio.processor.admin
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.processor.config.allTopics
import dev.adamko.kafkatorio.processor.config.retainedForeverTopics
import java.util.concurrent.TimeUnit
import mu.KotlinLogging
import org.apache.kafka.clients.admin.Admin
import org.apache.kafka.clients.admin.AlterConfigOp
import org.apache.kafka.clients.admin.ConfigEntry
import org.apache.kafka.clients.admin.CreateTopicsResult
import org.apache.kafka.clients.admin.NewTopic
import org.apache.kafka.clients.admin.TopicListing
import org.apache.kafka.common.config.ConfigResource
import org.apache.kafka.common.config.TopicConfig
class KafkatorioKafkaAdmin(
@ -49,6 +54,22 @@ class KafkatorioKafkaAdmin(
logger.info("Topic: $it")
}
}
retainTopicsForever()
}
/** Disable time-based deletion for [retainedForeverTopics] (including existing topics). */
private fun retainTopicsForever() {
val retainForever = AlterConfigOp(
ConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "-1"),
AlterConfigOp.OpType.SET,
)
val configs = retainedForeverTopics.associate { topic ->
ConfigResource(ConfigResource.Type.TOPIC, topic) to listOf(retainForever)
}
kafkaAdmin.incrementalAlterConfigs(configs).all().get()
logger.info("Retaining topics forever: $retainedForeverTopics")
}
private fun Admin.createTopics(

View file

@ -11,6 +11,7 @@ import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate
import dev.adamko.kafkatorio.schema.packets.MapChunkTileUpdate
import dev.adamko.kafkatorio.schema.packets.PlayerUpdate
import dev.adamko.kafkatorio.schema.packets.PrototypesUpdate
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate
import kotlin.reflect.KClass
@ -75,6 +76,7 @@ val KafkatorioPacketData.topicName: String
is KafkatorioPacketDataError -> packetTopicNames.getValue(KafkatorioPacketDataError::class)
is MapChunkEntityUpdate -> packetTopicNames.getValue(MapChunkEntityUpdate::class)
is MapChunkResourceUpdate -> packetTopicNames.getValue(MapChunkResourceUpdate::class)
is ResearchUpdate -> packetTopicNames.getValue(ResearchUpdate::class)
}
@ -90,10 +92,23 @@ private val packetTopicNames: Map<KClass<out KafkatorioPacketData>, String> = ma
MapChunkEntityUpdate::class to "map-chunk-entity",
MapChunkResourceUpdate::class to "map-chunk-resource",
KafkatorioPacketDataError::class to "error",
ResearchUpdate::class to "research",
).mapValues { (_, v) ->
"$DOMAIN.packet.$v"
}
/**
* Topics that are read from the beginning to rebuild in-memory views (e.g. the buildings on the
* web map), so their data must never be deleted.
*/
val retainedForeverTopics: Set<String>
get() = setOf(
MapChunkEntityUpdate::class.topicName,
MapChunkResourceUpdate::class.topicName,
ResearchUpdate::class.topicName,
)
val KClass<out KafkatorioPacketData>.topicName: String
get() = packetTopicNames.getValue(this)

View file

@ -5,6 +5,7 @@ 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.research.ResearchService
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
@ -23,6 +24,7 @@ suspend fun main(): Unit = coroutineScope {
val resourcePatchService = ResourcePatchService(appProps)
val buildingService = BuildingService(appProps)
val surfaceService = SurfaceService(appProps)
val researchService = ResearchService(appProps)
launch {
websocketBroadcaster(wsServer)
@ -48,6 +50,10 @@ suspend fun main(): Unit = coroutineScope {
surfaceService.consume()
}
launch {
researchService.consume()
}
launch {
startWebServer(
appProps = appProps,
@ -55,6 +61,7 @@ suspend fun main(): Unit = coroutineScope {
resourcePatchService = resourcePatchService,
buildingService = buildingService,
surfaceService = surfaceService,
researchService = researchService,
)
}
}

View file

@ -0,0 +1,37 @@
package dev.adamko.kafkatorio.server.web.research
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.packets.ResearchUpdate
import dev.adamko.kafkatorio.server.web.kafka.followTopic
import java.util.concurrent.ConcurrentHashMap
/** Keeps the latest research state of each force, for the research page. */
class ResearchService(
private val appProps: ApplicationProperties,
) {
private val research = ConcurrentHashMap<Pair<FactorioServerId, String>, ResearchUpdate>()
/** The mod sends the research state when research changes, and regularly with the progress. */
suspend fun consume(): Unit = followTopic(
appProps,
ResearchUpdate::class.topicName,
clientId = "kafkatorio.events-server-web.research",
) { serverId, data ->
if (data is ResearchUpdate) research[serverId to data.forceName] = data
}
fun research(serverId: FactorioServerId, forceName: String = PLAYER_FORCE): ResearchUpdate? =
research[serverId to forceName]
companion object {
/** The force that players are in, by default */
const val PLAYER_FORCE = "player"
}
}

View file

@ -9,7 +9,9 @@ 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.research.ResearchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.schema.common.MapSurface
import dev.adamko.kafkatorio.schema.common.MapBuilding
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
@ -38,6 +40,7 @@ internal fun Routing.factorioServersRoutes(
resourcePatchService: ResourcePatchService,
buildingService: BuildingService,
surfaceService: SurfaceService,
researchService: ResearchService,
) {
get<FactorioServers> {
@ -51,6 +54,15 @@ internal fun Routing.factorioServersRoutes(
call.respond(jsonMapper.encodeToJsonElement(ListSerializer(MapSurface.serializer()), surfaces))
}
get<FactorioServer.Research> { request ->
val research = researchService.research(request.server.factorioServerId)
if (research == null) {
call.respond(HttpStatusCode.NotFound)
} else {
call.respond(jsonMapper.encodeToJsonElement(ResearchUpdate.serializer(), research))
}
}
get<FactorioServer.MapData.Tile> { tile ->
handleTileRequest(tile, appProps)
}
@ -158,6 +170,13 @@ data class FactorioServer(
)
}
/** The research state of the players' force */
@Serializable
@Resource("research")
data class Research(
val server: FactorioServer,
)
@Serializable
@Resource("players")
data class Players(

View file

@ -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.research.ResearchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
@ -30,6 +31,7 @@ internal fun Application.webmapTileServer(
resourcePatchService: ResourcePatchService,
buildingService: BuildingService,
surfaceService: SurfaceService,
researchService: ResearchService,
) {
install(AutoHeadResponse)
@ -59,6 +61,6 @@ internal fun Application.webmapTileServer(
}
routing {
factorioServersRoutes(appProps, resourcePatchService, buildingService, surfaceService)
factorioServersRoutes(appProps, resourcePatchService, buildingService, surfaceService, researchService)
}
}

View file

@ -3,6 +3,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.research.ResearchService
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import dev.adamko.kafkatorio.server.web.rest.webmapTileServer
@ -19,6 +20,7 @@ internal suspend fun startWebServer(
resourcePatchService: ResourcePatchService,
buildingService: BuildingService,
surfaceService: SurfaceService,
researchService: ResearchService,
): Unit = coroutineScope {
embeddedServer(
@ -28,7 +30,7 @@ internal suspend fun startWebServer(
webmapWebsocketServer(wsServer)
webmapTileServer(appProps, resourcePatchService, buildingService, surfaceService)
webmapTileServer(appProps, resourcePatchService, buildingService, surfaceService, researchService)
}.start(wait = true)
}

View file

@ -4,6 +4,7 @@ import dev.adamko.kafkatorio.schema.packets.EventServerPacket
import dev.adamko.kafkatorio.webmap.layout.headerNav
import dev.adamko.kafkatorio.webmap.layout.homePage
import dev.adamko.kafkatorio.webmap.layout.servers.serverPage
import dev.adamko.kafkatorio.webmap.research.researchPage
import dev.adamko.kafkatorio.webmap.routing.SiteRouter
import dev.adamko.kafkatorio.webmap.routing.SiteView
import dev.adamko.kafkatorio.webmap.services.WebsocketService
@ -82,14 +83,15 @@ object App : Application() {
// Only re-render when the page itself changes. Re-rendering on every state update (e.g. each
// player position update) re-attaches the Leaflet map to a new element, which blanks the map.
val pageState = siteStateStore.sub { state ->
Triple(state.view, state.serverIds, state.factorioGameState?.map)
listOf(state.view, state.serverIds, state.factorioGameState?.map, state.serverId)
}
main().bind(pageState) { _ ->
val state = siteStateStore.getState()
div(className = "container-fluid") {
when (state.view) {
SiteView.HOME -> homePage(state)
SiteView.SERVER -> serverPage(state)
SiteView.SERVER -> serverPage(state)
SiteView.RESEARCH -> researchPage(state)
}
}
SiteRouter.updatePageLinks()

View file

@ -4,13 +4,22 @@ import dev.adamko.kafkatorio.webmap.routing.SiteView
import dev.adamko.kafkatorio.webmap.state.SiteState
import io.kvision.core.Container
import io.kvision.navbar.nav
import io.kvision.navbar.navLink
import io.kvision.navbar.navbar
fun Container.headerNav(state: SiteState) {
navbar(label = "Kafkatorio", link = SiteView.HOME.path) {
val serverId = state.serverId ?: return@navbar
nav {
// navLink("Home", SiteView.HOME.path)
navLink("Map", "/servers/${serverId.id}", className = navClass(state.view == SiteView.SERVER)) {
setAttribute("data-navigo", "true")
}
navLink("Research", "/servers/${serverId.id}/research", className = navClass(state.view == SiteView.RESEARCH)) {
setAttribute("data-navigo", "true")
}
}
}
}
private fun navClass(active: Boolean) = if (active) "active" else null

View file

@ -0,0 +1,252 @@
package dev.adamko.kafkatorio.webmap.research
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.webmap.services.TechnologyInfo
import kotlin.math.max
import kotlin.math.pow
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
enum class TechnologyStatus(val label: String) {
RESEARCHING("Researching"),
QUEUED("Queued"),
AVAILABLE("Available"),
LOCKED("Locked"),
RESEARCHED("Researched"),
}
/** Science packs, by name, and the amount of each */
typealias SciencePackCost = Map<String, Double>
/**
* The technology tree, combined with the research state of a force.
*/
class ResearchModel(
val technologies: Map<String, TechnologyInfo>,
val research: ResearchUpdate?,
) {
private val researched: Set<String> = research?.researched?.toSet() ?: emptySet()
private val queue: List<String> = research?.queue?.toList() ?: emptyList()
private val priceMultiplier: Double = research?.technologyPriceMultiplier ?: 1.0
/** The technologies that need each technology */
val successors: Map<String, List<String>> = buildMap<String, MutableList<String>> {
technologies.forEach { (name, tech) ->
tech.prerequisites.forEach { prerequisite -> getOrPut(prerequisite) { mutableListOf() }.add(name) }
}
}
/** The length of the longest chain of prerequisites, so early technologies sort first */
val depth: Map<String, Int> = buildMap {
fun depthOf(name: String, visiting: Set<String>): Int = getOrElse(name) {
val prerequisites = technologies[name]?.prerequisites.orEmpty().filter { it !in visiting }
val depth = prerequisites.maxOfOrNull { depthOf(it, visiting + name) + 1 } ?: 0
put(name, depth)
depth
}
technologies.keys.forEach { depthOf(it, emptySet()) }
}
val status: Map<String, TechnologyStatus> = technologies.mapValues { (name, tech) ->
when {
name in researched -> TechnologyStatus.RESEARCHED
name == research?.current -> TechnologyStatus.RESEARCHING
name in queue -> TechnologyStatus.QUEUED
!tech.disabled && tech.prerequisites.all { it in researched } -> TechnologyStatus.AVAILABLE
else -> TechnologyStatus.LOCKED
}
}
/** Science packs, sorted by how early in the tech tree they're first needed */
val sciencePacks: List<String> =
technologies.flatMap { (name, tech) -> tech.packs().map { pack -> pack to (depth[name] ?: 0) } }
.groupBy({ it.first }, { it.second })
.mapValues { (_, depths) -> depths.min() }
.entries
.sortedWith(compareBy({ it.value }, { it.key }))
.map { it.key }
val researchedCount: Int get() = researched.count { it in technologies }
/** Technologies that can be researched more than once never finish, so don't count them */
val finiteCount: Int get() = technologies.count { (_, tech) -> !tech.isInfinite() }
/** The level that will be researched next, for technologies with levels */
fun level(name: String): Int? {
val tech = technologies[name] ?: return null
if (tech.maxLevel == null) return null
return research?.levels?.get(name) ?: tech.level ?: 1
}
/** The science packs needed to research the next level of a technology */
fun cost(name: String): SciencePackCost {
val tech = technologies[name] ?: return emptyMap()
return tech.levelCost(level(name) ?: tech.level ?: 1)
}
/** Seconds per unit */
fun timePerUnit(name: String): Double? = technologies[name]?.cost?.time
/** The number of units of the next level */
fun units(name: String): Double? {
val tech = technologies[name] ?: return null
return tech.units(level(name) ?: tech.level ?: 1)
}
/**
* The science packs needed to research a technology, including all its prerequisites that
* aren't researched yet.
*/
fun costToReach(name: String): Pair<SciencePackCost, Int> {
val needed = mutableSetOf<String>()
fun visit(tech: String) {
if (status[tech] == TechnologyStatus.RESEARCHED || !needed.add(tech)) return
technologies[tech]?.prerequisites?.forEach { visit(it) }
}
visit(name)
return needed.map { cost(it) }.sum() to needed.size
}
/**
* The science packs needed to research everything that's left, excluding infinite
* technologies. For technologies with a limited number of levels, include all levels left.
*/
fun remainingCost(): SciencePackCost =
technologies.filter { (name, tech) -> status[name] != TechnologyStatus.RESEARCHED && !tech.isInfinite() }
.map { (name, tech) ->
val maxLevel = tech.maxLevel?.intOrNull
val level = level(name)
if (maxLevel != null && level != null) {
(level..maxLevel).map { tech.levelCost(it) }.sum()
} else {
cost(name)
}
}.sum()
private fun TechnologyInfo.levelCost(level: Int): SciencePackCost {
val units = units(level) ?: return emptyMap()
return packAmounts().mapValues { (_, amount) -> amount * units }
}
private fun TechnologyInfo.units(level: Int): Double? {
val cost = cost ?: return null
val units = cost.count ?: cost.countFormula?.let { evaluateCountFormula(it, level) } ?: return null
val multiplier = if (cost.ignoreMultiplier) 1.0 else priceMultiplier
return max(1.0, units * multiplier)
}
}
private fun TechnologyInfo.isInfinite(): Boolean = maxLevel?.contentOrNull == "infinite"
/** Science pack -> amount per unit */
fun TechnologyInfo.packAmounts(): Map<String, Double> =
cost?.ingredients.orEmpty().mapNotNull { ingredient ->
val pack = ingredient.getOrNull(0)?.contentOrNull ?: return@mapNotNull null
val amount = ingredient.getOrNull(1)?.doubleOrNull ?: 1.0
pack to amount
}.toMap()
fun TechnologyInfo.packs(): Set<String> = packAmounts().keys
private fun List<SciencePackCost>.sum(): SciencePackCost = buildMap {
this@sum.forEach { cost ->
cost.forEach { (pack, amount) -> put(pack, (get(pack) ?: 0.0) + amount) }
}
}
/**
* Evaluate a technology count formula, like `2^(L-6)*1000`.
*
* Factorio's formulas support `+ - * / ^`, brackets, numbers, and `L` (or `l`) for the level.
*/
fun evaluateCountFormula(formula: String, level: Int): Double? = runCatching {
FormulaParser(formula.replace(" ", ""), level.toDouble()).parse()
}.getOrNull()
private class FormulaParser(private val input: String, private val level: Double) {
private var pos = 0
fun parse(): Double {
val value = expression()
require(pos == input.length) { "unexpected '${input[pos]}' in $input" }
return value
}
private fun expression(): Double {
var value = term()
while (pos < input.length && input[pos] in "+-") {
value = if (input[pos++] == '+') value + term() else value - term()
}
return value
}
private fun term(): Double {
var value = power()
while (pos < input.length && input[pos] in "*/") {
value = if (input[pos++] == '*') value * power() else value / power()
}
return value
}
private fun power(): Double {
val base = unary()
if (pos < input.length && input[pos] == '^') {
pos++
return base.pow(power()) // right associative
}
return base
}
private fun unary(): Double {
if (pos < input.length && input[pos] == '-') {
pos++
return -unary()
}
return atom()
}
private fun atom(): Double {
require(pos < input.length) { "unexpected end of $input" }
val c = input[pos]
return when {
c == '(' -> {
pos++
val value = expression()
require(input.getOrNull(pos) == ')') { "missing ')' in $input" }
pos++
value
}
c == 'L' || c == 'l' -> {
pos++
level
}
c.isDigit() || c == '.' -> {
val start = pos
while (pos < input.length && (input[pos].isDigit() || input[pos] == '.')) pos++
input.substring(start, pos).toDouble()
}
else -> error("unexpected '$c' in $input")
}
}
}

View file

@ -0,0 +1,427 @@
package dev.adamko.kafkatorio.webmap.research
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.webmap.services.EventsServerClient
import dev.adamko.kafkatorio.webmap.services.TechnologyInfo
import dev.adamko.kafkatorio.webmap.state.SiteState
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.core.onEvent
import io.kvision.form.text.TextInput
import io.kvision.form.text.TextInputType
import io.kvision.html.Div
import io.kvision.html.button
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.h2
import io.kvision.html.h3
import io.kvision.html.image
import io.kvision.html.p
import io.kvision.html.span
import kotlinx.browser.document
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonPrimitive
import org.w3c.dom.events.KeyboardEvent
private val researchPageScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
/** The technology tree, and what's researched, with the science packs each technology needs. */
fun Container.researchPage(state: SiteState) {
val serverId = state.serverId ?: return
val page = div(className = "research-page") {
p("Loading research…", className = "home-muted")
}
researchPageScope.launch {
val technologies = async {
runCatching { EventsServerClient.technologies() }
.onFailure { println("[researchPage] failed to load technologies: $it") }
.getOrDefault(emptyMap())
}
val itemNames = async { runCatching { EventsServerClient.itemNames() }.getOrDefault(emptyMap()) }
val recipeNames = async { runCatching { EventsServerClient.recipeNames() }.getOrDefault(emptyMap()) }
val research = async { runCatching { EventsServerClient.research(serverId) }.getOrNull() }
val model = ResearchModel(technologies.await(), research.await())
page.removeAll()
if (model.technologies.isEmpty()) {
page.p("The technology tree hasn't been exported yet - see docs/guide.md.", className = "home-muted")
} else {
ResearchView(page, serverId, model, Names(itemNames.await(), recipeNames.await())).render()
}
}
}
private class Names(
val items: Map<String, String>,
val recipes: Map<String, String>,
) {
fun item(name: String) = items[name] ?: name
fun recipe(name: String) = recipes[name] ?: name
}
private class ResearchView(
private val page: Container,
private val serverId: FactorioServerId,
private val model: ResearchModel,
private val names: Names,
) {
private val cards = mutableMapOf<String, Div>()
// filters
private var search = ""
private var statusFilter: Set<TechnologyStatus>? = null
private var packFilter: String? = null
private lateinit var packFilterButtons: Map<String, Div>
private lateinit var statusButtons: Map<Set<TechnologyStatus>?, io.kvision.html.Button>
private lateinit var resultCount: Div
private lateinit var detailOverlay: Div
fun render() {
page.header()
page.remaining()
page.filters()
resultCount = page.div(className = "research-count home-muted")
page.div(className = "research-grid") {
sortedTechnologies().forEach { name -> cards[name] = technologyCard(name) }
}
detailOverlay = page.div(className = "research-detail-overlay") {
visible = false
onClick { event -> if (event.target == getElement()) closeDetail() }
}
document.addEventListener("keydown", { event ->
if ((event as KeyboardEvent).key == "Escape") closeDetail()
})
applyFilters()
}
private fun sortedTechnologies(): List<String> =
model.technologies.keys.sortedWith(
compareBy<String>(
{ model.status[it]?.ordinal ?: 0 },
{ if (model.status[it] == TechnologyStatus.QUEUED) model.research?.queue?.indexOf(it) ?: 0 else 0 },
{ model.depth[it] ?: 0 },
{ model.technologies[it]?.order ?: "" },
{ model.technologies[it]?.name ?: it },
)
)
private fun Container.header() {
div(className = "research-header") {
h1("Research")
val total = model.finiteCount
val done = model.researchedCount
div(className = "research-summary") {
span("$done of $total technologies researched", className = "research-summary-count")
div(className = "research-progress") {
div(className = "research-progress-bar") {
setStyle("width", "${if (total == 0) 0 else 100 * done / total}%")
}
}
}
val research = model.research
when {
research == null -> p(
"The game hasn't sent its research yet. It's sent once a minute, and whenever research changes.",
className = "home-muted",
)
research.current == null -> p("Nothing is being researched.", className = "home-muted")
else -> div(className = "research-current") {
val current = research.current!!
span("Researching ", className = "home-muted")
technologyLink(current)
val progress = ((research.progress ?: 0.0) * 100).toInt()
span(" — $progress%")
div(className = "research-progress research-progress-small") {
div(className = "research-progress-bar") { setStyle("width", "$progress%") }
}
val queued = research.queue.filter { it != current }
if (queued.isNotEmpty()) {
div(className = "research-queue") {
span("Queue: ", className = "home-muted")
queued.forEach { technologyLink(it) }
}
}
}
}
}
}
private fun Container.remaining() {
val remaining = model.remainingCost()
if (remaining.isEmpty()) return
div(className = "research-section") {
h2("Science packs needed for everything left")
p("Excluding infinite research. Click a science pack to show the technologies that need it.", className = "home-muted")
packFilterButtons = model.sciencePacks.filter { it in remaining }.associateWith { pack ->
div(className = "pack-total") {
title = names.item(pack)
packIcon(pack)
span(formatAmount(remaining.getValue(pack)))
onClick { togglePackFilter(pack) }
}
}
}
}
private fun Container.filters() {
div(className = "research-filters") {
val searchInput = TextInput(TextInputType.SEARCH) {
placeholder = "Search technologies or recipes"
addCssClass("research-search")
}
searchInput.onEvent {
input = {
search = searchInput.value?.trim()?.lowercase() ?: ""
applyFilters()
}
}
add(searchInput)
val options = listOf(
"All" to null,
"Available" to setOf(TechnologyStatus.RESEARCHING, TechnologyStatus.QUEUED, TechnologyStatus.AVAILABLE),
"Locked" to setOf(TechnologyStatus.LOCKED),
"Researched" to setOf(TechnologyStatus.RESEARCHED),
)
div(className = "research-status-filter") {
statusButtons = options.associate { (label, statuses) ->
statuses to button(label, className = "research-filter-button") {
onClick {
statusFilter = statuses
applyFilters()
}
}
}
}
}
}
private fun togglePackFilter(pack: String) {
packFilter = if (packFilter == pack) null else pack
applyFilters()
}
private fun applyFilters() {
var shown = 0
cards.forEach { (name, card) ->
val tech = model.technologies.getValue(name)
val visible = (statusFilter == null || model.status[name] in statusFilter!!)
&& (packFilter == null || packFilter in tech.packs())
&& (search.isEmpty() || matchesSearch(name, tech))
card.visible = visible
if (visible) shown++
}
statusButtons.forEach { (statuses, button) ->
if (statuses == statusFilter) button.addCssClass("active") else button.removeCssClass("active")
}
if (::packFilterButtons.isInitialized) {
packFilterButtons.forEach { (pack, button) ->
if (pack == packFilter) button.addCssClass("active") else button.removeCssClass("active")
}
}
val packText = packFilter?.let { " that need ${names.item(it)}" } ?: ""
resultCount.content = "$shown technologies$packText"
}
private fun matchesSearch(name: String, tech: TechnologyInfo): Boolean =
tech.name.lowercase().contains(search)
|| name.contains(search)
|| tech.unlocks.any { names.recipe(it).lowercase().contains(search) }
private fun Container.technologyCard(name: String): Div {
val tech = model.technologies.getValue(name)
val status = model.status[name] ?: TechnologyStatus.LOCKED
return div(className = "tech-card tech-${status.name.lowercase()}") {
image("/kafkatorio/icons/technology/$name.png", alt = "", className = "tech-card-icon") {
setAttribute("loading", "lazy")
}
div(className = "tech-card-body") {
div(className = "tech-card-name") { content = tech.displayName(name) }
div(className = "tech-card-cost") { costSummary(name, tech) }
span(status.label, className = "tech-status")
}
onClick { showDetail(name) }
}
}
/** e.g. `150 × [packs]`, or `Craft 10 Iron plate` */
private fun Container.costSummary(name: String, tech: TechnologyInfo) {
val units = model.units(name)
if (units == null) {
span(tech.triggerDescription(names), className = "home-muted")
return
}
span("${formatAmount(units)} ×")
tech.packs().forEach { pack -> packIcon(pack, small = true) }
}
private fun Container.packIcon(pack: String, small: Boolean = false) {
image("/kafkatorio/icons/item/$pack.png", alt = names.item(pack), className = if (small) "pack-icon pack-icon-small" else "pack-icon") {
title = names.item(pack)
}
}
private fun Container.technologyLink(name: String) {
span(model.technologies[name]?.displayName(name) ?: name, className = "tech-link") {
onClick { showDetail(name) }
}
}
private fun closeDetail() {
detailOverlay.visible = false
detailOverlay.removeAll()
}
private fun showDetail(name: String) {
val tech = model.technologies[name] ?: return
val status = model.status[name] ?: TechnologyStatus.LOCKED
detailOverlay.removeAll()
detailOverlay.div(className = "research-detail tech-${status.name.lowercase()}") {
button("×", className = "research-detail-close") {
title = "Close"
onClick { closeDetail() }
}
div(className = "research-detail-title") {
image("/kafkatorio/icons/technology/$name.png", alt = "", className = "research-detail-icon")
div {
h3(tech.displayName(name))
span(status.label, className = "tech-status")
model.level(name)?.let { level ->
val max = tech.maxLevel?.jsonPrimitive?.let { it.intOrNull?.toString() ?: it.contentOrNull }
span(" Level $level${if (max == "infinite") " (infinite)" else ""}", className = "home-muted")
}
}
}
val units = model.units(name)
div(className = "research-detail-section") {
h3("Cost")
if (units == null) {
p(tech.triggerDescription(names))
} else {
val time = model.timePerUnit(name)
p("${formatAmount(units)} units${time?.let { ", ${formatAmount(it)}s each" } ?: ""}", className = "home-muted")
packList(model.cost(name))
}
}
if (status != TechnologyStatus.RESEARCHED) {
val (toReach, count) = model.costToReach(name)
if (count > 1) {
div(className = "research-detail-section") {
h3("Total to reach")
p("$count technologies, including the prerequisites that aren't researched yet", className = "home-muted")
packList(toReach)
}
}
}
technologyList("Requires", tech.prerequisites)
technologyList("Leads to", model.successors[name].orEmpty())
if (tech.unlocks.isNotEmpty()) {
div(className = "research-detail-section") {
h3("Unlocks")
div(className = "recipe-list") {
tech.unlocks.forEach { recipe ->
div(className = "recipe-item") {
image("/kafkatorio/icons/recipe/$recipe.png", alt = "", className = "pack-icon pack-icon-small")
span(names.recipe(recipe))
}
}
}
}
}
}
detailOverlay.visible = true
}
private fun Container.packList(cost: SciencePackCost) {
div(className = "pack-list") {
model.sciencePacks.filter { it in cost }.forEach { pack ->
div(className = "pack-total") {
title = names.item(pack)
packIcon(pack)
span(formatAmount(cost.getValue(pack)))
}
}
}
}
private fun Container.technologyList(title: String, technologies: List<String>) {
val known = technologies.filter { it in model.technologies }
if (known.isEmpty()) return
div(className = "research-detail-section") {
h3(title)
div(className = "tech-chip-list") {
known.sortedBy { model.depth[it] ?: 0 }.forEach { name ->
val status = model.status[name] ?: TechnologyStatus.LOCKED
div(className = "tech-chip tech-${status.name.lowercase()}") {
image("/kafkatorio/icons/technology/$name.png", alt = "", className = "pack-icon pack-icon-small")
span(model.technologies.getValue(name).displayName(name))
onClick { showDetail(name) }
}
}
}
}
}
}
/** The in-game name. Technologies with levels (e.g. `Mining productivity 3`) already include it. */
private fun TechnologyInfo.displayName(id: String): String = name.ifBlank { id }
/** e.g. `Craft 10 Iron plate`, for technologies researched by doing something */
private fun TechnologyInfo.triggerDescription(names: Names): String {
val trigger = trigger ?: return "Unknown cost"
fun field(key: String) = trigger[key]?.jsonPrimitive?.contentOrNull
val type = field("type") ?: return "Unknown cost"
val count = field("count")?.let { "$it " } ?: ""
return when (type) {
"craft-item" -> "Craft $count${names.item(field("item") ?: "?")}"
"mine-entity" -> "Mine ${names.item(field("entity") ?: "?").replace('-', ' ')}"
"build-entity" -> "Build ${names.item(field("entity") ?: "?").replace('-', ' ')}"
else -> type.replace('-', ' ').replaceFirstChar { it.uppercase() }
}
}
private fun formatAmount(amount: Double): String = when {
amount >= 1_000_000_000 -> "${(amount / 100_000_000).toLong() / 10.0}B"
amount >= 1_000_000 -> "${(amount / 100_000).toLong() / 10.0}M"
amount >= 10_000 -> "${(amount / 100).toLong() / 10.0}k"
amount == kotlin.math.floor(amount) -> amount.toLong().toString()
else -> "${(amount * 10).toLong() / 10.0}"
}

View file

@ -37,6 +37,10 @@ object SiteRouter : CoroutineScope {
log("routing.on HOME")
homepageView()
}
.on(SiteView.RESEARCH) { match ->
val serverId = match.data["serverId"] as? String ?: error("invalid server id")
App.siteStateStore.dispatch(SiteAction.ResearchPage(FactorioServerId(serverId)))
}
.on(SiteView.SERVER) { match ->
println("routing.on SERVER ${JSON.stringify(match)}")
val serverId = match.data["serverId"] as? String ?: error("invalid server id")

View file

@ -19,4 +19,8 @@ sealed interface SiteView {
object SERVER : DynamicPath {
override val path: String = "/servers/:serverId/"
}
object RESEARCH : DynamicPath {
override val path: String = "/servers/:serverId/research"
}
}

View file

@ -4,11 +4,15 @@ 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.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.webmap.config.jsonMapper
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import io.kvision.rest.RestClient
import io.kvision.rest.call
import kotlinx.browser.window
@ -84,6 +88,32 @@ object EventsServerClient :
suspend fun resourceNames(): Map<String, String> = displayNames("resources.json")
/** Fetch the display name of science packs and other items used by research. */
suspend fun itemNames(): Map<String, String> = displayNames("items.json")
/** Fetch the research state of the players' force, or `null` if the mod hasn't sent it yet. */
suspend fun research(serverId: FactorioServerId): ResearchUpdate? {
val response = window.fetch("${window.location.origin}/kafkatorio/data/servers/${serverId.id}/research").await()
if (!response.ok) return null
val json = response.text().await()
return jsonMapper.decodeFromString(ResearchUpdate.serializer(), json)
}
/** Fetch the technology tree (exported like [buildingInfo]). */
suspend fun technologies(): Map<String, TechnologyInfo> {
val response = window.fetch("${window.location.origin}/kafkatorio/icons/technologies.json").await()
if (!response.ok) return emptyMap()
val json = response.text().await()
return lenientJson.decodeFromString(MapSerializer(String.serializer(), TechnologyInfo.serializer()), json)
}
/** For data exported from Factorio, which might have more properties in future */
private val lenientJson = Json { ignoreUnknownKeys = true }
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()
@ -100,3 +130,38 @@ data class BuildingInfo(
val h: Int,
val name: String,
)
/** A technology, from Factorio's prototype data */
@Serializable
data class TechnologyInfo(
val name: String,
val prerequisites: List<String> = emptyList(),
val order: String = "",
/** The recipes that this technology unlocks */
val unlocks: List<String> = emptyList(),
/** The science packs needed, or `null` if this is researched by a [trigger] */
val cost: TechnologyCost? = null,
/** e.g. `{"type": "craft-item", "item": "iron-plate", "count": 10}` */
val trigger: JsonObject? = null,
/** A number, or `"infinite"`, for technologies that have levels */
val maxLevel: JsonPrimitive? = null,
/** The level of the first technology of a series (e.g. 3 for `mining-productivity-3`) */
val level: Int? = null,
val upgrade: Boolean = false,
val disabled: Boolean = false,
)
@Serializable
data class TechnologyCost(
/** The number of units, or `null` if [countFormula] is used instead */
val count: Double? = null,
/** The number of units for each level, e.g. `2^(L-6)*1000` */
val countFormula: String? = null,
/** Seconds per unit */
val time: Double? = null,
/** `[science pack, amount per unit]` */
val ingredients: List<List<JsonPrimitive>> = emptyList(),
val ignoreMultiplier: Boolean = false,
)

View file

@ -11,6 +11,7 @@ import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate
import dev.adamko.kafkatorio.schema.packets.MapChunkTileUpdate
import dev.adamko.kafkatorio.schema.packets.PlayerUpdate
import dev.adamko.kafkatorio.schema.packets.PrototypesUpdate
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate
import dev.adamko.kafkatorio.webmap.App
import dev.adamko.kafkatorio.webmap.state.SiteAction
@ -98,6 +99,7 @@ object WebsocketService : CoroutineScope {
is MapChunkResourceUpdate,
is MapChunkTileUpdate,
is PrototypesUpdate,
is ResearchUpdate,
is SurfaceUpdate,
is KafkatorioPacketDataError -> {
// to be continued...

View file

@ -10,6 +10,7 @@ import io.kvision.redux.RAction
sealed interface SiteAction : RAction {
object HomePage : SiteAction
data class ServerPage(val serverId: FactorioServerId) : SiteAction
data class ResearchPage(val serverId: FactorioServerId) : SiteAction
data class ServerIdsLoaded(val serverIds: List<FactorioServerId>) : SiteAction

View file

@ -18,19 +18,27 @@ data class SiteState(
val serverIds: List<FactorioServerId>? = null,
val factorioGameState: FactorioGameState? = null,
/** The server whose pages are shown (the map, or research) */
val serverId: FactorioServerId? = null,
) : CoroutineScope {
override val coroutineContext: CoroutineContext =
Dispatchers.Default + SupervisorJob(rootJob) + CoroutineName("SiteState")
operator fun plus(action: SiteAction): SiteState = when (action) {
is SiteAction.HomePage -> copy(view = SiteView.HOME)
is SiteAction.HomePage -> copy(view = SiteView.HOME, serverId = null)
is SiteAction.ServerPage -> copy(
view = SiteView.SERVER,
factorioGameState = FactorioGameState(action.serverId),
serverId = action.serverId,
// keep the map when coming back from another page of the same server
factorioGameState = factorioGameState?.takeIf { it.serverId == action.serverId }
?: FactorioGameState(action.serverId),
)
is SiteAction.ResearchPage -> copy(view = SiteView.RESEARCH, serverId = action.serverId)
is SiteAction.ServerIdsLoaded -> copy(serverIds = action.serverIds)
is SiteAction.FactorioUpdate -> copy(

View file

@ -202,6 +202,398 @@ header .navbar-brand:hover {
}
/* Header navigation */
header .navbar .nav-link {
color: var(--kt-muted);
font-weight: 600;
}
header .navbar .nav-link:hover,
header .navbar .nav-link.active {
color: var(--kt-heading);
}
header .navbar .nav-link.active {
box-shadow: inset 0 -2px 0 var(--kt-accent);
}
header .navbar .navbar-toggler {
border-color: var(--kt-border);
filter: invert(1);
}
/* Research */
.research-page {
max-width: 1300px;
margin: 0 auto;
padding: 24px 0 48px;
}
.research-header h1 {
color: var(--kt-heading);
font-weight: 700;
font-size: 2rem;
margin-bottom: 8px;
}
.research-summary {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.research-summary-count {
font-weight: 600;
}
.research-progress {
flex: 1;
min-width: 200px;
max-width: 480px;
height: 10px;
background: var(--kt-panel-raised);
border-radius: 5px;
overflow: hidden;
}
.research-progress-small {
height: 6px;
margin: 6px 0;
}
.research-progress-bar {
height: 100%;
background: var(--kt-accent);
}
.research-current,
.research-queue {
margin-bottom: 8px;
}
.research-queue {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
}
.tech-link {
color: var(--kt-accent);
cursor: pointer;
font-weight: 600;
}
.tech-link:hover {
color: var(--kt-accent-hover);
text-decoration: underline;
}
.research-section {
margin: 20px 0;
}
.research-section h2 {
color: var(--kt-heading);
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 4px;
}
.research-section > p {
margin-bottom: 10px;
}
.research-section .pack-total,
.pack-list .pack-total {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0 8px 8px 0;
padding: 4px 10px 4px 4px;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-radius: 6px;
font-variant-numeric: tabular-nums;
font-weight: 600;
}
.research-section .pack-total {
cursor: pointer;
}
.research-section .pack-total:hover {
border-color: var(--kt-accent-hover);
}
.research-section .pack-total.active {
border-color: var(--kt-accent);
background: #4a3a1e;
}
.pack-icon {
width: 32px;
height: 32px;
}
.pack-icon-small {
width: 20px;
height: 20px;
}
.research-filters {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
margin: 20px 0 8px;
}
.research-filters .research-search {
width: 320px;
max-width: 100%;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
color: var(--kt-text);
}
.research-filters .research-search:focus {
background: var(--kt-panel);
color: var(--kt-text);
border-color: var(--kt-accent);
box-shadow: none;
}
.research-filters .research-search::placeholder {
color: var(--kt-muted);
}
.research-status-filter {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.research-filter-button {
background: var(--kt-panel);
border: 1px solid var(--kt-border);
color: var(--kt-text);
border-radius: 6px;
padding: 4px 12px;
}
.research-filter-button:hover {
border-color: var(--kt-accent-hover);
}
.research-filter-button.active {
background: var(--kt-accent);
border-color: var(--kt-accent);
color: #1e1d1e;
font-weight: 600;
}
.research-count {
margin-bottom: 12px;
}
.research-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 10px;
}
.tech-card {
display: flex;
gap: 10px;
padding: 8px;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-left: 4px solid var(--tech-status-colour);
border-radius: 6px;
cursor: pointer;
transition: border-color 0.15s, background 0.15s;
}
.tech-card:hover {
background: var(--kt-panel-raised);
border-color: var(--tech-status-colour);
}
.tech-card-icon {
width: 56px;
height: 56px;
flex-shrink: 0;
}
.tech-card-body {
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.tech-card-name {
font-weight: 600;
line-height: 1.2;
color: var(--kt-heading);
}
.tech-card-cost {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 2px;
font-size: 0.9rem;
}
.tech-card-cost > span:first-child {
margin-right: 4px;
}
.tech-status {
font-size: 0.8rem;
font-weight: 600;
color: var(--tech-status-colour);
}
/* status colours, like Factorio's technology screen */
.tech-researched { --tech-status-colour: #5fb948; }
.tech-researching { --tech-status-colour: #ff9f1b; }
.tech-queued { --tech-status-colour: #e8c547; }
.tech-available { --tech-status-colour: #e8c547; }
.tech-locked { --tech-status-colour: #8a8784; }
.tech-locked .tech-card-icon {
filter: grayscale(0.7) brightness(0.8);
}
.research-detail-overlay {
position: fixed;
inset: 0;
z-index: 2000;
background: rgba(0, 0, 0, 0.65);
display: flex;
align-items: flex-start;
justify-content: center;
padding: 48px 16px;
overflow-y: auto;
}
.research-detail {
position: relative;
width: 640px;
max-width: 100%;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-top: 4px solid var(--tech-status-colour);
border-radius: 8px;
padding: 20px 24px;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.6);
}
.research-detail-close {
position: absolute;
top: 8px;
right: 12px;
background: none;
border: none;
color: var(--kt-muted);
font-size: 1.8rem;
line-height: 1;
}
.research-detail-close:hover {
color: var(--kt-text);
}
.research-detail-title {
display: flex;
gap: 16px;
align-items: center;
margin-bottom: 8px;
}
.research-detail-title h3 {
color: var(--kt-heading);
font-size: 1.5rem;
font-weight: 700;
margin: 0;
}
.research-detail-icon {
width: 96px;
height: 96px;
flex-shrink: 0;
}
.research-detail-section {
margin-top: 16px;
}
.research-detail-section h3 {
color: var(--kt-heading);
font-size: 1.05rem;
font-weight: 600;
margin-bottom: 6px;
}
.research-detail-section p {
margin-bottom: 6px;
}
.tech-chip-list,
.recipe-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.tech-chip,
.recipe-item {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px 3px 4px;
background: var(--kt-panel-raised);
border: 1px solid var(--kt-border);
border-left: 3px solid var(--tech-status-colour, var(--kt-border));
border-radius: 6px;
font-size: 0.9rem;
}
.tech-chip {
cursor: pointer;
}
.tech-chip:hover {
border-color: var(--tech-status-colour);
}
@media (max-width: 600px) {
.research-page {
padding-top: 12px;
}
.research-detail-overlay {
padding: 16px 8px;
}
.research-detail {
padding: 16px;
}
.research-detail-icon {
width: 64px;
height: 64px;
}
}
/* Map */
.leaflet-tile {