# chartKit: game-quality charts for your world's UI
chartKit draws charts and graphs for any screen in a Zero world: a stats screen after a match,
a benchmark results page, a HUD strip that shows frame time live, a loading timeline, a
before-and-after comparison. Every chart is drawn as SVG in one of eleven art styles, and
**one call switches the style of every chart in the world**. Fourteen chart kinds, four sizes
(down to a 390-point-wide phone and a thin HUD strip), and long series of 50,000+ points that
build in a few milliseconds without ever hiding a spike. Point at (or tap) any part of a chart
to read its exact value, and put a chart on a panel standing in the 3D world.
No dependencies. When Graphics Presets is installed, chartKit reads its looks so charts match
those pickers; otherwise built-in copies of the same palettes stand in.
## Quick start
```lua
local Charts = require("chartKit.charts")
local frameTimes = { 8.1, 8.4, 9.0, 31.5, 8.2, 8.6 } -- any list of numbers, 50k is fine
ui.registerScreen("myStats", { type = "vertical", style = { padding = 16, gap = 12 }, children = {
Charts.line {
title = "Frame time", subtitle = "Last run", unit = "ms",
series = { { name = "Frame", values = frameTimes } },
refLines = { { y = 16.7, label = "60 fps", kind = "budget" } },
},
} })
ui.showScreen("myStats")
Charts.setStyle("pixel") -- every chart built from now on is pixel art
```
To see everything at once: `require("chartKit.charts").gallery.show()` puts up a scrolling
gallery of every kind, with buttons to switch style and size. `gallery.hide()` takes it down.
## Two forms of every chart
- `Charts.<kind>(spec)` returns a **UI node**: a styled card with the title, subtitle, an
optional big `headline` value at the right, the chart, and a legend. Put it anywhere in a
screen tree. `spec.id` becomes the card's id (and `id/svg`, `id/plot`, `id/title`, `id/legend`
inside; `id/plot` holds the svg and the readout's hit boxes).
- `Charts.svg.<kind>(spec)` returns `(markup, width, height)`: the bare SVG, for your own
`{ type = "svg", props = { svg = markup }, style = { width = width, height = height } }`.
Note an `svg` widget must not be the direct child of an `anchor`; wrap it in a vertical.
## Options every chart takes
| field | meaning |
|---|---|
| `size` | `"panel"` (about 720 wide, the default), `"tile"` (about 240), `"phone"` (about 358, readable on a 390-wide portrait phone), `"hud"` (a 320x36 strip, no axes) |
| `width`, `height` | override the chart's own size in points |
| `title`, `subtitle`, `headline` | card text (node form) |
| `unit` | "ms", "MB", "%", ... added to axis and value labels |
| `style` | draw this one chart in another style than the world's |
| `legend` | `true` / `false` to force the legend on or off |
| `id` | the card's widget id (one is made up when left out) |
| `readout` | `false` turns off the hover and tap readout for this chart |
## The chart kinds
**line**: one or more series over x, with reference lines, segment marks, shaded bands and hitch dots.
```lua
Charts.line {
title = "Frame time", unit = "ms",
series = { { name = "Frame", values = ft }, { name = "GPU", values = gpu, color = "#ff3e9a" } },
x = { label = "frame" }, -- or x = { values = { ... } } for numeric x or text categories
refLines = { { y = 16.7, label = "60 fps", kind = "budget" }, { y = 9.4, kind = "median" } },
marks = { { x = 1, label = "Orbit" }, { x = 900, label = "Fly-through" } },
bands = { { from = 900, to = 1400, label = "Heavy area" } },
highlights = { { x = 512, label = "31 ms hitch" } }, -- value is looked up when left out
}
```
A series can also be `points = { { x, y }, ... }`. `yMin`, `yMax` fix the axis.
**area**: the same spec as line, filled. Larger areas are drawn first so a smaller one is never hidden.
**stacked**: stacked areas over x, e.g. GPU passes per frame; `bars = true` draws stacked columns.
```lua
Charts.stacked { title = "GPU passes", unit = "ms", series = {
{ name = "Opaque", values = opaque }, { name = "Shadows", values = shadows }, { name = "Post", values = post } } }
```
**histogram**: raw samples (`values`) or ready `bins = { { from, to, count } }`. Bins past a budget line turn the style's "bad" colour; a lone huge hitch goes into an overflow bin marked "+".
```lua
Charts.histogram { title = "Distribution", unit = "ms", values = ft, refLines = { { x = 16.7, kind = "budget" } } }
```
**bar**: labelled values, horizontal by default; `horizontal = false` for columns, `sort = true` biggest first, `colorful = true` one colour per bar.
```lua
Charts.bar { title = "Top costs", unit = "ms", sort = true, items = {
{ label = "Shadows", value = 3.4, note = "4 cascades" }, { label = "Physics", value = 1.7 } } }
```
**ring**: a donut with a centre value and, at panel and phone size, a list with values and percentages.
```lua
Charts.ring { title = "Memory", unit = "MB", center = { value = 1840, label = "MB total" },
items = { { label = "Textures", value = 820 }, { label = "Meshes", value = 410 } } }
```
**flame**: a flame graph from a tree or folded stacks. `inverted = true` draws an icicle (root on top).
```lua
Charts.flame { title = "Where a frame goes", folded = "frame;render;shadows 420\nframe;update;physics 330" }
Charts.flame { root = { name = "frame", value = 16, children = { { name = "render", value = 10 } } }, inverted = true }
```
`minFraction` hides boxes narrower than that share; `maxDepth` limits rows.
**sparkline**: a small line with no axes.
```lua
Charts.sparkline { values = ft, refLine = 16.7 }
```
**overlay**: two runs on one axis; `a` is drawn dashed (the baseline), `b` solid.
```lua
Charts.overlay { title = "Before vs after", unit = "ms", a = { name = "Baseline", values = old }, b = { name = "This build", values = new } }
```
**diffBars**: change from `a` to `b` per row, coloured good or bad with the percent.
```lua
Charts.diffBars { aName = "Baseline", bName = "This build", items = {
{ label = "Median", a = 10.4, b = 9.6, unit = "ms" }, -- lower is better by default
{ label = "1% low fps", a = 58, b = 66, lowerIsBetter = false } } }
```
**heatStrip**: one row of coloured cells (e.g. every frame's time; a long row keeps each cell's worst value), or a heat map with `rows`.
```lua
Charts.heatStrip { values = ft, thresholds = { good = 11, warn = 16.7 } }
Charts.heatStrip { rows = { { label = "Orbit", values = a }, { label = "Fly", values = b } } }
```
**gantt**: lanes of timed items, e.g. loading and shader compiles.
```lua
Charts.gantt { unit = "s", lanes = {
{ name = "Textures", items = { { start = 0.3, finish = 3.1, label = "stream" } } },
{ name = "Shaders", items = { { start = 0.5, finish = 1.6, label = "compile" } } } },
marks = { { x = 3.1, label = "playable" } } }
```
**statTile**: a big number with an optional change and sparkline.
```lua
Charts.statTile { label = "Median frame", value = 9.6, unit = "ms", delta = -7.7, lowerIsBetter = true, spark = ft }
```
**treemap**: shares of a whole as nested rectangles (squarified, so cells stay close to square). Labels sit in the cells that fit them, with the value and share underneath when there is room. An item with `children` is drawn as a group with its children inside. `sort` defaults to biggest first (`"asc"`, or `false` to keep your order). At hud size it draws a one-row share strip led by the biggest item.
```lua
Charts.treemap { title = "Memory", unit = "MB", items = {
{ label = "Textures", children = { { label = "Terrain", value = 380 }, { label = "UI", value = 60 } } },
{ label = "Meshes", value = 410 }, { label = "Audio", value = 230, color = "#ff9f1c" } } }
```
## Hover and tap readout
Every chart card tells the player the exact value under their pointer, on by default:
- **Mouse**: hovering shows the engine's tooltip with the label, value and unit. On `line`, `area`,
`stacked` and `overlay` it names the x position ("frame 512", or "frames 500-528" on a long run)
and every series' value there, with the column's max when a spike sits inside it.
- **Touch**: a tap pins a small readout bubble beside the finger, drawn in the chart's style; a
tap anywhere else (or on the same spot) dismisses it. A mouse click pins it too.
It covers `line`, `area`, `stacked` (areas and columns), `overlay`, `histogram` (range, count and
share), `bar`, `ring` (slices and list rows), `treemap`, `flame`, `heatStrip`, `gantt` (start, end,
duration), `diffBars` and `sparkline`. The card holds transparent hit boxes over the svg; the svg is
never rebuilt on hover or tap, only the small `chartKit.readout` screen changes, and nothing runs
per frame. `readout = false` turns it off for one chart. A chart without an `id` gets one
(`ck.auto.<n>`); give your own to drive it from code: `Charts.readout.show(id, box)`,
`Charts.readout.hide()`, `Charts.readout.current()`.
A screen your **component** registers sends its callbacks to that component, so forward them:
```lua
local Charts = require("chartKit.charts")
function onCallback(id, data)
if Charts.onCallback(id, data) then return end -- a chart readout tap
if id == "stats.close" then closeStats() end
end
```
Screens registered from a module, a scene script or `execute` need nothing: chartKit owns a
callback env for them.
## Charts on a panel in the 3D world
A scoreboard on a wall, a lobby stats board, a sign that charts progress:
```lua
local board = Charts.worldPanel { kind = "bar", position = { 0, 2, -6 }, yaw = 180, width = 3,
spec = { title = "Top scores", unit = "pts", sort = true, items = { { label = "Ann", value = 120 } } } }
board.set({ title = "Top scores", unit = "pts", sort = true, items = newItems }) -- redraws once
board.destroy()
```
Or put the **`ChartPanel`** component on an entity in your scene: `kind`, `spec` (exactly what
`Charts.<kind>` takes), `size`, `style` (empty follows the world style), `width` in metres and
`height` above the entity.
```lua
entity(boardId).component.add("ChartPanel", { kind = "treemap", width = 3, height = 2,
spec = { title = "Memory", unit = "MB", items = items } })
entity(boardId).component.get("ChartPanel").spec = { title = "Memory", unit = "MB", items = newItems }
```
The card is laid out on a hidden screen and rasterised into a texture (up to twice its size, so
text stays crisp up close) that an unlit quad shows; the quad faces the entity's +Z and respects
depth like any mesh. It is drawn again only when the spec, kind, size or style changes or the
world chart style changes, never per frame. The ChartPanel fields are synced: the peer that owns
the entity writes `spec` and every player's engine draws the same chart. `Charts.worldPanel`
makes a panel on the peer that calls it (a temporary entity, never saved into the scene), so
call it from code every player runs. World panels have no readout (nobody points at a texture).
## Helpers
- `Charts.legend(items, opts)`: a legend node, `items = { { name, color, dash?, fill? } }`.
- `Charts.folded(text)`: parse folded stacks into `{ name, value, children }`.
- `Charts.decimate(values, buckets)`: `(ys, idx)` keeping each bucket's min and max in order.
- `Charts.binValues(values, binCount?, binWidth?)`: histogram bins.
- `Charts.format(v, unit)`: "16.7 ms", "12.3k".
- `Charts.build(kind, spec)`: any kind by name.
## Styles
`Charts.setStyle(name)` sets the style for every chart in the world; `Charts.style()` reads it,
`Charts.styles()` lists them, `Charts.theme(name?)` returns the colours and fonts (to style the
rest of your screen to match), and `Charts.onStyleChanged(fn)` tells you when to rebuild screens
already on show. `Charts.defineStyle(name, { base = "scifi", accent = "#39ff14" })` adds your own.
| style | look |
|---|---|
| minimal | white cards, hairline grid, ink black and one red accent |
| scifi | dark navy, glowing cyan lines, corner brackets, upper-case mono labels |
| fantasy | parchment gradient, serif type, inked double strokes, hatched fills, double-rule frame |
| cartoon | yellow page, white cards, thick black outlines, bright flat fills, chunky shadow |
| pixel | stepped lines, square markers, dithered fills, block bars, crisp edges, mono type |
| cozy | warm cream, rounded, soft pastel colours and thick round lines |
| realistic | graphite instrument cluster, white type, one amber accent |
| horror | near-black, blood-red glow, vignette, serif type |
| military | olive drab, stencil titles, amber, corner brackets, hatched fills |
| colorblind | Okabe-Ito palette, and every series also gets its own dash and hatch angle |
| highContrast | black, white and yellow, thick strokes, text 25% larger |
## Sizes and phones
`panel` suits desktop screens; `phone` fits a 390-point-wide portrait phone (358 wide with its
padding, fewer ticks, labels kept apart); `tile` is for grids of small charts; `hud` is a thin
strip with a caption on the left and the latest value on the right, for in-game overlays.
## Performance
Series of any length are reduced to about two points per horizontal pixel, keeping each
pixel column's minimum and maximum, so a single-frame spike always shows. Strings are built with
`table.concat` and paths are written compactly. Measured in this engine: a 50,000-point line
chart builds in **2.6 ms on an idle engine and 5 to 7 ms with a benchmark running beside it** (svg and node form alike, every style); the test suite fails if
it ever takes 50 ms. The engine's svg widget draws nothing for markup much past 64 KB, so any
chart that would exceed 60 KB is rebuilt at lower detail automatically.
**A chart on screen costs nothing per frame (1.0.2).** The engine rasterises an svg widget's
markup once, on the main thread, and keeps the picture for as long as the markup string is the
same. 1.0.1 was reported making the worst frame of a 4 s profiler capture 83.7 ms with a chart
open against 48.4 ms closed. Measured with `profiler.startCapture(label, { level = "frames" })`
and the per-frame `prepare_ui_rendering.svg.render` time, the causes were:
- **Blur filters.** The glow of scifi and horror (and the glow under bars) was an SVG
`feGaussianBlur`. Rasterising a 2,400-point scifi line chart took **130 ms (min of 3; median
145 ms) with the filter and 21 ms (median 31 ms) without it**. Glows are now two wide
translucent strokes (or a soft rect), no filter anywhere; a test fails if one comes back.
- **New markup on every build.** Every chart carried a fresh numeric id in its gradient and
pattern ids, so rebuilding a chart with the same data (a style listener, a canvas event, the
gallery, a game refreshing its stats) produced different markup and a full re-raster (11.4 ms
for one minimal line chart, all 16 gallery charts at once on each gallery rebuild). Ids are
now fixed per document, so the same data gives byte-identical markup and **re-showing or
rebuilding a chart re-rasterises nothing (measured 0 ms)**; a test checks two builds match.
- **The gallery** keeps its built charts per style, size and width (a canvas event that changes
none of them rebuilds nothing) and comes up two charts per frame, so first-show rasters are
spread over frames.
After, alternating open and closed 4 s captures on this shared, busy machine (each window started
0.5 s after opening, so it shows the steady state):
| capture | median frame open / closed | worst frame open / closed | svg raster while open |
|---|---|---|---|
| gallery, 3 pairs | 19.6, 24.9, 24.0 ms / 20.5, 24.4, 22.6 ms | 39.8, 49.9, 47.5 ms / 47.7, 47.6, 49.2 ms | 0 ms |
| one scifi line chart, 3 pairs | 27.6, 22.4, 31.4 ms / 28.9, 22.4, 28.2 ms | 50.4, 102.5, 178.6 ms / 37.2, 73.1, 49.9 ms | 0 ms |
The open and closed medians match. The worst single frames swing with the machine's other load
in both columns: the open windows' worst frames were all render-thread waits
(`render_frame.tail_finish`, `tail_submit`, `deferred_oit` as their top keys) with zero svg or UI
work in them. What a chart still costs is the one raster when new markup is first shown, about
10 to 30 ms for a full panel chart on this machine (pixel style is the cheapest); show charts
before the moment that matters (a results screen as the round ends) and update live charts a few
times a second, not every frame.
## Multiplayer
Charts are local UI: each player builds the screens they see from the data they have, and
`setStyle` changes the style on the peer that calls it. To show every player the same numbers,
replicate the numbers (the engine's multiplayer state), not the chart.
## What else is in the package
- `chartKit.gallery`: the gallery screen (`show`, `hide`, `node`, `sampleData`).
- `chartKit.readout`: the hover and tap readout behind every card.
- `chartKit.panel` and the `ChartPanel` component: charts on panels in the 3D world.
- `chartKit.example`: "Star Catcher", a small playable game with a stats screen
(`require("chartKit.example").start()`); its guide walks through building it.
- Guides: *how to draw graphs and charts in my game's UI* and *example: a small game with a stats
screen using charts*.
- `chartKitTests`: `zero tests run --suite chartKitTests`.