The basics

Packages and imports

How a folder becomes a unit of code, and how units find each other.

src/palace/palace.odin odin
package palace

import "core:math"
import "core:slice"
import sa "core:container/small_array"

import "../iso"
import "../level"

Cell :: iso.Cell

reading the code

package palace
The first line of every file names its package. All the files of one folder share the same package name: the folder is the package.
import "core:math"
core: is Odin's standard library, shipped with the compiler. There is no package manager and nothing to install.
import sa "core:…"
A name before the path is an alias: sa. stands for small_array.. Handy for long names or clashes.
import "../iso"
Your own packages are imported by relative path. The game's packages form a tidy ladder: iso knows nothing, level uses iso, palace uses both.
iso.Cell
Everything is reached through the package name. Cell :: iso.Cell gives iso.Cell a shorter local name.

why it is so

No header files, no include paths, and import cycles are forbidden: the compiler reads the whole program and builds the packages in the right order. A file never has to be told what comes before it.

See the file on GitHub (opens in a new tab)

Constants

`::` binds a name to something fixed at compile time.

src/iso/iso.odin odin
HALF_W :: 64.0
HALF_H :: 32.0
WALL :: 64.0

// View-space point -> proto pixels.
project :: proc(v: Vec3) -> Vec2 {
    return {(v.x - v.y) * HALF_W, (v.x + v.y) * HALF_H - v.z * WALL}
}

reading the code

::
Read it as “is defined as”. It makes a constant: a number, a string, but also a type or a procedure. Almost everything with a name in Odin is declared with ::.
HALF_W :: 64.0
The half-width of a tile in pixels. It lives in the compiled code: no memory, no way to change it by mistake.
UPPER_CASE
Not enforced, but it is the habit for constants, so they stand out in a formula.
* HALF_W
A constant like 64.0 has no type yet. It becomes an f32 here because it meets one; in an f64 formula it would become an f64. No casts needed.

why it is so

Magic numbers in a projection formula are unreadable. A named constant costs nothing at run time, and the geometry of the isometric view is written once, in one place.

See the file on GitHub (opens in a new tab)

Variables

`:=` declares and infers the type, `x: T` declares and starts from zero.

src/progress/progress.odin odin
seal :: proc(text: string, allocator := context.allocator) -> []byte {
    N :: chacha20poly1305.IV_SIZE
    T :: chacha20poly1305.TAG_SIZE
    out := make([]byte, len(MAGIC) + N + T + len(text), allocator)
    copy(out, MAGIC)
    nonce := out[len(MAGIC):][:N]
    // …
    ctx: chacha20poly1305.Context
    chacha20poly1305.init(&ctx, KEY[:], .Portable)
    // …
}

reading the code

out := make(…)
name := value declares a variable and takes its type from the value. Here a []byte.
ctx: Context
name: Type declares a variable with no value given: it starts as zero. The compiler never leaves garbage in memory.
N :: …
Constants can live inside a procedure too: N and T exist only for the lines below, and cost nothing.
nonce := out[…]
nonce is not a copy: it looks at part of out. Variables hold values; slices (see Slices) are views.

why it is so

Inference keeps the code short; the explicit x: T form says “start from nothing” on purpose. With = you assign, with := you declare: the two are never confused.

See the file on GitHub (opens in a new tab)

Zero is initialisation

Every value starts as zero, so a struct is ready to use the moment it exists.

src/dead_ends.odin odin
Dead_End_Job :: struct {
    index:   int,
    diorama: int,
    source:  string, // the diorama's text
    keep:    bool, // a level slot's own text: remembered for the session
    result: []palace.State,
    done:   bool, // set by the worker (atomic)
}

// …
    job := Dead_End_Job{index = index, diorama = diorama, source = source, keep = keep}

reading the code

Dead_End_Job :: struct
Six fields, and nobody wrote a constructor. Declare one with job: Dead_End_Job and it is all zeroes: 0, "", false, nil.
result, done
These two are filled in later, by the worker thread. The literal below never sets them, and doesn't need to: zero (a nil slice, false) means “not yet”.
Dead_End_Job{index = index, …}
A struct literal names the fields it sets. The ones left out stay zero.
g^ = {}
The same idea, reversed: an empty literal is the zero value. The game resets a whole Game to its initial state by assigning one to it (see Pointers).

why it is so

No half-built objects, no forgotten initialisation, no constructors to maintain. Design types so that zero is a sensible state — idle, empty, off — and an empty literal becomes the reset button.

See the file on GitHub (opens in a new tab)

Numbers and conversions

Integers and floats of exact size, and conversions you spell out.

src/iso/iso.odin odin
// A world point seen from the continuous view angle (in quarter turns),
// rotated about the vertical axis through the centre of the size x size grid.
view_point :: proc(p: Vec3, angle: f32, size: i32) -> Vec3 {
    th := angle * math.PI * 0.5
    h := f32(size) * 0.5
    c, s := math.cos(th), math.sin(th)
    cx, cy := p.x - h, p.y - h
    return {cx * c - cy * s + h, cx * s + cy * c + h, p.z}
}

reading the code

f32(size)
size is an i32, the formula needs an f32: Odin never converts silently. You write f32(size) and you can see where the change happens.
c, s := …
Several names on each side declare several variables at once: here c and s (cosine and sine).
return {…}
A literal in braces gets its type from the context: the procedure returns a Vec3, so the three numbers build one.
i32, f32
The size is in the name: i32 is 32 bits, u8 an unsigned byte, f32 a 32-bit float. int is the machine's word, for counts and indices.

why it is so

A game moves bytes between the CPU, files, the GPU and the audio device: the exact size of every number matters. Explicit conversions make a lost fraction or an overflow visible in the code, not in a bug report.

See the file on GitHub (opens in a new tab)

Types

Structs

Plain data grouped under a name. No classes, no inheritance.

src/palace/solve.odin odin
Spot :: struct {
    cell:  Cell,
    under: bool,
}

State :: struct {
    cfg:   Config,
    cell:  Cell,
    view:  u8,
    lamp:  bool,
    boats: level.Boats,
}

// Is she at `spot` in state st?
at_spot :: proc(st: State, spot: Spot) -> bool {
    return st.cell == spot.cell && st.cfg.upside == spot.under
}

reading the code

Spot :: struct
A type is declared with :: like anything else. A Spot is a cell and whether she is on the underside of the world.
cell: Cell
Fields read name: Type, the same shape as a variable. Fields can be other structs: State holds a Config.
cfg: Config
Nested data is stored inline, in one block: no pointer to chase, and one copy copies everything.
st.cfg.upside
A dot reaches into a field, as deep as needed.
==
Structs made of comparable fields compare with ==, field by field. State can even be the key of a map.

why it is so

Data and behaviour stay apart: State is just numbers, and the procedures that use it (at_spot) are ordinary procedures beside it. A value that is cheap to copy and compare is exactly what a puzzle solver needs by the million.

See the file on GitHub (opens in a new tab)

Enums

A closed list of named choices, instead of magic numbers.

src/palace/solve.odin odin
Move :: enum u8 {
    Start,
    Step,
    Turn_Left,
    Turn_Right,
    Light,
    Douse,
    Handle,
    Time, // the spindle on a sundial: day <-> evening
    Flight, // Jupiter's eagle: from its perch to its landing, one way
    Overturn, // the spindle on a pomegranate: the world turned over (or back)
    Ferry, // Charon's ferry: from the landing where the boat waits to the other
}

reading the code

Move :: enum u8
Every move the solver can make. u8 is the type underneath: one byte is plenty for eleven values.
Start
Values count up from 0 in the order written: Start is 0, Step is 1… You almost never need the numbers, only the names.
Turn_Left
The naming style is Ada_Case: capitals, underscores between words. Types and enum members share it.
// the spindle on a sundial
A comment after the comma documents that one value. Comments start with //.

why it is so

A Move can be nothing but one of these eleven. The compiler rejects a typo, switch can check you handled them all, and the code says .Light where C would say 3.

See the file on GitHub (opens in a new tab)

Arrays indexed by an enum

A lookup table whose index is a name, not a number.

src/iso/iso.odin odin
Dir :: enum u8 {
    PX,
    MX,
    PY,
    MY,
}

DIR_VEC := [Dir][2]i32 {
    .PX = {1, 0},
    .MX = {-1, 0},
    .PY = {0, 1},
    .MY = {0, -1},
}

DIR_NAME := [Dir]string {
    .PX = "px",
    .MX = "mx",
    .PY = "py",
    .MY = "my",
}

rot_dir :: proc(d: Dir, r: int) -> Dir {
    out, _ := dir_from_vec(rot_vec(DIR_VEC[d], r))
    return out
}

reading the code

[Dir][2]i32
An array with one slot per Dir: here a pair of integers each. The enum itself is the size.
.PX = {1, 0}
Slots are filled by name. The compiler checks you gave one for every value.
[Dir]string
Same trick for text: the name of each direction, as written in the level files.
DIR_VEC[d]
Index it with the enum value: DIR_VEC[.MX] is -1, 0. No switch, no chain of ifs.
out, _ :=
_ throws a value away. dir_from_vec returns a direction and an ok; here we know it cannot fail.

why it is so

Add a fifth direction and the compiler points at every table that lacks it. The game is full of these tables: names, costs, colours, translation keys per act, per achievement, per move.

See the file on GitHub (opens in a new tab)

Bit sets

A set of enum values stored in a single integer.

src/progress/progress.odin odin
Aid :: enum u8 {
    Highlight,   // the stones under the devices glow
    Sense,       // seals and veiled stones sparkle as her flame nears
    Dead_Ends,   // she is told when she stands in a dead end
    Endless_Oil, // the lamp never runs dry
    Guide,       // the light on Psyche also shows the way to the next thing to do
}

Aids :: bit_set[Aid]

Level_Set :: bit_set[0 ..< 32] // indices into content.LEVELS

game_finished :: proc(p: Progress) -> bool {
    return .Wedding in p.achievements
}

collect_fragment :: proc(p: ^Progress, fragment: int) -> (unlocked: Achievements, new_page: bool) {
    new_page = fragment not_in p.fragments
    p.fragments += {fragment}
    return award(p, {}), new_page
}

reading the code

Aids :: bit_set[Aid]
A set that can hold any combination of the five Aids: each one is a bit. The whole set is as big as one small integer.
bit_set[0 ..< 32]
It can be a set of plain integers too: the levels a player completed, by index. 0 ..< 32 is a range, from 0 up to but not including 32.
in
x in set asks whether the value is in. A fast single-bit test.
not_in
The negation. It reads like a sentence: fragment not_in p.fragments.
+= {…}
+= adds members, -= removes them. A set literal looks like a struct literal: the members between braces.

why it is so

Progress is a handful of yes/no facts per level and achievement. As bit sets they are copied, compared and saved as numbers, with no allocation. #assert (see Compile-time checks) guards the 32-level limit.

See the file on GitHub (opens in a new tab)

Maybe: a value, or nothing

How Odin says “there might not be one” without a null pointer.

src/dead_ends.odin odin
Dead_Ends :: struct {
    known:   [content.LEVEL_COUNT][level.MAX_DIORAMAS]Maybe([]palace.State), // in the heap, for the session
    worker:  ^thread.Thread,
    job:     Dead_End_Job,
    pending: Maybe(Dead_End_Job), // asked for while the worker was busy
}

// …
    if dead, ok := d.known[index][diorama].?; ok && keep {
        game.know_dead_ends(&app.game, dead)
        return
    }
// …
    if next, ok := d.pending.?; ok {
        d.pending = nil
        // …
    }

reading the code

Maybe(T)
Either a T or nil. pending is a job only while one waits; the type says so.
.?
Unwraps it into two values: the content and an ok that tells whether anything was there.
if v, ok := x.?; ok
An if can start with a statement, then a ;, then the condition. dead and ok exist only inside this if.
= nil
Putting the slot back to empty is just assigning nil.

why it is so

Maybe is a union (a type that is one of several): the compiler makes you unwrap before use, so “forgot to check” cannot happen. No sentinel such as -1, and no null pointer to dereference.

See the file on GitHub (opens in a new tab)

Collections

Fixed arrays and vector maths

`[3]i32` is three integers in a row, and arithmetic works on all of them.

src/iso/iso.odin odin
Cell :: [3]i32
Vec2 :: [2]f32
Vec3 :: [3]f32

in_diamond :: proc(point, center: Vec2, scale: f32 = 1) -> bool {
    d := point - center
    return abs(d.x) / (HALF_W * scale) + abs(d.y) / (HALF_H * scale) <= 1
}

manhattan2 :: proc(a, b: Cell) -> i32 {
    return abs(a.x - b.x) + abs(a.y - b.y)
}

reading the code

Cell :: [3]i32
A fixed-size array: the size is part of the type. Cell is a name for it — a grid position x, y, z.
point - center
Arithmetic on arrays applies to every element: one subtraction yields a vector. No vector library needed.
d.x, d.y
The first elements of a small array answer to x, y, z, w (or r, g, b, a for colours).
dv == v
abs is built in. Arrays of the same type also compare with ==, which is how cells are compared throughout the game.
scale: f32 = 1
A parameter with a default value: callers may leave it out (see Default arguments).

why it is so

Isometric maths is all small vectors. Plain arrays stay inline and cheap, compare with ==, serve as map keys, and the compiler does the per-component work.

See the file on GitHub (opens in a new tab)

Slices

A window on memory that already exists: a pointer and a length.

src/level/level.odin odin
// The dioramas of a slot's text: slices of it, in order.
dioramas :: proc(text: string, allocator := context.temp_allocator) -> []string {
    parts := make([dynamic]string, 0, MAX_DIORAMAS, allocator)
    start := 0
    rest := text
    at := 0
    for line in strings.split_lines_iterator(&rest) {
        next := len(text) - len(rest)
        if strings.trim_space(line) == "diorama" {
            append(&parts, text[start:at])
            start = next
        }
        at = next
    }
    append(&parts, text[start:])
    return parts[:]
}

reading the code

[]string
[]T is a slice: it owns nothing, it looks at a run of Ts somewhere else. A string is itself a slice of bytes.
text[start:at]
Cuts a piece, from start up to but not including at. No copy: it is the same memory.
text[start:]
Leaving a bound out means “to the end” (or “from the start”).
parts[:]
[:] turns the whole dynamic array into a slice, to hand it over as a plain view.

why it is so

The game cuts a level file into its dioramas without copying a byte. The price: a slice lives only as long as what it looks at, which is why the comment says “slices of it”.

See the file on GitHub (opens in a new tab)

Dynamic arrays

A list that grows: `[dynamic]T`, `append`, `len`.

src/palace/solve.odin odin
Solver :: struct {
    p:        ^Palace,
    changing: [dynamic]int, // block index of each changing block (bit order)
    cache:    map[Config]^Config_Graph,
}

solve :: proc(p: ^Palace, goal: Spot, avoid: Maybe(Spot) = nil, allocator := context.allocator, limit := 0, dead: ^[dynamic]State = nil, from: Maybe(State) = nil) -> (sol: Solution) {
    s := Solver{p = p}
    // …
    for e, i in p.data.blocks {
        if e.trait == .Veiled {
            append(&s.changing, i)
        }
    }
    // …
    entries := make([dynamic]Entry, 0, 4096)
    edges := make([dynamic]Edge, 0, 16384)

reading the code

[dynamic]int
A growable array. Declared, it holds nothing yet; it needs make to get memory.
make([dynamic]T, 0, 4096)
Starts with length 0 and room for 4096 elements. Asking for room up front avoids regrowing while the solver explores.
append(&s.changing, i)
Adds at the end. It takes the array's address (&) because it may have to move it to new memory.
for e, i in …
Loops over the items: e is the item and i its index. len(arr) is how many there are.

why it is so

Sizes known only at run time — the blocks of a level, the states a solver visits — need a list that grows. Saying the capacity up front keeps allocations rare and predictable.

See the file on GitHub (opens in a new tab)

Maps

Look things up by key.

src/palace/solve.odin odin
Config_Graph :: struct {
    nodes: []Node,
    index: map[Cell]i32,
    // …
}

Solver :: struct {
    p:        ^Palace,
    changing: [dynamic]int,
    cache:    map[Config]^Config_Graph,
}

solve :: proc(p: ^Palace, goal: Spot, avoid: Maybe(Spot) = nil, allocator := context.allocator, limit := 0, dead: ^[dynamic]State = nil, from: Maybe(State) = nil) -> (sol: Solution) {
    s := Solver{p = p}
    s.cache = make(map[Config]^Config_Graph)
    // …
    seen := make(map[State]i32)

reading the code

map[Cell]i32
From a Cell to an i32: which node of the walk graph sits there. The key can be any comparable type.
map[Config]^Config_Graph
Values can be pointers: a cache from a configuration of the palace to the graph already built for it.
make(map[State]i32)
A map needs make, like a dynamic array. seen remembers every state already visited.
State as a key
Structs of plain fields hash and compare by value — there is no hash function to write.

why it is so

A puzzle solver is a search over states, and “have I been here?” must be instant. A map keyed by the plain State struct answers it.

See the file on GitHub (opens in a new tab)

Procedures

Procedures

Odin's functions: `name :: proc(…) -> T`.

src/game/plan.odin odin
// Nothing is moving: the next move can be given.
idle :: proc(g: ^Game) -> bool {
    settled := g.light == (g.lamp_on ? 1 : 0)
    return !g.psyche.walking && !g.turning && settled && (g.phase == .Play || is_over(g))
}

// After the plan's last move: a plan ends on the exit, and where Charon's
// boat waits there, she boards it. False if the game refuses it.
board_at_end :: proc(g: ^Game) -> bool {
    return !g.data.has_boat || is_over(g) || board_boat(g)
}

reading the code

idle :: proc(g: ^Game) -> bool
A procedure is a constant like any other, hence ::. Parameters read name: Type, the result follows ->. (^Game is a pointer, see Pointers.)
a ? b : c
The ternary: if lamp_on then 1, else 0.
&& ||
“and”, “or” and “not” (!) work on booleans and stop early: the right side runs only if it can change the result.
board_boat(g)
…which is why board_boat(g), a call with an effect, can sit in a condition: it happens only when the earlier tests fail.

why it is so

No methods, no hidden this: the data a procedure works on is in its parameters, so the signature tells you what it touches. The comment sits above and says what the procedure is for, not how.

See the file on GitHub (opens in a new tab)

Multiple return values

How Odin reports failure: a value and an `ok`, no exceptions.

src/progress/progress.odin odin
// The text sealed in data; ok is false when the file was edited, cut or isn't a save.
unseal :: proc(data: []byte, allocator := context.allocator) -> (text: string, ok: bool) {
    N :: chacha20poly1305.IV_SIZE
    T :: chacha20poly1305.TAG_SIZE
    if len(data) < len(MAGIC) + N + T || string(data[:len(MAGIC)]) != MAGIC {
        return "", false
    }
    // …
    return string(out), true
}

// …
    if data, err := os.read_entire_file_from_path(path, context.temp_allocator); err == nil {
        if text, ok := unseal(data, context.temp_allocator); ok {
            // …
        }
    }

reading the code

-> (text: string, ok: bool)
A procedure may return several values, even named ones: text and ok.
return "", false
On failure: an empty value and false. The caller must decide what to do.
return string(out), true
On success: the value and true.
ok := …
The caller takes both: text, ok := unseal(…), often inside an if. Others return an err that is nil on success, like os.read_entire_file_from_path.

why it is so

Failure is an ordinary value, visible in the signature and handled where the call is made. A tampered save file is not an exception, just ok == false.

See the file on GitHub (opens in a new tab)

Default arguments

Parameters that callers may leave out.

src/level/level.odin odin
dioramas :: proc(text: string, allocator := context.temp_allocator) -> []string {
    // …
}

parse :: proc(text: string, allocator := context.allocator) -> (data: Level_Data, err: Maybe(Parse_Error)) {
    context.allocator = allocator
    // …
}

reading the code

allocator := context.allocator
name := value in a parameter list gives a default. parse(text) works; parse(text, my_arena) overrides it.
context.temp_allocator
A default can differ per procedure: dioramas hands back short-lived slices, so it defaults to scratch memory.
context.allocator = allocator
Inside, the parameter replaces the context's allocator (see The context), so every make below uses it.

why it is so

Most callers don't care where memory comes from, a few do. A default keeps the common call short and the rare one possible, without overloads. Calls can also name their arguments (limit = 5) to skip the ones in between.

See the file on GitHub (opens in a new tab)

Procedures inside procedures

A helper that lives where it is used. No closures.

src/dead_ends.odin odin
poll_dead_ends :: proc(app: ^App) {
    d := &app.dead_ends
    // …
    job := d.job
    g := &app.game
    playing :: proc(g: ^game.Game, job: Dead_End_Job) -> bool {
        return g.level_index == job.index && g.diorama == job.diorama
    }
    known := &d.known[job.index][job.diorama]
    if playing(g, job) && (!job.keep || known^ == nil) {
        game.know_dead_ends(g, job.result)
    }
    // …
}

reading the code

playing :: proc(…)
A procedure can be declared in another's body: here a one-line helper used twice below.
g, job
It sees none of the surrounding variables. What it needs, it takes as parameters. (Odin has no closures: a nested procedure is a constant like any other.)
playing(g, job)
Called like any procedure.

why it is so

A procedure that captures variables hides what it depends on. Without captures a procedure is just an address: cheap to pass around, even to another thread (see Threads).

See the file on GitHub (opens in a new tab)

Pointers

`^T` points to a `T`, `&` takes an address, `^` after a name follows it.

src/dead_ends.odin odin
poll_dead_ends :: proc(app: ^App) {
    d := &app.dead_ends
    if d.worker == nil || !sync.atomic_load(&d.job.done) {
        return
    }
    thread.join(d.worker)
    thread.destroy(d.worker)
    d.worker = nil
    // …
    known := &d.known[job.index][job.diorama]
    // …
    if job.keep && known^ == nil {
        known^ = job.result
    }
}

reading the code

app: ^App
^App is “pointer to an App”. The procedure gets the one real app, not a copy: what it changes stays changed.
&app.dead_ends
& takes the address of something: d points inside the app.
d.worker
A dot works through a pointer as if it weren't one. No -> as in C.
known^
Postfix ^ follows the pointer to the value: known^ = job.result writes into the table's slot. nil is the pointer that points nowhere.

why it is so

The App is large, and a procedure must modify it, not a copy. Passing a pointer is the way. Odin keeps pointers plain: no arithmetic on them, no ->, no ownership rules to learn.

See the file on GitHub (opens in a new tab)

Control flow

Loops

One keyword, `for`, does every kind of loop.

src/iso/iso.odin odin
dir_from_name :: proc(name: string) -> (d: Dir, ok: bool) {
    for n, k in DIR_NAME {
        if n == name {
            return k, true
        }
    }
    return .PX, false
}

// Rotate a grid vector by r quarter turns: (x, y) -> (-y, x) each turn.
rot_vec :: proc(v: [2]i32, r: int) -> [2]i32 {
    out := v
    for _ in 0 ..< ((r % 4) + 4) % 4 {
        out = {-out.y, out.x}
    }
    return out
}

reading the code

for n, k in DIR_NAME
Loops over a collection: n is each item, k its index (here its enum key).
for _ in 0 ..< n
Repeats a number of times; _ says the counter isn't needed.
..<
A half-open range: it includes the start and excludes the end. ..= includes both. 0 ..< 4 is 0, 1, 2, 3.
if n == name {
No parentheses around conditions, and the braces are always required.

why it is so

for alone is forever, for cond is a while, for i := 0; i < n; i += 1 is the C way, for x in xs is a foreach: one construct to read, whatever it does. And ((r % 4) + 4) % 4 makes a negative turn count wrap round to 0–3.

See the file on GitHub (opens in a new tab)

Switch

Pick by value; no fall through.

src/game/plan.odin odin
apply_move :: proc(g: ^Game, st: pl.Plan_Step) -> bool {
    switch st.move {
    case .Start:
    case .Step:
        if pl.is_passage(&g.palace, g.psyche.cell, st.cell) {
            return enter_cave(g)
        }
        return walk_to(g, st.cell)
    case .Turn_Left:
        request_turn(g, -1)
    case .Turn_Right:
        request_turn(g, 1)
    case .Light, .Douse:
        before := g.lamp_on
        toggle_lamp(g)
        return g.lamp_on != before
    // …
    }
    return true
}

reading the code

switch st.move
Branches on the enum. Each case ends by itself: no break to forget.
case .Light, .Douse:
Several values can share a case, separated by commas.
case .Start:
An empty case does nothing — and that is deliberate: the plan's first step needs no action.
return true
Reached by the cases that didn't return.

why it is so

A switch over an enum must name every member, or the compiler refuses. Add a twelfth Move and this procedure stops building until you say what it does. (When you really mean “only some”, write #partial switch, as the solver does.)

See the file on GitHub (opens in a new tab)

Defer

Run this when the scope ends, however it ends.

src/progress/progress.odin odin
save :: proc(p: Progress, slot: int) -> bool {
    heap := runtime.heap_allocator()
    text := serialize(p, heap)
    defer delete(text, heap)
    name := slot_file(slot)
    for _ in 0 ..< 2 {
        sealed := seal(text, heap)
        written := settings.write_config_file(name, string(sealed))
        delete(sealed, heap)
        if !written {
            return false
        }
        // …
    }
    // …
}

reading the code

defer delete(text, heap)
The call is postponed to the end of the enclosing block. Written right after the allocation, so you can't forget it.
every return
return false inside the loop leaves the procedure early: text is still freed. Same for the final return.
delete(sealed, heap)
This one is not deferred: sealed is rebuilt on every pass of the loop and freed at the end of each, not at the end of the procedure.

why it is so

Cleanup written beside the acquisition survives later edits: add another early return and nothing leaks. Several defers run in reverse order, like unstacking plates.

See the file on GitHub (opens in a new tab)

Memory

Allocators

Odin asks where memory comes from, every time.

src/main.odin odin
// Memory:
//   - context.allocator: the few things that live as long as the program
//     (audio WAV buffers); in debug builds it is wrapped in a tracking
//     allocator that reports leaks at exit.
//   - the level arena (inside game.Game): everything a level needs, freed in
//     one go when the level restarts or changes.
//   - context.temp_allocator: per-frame scratch, freed at the end of every frame.

// …
    for !rl.WindowShouldClose() && !app.quit {
        frame(app)
        free_all(context.temp_allocator)
    }

reading the code

context.allocator
The default allocator. Long-lived things come from here.
the level arena
A block of memory handed out in sequence and thrown away whole (see Arenas).
context.temp_allocator
Scratch memory, for results needed for a moment: a string to format, a file just read.
free_all(context.temp_allocator)
Once per frame the whole scratch space is emptied in one call. Nothing in the frame has to free its temporary things.

why it is so

A game has three lifetimes — the program, the level, the frame — so it uses three allocators and never frees item by item. No garbage collector means no pauses, and every allocation says who is in charge of it.

See the file on GitHub (opens in a new tab)

The context

An implicit parameter every procedure receives.

src/level/level.odin odin
// Parse a level. Every allocation (arrays, error text) uses `allocator`,
// typically the level arena, so the whole level is freed at once.
parse :: proc(text: string, allocator := context.allocator) -> (data: Level_Data, err: Maybe(Parse_Error)) {
    context.allocator = allocator

    data.blocks = make([dynamic]Solid_Entry, 0, 128)
    data.rise = make([dynamic]Solid_Entry, 0, 8)
    data.props = make([dynamic]Prop, 0, 32)
    // …
    floor_given := make([dynamic][2]bool, context.temp_allocator) // each floor: its rim, its fluid written in the file
    // …
}

reading the code

context.allocator = allocator
context is passed to every procedure behind the scenes. Setting its allocator redirects every allocation below, and in the procedures called from here.
make([dynamic]…)
No allocator argument here: make uses the context's. After the assignment above, that is the level arena.
context.temp_allocator
An explicit allocator wins over the context: this temporary list goes in scratch memory.

why it is so

Dozens of make calls in parse read as plain code, yet the caller chooses where they land. The change lasts only until the procedure returns, so it can't leak into the rest of the program.

See the file on GitHub (opens in a new tab)

make, delete, new, free

Asking for memory and giving it back.

src/progress/progress.odin odin
unseal :: proc(data: []byte, allocator := context.allocator) -> (text: string, ok: bool) {
    // …
    out := make([]byte, len(body), allocator)
    ctx: chacha20poly1305.Context
    chacha20poly1305.init(&ctx, KEY[:], .Portable)
    if !chacha20poly1305.open(&ctx, out, nonce, transmute([]byte)string(MAGIC), body, tag) {
        delete(out, allocator)
        return "", false
    }
    return string(out), true
}

reading the code

make([]byte, n, allocator)
make builds slices, dynamic arrays and maps: here a buffer of len(body) bytes from the allocator given. The allocator argument is optional.
delete(out, allocator)
delete is the pair of make. Give back to the same allocator the memory came from.
new / free
new(T) allocates a single value and returns a pointer; free returns it. main does exactly that: app := new(App) then defer free(app).

why it is so

Memory is never hidden: every owner frees. unseal frees out itself on failure and hands it to the caller on success, where the caller's allocator decides. In debug builds a tracking allocator (see Leak tracking) reports what was forgotten.

See the file on GitHub (opens in a new tab)

Arenas

Allocate freely, free everything at once.

src/game/game.odin odin
Game :: struct {
    arena:          virtual.Arena,
    level_index:    int,
    // …
}

// …
    arena := g.arena
    if arena.curr_block == nil {
        if virtual.arena_init_growing(&arena) != nil {
            return Load_Error{0, "cannot reserve memory for the level"}
        }
    } else {
        virtual.arena_free_all(&arena)
    }
    g^ = {}
    g.arena = arena
    // …
    alloc := virtual.arena_allocator(&g.arena)
    data, perr := level.parse(parts[diorama], alloc)

// …
destroy :: proc(g: ^Game) {
    virtual.arena_destroy(&g.arena)
    g^ = {}
}

reading the code

virtual.Arena
A big region handed out in order, from core:mem/virtual. Game carries one for the current level.
arena_init_growing
Prepares the arena to ask the system for more room as it fills. The first time only; it returns an error if memory can't be reserved.
arena_free_all
Between levels: everything the previous level allocated vanishes in one call.
arena_allocator
Wraps the arena as an ordinary allocator, which level.parse receives as its allocator argument. Every array of the level now lives in the arena.
arena_destroy
At shutdown the region goes back to the system.

why it is so

A level is thousands of small allocations with one shared lifetime. Freeing each one is a chance for a leak or a dangling pointer; resetting the arena is one line and cannot miss any.

See the file on GitHub (opens in a new tab)

Leak tracking and `when`

Debug builds check their own memory; release builds don't pay for it.

src/main.odin odin
main :: proc() {
    when ODIN_DEBUG {
        track: mem.Tracking_Allocator
        mem.tracking_allocator_init(&track, context.allocator)
        context.allocator = mem.tracking_allocator(&track)
        defer {
            for _, leak in track.allocation_map {
                fmt.eprintfln("leak: %v bytes at %v", leak.size, leak.location)
            }
            for bad in track.bad_free_array {
                fmt.eprintfln("bad free at %v", bad.location)
            }
            mem.tracking_allocator_destroy(&track)
        }
    }

    app := new(App)
    defer free(app)
    // …
}

reading the code

when ODIN_DEBUG
when is an if decided at compile time. In a release build this block does not exist at all.
mem.Tracking_Allocator
An allocator that wraps another and records every allocation. It becomes context.allocator, so every allocation of the program goes through it.
defer { … }
A deferred block: it runs when main ends and prints whatever is still allocated, and anything freed twice.
allocation_map
for _, leak in … loops over a map, ignoring the key. Each entry holds the size and the source line of the allocation.

why it is so

A leak report with file and line, for free, in the build you test with — and nothing in the build you ship. ./build.sh debug is that build.

See the file on GitHub (opens in a new tab)

Tools and more

Attributes: `@(…)`

Notes to the compiler placed above a declaration.

src/palace/solve.odin odin
// The palace in one configuration, in every view.
@(private = "file")
Config_Graph :: struct {
    nodes: []Node,
    index: map[Cell]i32,
    // …
}

// Is she at `spot` in state st?
@(private = "file")
at_spot :: proc(st: State, spot: Spot) -> bool {
    return st.cell == spot.cell && st.cfg.upside == spot.under
}

reading the code

@(private = "file")
Visible only in this file. Other files of the package cannot name Config_Graph.
@(private)
Alone, it means private to the package: other packages can't use it.
@(test)
Marks a procedure as a test (see Tests).
@(require)
On an import, keeps it even if unused. The game does this for core:mem, which only debug builds use.

why it is so

Everything is public by default; privacy is opt-in, at two sizes. Small internals — the solver's graphs — stay out of the package's API, so they can change freely.

See the file on GitHub (opens in a new tab)

Compile-time checks

Make the build fail instead of the game.

src/progress/progress.odin odin
#assert(content.LEVEL_COUNT <= 32)
Level_Set :: bit_set[0 ..< 32] // indices into content.LEVELS
#assert(content.FRAGMENT_COUNT <= 64)
Fragment_Set :: bit_set[0 ..< 64] // indices into content.FRAGMENTS

reading the code

#assert(…)
A directive: a condition checked while compiling. If it is false, there is no executable.
LEVEL_COUNT <= 32
Constants can appear in the condition: here the content package's own LEVEL_COUNT.
bit_set[0 ..< 32]
What the assertion guards: a set of 32 bits holds at most 32 levels.

why it is so

The day a 33rd level is added, the compiler says so, right where the limit is written, instead of a save file silently losing a bit.

See the file on GitHub (opens in a new tab)

Embedding files with `#load`

How a game with no asset folder carries its levels.

src/content/content.odin odin
// Assets embedded in the executable at compile time (#load): level files,
// shaders and fonts. No file IO at runtime, nothing to lose next to the binary.

Level_Info :: struct {
    id:     string, // stable name, used in the save file: never change it
    act:    Act,
    title:  i18n.Key,
    place:  i18n.Key, // where it is, in a line (the level select)
    cite:   string, // where it happens in the tale (Metamorphoses book.chapter)
    source: string, // the level file; "" while the level is not built
}

LEVELS := [?]Level_Info {
    {"I.1", .I, .Level_I_1, .Where_I_1, "IV.33–35", #load("../../assets/levels/level_01.txt", string)},
    {"I.2", .I, .Level_I_2, .Where_I_2, "V.1–3", #load("../../assets/levels/level_02.txt", string)},
    // …
}

reading the code

#load(path, string)
At compile time, reads the file and puts its content in the program. The path is relative to the source file.
[?]Level_Info
[?] means “count the elements for me”: an array as long as the list below.
{"I.1", .I, …}
A struct literal without field names: values in the order the fields are declared. Compact for tables; enum values are written with the leading dot.
source: string
The level's text, always at hand: no file to open at run time, no way for it to be missing.

why it is so

The executable is the game: copy one file and it runs. It is also how the site can say “zero image or audio files”: levels, shaders and fonts travel inside the binary.

See the file on GitHub (opens in a new tab)

Reinterpreting data: `transmute`

Same bytes, another type.

src/progress/progress.odin odin
seal :: proc(text: string, allocator := context.allocator) -> []byte {
    // …
    ctx: chacha20poly1305.Context
    chacha20poly1305.init(&ctx, KEY[:], .Portable)
    chacha20poly1305.seal(&ctx, body, tag, nonce, transmute([]byte)string(MAGIC), transmute([]byte)text)
    return out
}

reading the code

transmute([]byte)text
Reads the bits of text (a string) as a []byte. Nothing is copied or converted; the compiler checks both sizes match.
string(MAGIC)
A normal conversion, T(x), where the value is converted rather than reinterpreted. Here a constant becomes a typed string.
KEY[:]
Slicing a fixed array gives a slice of its elements, the form that procedures like init accept.

why it is so

string and []byte have the same layout, so the cryptographic call can take the text as it is. transmute is the explicit, greppable way to say “I know what I'm doing”: rare, and visible in review.

See the file on GitHub (opens in a new tab)

Threads

Work off the main loop, and how to know it finished.

src/dead_ends.odin odin
start_dead_end_job :: proc(d: ^Dead_Ends, job: Dead_End_Job) {
    d.job = job
    d.worker = thread.create_and_start_with_poly_data(&d.job, proc(job: ^Dead_End_Job) {
        job.result = game.search_dead_ends(job.source, runtime.heap_allocator())
        sync.atomic_store(&job.done, true)
    })
}

poll_dead_ends :: proc(app: ^App) {
    d := &app.dead_ends
    if d.worker == nil || !sync.atomic_load(&d.job.done) {
        return
    }
    thread.join(d.worker)
    thread.destroy(d.worker)
    // …
}

reading the code

thread.create_and_start_with_poly_data
Starts a thread running a procedure, passing it one value of any type (&d.job). core:thread is part of the standard library.
proc(job: ^Dead_End_Job) { … }
A procedure literal, written where it is used: the thread's body. No captures (see Procedures inside procedures): the job arrives as the parameter.
sync.atomic_store
Sets the done flag in a way another thread is sure to see. The main loop reads it with atomic_load.
thread.join
Waits for the thread to end, then destroy frees it. It is only called once done is true, so it doesn't wait.

why it is so

Searching for dead ends can take seconds on a big level, and the game must keep drawing. The worker allocates from the heap allocator because the level arena and the scratch space belong to the main thread.

See the file on GitHub (opens in a new tab)

Tests

`@(test)` turns a procedure into a test; the compiler brings the runner.

tests/support_test.odin odin
@(test)
settings_ignore_bad_values :: proc(t: ^testing.T) {
    s := settings.defaults()
    before := s
    settings.parse("resolution = 12x5\nmusic = loud\nfps_limit = -3\nnonsense\nlanguage = xx\nmaster = 7\nquality = insane\n", &s)
    before.master = 1 // clamped to 0..1
    testing.expect(t, s == before, "malformed lines keep the previous values")
    testing.expect(t, i18n.language_from_locale("it_IT.UTF-8") == .Italian, "Italian locale")
    testing.expect(t, i18n.language_from_locale("C") == .English, "English otherwise")
}

reading the code

@(test)
Marks the procedure below. odin test finds every one in the package and runs it.
t: ^testing.T
Every test receives the test state, a pointer, to report failures.
testing.expect(t, …)
A condition and a message printed if it is false. The test goes on after a failure; expect returns the result, so you can stop early.
./build.sh test
The game's script runs odin test tests: rules, levels, translations, settings and audio, headless.

why it is so

No framework to install or learn. The game's puzzles are checked by tests that also replay a solver's plan through the game, proving the two follow the same rules.

See the file on GitHub (opens in a new tab)

Using a C library: raylib

`vendor:` packages bind popular C libraries, ready to import.

src/main.odin odin
import rl "vendor:raylib"

// …
    flags := rl.ConfigFlags{.WINDOW_RESIZABLE, .MSAA_4X_HINT}
    if app.cfg.vsync {
        flags += {.VSYNC_HINT}
    }
    rl.SetConfigFlags(flags)
    rl.InitWindow(app.cfg.resolution.x, app.cfg.resolution.y, WINDOW_TITLE)
    if !rl.IsWindowReady() {
        fmt.eprintln("cannot open a window")
        return false
    }
    rl.SetTargetFPS(app.cfg.fps_limit)

reading the code

import rl "vendor:raylib"
vendor: is the collection of bindings shipped with Odin. raylib opens the window, reads the input, draws and plays the sounds the synth builds.
rl.ConfigFlags{…}
A raylib flag set is an Odin bit_set: build it like any set, with named members.
flags += {…}
…and add to it conditionally, with +=.
rl.InitWindow(…)
Calls are plain procedure calls, prefixed by the alias. rl.IsWindowReady() then tells whether it worked.

why it is so

No wrapper code to write, no build system for bindings: import and call. The game's only dependencies are the Odin compiler and raylib, which ships inside it.

See the file on GitHub (opens in a new tab)

This site

Settings

Language
Animations
Text size

Your privacy

  • No cookies, no accounts, no analytics.
  • Your settings are saved only in this browser, with localStorage. They never leave your device, and you can erase them here.

What this browser stores

localStorage · psyche:settings

Nothing: you are using the defaults.