~/codex Learn Odin
Codex
A glossary of the Odin language, told through this game's own source. Open an entry to read real code from the game, what each piece means, and why Odin does it that way.
34 entries from the game's source Abridged: “// …” marks what was cut.
Not a course: a map to find your way around the language. For the whole picture, read the official Odin overview.
The basics
Packages and imports
How a folder becomes a unit of code, and how units find each other.
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 forsmall_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:
isoknows nothing,levelusesiso,palaceuses both. iso.Cell- Everything is reached through the package name.
Cell :: iso.Cellgivesiso.Cella 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.
Constants
`::` binds a name to something fixed at compile time.
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.0has no type yet. It becomes anf32here because it meets one; in anf64formula it would become anf64. 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.
Variables
`:=` declares and infers the type, `x: T` declares and starts from zero.
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 := valuedeclares a variable and takes its type from the value. Here a[]byte.ctx: Contextname: Typedeclares 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:
NandTexist only for the lines below, and cost nothing. nonce := out[…]nonceis not a copy: it looks at part ofout. 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.
Zero is initialisation
Every value starts as zero, so a struct is ready to use the moment it exists.
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_Joband 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
nilslice,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
Gameto 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.
Numbers and conversions
Integers and floats of exact size, and conversions you spell out.
// 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)sizeis ani32, the formula needs anf32: Odin never converts silently. You writef32(size)and you can see where the change happens.c, s := …- Several names on each side declare several variables at once: here
cands(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:
i32is 32 bits,u8an unsigned byte,f32a 32-bit float.intis 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.
Types
Structs
Plain data grouped under a name. No classes, no inheritance.
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. ASpotis 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:Stateholds aConfig. 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.Statecan even be the key of amap.
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.
Enums
A closed list of named choices, instead of magic numbers.
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.
u8is the type underneath: one byte is plenty for eleven values. Start- Values count up from 0 in the order written:
Startis 0,Stepis 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.
Arrays indexed by an enum
A lookup table whose index is a name, not a number.
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. Noswitch, no chain ofifs. out, _ :=_throws a value away.dir_from_vecreturns a direction and anok; 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.
Bit sets
A set of enum values stored in a single integer.
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 ..< 32is a range, from 0 up to but not including 32. inx in setasks 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.
Maybe: a value, or nothing
How Odin says “there might not be one” without a null pointer.
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
Tornil.pendingis a job only while one waits; the type says so. .?- Unwraps it into two values: the content and an
okthat tells whether anything was there. if v, ok := x.?; ok- An
ifcan start with a statement, then a;, then the condition.deadandokexist only inside thisif. = 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.
Collections
Fixed arrays and vector maths
`[3]i32` is three integers in a row, and arithmetic works on all of them.
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.
Cellis 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(orr,g,b,afor colours). dv == vabsis 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.
Slices
A window on memory that already exists: a pointer and a length.
// 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[]Tis a slice: it owns nothing, it looks at a run ofTs somewhere else. Astringis itself a slice of bytes.text[start:at]- Cuts a piece, from
startup to but not includingat. 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”.
Dynamic arrays
A list that grows: `[dynamic]T`, `append`, `len`.
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
maketo get memory. make([dynamic]T, 0, 4096)- Starts with length
0and 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:
eis the item andiits 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.
Maps
Look things up by key.
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
Cellto ani32: 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.seenremembers 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.
Procedures
Procedures
Odin's functions: `name :: proc(…) -> T`.
// 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 readname: Type, the result follows->. (^Gameis a pointer, see Pointers.) a ? b : c- The ternary: if
lamp_onthen1, else0. && ||- “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.
Multiple return values
How Odin reports failure: a value and an `ok`, no exceptions.
// 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:
textandok. 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 anif. Others return anerrthat isnilon success, likeos.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.
Default arguments
Parameters that callers may leave out.
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.allocatorname := valuein a parameter list gives a default.parse(text)works;parse(text, my_arena)overrides it.context.temp_allocator- A default can differ per procedure:
dioramashands 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
makebelow 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.
Procedures inside procedures
A helper that lives where it is used. No closures.
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).
Pointers
`^T` points to a `T`, `&` takes an address, `^` after a name follows it.
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^Appis “pointer to anApp”. The procedure gets the one real app, not a copy: what it changes stays changed.&app.dead_ends&takes the address of something:dpoints 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.resultwrites into the table's slot.nilis 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.
Control flow
Loops
One keyword, `for`, does every kind of loop.
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:
nis each item,kits 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 ..< 4is 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.
Switch
Pick by value; no fall through.
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
caseends by itself: nobreakto 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.)
Defer
Run this when the scope ends, however it ends.
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 returnreturn falseinside the loop leaves the procedure early:textis still freed. Same for the finalreturn.delete(sealed, heap)- This one is not deferred:
sealedis 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.
Memory
Allocators
Odin asks where memory comes from, every time.
// 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.
The context
An implicit parameter every procedure receives.
// 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 = allocatorcontextis 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:
makeuses 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.
make, delete, new, free
Asking for memory and giving it back.
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)makebuilds slices, dynamic arrays and maps: here a buffer oflen(body)bytes from the allocator given. The allocator argument is optional.delete(out, allocator)deleteis the pair ofmake. Give back to the same allocator the memory came from.new / freenew(T)allocates a single value and returns a pointer;freereturns it.maindoes exactly that:app := new(App)thendefer 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.
Arenas
Allocate freely, free everything at once.
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.Gamecarries 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.parsereceives as itsallocatorargument. 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.
Leak tracking and `when`
Debug builds check their own memory; release builds don't pay for it.
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_DEBUGwhenis anifdecided 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
mainends and prints whatever is still allocated, and anything freed twice. allocation_mapfor _, 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.
Tools and more
Attributes: `@(…)`
Notes to the compiler placed above a declaration.
// 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.
Compile-time checks
Make the build fail instead of the game.
#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.
Embedding files with `#load`
How a game with no asset folder carries its levels.
// 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.
Reinterpreting data: `transmute`
Same bytes, another type.
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
initaccept.
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.
Threads
Work off the main loop, and how to know it finished.
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:threadis 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
doneflag in a way another thread is sure to see. The main loop reads it withatomic_load. thread.join- Waits for the thread to end, then
destroyfrees it. It is only called oncedoneis 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.
Tests
`@(test)` turns a procedure into a test; the compiler brings the runner.
@(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 testfinds 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;
expectreturns 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.
Using a C library: raylib
`vendor:` packages bind popular C libraries, ready to import.
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.