Add a production dashboard

Every minute, the mod diffs the force's production statistics for each
surface against the totals it sent last time (kept in
storage.productionTotals), and sends what was produced and consumed as a
ProductionUpdate.

events-server-web keeps the statistics in ring buffers (1440 minutes and
168 hours), and serves them at
/kafkatorio/data/servers/{id}/production, for a range of game time and
optionally one surface.

The web map has a production page (/servers/{id}/production, linked from
the header) with science packs used per minute (in total and per pack),
production per minute as a line chart, and a searchable table of
everything produced and consumed.

export_building_icons.py now also exports every item and fluid icon and
name (items.json, fluids.json), for the production page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lazzexus 2026-11-22 10:26:16 +01:00
parent 8770a0617b
commit 0e1b315a6d
24 changed files with 1524 additions and 30 deletions

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.production.productionPage
import dev.adamko.kafkatorio.webmap.research.researchPage
import dev.adamko.kafkatorio.webmap.routing.SiteRouter
import dev.adamko.kafkatorio.webmap.routing.SiteView
@ -92,6 +93,7 @@ object App : Application() {
SiteView.HOME -> homePage(state)
SiteView.SERVER -> serverPage(state)
SiteView.RESEARCH -> researchPage(state)
SiteView.PRODUCTION -> productionPage(state)
}
}
SiteRouter.updatePageLinks()

View file

@ -15,6 +15,9 @@ fun Container.headerNav(state: SiteState) {
navLink("Map", "/servers/${serverId.id}", className = navClass(state.view == SiteView.SERVER)) {
setAttribute("data-navigo", "true")
}
navLink("Production", "/servers/${serverId.id}/production", className = navClass(state.view == SiteView.PRODUCTION)) {
setAttribute("data-navigo", "true")
}
navLink("Research", "/servers/${serverId.id}/research", className = navClass(state.view == SiteView.RESEARCH)) {
setAttribute("data-navigo", "true")
}

View file

@ -0,0 +1,235 @@
package dev.adamko.kafkatorio.webmap.production
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.log10
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlinx.browser.document
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
import org.w3c.dom.events.MouseEvent
data class ChartSeries(
val label: String,
val colour: String,
val values: List<Double>,
)
/**
* A line chart drawn as SVG: a recessive grid, 2px lines, and a crosshair that shows every
* series' value at the hovered point.
*/
class LineChart(
private val root: HTMLElement,
/** e.g. `/min` */
private val unit: String,
) {
private var series: List<ChartSeries> = emptyList()
private var xLabels: List<String> = emptyList()
private val tooltip = (document.createElement("div") as HTMLElement).apply {
className = "chart-tooltip"
style.display = "none"
}
fun render(series: List<ChartSeries>, xLabels: List<String>) {
this.series = series
this.xLabels = xLabels
redraw()
}
fun redraw() {
root.innerHTML = ""
root.appendChild(tooltip)
tooltip.style.display = "none"
val width = max(root.clientWidth, 300).toDouble()
val height = HEIGHT
val points = xLabels.size
if (series.isEmpty() || points == 0) {
val empty = document.createElement("div")
empty.className = "chart-empty"
empty.textContent = "Select items in the table below to chart them."
root.appendChild(empty)
return
}
// direct labels at the end of each line, when there are few enough to fit
val directLabels = series.size <= 4
val right = if (directLabels) 120.0 else 16.0
val plotWidth = width - LEFT - right
val plotHeight = height - TOP - BOTTOM
val maxValue = series.maxOf { s -> s.values.maxOrNull() ?: 0.0 }
val ticks = niceTicks(maxValue)
val yMax = ticks.last()
fun x(i: Int) = LEFT + if (points == 1) plotWidth / 2 else plotWidth * i / (points - 1)
fun y(value: Double) = TOP + plotHeight * (1 - value / yMax)
val svg = svg("svg", "width" to width, "height" to height, "class" to "line-chart")
// grid and y axis labels
ticks.forEach { tick ->
svg.add("line", "x1" to LEFT, "x2" to LEFT + plotWidth, "y1" to y(tick), "y2" to y(tick), "class" to "chart-grid")
svg.add("text", "x" to LEFT - 8, "y" to y(tick) + 4, "class" to "chart-axis-label", "text-anchor" to "end")
.textContent = formatRate(tick)
}
// x axis labels: the first, middle and last
listOf(0, (points - 1) / 2, points - 1).distinct().forEach { i ->
val anchor = when (i) {
0 -> "start"
points - 1 -> "end"
else -> "middle"
}
svg.add("text", "x" to x(i), "y" to height - 6, "class" to "chart-axis-label", "text-anchor" to anchor)
.textContent = xLabels[i]
}
// lines
series.forEach { s ->
val path = s.values.mapIndexed { i, v -> "${if (i == 0) "M" else "L"}${x(i).fmt()},${y(v).fmt()}" }.joinToString("")
svg.add("path", "d" to path, "class" to "chart-line", "stroke" to s.colour)
}
if (directLabels) {
// push labels apart so they don't overlap
val labelYs = series.map { y(it.values.lastOrNull() ?: 0.0) }.toMutableList()
val order = labelYs.indices.sortedBy { labelYs[it] }
for (k in 1 until order.size) {
val previous = labelYs[order[k - 1]]
if (labelYs[order[k]] - previous < 14) labelYs[order[k]] = previous + 14
}
series.forEachIndexed { i, s ->
svg.add("circle", "cx" to x(points - 1), "cy" to y(s.values.lastOrNull() ?: 0.0), "r" to 3, "fill" to s.colour)
svg.add("text", "x" to x(points - 1) + 8, "y" to labelYs[i] + 4, "class" to "chart-direct-label")
.textContent = s.label.truncate(16)
}
}
// crosshair
val crosshair = svg.add("line", "y1" to TOP, "y2" to TOP + plotHeight, "class" to "chart-crosshair")
crosshair.setAttribute("visibility", "hidden")
val markers = series.map { s ->
svg.add("circle", "r" to 4, "fill" to s.colour, "class" to "chart-marker").also {
it.setAttribute("visibility", "hidden")
}
}
val hitArea = svg.add("rect", "x" to LEFT, "y" to TOP, "width" to plotWidth, "height" to plotHeight, "fill" to "transparent")
hitArea.addEventListener("pointermove", { event ->
val e = event as MouseEvent
val bounds = root.getBoundingClientRect()
val px = e.clientX - bounds.left
val i = if (points == 1) 0 else ((px - LEFT) / plotWidth * (points - 1)).roundToInt().coerceIn(0, points - 1)
crosshair.setAttribute("x1", x(i).fmt())
crosshair.setAttribute("x2", x(i).fmt())
crosshair.setAttribute("visibility", "visible")
markers.forEachIndexed { k, marker ->
marker.setAttribute("cx", x(i).fmt())
marker.setAttribute("cy", y(series[k].values.getOrElse(i) { 0.0 }).fmt())
marker.setAttribute("visibility", "visible")
}
showTooltip(i, x(i), width)
})
hitArea.addEventListener("pointerleave", {
crosshair.setAttribute("visibility", "hidden")
markers.forEach { it.setAttribute("visibility", "hidden") }
tooltip.style.display = "none"
})
root.appendChild(svg)
}
private fun showTooltip(i: Int, x: Double, width: Double) {
tooltip.innerHTML = ""
val title = document.createElement("div")
title.className = "chart-tooltip-title"
title.textContent = xLabels[i]
tooltip.appendChild(title)
series.sortedByDescending { it.values.getOrElse(i) { 0.0 } }.forEach { s ->
val row = document.createElement("div")
row.className = "chart-tooltip-row"
val swatch = document.createElement("span")
swatch.className = "chart-swatch"
(swatch as HTMLElement).style.background = s.colour
val value = document.createElement("strong")
value.textContent = formatRate(s.values.getOrElse(i) { 0.0 }) + unit
val label = document.createElement("span")
label.textContent = " " + s.label
row.appendChild(swatch)
row.appendChild(value)
row.appendChild(label)
tooltip.appendChild(row)
}
tooltip.style.display = "block"
// keep the tooltip inside the chart, on the side away from the pointer
if (x > width / 2) {
tooltip.style.left = ""
tooltip.style.right = "${(width - x + 12).fmt()}px"
} else {
tooltip.style.right = ""
tooltip.style.left = "${(x + 12).fmt()}px"
}
}
companion object {
private const val HEIGHT = 300.0
private const val LEFT = 56.0
private const val TOP = 12.0
private const val BOTTOM = 28.0
}
}
/** 0, then 3-5 evenly spaced 'nice' values (1, 2, 2.5 or 5 x 10^n) covering [maxValue] */
private fun niceTicks(maxValue: Double): List<Double> {
if (maxValue <= 0) return listOf(0.0, 1.0)
val rough = maxValue / 4
val magnitude = 10.0.pow(floor(log10(rough)))
val step = listOf(1.0, 2.0, 2.5, 5.0, 10.0).map { it * magnitude }.first { it >= rough }
val count = ceil(maxValue / step).toInt()
return (0..count).map { it * step }
}
/** e.g. `1.2k`, `350`, `2.5` */
fun formatRate(value: Double): String {
val v = abs(value)
val sign = if (value < 0) "-" else ""
return sign + when {
v >= 1_000_000 -> "${((v / 100_000).roundToInt() / 10.0).trimZero()}M"
v >= 1_000 -> "${((v / 100).roundToInt() / 10.0).trimZero()}k"
v >= 100 -> "${v.roundToInt()}"
v >= 10 -> "${((v * 10).roundToInt() / 10.0).trimZero()}"
else -> "${((v * 100).roundToInt() / 100.0).trimZero()}"
}
}
private fun Double.trimZero(): String = toString().removeSuffix(".0")
private fun Double.fmt(): String = ((this * 10).roundToInt() / 10.0).toString()
private fun String.truncate(length: Int) = if (this.length <= length) this else take(length - 1) + "…"
private const val SVG_NS = "http://www.w3.org/2000/svg"
private fun svg(tag: String, vararg attributes: Pair<String, Any>): Element =
document.createElementNS(SVG_NS, tag).apply {
attributes.forEach { (name, value) -> setAttribute(name, value.toString()) }
}
private fun Element.add(tag: String, vararg attributes: Pair<String, Any>): Element =
svg(tag, *attributes).also { appendChild(it) }

View file

@ -0,0 +1,460 @@
package dev.adamko.kafkatorio.webmap.production
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.MapSurface
import dev.adamko.kafkatorio.webmap.research.packs
import dev.adamko.kafkatorio.webmap.services.EventsServerClient
import dev.adamko.kafkatorio.webmap.services.ProductionEntry
import dev.adamko.kafkatorio.webmap.services.ProductionReport
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.select.SimpleSelect
import io.kvision.form.text.TextInput
import io.kvision.form.text.TextInputType
import io.kvision.html.Button
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.image
import io.kvision.html.p
import io.kvision.html.span
import kotlinx.browser.window
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.w3c.dom.HTMLElement
private val productionPageScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
/** Reloads the statistics while the page is shown */
private var refreshJob: Int? = null
/** What's produced and consumed, over time. */
fun Container.productionPage(state: SiteState) {
val serverId = state.serverId ?: return
val page = div(className = "production-page") {
p("Loading production statistics…", className = "home-muted")
}
productionPageScope.launch {
val itemNames = async { runCatching { EventsServerClient.itemNames() }.getOrDefault(emptyMap()) }
val fluidNames = async { runCatching { EventsServerClient.fluidNames() }.getOrDefault(emptyMap()) }
val surfaces = async { runCatching { EventsServerClient.surfaces(serverId) }.getOrDefault(emptyList()) }
val sciencePacks = async {
runCatching { EventsServerClient.technologies() }.getOrDefault(emptyMap())
.values.flatMap { it.packs() }.toSet()
}
page.removeAll()
ProductionView(
page = page,
serverId = serverId,
itemNames = itemNames.await(),
fluidNames = fluidNames.await(),
surfaces = surfaces.await(),
sciencePacks = sciencePacks.await(),
).render()
}
}
private enum class Kind(val label: String, val iconDir: String) {
ITEMS("Items", "item"),
FLUIDS("Fluids", "fluid"),
}
private enum class Range(val label: String, val api: String) {
TEN_MINUTES("10m", "TEN_MINUTES"),
ONE_HOUR("1h", "ONE_HOUR"),
SIX_HOURS("6h", "SIX_HOURS"),
ONE_DAY("24h", "ONE_DAY"),
ONE_WEEK("7d", "ONE_WEEK"),
}
private enum class SortColumn { NAME, PRODUCED, CONSUMED, NET }
private class ProductionView(
private val page: Container,
private val serverId: FactorioServerId,
private val itemNames: Map<String, String>,
private val fluidNames: Map<String, String>,
private val surfaces: List<MapSurface>,
private val sciencePacks: Set<String>,
) {
// filters
private var surfaceIndex: Int? = 1
private var range = Range.ONE_HOUR
private var kind = Kind.ITEMS
private var search = ""
private var sortColumn = SortColumn.PRODUCED
private var sortDescending = true
private var report: ProductionReport? = null
private var loading: Job? = null
/** Charted entries (`kind/name`), with their colour slot - colour follows the entry */
private val charted = linkedMapOf<String, Int>()
private var chartedChosenByUser = false
private lateinit var rangeButtons: Map<Range, Button>
private lateinit var kindButtons: Map<Kind, Button>
private lateinit var tiles: Div
private lateinit var legend: Div
private lateinit var chart: LineChart
private lateinit var table: Div
private lateinit var status: Div
private lateinit var tableTitle: io.kvision.html.H2
fun render() {
page.div(className = "production-header") {
h1("Production")
status = div(className = "home-muted")
}
page.filters()
tiles = page.div(className = "production-tiles")
page.div(className = "production-section") {
h2("Production per minute")
legend = div(className = "chart-legend")
val chartRoot = div(className = "line-chart-root")
chartRoot.addAfterInsertHook {
if (!::chart.isInitialized) {
chart = LineChart(chartRoot.getElement() as HTMLElement, unit = "/min")
// don't change other widgets while KVision is still inserting this one
window.setTimeout({ redrawAll() }, 0)
}
}
}
page.div(className = "production-section") {
div(className = "production-table-header") {
tableTitle = h2("")
val searchInput = TextInput(TextInputType.SEARCH) {
placeholder = "Search"
addCssClass("research-search")
}
searchInput.onEvent {
input = {
search = searchInput.value?.trim()?.lowercase() ?: ""
renderTable()
}
}
add(searchInput)
}
p("Select up to ${PALETTE.size} rows to chart them.", className = "home-muted")
table = div(className = "production-table")
}
window.addEventListener("resize", { if (::chart.isInitialized) chart.redraw() })
refreshJob?.let { window.clearInterval(it) }
refreshJob = window.setInterval({
// stop when the page isn't shown any more
if (!page.getElement().isConnectedCompat()) {
refreshJob?.let { window.clearInterval(it) }
} else {
load()
}
}, 60_000)
load()
}
private fun Container.filters() {
div(className = "research-filters") {
val options = listOf("" to "All surfaces") +
surfaces.map { "${it.index}" to it.name.replaceFirstChar { c -> c.uppercase() } }
add(SimpleSelect(options = options, value = "1") {
addCssClass("production-surface")
onEvent {
change = {
surfaceIndex = self.value?.toIntOrNull()
load()
}
}
})
div(className = "research-status-filter") {
rangeButtons = Range.values().associateWith { r ->
button(r.label, className = "research-filter-button") {
title = "The last ${r.label} of game time"
onClick {
range = r
load()
}
}
}
}
div(className = "research-status-filter") {
kindButtons = Kind.values().associateWith { k ->
button(k.label, className = "research-filter-button") {
onClick {
if (kind != k) {
kind = k
charted.clear()
chartedChosenByUser = false
redrawAll()
}
}
}
}
}
}
}
private fun load() {
loading?.cancel()
updateButtons()
loading = productionPageScope.launch {
val loaded = runCatching { EventsServerClient.production(serverId, surfaceIndex, range.api) }
.onFailure { println("[productionPage] failed to load production: $it") }
.getOrNull()
report = loaded
redrawAll()
}
}
private fun updateButtons() {
rangeButtons.forEach { (r, b) -> if (r == range) b.addCssClass("active") else b.removeCssClass("active") }
kindButtons.forEach { (k, b) -> if (k == kind) b.addCssClass("active") else b.removeCssClass("active") }
}
private fun redrawAll() {
updateButtons()
val report = report
status.content = when {
report == null -> "Couldn't load the production statistics."
report.latestTick == null -> "The game hasn't sent production statistics yet. They're sent every minute."
else -> "Game time ${formatGameTime(report.latestTick)} · averages over the last " +
formatDuration(coveredMinutes()) +
if (coveredMinutes() < rangeMinutes(range)) " (statistics started then)" else ""
}
renderTiles()
renderChart()
renderTable()
}
/** Averages are per minute of the range that has statistics, so a new server isn't diluted */
private val minutes: Double get() = coveredMinutes().toDouble()
/** The minutes of the range since the first statistics, rounded to whole buckets */
private fun coveredMinutes(): Int {
val report = report ?: return rangeMinutes(range)
val buckets = report.entries.firstOrNull()?.producedSeries?.size ?: return rangeMinutes(range)
val firstBucket = report.entries.minOfOrNull { entry ->
(entry.producedSeries.indices).firstOrNull { entry.producedSeries[it] > 0 || entry.consumedSeries[it] > 0 }
?: buckets
} ?: 0
return maxOf(1, buckets - firstBucket) * report.bucketMinutes
}
private fun rangeMinutes(r: Range) = when (r) {
Range.TEN_MINUTES -> 10
Range.ONE_HOUR -> 60
Range.SIX_HOURS -> 6 * 60
Range.ONE_DAY -> 24 * 60
Range.ONE_WEEK -> 7 * 24 * 60
}
private fun entries(): List<ProductionEntry> =
report?.entries.orEmpty().filter { it.kind == kind.iconDir }
/** Science per minute: the science packs consumed by research */
private fun renderTiles() {
tiles.removeAll()
val packs = report?.entries.orEmpty().filter { it.kind == "item" && it.name in sciencePacks && it.consumed > 0 }
.sortedByDescending { it.consumed }
val spm = packs.sumOf { it.consumed } / minutes
tiles.div(className = "stat-tile") {
div("Science packs per minute", className = "stat-tile-label")
div(formatRate(spm), className = "stat-tile-value")
div("consumed by research", className = "stat-tile-sub")
}
if (packs.isNotEmpty()) {
tiles.div(className = "stat-tile stat-tile-wide") {
div("By science pack", className = "stat-tile-label")
div(className = "pack-rates") {
packs.forEach { entry ->
div(className = "pack-rate") {
title = name(entry)
image("/kafkatorio/icons/item/${entry.name}.png", alt = name(entry), className = "pack-icon pack-icon-small")
span("${formatRate(entry.consumed / minutes)}/min")
}
}
}
}
}
}
private fun renderChart() {
if (!::chart.isInitialized) return
val entries = entries()
// by default, chart what's produced the most
if (!chartedChosenByUser) {
charted.clear()
entries.take(DEFAULT_CHARTED).forEach { addToChart(it) }
}
val bucketMinutes = report?.bucketMinutes ?: 1
val byKey = entries.associateBy { key(it) }
val series = charted.mapNotNull { (key, slot) ->
val entry = byKey[key] ?: return@mapNotNull null
ChartSeries(name(entry), PALETTE[slot], entry.producedSeries.map { it / bucketMinutes })
}
val buckets = report?.entries?.firstOrNull()?.producedSeries?.size ?: 0
val labels = (0 until buckets).map { i ->
val minutesAgo = (buckets - 1 - i) * bucketMinutes
if (minutesAgo == 0) "now" else "-${formatDuration(minutesAgo)}"
}
chart.render(series, labels)
legend.removeAll()
series.forEach { s ->
legend.div(className = "chart-legend-item") {
span(className = "chart-swatch") { setStyle("background", s.colour) }
span(s.label)
}
}
}
private fun addToChart(entry: ProductionEntry): Boolean {
if (charted.size >= PALETTE.size) return false
val used = charted.values.toSet()
charted[key(entry)] = PALETTE.indices.first { it !in used }
return true
}
private fun renderTable() {
tableTitle.content = "All ${kind.label.lowercase()}"
table.removeAll()
val rows = entries()
.filter { search.isEmpty() || name(it).lowercase().contains(search) || it.name.contains(search) }
.sortedWith(comparator())
if (rows.isEmpty()) {
table.p("Nothing to show.", className = "home-muted")
return
}
table.div(className = "production-row production-row-header") {
headerCell("", null)
headerCell(kind.label.removeSuffix("s"), SortColumn.NAME)
headerCell("Produced /min", SortColumn.PRODUCED)
headerCell("Consumed /min", SortColumn.CONSUMED)
headerCell("Net /min", SortColumn.NET)
}
rows.forEach { entry ->
val slot = charted[key(entry)]
table.div(className = "production-row" + if (slot != null) " charted" else "") {
span(className = "chart-swatch production-row-swatch") {
if (slot != null) setStyle("background", PALETTE[slot])
}
div(className = "production-name") {
image("/kafkatorio/icons/${kind.iconDir}/${entry.name}.png", alt = "", className = "pack-icon pack-icon-small") {
setAttribute("loading", "lazy")
}
span(name(entry))
}
div(formatRate(entry.produced / minutes), className = "production-number")
div(formatRate(entry.consumed / minutes), className = "production-number")
val net = (entry.produced - entry.consumed) / minutes
div((if (net > 0) "+" else "") + formatRate(net), className = "production-number")
onClick {
chartedChosenByUser = true
if (charted.remove(key(entry)) == null) addToChart(entry)
renderChart()
renderTable()
}
}
}
}
private fun Container.headerCell(label: String, column: SortColumn?) {
div(className = "production-header-cell" + if (column == sortColumn) " sorted" else "") {
content = label + if (column == sortColumn) (if (sortDescending) " ▼" else " ▲") else ""
if (column != null) {
onClick {
if (sortColumn == column) sortDescending = !sortDescending
else {
sortColumn = column
sortDescending = column != SortColumn.NAME
}
renderTable()
}
}
}
}
private fun comparator(): Comparator<ProductionEntry> {
val base: Comparator<ProductionEntry> = when (sortColumn) {
SortColumn.NAME -> compareBy { name(it).lowercase() }
SortColumn.PRODUCED -> compareBy { it.produced }
SortColumn.CONSUMED -> compareBy { it.consumed }
SortColumn.NET -> compareBy { it.produced - it.consumed }
}
return if (sortDescending) base.reversed() else base
}
private fun key(entry: ProductionEntry) = "${entry.kind}/${entry.name}"
private fun name(entry: ProductionEntry): String {
val names = if (entry.kind == "fluid") fluidNames else itemNames
return names[entry.name] ?: entry.name.replace('-', ' ').replaceFirstChar { it.uppercase() }
}
companion object {
private const val DEFAULT_CHARTED = 5
/** Categorical colours, validated for CVD separation on the dark chart surface */
val PALETTE = listOf(
"#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300", "#9085e9", "#e66767",
)
}
}
private fun org.w3c.dom.Node?.isConnectedCompat(): Boolean = this?.asDynamic()?.isConnected == true
private fun formatDuration(minutes: Int): String = when {
minutes % (24 * 60) == 0 -> "${minutes / (24 * 60)}d"
minutes % 60 == 0 -> "${minutes / 60}h"
minutes > 60 -> "${minutes / 60}h${minutes % 60}m"
else -> "${minutes}m"
}
/** e.g. `412h 05m` */
private fun formatGameTime(tick: Long): String {
val totalMinutes = tick / 3600
return "${totalMinutes / 60}h ${(totalMinutes % 60).toString().padStart(2, '0')}m"
}

View file

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

View file

@ -20,6 +20,10 @@ sealed interface SiteView {
override val path: String = "/servers/:serverId/"
}
object PRODUCTION : DynamicPath {
override val path: String = "/servers/:serverId/production"
}
object RESEARCH : DynamicPath {
override val path: String = "/servers/:serverId/research"
}

View file

@ -92,6 +92,22 @@ object EventsServerClient :
suspend fun itemNames(): Map<String, String> = displayNames("items.json")
/** Fetch the display name of each fluid (exported like [buildingInfo]). */
suspend fun fluidNames(): Map<String, String> = displayNames("fluids.json")
/**
* Fetch what the players' force produced and consumed during a range of game time (see
* `ProductionRange` in events-server-web). If [surfaceIndex] is `null`, sum all surfaces.
*/
suspend fun production(serverId: FactorioServerId, surfaceIndex: Int?, range: String): ProductionReport {
val surface = surfaceIndex?.let { "&surface=$it" } ?: ""
val url = "${window.location.origin}/kafkatorio/data/servers/${serverId.id}/production?range=$range$surface"
val json = window.fetch(url).await().text().await()
return lenientJson.decodeFromString(ProductionReport.serializer(), 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()
@ -165,3 +181,28 @@ data class TechnologyCost(
val ingredients: List<List<JsonPrimitive>> = emptyList(),
val ignoreMultiplier: Boolean = false,
)
/** What was produced and consumed during a range of game time */
@Serializable
data class ProductionReport(
val range: String,
val bucketMinutes: Int,
/** The game tick of the latest statistics, or `null` if there are none */
val latestTick: Long? = null,
val entries: List<ProductionEntry> = emptyList(),
)
@Serializable
data class ProductionEntry(
/** `item` or `fluid` */
val kind: String,
val name: String,
/** The total amount produced during the range */
val produced: Double,
val consumed: Double,
/** The amount produced in each bucket of [ProductionReport.bucketMinutes], oldest first */
val producedSeries: List<Double>,
val consumedSeries: List<Double>,
)

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.ProductionUpdate
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate
import dev.adamko.kafkatorio.webmap.App
@ -100,6 +101,7 @@ object WebsocketService : CoroutineScope {
is MapChunkTileUpdate,
is PrototypesUpdate,
is ResearchUpdate,
is ProductionUpdate,
is SurfaceUpdate,
is KafkatorioPacketDataError -> {
// to be continued...

View file

@ -11,6 +11,7 @@ sealed interface SiteAction : RAction {
object HomePage : SiteAction
data class ServerPage(val serverId: FactorioServerId) : SiteAction
data class ResearchPage(val serverId: FactorioServerId) : SiteAction
data class ProductionPage(val serverId: FactorioServerId) : SiteAction
data class ServerIdsLoaded(val serverIds: List<FactorioServerId>) : SiteAction

View file

@ -39,6 +39,8 @@ data class SiteState(
is SiteAction.ResearchPage -> copy(view = SiteView.RESEARCH, serverId = action.serverId)
is SiteAction.ProductionPage -> copy(view = SiteView.PRODUCTION, serverId = action.serverId)
is SiteAction.ServerIdsLoaded -> copy(serverIds = action.serverIds)
is SiteAction.FactorioUpdate -> copy(

View file

@ -353,7 +353,7 @@ header .navbar .navbar-toggler {
margin: 20px 0 8px;
}
.research-filters .research-search {
.research-search {
width: 320px;
max-width: 100%;
background: var(--kt-panel);
@ -361,14 +361,14 @@ header .navbar .navbar-toggler {
color: var(--kt-text);
}
.research-filters .research-search:focus {
.research-search:focus {
background: var(--kt-panel);
color: var(--kt-text);
border-color: var(--kt-accent);
box-shadow: none;
}
.research-filters .research-search::placeholder {
.research-search::placeholder {
color: var(--kt-muted);
}
@ -594,6 +594,287 @@ header .navbar .navbar-toggler {
}
/* Production */
.production-page {
max-width: 1300px;
margin: 0 auto;
padding: 24px 0 48px;
}
.production-header h1 {
color: var(--kt-heading);
font-weight: 700;
font-size: 2rem;
margin-bottom: 2px;
}
.production-surface select,
select.production-surface {
background: var(--kt-panel);
border: 1px solid var(--kt-border);
color: var(--kt-text);
min-width: 180px;
}
.production-tiles {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 8px 0 20px;
}
.stat-tile {
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-radius: 8px;
padding: 12px 16px;
min-width: 200px;
}
.stat-tile-wide {
flex: 1;
min-width: 280px;
}
.stat-tile-label {
color: var(--kt-muted);
font-size: 0.9rem;
}
.stat-tile-value {
color: var(--kt-heading);
font-size: 2.2rem;
font-weight: 700;
line-height: 1.1;
font-variant-numeric: tabular-nums;
}
.stat-tile-sub {
color: var(--kt-muted);
font-size: 0.85rem;
}
.pack-rates {
display: flex;
flex-wrap: wrap;
gap: 6px 16px;
margin-top: 6px;
}
.pack-rate {
display: inline-flex;
align-items: center;
gap: 4px;
font-variant-numeric: tabular-nums;
}
.production-section {
margin-top: 20px;
}
.production-section h2 {
color: var(--kt-heading);
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 6px;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 4px 16px;
margin-bottom: 6px;
min-height: 1.5em;
}
.chart-legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.chart-swatch {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 2px;
flex-shrink: 0;
}
.line-chart-root {
position: relative;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-radius: 8px;
padding: 8px 4px 0;
min-height: 300px;
}
.line-chart {
display: block;
}
.chart-grid {
stroke: var(--kt-panel-raised);
stroke-width: 1;
}
.chart-axis-label {
fill: var(--kt-muted);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.chart-direct-label {
fill: var(--kt-text);
font-size: 12px;
}
.chart-line {
fill: none;
stroke-width: 2;
stroke-linejoin: round;
stroke-linecap: round;
}
.chart-crosshair {
stroke: var(--kt-muted);
stroke-width: 1;
}
.chart-marker {
stroke: var(--kt-panel);
stroke-width: 2;
}
.chart-empty {
padding: 100px 16px;
text-align: center;
color: var(--kt-muted);
}
.chart-tooltip {
position: absolute;
top: 12px;
z-index: 10;
pointer-events: none;
background: #141314;
border: 1px solid var(--kt-border);
border-radius: 6px;
padding: 6px 10px;
font-size: 0.85rem;
white-space: nowrap;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
}
.chart-tooltip-title {
color: var(--kt-muted);
margin-bottom: 2px;
}
.chart-tooltip-row {
display: flex;
align-items: center;
gap: 6px;
}
.chart-tooltip-row strong {
font-variant-numeric: tabular-nums;
}
.production-table-header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.production-table-header .research-search {
width: 240px;
}
.production-table {
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-radius: 8px;
overflow: hidden;
}
.production-row {
display: grid;
grid-template-columns: 14px minmax(0, 1fr) repeat(3, minmax(70px, 120px));
gap: 8px;
align-items: center;
padding: 4px 12px;
border-top: 1px solid var(--kt-panel-raised);
cursor: pointer;
}
.production-row:hover {
background: var(--kt-panel-raised);
}
.production-row.charted {
background: #383226;
}
.production-row-header {
border-top: none;
cursor: default;
color: var(--kt-muted);
font-size: 0.85rem;
font-weight: 600;
}
.production-row-header:hover {
background: none;
}
.production-header-cell {
cursor: pointer;
user-select: none;
}
.production-header-cell.sorted {
color: var(--kt-heading);
}
.production-row-header .production-header-cell:nth-child(n+3) {
text-align: right;
}
.production-name {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.production-number {
text-align: right;
font-variant-numeric: tabular-nums;
}
@media (max-width: 600px) {
.production-row {
grid-template-columns: 10px minmax(0, 1fr) repeat(3, minmax(48px, 64px));
gap: 4px;
padding: 4px 8px;
font-size: 0.85rem;
}
.stat-tile {
min-width: 0;
flex: 1;
}
}
/* Map */
.leaflet-tile {