Frostdev

KilnAPI reference Guide

Mod UI in the game's look (since 0.2.0-dev.32.2)

Kiln 0.2.0-dev.32.2 (mod API 0.2.35) rebuilt Kiln's in-game UI in the game's own look: its font, its framed panels, its buttons and switches, its controller glyphs and its menu sounds. Your mod's windows get that look, and the same pieces are yours to use: the design's tokens and type scale, the game's UI art, the widget set Kiln's own menu is drawn with, and a place for your mod in Kiln's menu (its icon, its settings form, its keys).

Everything of the game's (the font, the UI textures, the sounds) is read from the player's own game files while the game runs. Kiln never ships them, and neither should your mod. Where a piece cannot be read, the UI stays usable: flat colours, the system font, no sound.

This page is the guide. To make a whole window look like Kiln's own pages (the list book beside a framed inspector, heads, dividers, hand-drawn rows), use the kit those pages are drawn with: ui-kit.md. Follow its names, pickers and controller rules for player-facing rows and choices. The reference is the API's XML docs; ui.md has the rest of Kiln.Ui (windows, screens, HUD lines, key bindings, the game's own menus). Players: the Kiln menu.

Opting in

The new API is experimental while the rebuild settles: [Experimental("KILNX033")], so the compiler stops at its first use until you opt in (analyzers.md). Names and token sets can still change.

<PropertyGroup>
  <NoWarn>$(NoWarn);KILNX033</NoWarn>
</PropertyGroup>

A mod built with the 0.2.0-dev.32.2 dev kit asks for mod API 0.2.35 (the 0.2.0-dev.32.9 kit asks for 0.2.37), so older Kilns refuse it. Nothing you already call changed its name or its arguments.

What your windows look like

A Ui.Window or Ui.Screen of a mod built for mod API 0.2.35 or later, in the player's look (the default, and the game's look unless the player picked another), is drawn in the game's look:

  • a solid reading surface (see-through only when the player chose the translucent look, or the window sets BackgroundAlpha), the game's ornamented gold frame around it, and a title row with Kiln's mark, the window's title in capitals and a close button;
  • the plain ImGui drawn inside it (ui.Button, ui.Checkbox, tables) takes the game look's colours, paddings and the game's font: you don't have to change your drawing code;
  • ui.Scale inside it follows the game's own UI scale (Sizes);
  • while it takes the mouse and keys (Interactive, the default), the world behind is blurred and dimmed like behind the game's own menus, as the player's Blur behind menus setting says (services/screen.md).

A full-screen Ui.Screen gets no frame (it is the whole screen), but its plain ImGui takes the look too.

Older mods keep their look. A mod made for an older mod API keeps how its windows looked in 0.2.0-dev.32.1: the game's colours on ImGui's own style, no frame, sizes from the display's DPI as before, and no blur behind them (a screen that dims the world keeps its plain dark layer). What does change for every mod, old or new, is Kiln's own drawing: the controller rules in Kiln's windows and the toasts and HUD lines. "Made for" is the mod API the mod was built against: its manifest's kilnBuild.api (Kiln.Sdk writes it, manifest.md), else the lowest version its apiVersion admits; a mod with neither counts as older.

Your choices.

You want Set
The world behind stays sharp (a utility kept open while playing, a window that is part of your HUD) Backdrop = false (UiWindowOptions); a window with Interactive = false never blurs anything
No title row (the frame stays) TitleBar = false
Your own look instead of the frame a theme of your own (Theme, ui.md) or Style = UiStyle.Kiln: such windows are drawn as before, without the frame
A screen without the blur DimBackground = false (UiScreenOptions)
var tools = Ui.Window("Lantern tools", Draw, new UiWindowOptions
{
    Width = 520, Height = 380,
    Backdrop = false,   // keep the world sharp: the player works beside this window
});

There is no switch back to the 0.2.0-dev.32.1 look for a mod built for 0.2.35: pick a theme of your own if the frame does not suit your window.

Sizes: UI units and the scale

Kiln's game look measures in UI units: a unit is a pixel on a 1920 x 1080 display at scale 1, like the game's own UI.

  • UiGameLook.Scale.Scale is the one UI scale: the game's own pixels per UI unit (its 1920 x 1080 canvas and the game's UI-scale setting) times the player's Kiln size. Any thread. UiScaleInfo also has the parts (PixelsPerUnit, GameScale, PlayerScale, TextScale), the canvas in units and FromGame (false: the game's value was not readable this second and the display rule min(width / 1920, height / 1080) stands in).
  • ui.Scale in a draw callback is the scale of the look in effect there: inside a window in the game's look the same UI scale, elsewhere the display's DPI scale as before; the player's Kiln size applies to both. Multiply your own pixel sizes by it, as always. The player can switch the game-scale part off (Match game UI scale, Settings > Kiln): the windows then size by the display's DPI again.
  • The widgets take sizes in UI units (UiWidgetOptions.Width, row heights); drawing calls (ui.DrawRect, ui.StyledText, ui.NineSlice, ui.PlaceNextWidget) take screen pixels.
Display Pixels per unit at the default sizes
1920 x 1080 1
2560 x 1440, and 3440 x 1440 (ultrawide) 1.33
3840 x 2160 2
var s = UiGameLook.Scale.Scale;                               // pixels per UI unit
var pad = UiGameLook.Tokens.Metric(UiMetric.PanelPadding) * s; // 32 units in pixels
var (x, y) = (ui.Cursor.ScreenX, ui.Cursor.ScreenY);            // drawing calls take screen pixels
ui.DrawRect(UiLayer.Window, x, y, x + 300 * s, y + 49 * s, UiGameLook.Tokens[UiToken.Panel]);

Tokens

A token is one named decision of the design: a colour, a size, a type style, a duration. Kiln's own UI draws only with tokens, so a window that uses them matches Kiln's menu and follows the player's settings (text size, reduced motion, sounds). UiGameLook.Tokens is the set in effect: Kiln's design with the player's settings, and inside a draw callback your TokenOverride. It is cheap to ask every frame.

  • Colours (tokens[UiToken.Ink] and the others, UiToken):
    • text: Ink (names, actions, body), Sub (descriptions), Muted (metadata, idle tabs), Placeholder;
    • surfaces: Panel, PanelDark, ListTop / ListBottom (a list's gradient), Field (text fields and drop-downs), Rail, Bar (header and hint bar), Tooltip, Toast, Badge, Scrim (the dimming behind a confirmation);
    • lines: Edge, FieldEdge, Rule, Divider, TooltipEdge, ToastEdge, Pattern (the panels' faint rings);
    • states: Hover, HoverControl, Selected, SelectedBar;
    • gold and focus: Trim (the frames' ornament), Gold (the focus outline), TabRule, CaptionGold, FocusFill / FocusInk / FocusSub (a focused row's cream fill and its text);
    • outcomes, always with words beside them: Ok, Info, Warn, Bad;
    • controls: ButtonLabel, DestructiveLabel, Destructive, Keycap, KeycapInk, KeycapShade, SliderFill, ScrollThumb;
    • Ember: Kiln's own colour, for small origin marks only.
  • Sizes (tokens.Metric(UiMetric.Gutter) and the others, UiMetric; UI units): the spacing scale Space1 to Space6 (4, 8, 12, 16, 24, 32), PanelPadding, Gutter, ControlHeight (47), ButtonHeight (49), LibraryRow (82), PropertyRow (78), ListIcon (56), FocusWidth / FocusOffset, CornerRadius (0: the game's corners are square), and the shell's own (OuterInset, SidebarWidth, HeaderHeight, FooterHeight, WorkMaxWidth, ...).
  • Type (tokens.TypeOf(GameTextStyle.UiBody)): size, tracking, line height, face, capitals and colour of each of the text styles below.
  • Motion (tokens.Motion(UiMotion.OpenMs) and the others, UiMotion: milliseconds or units; and tokens.Ease(UiEase.Standard, elapsed, duration)): open 220 ms, close 150 ms, hover 100 ms, press 70 ms, a notice's entrance, hold and exit. With the player's reduced motion every duration and travel is 0, and Ease answers 1.
  • The player's settings: TextScale (0.8, 1, 1.2 or 1.4), ReducedMotion, SoundsOff.

Changing tokens for your drawing. ui.TokenOverride replaces some tokens for what your callback draws until the scope ends (Kiln's widgets, TokenLook, StyledText); nothing else changes. Dispose the scope (using).

Plain ImGui in the game look. ui.TokenLook() styles the plain ImGui widgets drawn inside from the tokens (opaque surfaces, square corners, the design's paddings at the UI scale, the game's font at the body size), for a child region or a window in another look.

var frost = new UiTokenOverride()
    .SetColor(UiToken.Gold, Color.FromRgba(0x93cddbff))   // a frost-blue focus outline
    .SetMetric(UiMetric.ButtonHeight, 40);
using (ui.TokenOverride(frost))
{
    ui.Text("Frost tools");
}
using (ui.TokenLook())
{
    ui.Checkbox("Plain ImGui, game look", ref _plain);
}

Text styles

The design's type scale is thirteen text styles in the game's font (Harmonique Display, read from the game; its italic faces are UiFont.GameItalic and UiFont.GameBoldItalic):

Style Size (units) For
UiScreenTitle 46, bold capitals a screen's title
UiWindowTitle 43, bold a window's or a detail's title
UiSubsection 30, bold a subsection
UiListName 25, bold a row's name
UiBody 24 body text
UiControl 21 values, choices, hints
UiSecondary 18 second lines, metadata
UiCaption 16, bold tracked capitals captions over a group
UiMark 14, bold gold capitals small marks
UiTab 18, bold capitals tabs
UiButton 21, bold button labels
UiKeycap 15, bold key cap legends
UiPlaceholder 22, italic an empty field's hint

Sizes are ems, as the game and the design size text, not ImGui's line height (the font's line is 1.2 ems tall): Kiln converts. They are times the UI scale and the player's text size. Draw with ui.StyledText(x, y, text, style) in a window (screen pixels; size 0 is the style's own) and measure with ui.MeasureStyledText; on the overlay, RenderDraw.GameText takes the same styles. Text you draw with a style grows with the player's text size: leave room for it, and let rows grow.

var c = ui.Cursor;
ui.StyledText(c.ScreenX, c.ScreenY, "LANTERNS", GameTextStyle.UiCaption);
var (w, h) = ui.MeasureStyledText("LANTERNS", GameTextStyle.UiCaption);
ui.StyledText(c.ScreenX, c.ScreenY + h + 4 * ui.Scale, "Moon white", GameTextStyle.UiBody);

The game's art

UiGameLook.Art(UiArt.FrameFull) is a piece of the game's UI art by Kiln's name for it (frames, panel bodies and patterns, the buttons' stones and glows, switches, slider parts, the scroll thumb and rail, tabs, separators, slots, cards, the loading bar). UiGameLook.ArtAt("menu.fancyBox.frameFull") takes any texture field of the game's UI configuration by its path. Both are read from the player's game the first time they are asked for: ask every frame (it allocates nothing), and draw a flat fallback until State is Ready. Missing (not in this game build) and Failed stay that way. Pictures stay loaded for the session; Kiln keeps at most 4096 paths and 384 pictures, so ask for the pieces you draw, not for every field.

  • ui.NineSlice(art, x0, y0, x1, y1, tint) draws it over a rectangle in nine pieces, the corners keeping their shape, with the border the game's own data gives. Most of the game's shapes are white masks: tint gives them their colour, usually a token. UiNineSliceOptions cuts it another way (Stretch, NoCenter, flips, a source rectangle).
  • Your own PNG frame: ui.NineSliceImage(image, x0, y0, x1, y1, new UiNineSliceOptions { Border = (...) }) with an image from Ui.LoadImage.
  • UiGameLook.Preload() starts reading Kiln's art and sounds now (Kiln calls it at the main menu), so a first window has them on its first frame.

Never put the game's textures, font or sounds in your mod: they are the game's, and reading them at run time is the only way Kiln uses them.

var frame = UiGameLook.Art(UiArt.FrameFull);
var t = UiGameLook.Tokens;
ui.DrawRect(UiLayer.Window, x0, y0, x1, y1, t[UiToken.Panel]);                    // the surface, always
if (frame is null || !ui.NineSlice(frame, x0, y0, x1, y1, t[UiToken.Trim]))
    ui.DrawRect(UiLayer.Window, x0, y0, x1, y1, t[UiToken.Edge], 0, 2 * ui.Scale);  // the flat fallback: an outline

Sounds

UiGameLook.PlaySound(UiSound.Confirm) plays one of the game's own menu sounds (hover, focus, click, confirm, back, cancel, error, open, close, tab, toggle, slider step, notice, typing with the controller, ...) on the game's UI sound scene, at the player's menu volume. Hover has the game's one-second cooldown. It answers false when the player turned Kiln's interface sounds off (Settings > Kiln) or the sound is not there. The widgets below play their own sounds: call it for your hand-drawn controls only.

Controller glyphs

UiGameLook.PadGlyph(UiPadFamily.Current, UiPadButton.FaceBottom) is the game's own picture of a controller button (A on Xbox, Cross on PlayStation), for every button of the Xbox, PlayStation and Switch families (UiPadButton: the face buttons, shoulders, triggers, View, Menu, the d-pad and the sticks with their directions). UiPadFamily.Current is the family Kiln's hints show now: the player's Controller glyphs setting (on Automatic, Xbox for now: Kiln does not tell a PlayStation or Switch controller apart yet). Draw it with ui.NineSlice and new UiNineSliceOptions { Stretch = true }. UiWidgets.Input says which device the player used last (Device) and which family hints draw (Glyphs): show the keyboard's key to a keyboard player and the glyph to a controller player. ui.KeyHint and ui.HintBar below do that for you.

The widget set

The controls of Kiln's own menu, drawn by Kiln with the game's art, type and sounds: the six states of the design (normal, hover, pressed, focused with the gold outline, disabled, error), the sounds, mouse, keyboard and controller. They are methods of UiDraw and draw at the cursor of the current window, like any ImGui widget (ui.PlaceNextWidget puts the next one in a rectangle instead). Call them inside a draw callback.

  • Here or not. UiWidgets.Available is false where Kiln's widget service is not there: a dedicated server, a game without the overlay, or a hand-mixed install whose kiln-ui.dll is older than its Kiln.Ui. There every widget draws nothing and answers false (UiWidgetResult.None, Begin false). Keep a plain ImGui path for that case (below).
  • Options. Most take a last UiWidgetOptions: new() { Disabled = busy, Error = "Not a number" }. Disabled (dimmed, no input, skipped by keyboard and controller), Error (a red edge and the message under the control), Invalid (the red edge alone), DefaultFocus (focused when its window appears: a dialog's safe choice), Selected (tabs, rows, cards, slots), Compact (a smaller size for dense tool windows), Width (UI units; 0 its own width, negative the rest of the line), NoFindKeys (search only).
  • Labels and ids follow Dear ImGui's rules: "Remove##lantern7" shows "Remove" and is told apart by the whole text. A label of only an id ("##volume") draws no label.
  • What it did. Interactive widgets answer true when clicked or changed. ui.LastWidget tells more about the one drawn last: Hovered, Focused, Active, its rectangle, and GestureBegin / GestureEnd around a slider drag, a held key or typing (one Undo step: save the value when the gesture ends), Submitted (Enter), Cancelled (Esc / B).

ActionButton

The game's buttons: UiButtonKind.Primary is the gold-trimmed stone for the main action (one per panel), Secondary the plain square-ended stone (Settings, Undo, Cancel), Destructive and DestructivePlain the red ones (ask first, with the focus on the safe choice). True on the frame it is activated: a click released over it, or A / Enter while focused. A button is at least 170 units wide unless Width says otherwise.

if (ui.ActionButton("Apply to lanterns")) Relight();
ui.SameLine();
if (ui.ActionButton("Restore", UiButtonKind.Secondary, new() { Disabled = !_changed })) Restore();

Toggle and CheckOption

Toggle is the game's switch, CheckOption a check box; both flip a bool on a click, A or Enter, and answer true on that frame. A toggle whose label is only an id shows On / Off in the player's language.

if (ui.Toggle("Light the lanterns at dusk", ref _atDusk)) Save();
if (ui.CheckOption("Only my lanterns", ref _mineOnly)) Save();

ValueSlider

A slider from min to max in steps of step (0: continuous), with its value as text after it; true on every frame the value changes. Left / right and the d-pad move one step, LT / RT held ten; the mouse wheel moves one step, but only once the pointer has rested on the slider (a page scrolled past it never changes it). Clicking the number (or A / Enter on it) types an exact value: Enter commits it (clamped to the range, on the step), Esc / B cancels. A drag is one gesture. In a PlaceNextWidget rectangle narrower than its own width the track gives way, so the value text keeps its gap (the track never narrower than two knobs).

format is printf-style with exactly one floating-point conversion: %f, %e, %g or %a (or their capitals), with the flags -, +, space, # and 0, at most two digits each of width and precision, and any words around it; a % in the words is written %%; under 64 bytes. Examples: "%.0f m", "%.1f%%", "x %.2f". Empty: as many decimals as the step has. Any other format (%s, %d, two conversions, *, a length modifier) is never used: the value shows with the step's decimals instead, so a format from a config file or a player is safe to pass.

if (ui.ValueSlider("Radius", ref _radius, 4, 64, 1, "%.0f m")) Preview(_radius);
if (ui.LastWidget.GestureEnd) Save();   // the drag ended: one save, one Undo step

The chosen entry of choices in a sunken box; a click, A or Enter opens the list in the game's pop-up box. True on the frame a choice sets the index. An index outside the list shows the box empty.

if (ui.Dropdown("Light", ref _light, Lights)) Save();

TextBox and SearchField

TextBox edits a one-line text (at most maxBytes UTF-8 bytes) with an italic placeholder while it is empty; true on every frame the text changes. Typing is one gesture; Enter answers Submitted; Esc or B drops the edit and puts the text back. A text too long for maxBytes is shown cut and disabled, and your string is never changed.

SearchField is the search box: a magnifier, the placeholder, and an "X" inside its right end while it holds a term, which erases the term in one click. Esc on a box with a term clears it; Esc on an empty box leaves it. X / Square clears it from a controller. Ctrl+F and Y / Triangle focus the first search box of the frame (NoFindKeys keeps one out). For a controller player, open the letter board to type.

if (ui.TextBox("Greeting", ref _greeting, "Welcome, Flameborn", 80)) Save();
if (ui.SearchField("##find", ref _term, "Search lanterns")) _list.ScrollToTop();

TabStrip

Tabs as letter-spaced capitals over a rule, the chosen one in ink with the gold rule under it. A click, or left / right while focused, sets the index; true on that frame.

if (ui.TabStrip("lantern-tabs", Tabs, ref _tab)) _list.ScrollToTop();

SectionDivider, ValueRow, StateBadge

SectionDivider is a gold caption in capitals on the design's diamond-tipped rule, with an optional muted text at its right end. ValueRow is a key and a value over a hairline (a detail's "Version 1.4.2"). StateBadge is a state in words with its tone's colour and glyph: UiTone.Ok (On, Ready), Info, Warn (Needs restart), Bad (Error), Neutral (Off). Words always come with the colour.

ui.SectionDivider("Installation", "3 lanterns");
_ = ui.ValueRow("Placed", "12 November");
_ = ui.StateBadge("Needs restart", UiTone.Warn);

InfoTip and InfoLine

InfoTip shows the design's tooltip over the widget drawn last while it is hovered or focused. InfoLine draws the same surface in the layout at the cursor, for a line that explains a form.

ui.ActionButton("Relight", UiButtonKind.Secondary);
_ = ui.InfoTip("Lights every lantern near you again with your chosen light.");
_ = ui.InfoLine("Changes apply as you make them.");

KeyHint and HintBar

KeyHint draws one hint: the key cap or controller glyph of an action (UiHintAction) for the device the player used last, and its words; true when clicked with the mouse (a hint is a button too). HintBar draws a row of them, like the game's own hint bar, and answers the index of the hint clicked this frame, or -1. After ui.PlaceNextWidget the row is right-aligned in that rectangle.

  • A hint with an empty label belongs to the next one: (Previous, "") and (Next, "Sections") read [Q][E] Sections.
  • Key gives the keyboard legend: "+" separates key caps ("Ctrl+F" draws [Ctrl][F]) and an arrow (U+2190 to U+2193) draws an arrow cap. Without it each action has its default key: Confirm Enter, Back Esc, Search Ctrl+F, Previous Q, Next E, Move the arrow keys, Scroll the wheel, Menu Insert, View Tab (Alt has none).
  • Disabled dims a hint that is not available now.
  • Make the list once (a field), not in the call: a list written in the call is a new one every frame.
  • ui.MeasureHintBar(hints) (since 0.2.0-dev.32.9) answers the size the row takes with this frame's key caps or glyphs, so a foot can share its room with a message: ui-kit.md.
private static readonly UiHint[] Foot =
[
    new(UiHintAction.Confirm, "Select"),
    new(UiHintAction.Previous, ""), new(UiHintAction.Next, "Tabs"),
    new(UiHintAction.Back, "Back"),
];

private void DrawFoot(UiDraw ui)
{
    if (ui.HintBar(Foot) == 3) _window?.Hide();   // "Back" clicked with the mouse
}

FocusRing and PlaceNextWidget

FocusRing draws the gold focus outline around a rectangle you draw yourself. PlaceNextWidget puts the next widget in a rectangle (screen pixels) instead of at the cursor, for a page laid out by hand; the cursor does not move.

var (x, y) = (ui.Cursor.ScreenX, ui.Cursor.ScreenY);
ui.PlaceNextWidget(x, y, x + 220 * ui.Scale, y + 49 * ui.Scale);
if (ui.ActionButton("Light all")) LightAll();
if (ui.LastWidget.Focused) ui.FocusRing(x - 4, y - 4, x + 224 * ui.Scale, y + 53 * ui.Scale);

BeginGamePanel and EndGamePanel

A panel is a child region in the game's look: UiPanelStyle.Plain (the reading surface), Framed (the surface, the ring pattern and the game's ornamented frame: a detail) or Book (a list's gradient with a quiet frame). Width and height in UI units: 0 the space available, negative the space available less that much. Call EndGamePanel only when BeginGamePanel answered true. Panels nest.

if (ui.BeginGamePanel("details", UiPanelStyle.Framed, 520, 0))
{
    ui.SectionDivider("Lantern");
    _ = ui.ValueRow("Light", "Moon white");
    ui.EndGamePanel();
}

UiScrollList and ListRow

UiScrollList is a virtualised list in the game's look: the game's gold thumb on its dark rail, fades at a cut edge, smooth scrolling with the wheel and the right stick, the arrows and the d-pad moving the selection one row and keeping it in view. Keep one per list (a field): it remembers the selection, and Kiln keeps its scroll position per id. Draw only the rows in Visible, then call End (only when Begin answered true).

ListRow is the library row of Kiln's Mods page (82 units: an icon in a 56-unit slot, the name, a second line, a right-aligned text and a state badge); inside a list it fills the next row's place. True when clicked or activated. UiRowContent.Icon takes a UiImage: your own (Ui.LoadImage), an item's (Ui.ItemImage), or your mod's icon (ModIcons.Of(id).Png given to Ui.LoadImage).

  • Selected is the selected row (-1 for none); set it on a click. SelectionMoved says the keys or free scrolling moved it this frame (scrolling the selection past a cut edge selects the nearest fully visible row).
  • ScrollToTop() after a search or filter change; Reveal() scrolls the selection into view.
  • The design's counter "12-19 of 46" is Visible.First + 1, Visible.Last + 1 and Count.
private readonly UiScrollList _list = new();

private void DrawList(UiDraw ui, IReadOnlyList<Lantern> lanterns)
{
    if (!_list.Begin(ui, "lanterns", lanterns.Count, 82)) return;
    foreach (var i in _list.Visible)
    {
        var l = lanterns[i];
        var row = new UiRowContent { Title = l.Name, Subtitle = l.Place, Trailing = l.Light, Badge = l.Lit ? "On" : "Off",
                                     Tone = l.Lit ? UiTone.Ok : UiTone.Neutral };
        if (ui.ListRow("lantern" + i, row, new() { Selected = i == _list.Selected })) _list.Selected = i;
    }
    _list.End();
}

Card, ItemSlotTile and Meter

Card is a picture with a small capitals caption, a title and a second line (UiCardContent). ItemSlotTile is the game's item slot with an icon in it, its shape and outline tinted by a rarity colour (null: the plain slot). Both answer true when clicked or activated. A page that handles its slots' input itself (drag and drop) draws the same slot with UiKit.ItemSlot (ui-kit.md). Meter is the game's loading bar filled to a fraction (0 to 1), with a label after it.

if (ui.Card("world", new UiCardContent { Caption = "World", Title = "Springlands", Subtitle = "4 players" })) Open();
if (ui.ItemSlotTile("fuel", Ui.ItemImage(_fuel), Color.FromRgba(0x78a1dbff))) PickFuel();
_ = ui.Meter("lit", 0.5f, "3 / 6");

A complete small window

public sealed class LanternKeeperMod : Mod
{
    private static readonly string[] Lights = ["Moon white", "Ember", "Frost"];
    private static readonly UiHint[] Foot = [new(UiHintAction.Confirm, "Select"), new(UiHintAction.Back, "Close")];

    private UiWindow? _window;
    private bool _atDusk = true;
    private float _radius = 24;
    private int _light;

    public override void OnLoad()
    {
        if (!Ui.Available) return;   // a dedicated server: no UI
        _window = Ui.Window("Lantern Keeper", Draw, new UiWindowOptions { Width = 560, Height = 420, StartOpen = false });
        KeyBindings.Register("lanterns.window", "F8", () => _window?.Toggle(), "Lantern Keeper window", "Lantern Keeper");
    }

    private void Draw(UiDraw ui)
    {
        if (!UiWidgets.Available)
        {
            // an older kiln-ui.dll: the same settings with plain ImGui
            ui.Checkbox("Light the lanterns at dusk", ref _atDusk);
            ui.Slider("Radius", ref _radius, 4, 64);
            if (ui.Button("Apply to lanterns")) Relight();
            return;
        }
        ui.SectionDivider("Lanterns", $"{_radius:0} m");
        ui.Toggle("Light the lanterns at dusk", ref _atDusk);
        ui.ValueSlider("Radius", ref _radius, 4, 64, 1, "%.0f m");
        ui.Dropdown("Light", ref _light, Lights);
        ui.Spacing();
        if (ui.ActionButton("Apply to lanterns")) Relight();
        ui.SameLine();
        if (ui.ActionButton("Close", UiButtonKind.Secondary)) _window?.Hide();
        if (ui.HintBar(Foot) == 1) _window?.Hide();
    }

    private void Relight() => Hud.Toast($"Lanterns relit: {Lights[_light]}", ToastKind.Success);   // any thread
}

On an older Kiln

  • A mod that calls these methods needs Kiln 0.2.0-dev.32.2 (mod API 0.2.35): an older Kiln refuses to load a mod built for it, so the methods are always there when your mod runs.
  • UiWidgets.Available can still be false: on a dedicated server, without the overlay, or next to an older kiln-ui.dll (a hand-mixed install). The widgets then draw nothing and answer false; draw your plain ImGui instead, as above.
  • UiGameLook.Available is the same question for the tokens, art and sounds: without it Tokens are Kiln's defaults, Scale is the display rule, Art and PadGlyph are null, PlaySound is false.

Controller and keyboard

Kiln's widgets, and the plain ImGui in your windows, work with the mouse, the keyboard and a controller:

  • Focus. The d-pad or the left stick moves the focus to the next control in that direction; the arrow keys, Tab and Shift+Tab do the same. The focused control has the gold outline (rows and cards: a cream fill). A or Enter activates it. Disabled controls are skipped. DefaultFocus puts the focus on a control when its window appears.
  • Scrolling. The right stick scrolls the window or list under the focus, smoothly; the mouse wheel scrolls where the pointer is.
  • Moving windows. Holding X (Square) and using the sticks moves and resizes windows, Dear ImGui's own controller windowing.
  • Hints. KeyHint and HintBar show the key caps of the keyboard after a key or mouse press and the controller's glyphs after a controller press, in the family the player set (Xbox on Automatic, for now).
  • Back. Esc and B close the topmost pop-up or drop an edit first (Cancelled). In Kiln's menu they go back one step at a time: a confirmation, then the page's own layer, then up one level, then to the section list, and close the menu last. Esc still closes a Ui.Screen of yours as before.
  • Texts. On a controller, use the letter board.

The letter board

UiLetterBoard is the design's text entry for controller players: the text, the keys A to Z, 0 to 9 and . , ! ?, then Capitals, Space, Delete, Clear and your main action. X / Square deletes, Y / Triangle types a space, LT switches capitals, Start / Options submits, B cancels. A keyboard types into its text too. It keeps its own copy of the text until it answers Submitted. Open it when a controller player activates your text field (UiWidgets.Input.Device is UiInputDevice.Gamepad).

private readonly UiLetterBoard _board = new(80);
private string _greeting = "";
private bool _typing;

private void DrawGreeting(UiDraw ui)
{
    if (!_typing)
    {
        if (UiWidgets.Input.Device != UiInputDevice.Gamepad)
        {
            if (ui.TextBox("Greeting", ref _greeting, "Welcome, Flameborn", 80)) Save();
        }
        else if (ui.ActionButton("Edit greeting", UiButtonKind.Secondary))
        {
            _board.Open(_greeting);
            _typing = true;
        }
        return;
    }
    switch (_board.Draw(ui, "Use greeting"))
    {
        case UiLetterBoardResult.Submitted: _greeting = _board.Text; _typing = false; Save(); break;
        case UiLetterBoardResult.Cancelled: _typing = false; break;
    }
}

Your mod in Kiln's menu

Kiln's menu (Insert, or Mods in the game's main and pause menus) is a full-screen page with sections: Mods, Settings, Keys, Server, Conflicts, and Tools for developers (the player's guide), and the sections mods add under a Mods caption (below). Your mod appears in it without code; a few things make it look its best.

Your icon

Put a mod-icon.png (256 x 256 px, sRGB, transparent background, the silhouette inside the middle 214 x 214 px) at the root of your mod's folder, or name another PNG with the manifest's icon (mod-icons.md, manifest.md). Kiln's Mods and Settings pages and the Kiln Launcher show it; without one your mod gets the default emblem of its framework (the Kiln flame for Kiln mods). ModIcons.Of(modId) gives you the picture for a window of your own (Png for Ui.LoadImage).

The Mods page

The Mods page lists every installed mod of every framework: its icon, its name, its author and framework, its version, and its state (On, Off, Error, Needs restart). Its detail shows the name, "By ... · Version ...", the description and where the mod runs. For a Kiln mod these come from kiln.mod.json: name, version, authors (a string or a list; author is read too) and description (line breaks kept). ShroudForge, EML, XHL, EMF and Shroudtopia mods are read from their mod.json the same way.

The detail's gold main action is your mod's entry in the game's menu: an entry you add with Ui.Menus.Add for the menu the player can open there (ui.md) shows as that button, with the same words and the same action; more entries are listed under it. A mod with settings gets a Settings button beside it (S on the keyboard, X / Square on a controller).

Your settings

Every typed config of your mod (config) becomes a form on your mod's page in Settings, drawn with the widgets above. Nothing to write:

  • Names. A key becomes words: trackingRadius reads "Tracking radius", max_FPS "Max FPS", an enum value DimOnly "Dim only". An entry inside a section (map.radius) shows under a caption of the section's name ("Map"); a mod with several configs gets a caption per file ("General" for the main one). [ConfigKey] changes the key, and so the words. The raw key shows only behind the inspector's # Show raw ID.
  • Descriptions. An entry's [Comment] is the text the side panel shows for the focused setting, with its current value, its default, its range or choices and who can change it. Write it for players.
  • Pickers. A bool is a switch; a number with a [Range] is a slider (a whole number over at most 100 000), with the step of [Range(min, max, step)] (the value shows with the step's decimals). With SoftMin / SoftMax the inspector takes a typed value past that end. An enum is a drop-down; anything else (a number without a range, a text, a duration, a list) is a text field. There is no unit attribute: say the unit in the comment.
  • Live. A change applies as it is made, and is saved a moment later on the tick (a slider drag is one save). There is no Apply button. Undo takes back the last change of this mod's page; Reset to defaults asks first and is one Undo step.
  • Needs restart. An entry with [RequiresRestart] saves at once, applies at the next launch, and shows "Needs restart" with what runs until then.
  • Server-locked. A server config is read-only while the player is connected to someone else's server; its [Synced] entries show the server's values, marked "Server-locked". While the player hosts or plays alone, the mod's server configs are theirs to change.
  • A value the config refuses shows its reason under the field (and a toast); the old value stays.

Buttons of your own. A setting applies as it changes, so the page has no Apply button. When your mod needs an action beside its settings (relight the lanterns with the light just chosen, rebuild a cache), Ui.AddSettingsActions adds a row of buttons under the form: a caption (by default your mod's name and "actions"), a line saying what they do, the buttons (UiButtonKind.Primary for the row's main action, the plain stone by default), and a status line. Enabled and Status are asked every frame the row shows, on the render thread: keep them cheap. A button's action runs on the render thread in your mod's context: post world changes to the tick. The row is yours until you dispose it or your mod unloads, and your mod is listed in Settings even without a config.

_actions = Ui.AddSettingsActions("lantern-keeper", new UiSettingsActions
{
    Description = "Relight the nearby lanterns with your chosen light.",
    Buttons =
    [
        new UiSettingsAction("Apply to lanterns", Relight) { Kind = UiButtonKind.Primary },
        new UiSettingsAction("Restore lanterns", Restore) { Enabled = () => _changed },
    ],
    Status = () => $"Nearby lanterns · {_lightName}",
});

A page of your own. A page you registered with Ui.AddConfigPage(modId, ui => ...) still works: it is drawn on your mod's Settings page, under the generated form, with your drawing code (use the widgets above to match).

Your own menu section (since 0.2.0-dev.32.3)

A page that is more than settings (a ledger, a map of your mod's places, a bestiary) can have its own section in the rail of Kiln's menu: Ui.AddMenuSection(modId, section) adds a row with your icon and title under the rail's Mods caption, between Conflicts and Developer, and shows your page in the work area when the player chooses it. Everything around the page is the menu's: the header, the hint bar, Back, the motion and sounds, LB / RB and Q / E (they step through your section like Kiln's own), and the focus your page had when the player left (as for every section). The caption only shows while a mod has a section; without one the rail is the six sections.

  • Two per mod. A mod may add up to two sections; the rail holds sixteen of every mod together. A third section, a second with the same Id, or one more than the rail holds is refused: Added is false on the handle, RefusedReason says why, and kiln.log has the same line. Nothing throws, so a refusal never stops your mod's load.
  • What you give (read once, when the section is added; add it again to change it): Title (a word or two, in the player's language: the rail cuts a longer one with "…"), Draw (required), and optionally Id ("main" when none; each section of a mod needs its own), Icon (your mod's icon by default), Order (lower first among the mods' sections), Panel (true: Kiln draws the page's surface with its padding; false: your page draws the whole work area, columns with BeginGamePanel of its own), Back, Hints, Badge, Open and Hidden.
  • The page. Draw(ui, page) runs every frame the section shows, in a scrolling region that starts at the page's top left; draw with the widget set above. page (UiMenuPageContext) has ModId (your mod) and SectionId (which of your sections this is), the page's area (Content, screen pixels), Scale and U(units), the device (Gamepad, NavVisible), routes (Route, Push, PopToRoot: Back pops a pushed route before it moves the focus to the rail), the focus memory (Focused(key) when a control has the focus, WantsFocus(key) / WantsDefaultFocus() to put it back), HoldKeys() while a text field or key capture of yours has the keyboard, ModalUp while a confirmation is over the page, FirstShown, and Close(). Choosing your section on the rail again goes back to its root route.
  • Back, hints, badge. Back is asked before the menu's own steps (true: your page used the press). Hints lists your page's hints (Search, a page action with its key); the menu adds Sections before them and Choose and Back after them, and leaves out Previous / Next (its section keys). Badge is the small number at your row's end (0: none).
  • Opening it. Ui.OpenMenuSection(modId) opens the menu on your first section, Ui.OpenMenuSection(modId, "map", "place:12") on the section "map" with a target its Open callback handles (push a route, select a row). False when the mod has no such section.
  • Threads and faults. The callbacks run on the render thread as your mod's code: keep them cheap (a Draw over 8 ms or another callback over 4 ms is logged once) and post world changes to the tick. What page asks of the menu (Push, Focused, Close ...) acts only on the render thread while your section shows: after an await (which continues on your mod's scheduler) it does nothing, so make the change in the next Draw. A Draw that throws removes the section for the session; another callback that throws is not asked again; each is logged once to your mod's log. Dispose the handle to remove the section; your mod unloading removes it too. When the section shown goes, the menu shows Mods and your page is told Hidden.
  • Where it shows. In Kiln's menu of every way in (Insert, the pause menu's and the main menu's Mods), with kiln.ui 0.2.0-dev.32.2 or later. An older Kiln menu has no rail.
using Kiln;

public sealed class LanternKeeper : Mod
{
    private UiMenuSectionHandle? _lanterns;
    private readonly UiScrollList _list = new();
    private string[] _names = [];
    private int _unlit;

    public override void OnLoad()
    {
        _lanterns = Ui.AddMenuSection("lantern-keeper", new UiMenuSection
        {
            Title = "Lanterns",
            Draw = DrawLanterns,
            Badge = () => _unlit,
            Hints = () => [new UiHint(UiHintAction.Alt, "Relight all", "R")],
            Back = page =>
            {
                if (page.Route.Length == 0) return false;  // the root: the menu's own Back
                page.PopToRoot();                          // a lantern's detail: back to the list
                return true;
            },
            // Ui.OpenMenuSection("lantern-keeper", target: "lantern:3")
            Open = target => target.StartsWith("lantern:", StringComparison.Ordinal),
        });
        if (!_lanterns.Added) Log.Warn(_lanterns.RefusedReason!);
    }

    private void DrawLanterns(UiDraw ui, UiMenuPageContext page)
    {
        ui.SectionDivider("Lanterns", $"{_names.Length}");
        if (ui.ActionButton("Relight all", UiButtonKind.Primary)) Context.Scheduler.Post(RelightAll);
        if (_list.Begin(ui, "##lanterns", _names.Length, 64))
        {
            foreach (var i in _list.Visible)
            {
                if (page.WantsFocus("lantern:" + i)) ui.FocusKeyboardHere();
                if (ui.ListRow("##lantern" + i, new UiRowContent { Title = _names[i], Chevron = true }))
                    page.Push("lantern/" + i);
                if (ui.LastItem.Focused) page.Focused("lantern:" + i);
            }
            _list.End();
        }
    }

    private void RelightAll() { /* tick thread: world changes */ }

    public override void OnUnload() => _lanterns?.Dispose();  // also done for you when the mod unloads
}

Your keys

Every KeyBindings.Register binding is on the Keys page, under its category (the last argument; your mod's name when you give none), with a Keyboard and a Controller column. The player rebinds by press, resets one binding or all of an owner's, or unbinds; actions that share a key are marked "Shared binding". Give each binding a description: it is the action's name there (without one, the id in words).

Confirmations

await Ui.Confirm(title, body, yes, no, token) asks the player a yes / no question (ui.md). While Kiln's menu or a full-screen Kiln screen is open, Kiln shows it in its own confirmation panel inside the menu, with the safe choice (no) focused; otherwise the game's own confirmation dialog asks. The answers, cancellation, the limit of 64 waiting questions and the task are the same either way. Closing the menu while your question waits answers false, as the game's back does. Kiln's menu does not open over the game's dialog: asked to open while your question shows there, it opens right after the answer.

Toasts, server notices and HUD lines

In the player's game look, Kiln draws Hud.Toast, server notices and Hud.Show lines in the new look, for every mod, old or new (your calls stay the same):

  • Toasts stack at the left of the play view, clear of the game's quest list, minimap and hotbar: an icon and an edge in the kind's colour, the kind in words as a caption ("Information", "Success", "Warning", "Error"), the text's first line as its title and the lines after it wrapped under it. They enter one after another with the game's notice sound. A toast that used to show at the bottom right shows in that stack now.
  • Server notices (Notices.ShowAt(player, text, NoticePlace.TopCenter)) show at the top centre under the compass with Kiln's mark, captioned "Server notice". The top corners (TopLeft, TopRight) have stacks of their own under the game's status bars and minimap. NoticePlace.GameLine and Banner are the game's own and unchanged.
  • HUD lines (Hud.Show) of one anchor share a box on the notices' surface, placed clear of the game's HUD (a top-left line sits under the game's status bars now, not in the corner). A line's own colour stays; the default white is the look's ink. PlayHudOnly works as before.

In another look (Kiln's ember look or a theme the player picked) toasts and HUD lines are drawn as before.

Native plugins

The same pieces are C tables next to kiln.ui: kiln.ui.theme (native/core/abi/services/kiln_ui_theme.h: tokens, the scale, styled text, the game's art, nine-slice, sounds, pad glyphs), kiln.ui.widgets (kiln_ui_widgets.h: the widget set, the scroll list, the input snapshot) and kiln.ui.chrome (kiln_ui_chrome.h: the window frame, notices and HUD boxes). Check header.size before calling a member, as for every Kiln table.

Enshrouded is a trademark of Keen Games GmbH. Kiln is unofficial.