The library

Core, standard and game functions are available without imports. Named modules such as layout, physics, physics3d, net, netplay, http and term require an explicit import, as their sections show. The reference excludes implementation storage and internal bridge functions; shader/backend plumbing and responsive layout remain experimental. Functions can be called as f(x, y) or x.f(y). Each topic starts with a whole program to try.

Built-in functions

Part of the language itself: printing, stopping with an error, and a few functions the compiler knows.

# example: built-in functions
print("hello", 42, 3.5, [1, 2, 3])      # any values, separated by spaces
xs = fill(0, 5)                          # five zeros
xs[2] = 7
assert(xs.len() == 5, "five of them")   # stops the program if not true
print(xs, sqrt(2.0), size_of(int))
b = bytes("hi")                          # a string's bytes, as u8[]
print(b, str_from_bytes(b))
if xs[2] != 7: panic("xs[2] changed")   # stop, with a message and where it happened

Run it in the playground

print(values...)

prints the values, separated by spaces, and a line break

assert(ok: bool, message: str = "")

stops the program (with the message, and where) if ok is false; with no message, a comparison says what its sides were: assertion failed: total == 10 (total is 9)

panic(message: str)

stops the program, with the message and where each function on the way was called

unwrap(r) -> T

the value of an optional, or of a result that can be an error (int | ParseError); none or an error stops the program, saying which and where

expect(r, message: str) -> T

the same, saying the message first when it stops: config = read_file(path).expect("the settings file")

fill[T](x: T, n: int) -> T[]

an array of n copies of x

sqrt(x: f64) -> f64
sqrt(x: f32) -> f32

the square root

embed(path: str) -> u8[]

a file's contents, read when the program is compiled and kept in it (the path is relative to the source file)

bytes(s: str) -> u8[]

a string's bytes (UTF-8)

str_from_bytes(b: u8[]) -> str

a string of these bytes

size_of(T) -> int

how many bytes a value of type T takes

align_of(T) -> int

the alignment in bytes of a value of type T

int(x)
i32(x)
u8(x)

a number as a whole number of that type (a float is cut toward zero: int(3.7) is 3); text is read with to_int(s), and c'A' is a character's code (65)

f64(x)
f32(x)

a number as a float of that size (f32 and f64 also mix by themselves)

str(x)

any value as text, as print shows it

Arrays

T[] is a growable array. Arrays are values: assigning one or passing it to a function gives a copy (shared until one of them changes). Functions can be called as f(xs, y) or xs.f(y). Binary search, orderings and choices (lower_bound, next_permutation, combinations): algo.jo below.

# example: arrays
scores = [12, 40, 7, 33]
scores.push(25)                          # add at the end
scores.sort()
print(scores)                            # [7, 12, 25, 33, 40]
print(scores.len(), scores.first(), scores.last(), scores.sum())

big = scores.filter((s): s > 20)         # a new array: [25, 33, 40]
print(big.map((s): s * 2))
print(scores.any((s): s > 35), scores.count((s): s % 2 == 1))

loop i in 0.. and s in scores:           # an index and the elements together
    print("{i}: {s}")

top = scores.pop()                       # take the last one off
scores.insert(0, 1)                      # put one in at the front
print(top, scores, scores.contains(12), scores.index_of(25))

print(scores.lower_bound(25), scores.join(" "))   # (scores is sorted) where 25 goes; as text

Run it in the playground

Built in

len(xs: T[]) -> int

how many elements

push(xs: mut T[], x: T)

adds x at the end

pop(xs: mut T[]) -> T

removes the last element and gives it back

insert(xs: mut T[], i: int, x: T)

puts x in at index i, moving the ones after it along

remove_at(xs: mut T[], i: int) -> T

takes out the element at i and gives it back (remove(x) takes out a value)

extend(xs: mut T[], ys: T[])

adds all of ys at the end

clear(xs: mut T[])

removes every element

truncate(xs: mut T[], n: int)

keeps the first n elements

resize(xs: mut T[], n: int)

makes it n long: new elements are zero

reserve(xs: mut T[], n: int)
cap(xs: T[]) -> int

makes room for n elements without growing again; cap is the room there is

array.jo

Generic array utilities. Arrays are values with copy-on-write storage.

is_empty[T] = (xs: T[]) -> bool
first[T] = (xs: T[]) -> T
last[T] = (xs: T[]) -> T
first[T] = (xs: T[], n: int) -> T[]

the first n elements (all of them when there are fewer: xs[..n] would panic)

last[T] = (xs: T[], n: int) -> T[]

the last n elements (all of them when there are fewer)

get[T] = (xs: T[], i: int) -> T?

element i, or none past either end (xs[i] stops the program there): xs.get(i) ?? fallback. Optionals flatten: for optional elements, check bounds to distinguish stored none from absence.

contains[T] = (xs: T[], x: T) -> bool
index_of[T] = (xs: T[], x: T) -> int?
map[T, U] = (xs: T[], f: (T) -> U) -> U[]
filter[T] = (xs: T[], f: (T) -> bool) -> T[]
retain[T] = (xs: mut T[], keep: (T) -> bool)

keep only the elements for which keep is true, in their order (in place: bullets.retain((b): b.alive))

remove[T] = (xs: mut T[], x: T) -> bool

take out the first element equal to x (Python's list.remove); false when there is none. By position: xs.remove_at(i)

each[T] = (xs: T[], f: (T) -> void)
reduce[T, A] = (xs: T[], init: A, f: (A, T) -> A) -> A
find_index[T] = (xs: T[], f: (T) -> bool) -> int?

the index of the first element f is true for, or none

any[T] = (xs: T[], f: (T) -> bool) -> bool
all[T] = (xs: T[], f: (T) -> bool) -> bool
find[T] = (xs: T[], f: (T) -> bool) -> T?
count[T] = (xs: T[], f: (T) -> bool) -> int
sum[T] = (xs: T[]) -> T
min[T] = (xs: T[]) -> T
max[T] = (xs: T[]) -> T
min[T] = (xs: T[], default: T) -> T

(the smallest or largest, or default when xs is empty: xs.max(default = 0))

max[T] = (xs: T[], default: T) -> T
min[T] = (a: T, b: T) -> T

the smaller and the larger of two values of a type with its own < (a big number, a version)

max[T] = (a: T, b: T) -> T
min[T, K] = (xs: T[], key: (T) -> K) -> T

the element with the smallest key, or the largest (the first of equal ones): the cheapest item, the nearest enemy (min(enemies, (e): distance(e.pos, me)))

max[T, K] = (xs: T[], key: (T) -> K) -> T
unique[T] = (xs: T[]) -> T[]

each different element once, in the order they first come

group_by[T, K] = (xs: T[], key: (T) -> K) -> {K: T[]}

the elements by a key: each key with the elements that have it, in order (keys in the order they first come)

reverse[T] = (xs: mut T[])
reversed[T] = (xs: T[]) -> T[]
range = (a: int, b: int) -> int[]
enumerate[T] = (xs: T[]) -> (int, T)[]
zip[A, B] = (xs: A[], ys: B[]) -> (A, B)[]
flatten[T] = (xss: T[][]) -> T[]
swap[T] = (xs: mut T[], i: int, j: int)

the elements at i and j trade places

Sorting

(<)[A, B] = (a: (A, B), b: (A, B)) -> bool

tuples compare element by element, the first that differs deciding (sorting (score, name) pairs sorts by score, then name)

(<)[A, B, C] = (a: (A, B, C), b: (A, B, C)) -> bool
sort[T] = (xs: mut T[], descending: bool = false)

sort in place, smallest first (using <), or largest first; equal elements keep their order

sort_with[T] = (xs: mut T[], less: (T, T) -> bool)

sort in place with a custom "less than" function (equal elements keep their order)

sort[T, K] = (xs: mut T[], key: (T) -> K, descending: bool = false)

sort in place by a key, smallest first or largest first (equal keys keep their order: sort by name, then by score, for the scores in order of name)

sorted[T] = (xs: T[], descending: bool = false) -> T[]

a sorted copy of xs

sorted[T, K] = (xs: T[], key: (T) -> K, descending: bool = false) -> T[]

a copy of xs sorted by a key

algo.jo

Searching sorted arrays, orderings and choices, as C++'s <algorithm> and Python's bisect and itertools have them:

xs = [1 3 3 5 8]
lower_bound(xs, 3)           # 1: the first index whose element is not less than 3
upper_bound(xs, 3)           # 3: the first index whose element is more than 3
partition_point(xs, (x): x < 4)   # 3: the first index where the condition stops holding
loop next_permutation(p): pass    # each ordering of p after the one it has, in sorted order
combinations(xs, 2)          # every choice of 2, as arrays

The binary searches take time in proportion to the log of the length; the array must be sorted (as by sort()) for their answers to mean anything.

lower_bound[T] = (xs: T[], x: T) -> int

the first index i where xs[i] is not less than x (xs.len() when there is none): where x would go in the sorted array before the ones equal to it (C++'s lower_bound; Python's bisect_left)

upper_bound[T] = (xs: T[], x: T) -> int

the first index i where x is less than xs[i] (xs.len() when there is none): where x would go after the ones equal to it; upper_bound - lower_bound is how many equal x (C++'s upper_bound; Python's bisect_right)

partition_point[T] = (xs: T[], f: (T) -> bool) -> int

the first index where f is false, for an f that is true for the first elements and false for the rest (xs.len() when it is true for all): partition_point(xs, (p): p.age < 30) in people sorted by age (Rust's partition_point; C++'s with a condition)

reverse[T] = (xs: mut T[], start: int, end: int)

the elements from index start up to (not including) end reversed in place: xs[start..end] backwards (reverse(xs) turns the whole array)

next_permutation[T] = (xs: mut T[]) -> bool

the next ordering of xs in sorted order (by <), in place, and true; for the last one (largest first) xs goes back to the first (sorted) and it gives false. Starting from a sorted array, loop next_permutation(p): after a first look at p goes through each ordering once, equal elements not repeating any (C++'s next_permutation)

prev_permutation[T] = (xs: mut T[]) -> bool

the previous ordering of xs in sorted order, in place, and true; for the first one (sorted) xs goes to the last (largest first) and it gives false (C++'s prev_permutation)

permutations[T] = (xs: T[]) -> T[][]

every ordering of xs, each an array: n! of them (10 elements are 3.6 million arrays; to go through them without keeping them all, sort and loop on next_permutation). In the order of Python's itertools.permutations: by the positions taken, so equal elements give repeats

permutations[T] = (xs: T[], k: int) -> T[][]

every ordering of k of the elements of xs: n! / (n - k)! arrays of k (permutations([1 2 3], 2) is [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]])

combinations[T] = (xs: T[], k: int) -> T[][]

every choice of k of the elements of xs, each an array in the order they are in xs: n! / (k! (n - k)!) of them (combinations([1 2 3 4], 2) is [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]], as Python's itertools.combinations; 30 choose 15 is 155 million arrays: count first)

join[T] = (xs: T[], sep: str = "") -> str

the elements as text with sep between them, as print shows each: [1 2 3].join(" ") is "1 2 3" (an array of str joins as it is)

Strings

str is text, in UTF-8. "{x}" puts a value in a string; "{x:.2}" rounds it to two decimals (more ways: the language). Strings are values, like arrays.

# example: strings
name = "  Sloppy  ".trim()
print(name.upper(), name.len(), name.starts_with("Slo"))

words = "the quick brown fox".split(" ")
print(words, words.join("-"))

# {...} puts a value in a string; after a colon, how to show it
pi = 3.14159
print("pi is about {pi:.2}, a million is {1000000:,}, a quarter is {0.25:.0%}")
print("[{name:<10}] [{name:>10}] [{7:03}]")

n = to_int("42") ?? 0                    # none if it is not a number: 0 instead
print(n + 1, "ab" * 3, "a,b,c".replace(",", "; "))
print("héllo".len(), "héllo".char_count())   # bytes (UTF-8), and characters

Run it in the playground

str.jo

String utilities. Strings are immutable UTF-8 byte sequences; indexing gives bytes.

is_digit = (c: u8) -> bool
is_alpha = (c: u8) -> bool
is_alnum = (c: u8) -> bool
is_space = (c: u8) -> bool
is_upper = (c: u8) -> bool
is_lower = (c: u8) -> bool
chr = (c: int) -> str

the character with code point c, as text (UTF-8: one to four bytes); chr(233) is "é"

byte_str = (b: int) -> str

a string of the one byte b (0 to 255; text in UTF-8 is made of these)

index_of = (s: str, sub: str, start: int = 0) -> int?

the first byte index of sub, or none; start is a byte offset in 0..len(s), inclusive. An empty needle matches start. Out-of-range starts give none.

last_index_of = (s: str, sub: str) -> int?

the last byte index of sub, or none; an empty needle matches len(s)

index_of = (s: str, c: u8, start: int = 0) -> int?

the first byte index of c, or none; start is a byte offset in 0..len(s), inclusive

contains = (s: str, sub: str) -> bool

whether sub occurs in the text

contains = (s: str, c: u8) -> bool

whether a byte (s[i]) is one of the text's: c in "aeiou"

starts_with = (s: str, prefix: str) -> bool
ends_with = (s: str, suffix: str) -> bool
trim = (s: str) -> str

remove ASCII spaces, tabs, carriage returns and line feeds from both ends

trim = (s: str, chars: str) -> str

remove any of the Unicode code points in chars from both ends; never split a character

trim_start = (s: str) -> str
trim_end = (s: str) -> str
split = (s: str, sep: str) -> str[]

the parts of s between the separators (split("a,b", ",") is ["a", "b"]; with "", the characters). For a text's lines, lines(s): split(s, "\n") keeps the "\r" of Windows line ends ("\r\n")

split = (s: str, sep: str, max: int) -> str[]

split at the first max separators only: the rest stays in the last part (split("k=v=w", "=", 1) is ["k", "v=w"])

count = (s: str, sub: str) -> int

how many times sub is in s, not overlapping ("banana".count("an") is 2)

pad_start = (s: str, width: int, fill: str = " ") -> str

s made width characters long with fill before it (pad_start("7", 3, "0") is "007"), or after it; a longer s stays as it is ("{s:>10}" and "{s:<10}" in a string do the same with spaces)

pad_end = (s: str, width: int, fill: str = " ") -> str
capitalize = (s: str) -> str

the first letter in upper case ("hello world" -> "Hello world")

split = (s: str) -> str[]

split on runs of whitespace

lines = (s: str) -> str[]

the lines of s, without their line ends ("\n", or Windows' "\r\n")

join = (parts: str[], sep: str = "") -> str
replace = (s: str, old: str, new: str) -> str
repeat = (s: str, n: int) -> str
(*) = (s: str, n: int) -> str
(*) = (n: int, s: str) -> str
upper = (s: str) -> str

s in capitals (letters of Latin, accented ones too, Greek and Cyrillic: "café" is "CAFÉ")

lower = (s: str) -> str

s in small letters (as upper)

to_int = (s: str) -> int?

parse an integer (decimal, or hex after 0x, binary after 0b, octal after 0o; _ may separate digits); none if it is not one or does not fit in an int. Spaces and line ends around it are left out (" 42\n" is 42, a line as read from a file); inside it they are not ("4 2" is none)

to_int = (s: str, base: int) -> int?

an integer written in base 2 to 36 (to_int("ff", 16) is 255; letters for the digits past 9, in either case; the base's own prefix may come first: "0xff", "0b101")

to_float = (s: str) -> f64?

Parse a decimal number. The result is the double nearest to the exact decimal value (ties to even), like C's strtod: an estimate, then exact big-integer comparisons. Spaces and line ends around it are left out, as for to_int.

Characters

reversed = (s: str) -> str

the characters (code points) in reverse order, as a new string

without_last_char = (s: str) -> str

s without its last character (all its bytes: backspace in a text field)

char_count = (s: str) -> int

number of unicode code points

first = (s: str, n: int) -> str

the first n characters (all of it when there are fewer; s[..n] counts bytes, and can cut an é in two)

last = (s: str, n: int) -> str

the last n characters (all of it when there are fewer)

chars = (s: str) -> int[]

unicode code points of s

hash = (s: str) -> u64

a number made from the text: the same for the same text (for maps, and to pick by name)

Regular expressions

regex(r"...") returns a compiled pattern or RegexError; s.find(r), s.find_all(r), s.matches(r), s.replace(r, "$1") and s.split(r) use it. Raw strings (r"\d+") keep the backslashes as they are.

# example: regex
log = "2026-10-14 08:15 error: disk full\n2026-10-14 08:16 info: retrying\n2026-10-14 08:20 error: gave up"
line = regex(r"^(\S+) (\S+) (\w+): (.*)$").unwrap()           # made once, used many times
loop m in log.find_all(line):
    if m.groups[2] == "error": print("{m.groups[1]} {m.groups[3]}")

print("ada@example.com".matches(regex(r"[\w.]+@[\w.]+\.\w+").unwrap()))   # all of it matches
print("a1b22c333".find_all(regex(r"\d+").unwrap()).map((m): m.text))
print("x = 1, y = 2".replace(regex(r"(\w) = (\d)").unwrap(), "$2=$1"))
print("one, two;three".split(regex(r"[,;]\s*").unwrap()))
print("Hello World".replace(regex(r"(?i)o").unwrap(), "0"))

Run it in the playground

regex.jo

Regular expressions: patterns to find in text, test it against, take apart and replace in.

date = regex(r"(\d{4})-(\d\d)-(\d\d)").unwrap()
if let m = "due 2026-10-14!".find(date): print(m.text, m.groups[0])   # 2026-10-14 2026
"2026-10-14".matches(date)                       # true: all of the text matches
"a1b22c333".find_all(regex(r"\d+").unwrap()).map((m): m.text)   # ["1", "22", "333"]
"x = 1, y = 2".replace(regex(r"(\w) = (\d)").unwrap(), "$2=$1")  # "1=x, 2=y"
"a, b;c".split(regex(r"[,;]\s*").unwrap())                       # ["a", "b", "c"]

Patterns: . (any character but a line break) [abc] [a-z] [^0-9] \d \w \s (and \D \W \S) ^ $ \b \B, x* x+ x? x{2} x{2,} x{2,5} (and lazy x*? x+? x?? x{2,5}?), a|b, (group) (?:group), \ before any of .[]{}()*+?^$|\ for itself, \n \t \r; (?i) at the start ignores case (in ASCII). \w takes letters of any script ("Zürich" is one word). regex(pattern) returns a Regex or RegexError, so patterns typed by users can be handled without a panic. Matching takes time in proportion to the text's length times the pattern's (it never backtracks without end), and works on characters (code points), not bytes. Make a Regex once and use it for every text: regex() reads and prepares the pattern each time. On a long text, a pattern without ^ $ \b \B is matched a character at a time by a table made as it goes (a DFA), a few nanoseconds a character.

struct Regex:
    pattern: str
    groups: int             # how many ( ) groups it has
struct Match:
    start: int
    end: int
    text: str
    groups: str[]

one match: where it is (byte offsets), its text, and the text of each ( ) group ("" for a group that took no part)

Using one

error struct RegexError:
    message: str
    position: int

a malformed pattern: message and one-based Unicode character position

regex = (pattern: str) -> Regex | RegexError

compile a pattern once, returning its error for malformed user input. Trusted patterns can use regex(r"\d+").unwrap().

find = (s: str, r: Regex, start: int = 0) -> Match?

the first match in s from byte offset start, or none; out-of-range starts give none

find_all = (s: str, r: Regex) -> Match[]

every match in s, from left to right, not overlapping

matches = (s: str, r: Regex) -> bool

the whole of s matches r (not only a part of it)

contains = (s: str, r: Regex) -> bool

r matches somewhere in s

replace = (s: str, r: Regex, with: str) -> str

s with each match of r replaced by with, where $0 is the match and $1, $2 ... its groups ($$ for a $)

replace = (s: str, r: Regex, f: (Match) -> str) -> str

s with each match of r replaced by what f makes of it

split = (s: str, r: Regex) -> str[]

the parts of s between the matches of r

Maps

{K: V} maps keys to values, in the order they were added.

# example: maps
ages = {"ada": 36, "alan": 41}
ages["grace"] = 85                       # add or change
print(ages["ada"], ages.len(), ages.contains("bob"))
print(ages.get("bob") ?? 0)              # none for a missing key: 0 instead

counts: {str: int} = {}
loop w in "a rose is a rose is a rose".split(" "):
    counts[w] += 1                       # a missing key starts at 0
loop word, n in counts:                  # in the order they were added
    print("{word}: {n}")
counts.remove("is")
print(counts.keys(), counts.values())

Run it in the playground

map.jo

Maps {K: V} keep insertion order and copy as values. Use get/contains for lookup and assignment/remove for updates; storage fields are library implementation details.

struct Map[K, V]
hash = (x: int) -> u64

full 64-bit avalanche (murmur3 finalizer): every key bit affects the low bits used for slots, so keys like multiples of 4096 or float bit patterns spread out

hash = (x: u64) -> u64
hash = (x: bool) -> u64
hash = (x)
([]=)[K, V] = (m: mut Map[K, V], k: K, v: V)
reserve[K, V] = (m: mut Map[K, V], n: int)

room for n entries without growing (when many are to come)

([])[K, V] = (m: Map[K, V], k: K) -> V
get[K, V] = (m: Map[K, V], k: K) -> V?

Optionals flatten: when V is optional, contains(m, k) distinguishes a stored none from absence.

get[K, V] = (m: Map[K, V], k: K, default: V) -> V
contains[K, V] = (m: Map[K, V], k: K) -> bool
len[K, V] = (m: Map[K, V]) -> int
is_empty[K, V] = (m: Map[K, V]) -> bool
keys[K, V] = (m: Map[K, V]) -> K[]
values[K, V] = (m: Map[K, V]) -> V[]
items[K, V] = (m: Map[K, V]) -> (K, V)[]

(the (key, value) pairs, in the order added: for sorting them, m.items().sort(...))

clear[K, V] = (m: mut Map[K, V])
remove[K, V] = (m: mut Map[K, V], k: K) -> bool

remove a key; returns true if it was present. The others keep their order.

(==)[K, V] = (a: Map[K, V], b: Map[K, V]) -> bool

the same keys with equal values (in any order) (not for sloppy0: it would take the generic (==) for all structs)

hash[K, V] = (m: Map[K, V]) -> u64

a number made from the entries, in any order: maps that are == hash alike (so a map can be a key). (Each entry's key and value hashed together, the entries' added up)

Math and random numbers

For vectors and matrices, see colors, vectors and matrices. int is 64 bits: gcd, isqrt, pow_mod and the others in integer.jo are exact for all of them. +, - and * on integers wrap around; checked_add and the others below say when they would. Past 64 bits: big integers, exact, and big numbers, a float with a large exponent (about 15 digits).

# example: math and random numbers
print(PI, sqrt(2.0), abs(-3), floor(2.7), round(2.5))
print(min(3, 8), max(2.5, 1.0), clamp(15, 0, 10))
print(sin(PI / 2.0), atan2(1.0, 1.0), degrees(PI), pow(2.0, 10.0))
print(lerp(0.0, 100.0, 0.25), smoothstep(0.0, 1.0, 0.5), mod(-1, 3))
print(gcd(12, 18), lcm(4, 6), isqrt(10 ^ 18), pow_mod(3, 10 ^ 18, 1_000_000_007), inv_mod(3, 7))
print(checked_add(MAX_INT, 1), saturating_add(u8(250), 10), checked_cast[u8](300), wrapping_mul(u8(16), 16))

seed_random(7)                           # the same numbers every run
print(random(), random(10.0, 20.0), random_int(1, 7))

r = rng(123)                             # a generator of its own
print(r.next_int(0, 100), r.next_float())

Run it in the playground

math.jo

Math basics.

const PI = 3.141592653589793
const TAU = 6.283185307179586
const E = 2.718281828459045
const INF = 1e308 * 10.0
const NAN = INF - INF
const MAX_INT = 9223372036854775807
const MIN_INT = -9223372036854775807 - 1
abs = (x: int) -> int
abs = (x: f64) -> f64
abs = (x: f32) -> f32
min = (a: int, b: int) -> int
max = (a: int, b: int) -> int
min = (a: f64, b: f64) -> f64
max = (a: f64, b: f64) -> f64
min = (a: f32, b: f32) -> f32
max = (a: f32, b: f32) -> f32
min = (a: int, b: int, c: int) -> int

(of three: max(a, b, c))

max = (a: int, b: int, c: int) -> int
min = (a: f64, b: f64, c: f64) -> f64
max = (a: f64, b: f64, c: f64) -> f64
clamp = (x: int, lo: int, hi: int) -> int
clamp = (x: f64, lo: f64, hi: f64) -> f64
clamp = (x: f32, lo: f32, hi: f32) -> f32
abs = (x: i32) -> i32

the other integer types keep their type (the int ones above take mixed ones: min(i8, u8))

abs = (x: i16) -> i16
abs = (x: i8) -> i8
min = (a: i32, b: i32) -> i32
min = (a: u32, b: u32) -> u32
min = (a: i16, b: i16) -> i16
min = (a: u16, b: u16) -> u16
min = (a: i8, b: i8) -> i8
min = (a: u8, b: u8) -> u8
min = (a: u64, b: u64) -> u64
max = (a: i32, b: i32) -> i32
max = (a: u32, b: u32) -> u32
max = (a: i16, b: i16) -> i16
max = (a: u16, b: u16) -> u16
max = (a: i8, b: i8) -> i8
max = (a: u8, b: u8) -> u8
max = (a: u64, b: u64) -> u64
clamp = (x: i32, lo: i32, hi: i32) -> i32
clamp = (x: u32, lo: u32, hi: u32) -> u32
clamp = (x: i16, lo: i16, hi: i16) -> i16
clamp = (x: u16, lo: u16, hi: u16) -> u16
clamp = (x: i8, lo: i8, hi: i8) -> i8
clamp = (x: u8, lo: u8, hi: u8) -> u8
clamp = (x: u64, lo: u64, hi: u64) -> u64
sign = (x: f64) -> f64
sign = (x: int) -> int
floor = (x: f64) -> f64
ceil = (x: f64) -> f64
round = (x: f64) -> f64

the nearest whole number; halves go away from zero (round(2.5) is 3.0, round(-2.5) is -3.0; Python's round goes to the even one, 2)

trunc = (x: f64) -> f64
fract = (x: f64) -> f64
mod = (x: f64, y: f64) -> f64
mod = (x: int, y: int) -> int
is_nan = (x: f64) -> bool
is_finite = (x: f64) -> bool

an ordinary number: not infinite and not NaN

is_inf = (x: f64) -> bool
lerp = (a: f64, b: f64, t: f64) -> f64
mix = (a: f64, b: f64, t: f64) -> f64
inverse_lerp = (a: f64, b: f64, x: f64) -> f64

where x is between a and b, from 0 (at a) to 1 (at b): lerp backwards

remap = (x: f64, a: f64, b: f64, c: f64, d: f64) -> f64

x moved from the range a..b to c..d, as p5's map: remap(mouse.x, 0, 1280, -1, 1)

smoothstep = (e0: f64, e1: f64, x: f64) -> f64
rk4[T] = (y: T, t: f64, dt: f64, rate: (T, f64) -> T) -> T

the state y of a simulation dt seconds on, by the classic Runge-Kutta method (far closer than y + rate(y, t) * dt, Euler's: an orbit stays closed, a spring keeps its energy): rate(y, t) says how fast y changes at time t. y is a number, a vector, an f64[], or a struct with + and * by a number of its own ((+) = (a: S, b: S) -> S: ...)

rk4 = (y: f64[], t: f64, dt: f64, rate: (f64[], f64) -> f64[]) -> f64[]
sin = (x: f64) -> f64
cos = (x: f64) -> f64
tan = (x: f64) -> f64
atan = (x0: f64) -> f64
atan2 = (y: f64, x: f64) -> f64
asin = (x: f64) -> f64
acos = (x: f64) -> f64
exp = (x: f64) -> f64
tanh = (x: f64) -> f64

the hyperbolic tangent: from -1 to 1, through 0 (a smooth limit: soft clipping, squashing)

log = (x: f64) -> f64
log2 = (x: f64) -> f64
log10 = (x: f64) -> f64
pow = (x: f64, y: f64) -> f64

x to the power y, within an ulp (fdlibm's: log2(x) in extra precision, times y, then 2 to that)

exp = (x: f32) -> f32

f32 versions (shader code, games): computed in double with shorter polynomials, so they are within an ulp of the f32 result at a fraction of the cost of the full-precision ones

log = (x: f32) -> f32
pow = (x: f32, y: f32) -> f32
sin = (x: f32) -> f32
cos = (x: f32) -> f32
pow = (x: int, n: int) -> int
f64_bits = (x: f64) -> u64

a float's bits as an integer, and back (IEEE 754: f64_bits(1.0) is 0x3FF0000000000000)

f64_from_bits = (b: u64) -> f64
f32_bits = (x: f32) -> u32
f32_from_bits = (b: u32) -> f32
hypot = (x: f64, y: f64) -> f64
radians = (deg: f64) -> f64
degrees = (rad: f64) -> f64

Random numbers (xoshiro256**)

struct Rng:
    s0: u64 = 0x9E3779B97F4A7C15
    s1: u64 = 0xBF58476D1CE4E5B9
    s2: u64 = 0x94D049BB133111EB
    s3: u64 = 0x2545F4914F6CDD1D
rng = (seed: int) -> Rng
next_u64 = (r: mut Rng) -> u64
next_float = (r: mut Rng) -> f64

uniform f64 in [0, 1)

next_normal = (r: mut Rng, mean: f64 = 0.0, sd: f64 = 1.0) -> f64

normally distributed, from r: mean 0 and standard deviation 1 (as randn), or the ones given

next_int = (r: mut Rng, lo: int, hi: int) -> int

uniform int in [lo, hi); equal bounds return lo without drawing, hi < lo panics

next_item[T] = (r: mut Rng, xs: T[]) -> T

an element of xs (not empty), from r

shuffle[T] = (r: mut Rng, xs: mut T[])

put xs in a random order from r

seed_random = (seed: int)
random = () -> f64

random f64 in [0, 1)

random = (lo: f64, hi: f64) -> f64

random f64 in [lo, hi); equal bounds return lo, hi < lo panics. This form always draws, including equal bounds, preserving seeded sequences used by existing games.

random_normal = (mean: f64 = 0.0, sd: f64 = 1.0) -> f64

a random number from a bell curve around mean: about two in three within sd of it (p5's randomGaussian; Rng's next_normal for a seeded one)

random_int = (lo: int, hi: int) -> int

a random whole number from lo up to hi, hi left out (as in lo..hi): random_int(0, xs.len()) picks a position, and a die is random_int(1, 7). Equal bounds return lo; hi < lo panics.

random_item[T] = (xs: T[]) -> T

a random element of xs (which must not be empty)

shuffle[T] = (xs: mut T[])

put xs in a random order

integer.jo

Number theory on whole numbers, as contests and puzzles want it: greatest common divisors, square roots and arithmetic modulo m, exact for every int (no float in between):

gcd(12, 18)                  # 6
isqrt(10 ^ 18 - 1)           # 999999999
pow_mod(3, 10 ^ 18, 1_000_000_007)
inv_mod(2, 1_000_000_007)    # 500000004 (an optional: none when there is none)
mul_mod(a, b, m)             # a * b mod m without overflow, for m up to 2^63

The results of the modulo functions are from 0 to m - 1, negative arguments too (as mod(x, m); % keeps the sign of x). Past 64 bits, BigInt keeps every digit, with gcd, isqrt, pow_mod and the others for it too (bigint.jo).

gcd = (a: int, b: int) -> int

the greatest common divisor, 0 or more (gcd(0, 0) is 0; gcd(-4, 6) is 2)

gcd = (a: u64, b: u64) -> u64
lcm = (a: int, b: int) -> int

the least common multiple, 0 or more (0 when either is 0; it wraps around when it does not fit, as * does)

lcm = (a: u64, b: u64) -> u64
isqrt = (n: int) -> int

the whole square root: the largest r with r * r <= n (isqrt(15) is 3), exact where int(sqrt(f64(n))) is not (past 2^52)

mul_mod = (a: int, b: int, m: int) -> int

a * b mod m, from 0 to m - 1, with the 128-bit product (a * b % m overflows once a * b passes 2^63, as it does for m past about 3e9)

mul_mod = (a: u64, b: u64, m: u64) -> u64
pow_mod = (base: int, e: int, m: int) -> int

base to the power e, mod m (from 0 to m - 1), in about log2(e) steps: pow_mod(2, 10 ^ 18, 1_000_000_007). A negative e is a power of base's inverse (pow_mod(2, -1, 7) is 4); without one it stops the program (inv_mod says whether there is one)

pow_mod = (base: u64, e: u64, m: u64) -> u64
inv_mod = (a: int, m: int) -> int?

the inverse of a mod m: the x from 0 to m - 1 with a * x mod m == 1, or none when a and m have a common divisor (inv_mod(3, 7) is 5; inv_mod(2, 4) is none). For a prime m it is also pow_mod(a, m - 2, m)

to_u64 = (s: str) -> u64?

parse a whole number from 0 to 2^64 - 1 (to_int stops at 2^63 - 1), as to_int does: decimal, or hex after 0x, binary after 0b, octal after 0o; _ may separate digits; none if it is not one, is negative or does not fit

to_u64 = (s: str, base: int) -> u64?

a whole number from 0 to 2^64 - 1 written in base 2 to 36 (to_u64("ffffffffffffffff", 16))

checked.jo

Integer arithmetic that says when it overflows. +, - and * on integers wrap around, in debug and release builds alike (i8(127) + i8(1) is -128); these say what to do instead:

checked_add(a, b)        # an optional: none when the sum does not fit the type
saturating_add(a, b)     # the type's largest (or smallest) value when it does not fit
wrapping_add(a, b)       # as a + b: wrapped around, said on purpose
checked_cast[u8](x)      # x as a u8 when it fits, else none (u8(x) keeps the low bits)
saturating_cast[u8](x)   # 0 below, 255 above

total = checked_add(total, n) ?? panic("total overflowed")
if let p = checked_mul(w, h): ...

They take two values of one integer type (int, i32, i16, i8, u64, u32, u16, u8) and give that type; values of mixed types go as the int ones, as other operators do (checked_add(x, n) with x an i32 and n an int is an int). A literal takes the other's type: checked_add(b, 1) with b a u8 is a u8.

Checked: none when the exact result does not fit

checked_add = (a: int, b: int) -> int?

a + b, or none when it overflows

checked_add = (a: u64, b: u64) -> u64?
checked_add = (a: i32, b: i32) -> i32?
checked_add = (a: i16, b: i16) -> i16?
checked_add = (a: i8, b: i8) -> i8?
checked_add = (a: u32, b: u32) -> u32?
checked_add = (a: u16, b: u16) -> u16?
checked_add = (a: u8, b: u8) -> u8?
checked_sub = (a: int, b: int) -> int?

a - b, or none when it overflows (for the unsigned types: when b > a)

checked_sub = (a: u64, b: u64) -> u64?
checked_sub = (a: i32, b: i32) -> i32?
checked_sub = (a: i16, b: i16) -> i16?
checked_sub = (a: i8, b: i8) -> i8?
checked_sub = (a: u32, b: u32) -> u32?
checked_sub = (a: u16, b: u16) -> u16?
checked_sub = (a: u8, b: u8) -> u8?
checked_mul = (a: int, b: int) -> int?

a * b, or none when it overflows

checked_mul = (a: u64, b: u64) -> u64?
checked_mul = (a: i32, b: i32) -> i32?
checked_mul = (a: i16, b: i16) -> i16?
checked_mul = (a: i8, b: i8) -> i8?
checked_mul = (a: u32, b: u32) -> u32?
checked_mul = (a: u16, b: u16) -> u16?
checked_mul = (a: u8, b: u8) -> u8?

Saturating: the nearest value the type has

saturating_add = (a: int, b: int) -> int

a + b, or the type's largest or smallest value when it overflows

saturating_add = (a: u64, b: u64) -> u64
saturating_add = (a: i32, b: i32) -> i32
saturating_add = (a: i16, b: i16) -> i16
saturating_add = (a: i8, b: i8) -> i8
saturating_add = (a: u32, b: u32) -> u32
saturating_add = (a: u16, b: u16) -> u16
saturating_add = (a: u8, b: u8) -> u8
saturating_sub = (a: int, b: int) -> int

a - b, or the type's largest or smallest value when it overflows (0 for the unsigned types when b > a)

saturating_sub = (a: u64, b: u64) -> u64
saturating_sub = (a: i32, b: i32) -> i32
saturating_sub = (a: i16, b: i16) -> i16
saturating_sub = (a: i8, b: i8) -> i8
saturating_sub = (a: u32, b: u32) -> u32
saturating_sub = (a: u16, b: u16) -> u16
saturating_sub = (a: u8, b: u8) -> u8
saturating_mul = (a: int, b: int) -> int

a * b, or the type's largest or smallest value when it overflows

saturating_mul = (a: u64, b: u64) -> u64
saturating_mul = (a: i32, b: i32) -> i32
saturating_mul = (a: i16, b: i16) -> i16
saturating_mul = (a: i8, b: i8) -> i8
saturating_mul = (a: u32, b: u32) -> u32
saturating_mul = (a: u16, b: u16) -> u16
saturating_mul = (a: u8, b: u8) -> u8

Wrapping: as the operators, said on purpose

wrapping_add = (a: int, b: int) -> int

a + b, wrapped around on overflow (as + does: this says it is meant)

wrapping_add = (a: u64, b: u64) -> u64
wrapping_add = (a: i32, b: i32) -> i32
wrapping_add = (a: i16, b: i16) -> i16
wrapping_add = (a: i8, b: i8) -> i8
wrapping_add = (a: u32, b: u32) -> u32
wrapping_add = (a: u16, b: u16) -> u16
wrapping_add = (a: u8, b: u8) -> u8
wrapping_sub = (a: int, b: int) -> int

a - b, wrapped around on overflow (as - does: this says it is meant)

wrapping_sub = (a: u64, b: u64) -> u64
wrapping_sub = (a: i32, b: i32) -> i32
wrapping_sub = (a: i16, b: i16) -> i16
wrapping_sub = (a: i8, b: i8) -> i8
wrapping_sub = (a: u32, b: u32) -> u32
wrapping_sub = (a: u16, b: u16) -> u16
wrapping_sub = (a: u8, b: u8) -> u8
wrapping_mul = (a: int, b: int) -> int

a * b, wrapped around on overflow (as * does: this says it is meant)

wrapping_mul = (a: u64, b: u64) -> u64
wrapping_mul = (a: i32, b: i32) -> i32
wrapping_mul = (a: i16, b: i16) -> i16
wrapping_mul = (a: i8, b: i8) -> i8
wrapping_mul = (a: u32, b: u32) -> u32
wrapping_mul = (a: u16, b: u16) -> u16
wrapping_mul = (a: u8, b: u8) -> u8

Conversions

checked_cast[T] = (x: int) -> T?

x as a T (an integer type: checked_castu8) when it has that value, else none (u8(x) keeps the low bits: u8(300) is 44, checked_castu8 none)

checked_cast[T] = (x: u64) -> T?
saturating_cast[T] = (x: int) -> T

x as a T (an integer type: saturating_castu8), or T's smallest or largest value when x is past it (saturating_castu8 is 255, saturating_castu8 0)

saturating_cast[T] = (x: u64) -> T

Big integers

BigInt is a whole number of any size, every digit kept, as Python's int: bigint(2) ^ 1000, bigint("123456789012345678901234567890"). The operators, comparisons and printing work as on ints, ints mixed in; it can be a map key or in a set. Nothing is imported (the compiler reads it for the programs that use it).

# example: exact big integers
f = bigint(1)
loop i in [1..50]: f *= i                # 50!, all 65 digits
print(f, len(str(f)))
x = bigint("123456789012345678901234567890")
print(x * x + 1, x / 7, x % 7, -x >> 3)
print(bigint(2) ^ 100 > x, digits(bigint(2) ^ 1000).sum(), str(bigint(255), 16))
print(gcd(f, bigint(2) ^ 100), isqrt(x), pow_mod(bigint(3), x, bigint(2) ^ 127 - 1))
print(int(x / bigint(10) ^ 20), to_int(x), to_bigint("0xffff_ffff_ffff_ffff_ff"))

Run it in the playground

bigint.jo

Exact whole numbers of any size: 2 ^ 1000's 302 digits, factorials, Fibonacci(10000), RSA's modular arithmetic. Every digit is kept (Big, use big, is a float with a large exponent: about 15 digits, for an idle game's money).

f = bigint(1)
loop i in [1..100]: f *= i               # 100!, all 158 digits
print(f)
x = bigint("123456789012345678901234567890")
y = (x * x + 1) % bigint(10) ^ 20
if y > x: print(str(y, 16))              # in hex
print(pow_mod(bigint(3), bigint(10) ^ 30, bigint(2) ^ 127 - 1))

+ - * / % and ^ (an int power) work as on ints, with BigInts and ints mixed (x * 2, 1 + x); / truncates toward zero and % keeps the sign of the left side, as for ints (-7 / 2 is -3, -7 % 3 is -1; mod(x, m) is from 0 to m - 1). Comparisons, ==, min, max and sort work, and a BigInt can be a map key or in a set. print shows its digits; int(x) or to_int(x) give it back as an int. to_text, to_json and saves write its fields, which read back.

struct BigInt
bigint = (n: int) -> BigInt

n as a BigInt

bigint = (n: u64) -> BigInt
bigint = (s: str) -> BigInt

the whole number written in text, as to_bigint reads it; text that is not one stops the program (to_bigint says none instead)

to_bigint = (s: str) -> BigInt?

the whole number written in text: decimal digits, or hex after 0x, binary after 0b, octal after 0o, with a sign before it if any; _ may separate digits, and spaces and line ends around it are left out (as to_int reads one, of any length). none if it is not one

to_bigint = (s: str, base: int) -> BigInt?

a whole number written in base 2 to 36 (to_bigint("ff", 16) is 255; letters for the digits past 9, in either case; the base's own prefix may come first: "0xff")

to_int = (x: BigInt) -> int?

x as an int, or none when it does not fit (from -2^63 to 2^63 - 1)

int = (x: BigInt) -> int

x as an int; one that does not fit stops the program (to_int says none instead)

to_u64 = (x: BigInt) -> u64?

x as a u64, or none when it is negative or past 2^64 - 1

f64 = (x: BigInt) -> f64

the f64 nearest x (infinity past about 1.8e308)

str = (x: BigInt, base: int) -> str

x shown in base 2 to 36, with lowercase letters for the digits past 9 (str(bigint(255), 16) is "ff"; a minus sign first when it is negative)

str = (x: BigInt) -> str

x in decimal: print(x) and "{x}" show it so

digits = (x: BigInt) -> int[]

the decimal digits of x, most significant first, without its sign (digits(bigint(2) ^ 10) is [1, 0, 2, 4]; for 0, [0]): digits(bigint(2) ^ 1000).sum()

bit_length = (x: BigInt) -> int

how many bits x takes without its sign: bit_length(bigint(255)) is 8; 0 for 0

sign = (x: BigInt) -> int

-1, 0 or 1

abs = (x: BigInt) -> BigInt
(-) = (a: BigInt) -> BigInt
(+) = (a: BigInt, b: BigInt) -> BigInt
(-) = (a: BigInt, b: BigInt) -> BigInt
(*) = (a: BigInt, b: BigInt) -> BigInt
(/) = (a: BigInt, b: BigInt) -> BigInt

truncated toward zero, as for ints (bigint(-7) / 2 is -3)

(%) = (a: BigInt, b: BigInt) -> BigInt

the remainder of a / b, with a's sign, as for ints (bigint(-7) % 3 is -1; mod(x, m) is from 0 to m - 1)

pow = (x: BigInt, e: int) -> BigInt

x to the power e (x ^ e). A negative e truncates as / does: 0 unless x is 1 or -1

(==) = (a: BigInt, b: BigInt) -> bool
(<) = (a: BigInt, b: BigInt) -> bool
hash = (x: BigInt) -> u64

a number made from x: the same for BigInts that are ==, so a BigInt can be a key

Mixed with ints

(+) = (a: BigInt, b: int) -> BigInt
(+) = (a: int, b: BigInt) -> BigInt
(-) = (a: BigInt, b: int) -> BigInt
(-) = (a: int, b: BigInt) -> BigInt
(*) = (a: BigInt, b: int) -> BigInt
(*) = (a: int, b: BigInt) -> BigInt
(/) = (a: BigInt, b: int) -> BigInt
(/) = (a: int, b: BigInt) -> BigInt
(%) = (a: BigInt, b: int) -> BigInt
(%) = (a: int, b: BigInt) -> BigInt
(==) = (a: BigInt, b: int) -> bool
(==) = (a: int, b: BigInt) -> bool
(<) = (a: BigInt, b: int) -> bool
(<) = (a: int, b: BigInt) -> bool
(<<) = (x: BigInt, n: int) -> BigInt

x shifted left n bits: x * 2 ^ n

(>>) = (x: BigInt, n: int) -> BigInt

x shifted right n bits, rounding down as >> on ints does (bigint(-7) >> 1 is -4)

Number theory

mod = (x: BigInt, m: BigInt) -> BigInt

x mod m, from 0 to m - 1 for m > 0 (with m's sign, as Python's %: mod(bigint(-7), 3) is 2)

mod = (x: BigInt, m: int) -> BigInt
gcd = (a: BigInt, b: BigInt) -> BigInt

the greatest common divisor, 0 or more (gcd of 0 and 0 is 0)

lcm = (a: BigInt, b: BigInt) -> BigInt

the least common multiple, 0 or more (0 when either is 0)

isqrt = (n: BigInt) -> BigInt

the whole square root: the largest r with r * r <= n

inv_mod = (a: BigInt, m: BigInt) -> BigInt?

the inverse of a mod m: the x from 0 to m - 1 with a * x mod m == 1, or none when a and m have a common divisor

pow_mod = (base: BigInt, e: BigInt, m: BigInt) -> BigInt

base to the power e, mod m (from 0 to m - 1), in about log2(e) steps: RSA's pow_mod(msg, e, n). A negative e is a power of base's inverse; without one it stops the program

pow_mod = (base: BigInt, e: int, m: BigInt) -> BigInt

Files, time and the system

In a web page, files are the ones the page was given, and env reads its address's parameters. What is at a web address: net.fetch(url), after import net (fetching from the web).

# example: files, time and the system
start = time()
write_file("notes.txt", "first line\nsecond line\n")
text = read_file("notes.txt")
if text is str:
    loop line in text.lines(): print("> {line}")
else: eprint("cannot read {text.path}: {text.message}")
print(file_exists("notes.txt"), args())
delete_file("notes.txt")
docs = documents_dir()                    # (C:\Users\me\Documents, /home/me/Documents)
print(home_dir(), join_path(docs, "report.txt"), cpu_count())
print("took {(time() - start) * 1000.0:.2} ms")

Run it in the playground

os.jo

Operating system access: files, arguments, environment, time.

exit = (code: int)
on_panic = (f: (str) -> void)

f called with a panic's message ("game.jo:12: index 7 out of bounds..."), as the program ends with it: to keep it where the program keeps its own log, say (a game in a web page, which a player can save after reloading it). Not for a panic that is caught (a server's handler's); once, even if f panics too

args = () -> str[]

command line arguments (args()[0] is the program as it was started: sloppy tool.jo gives "tool.jo")

env = (name: str) -> str?

an environment variable (in a web page: the page's URL parameter of that name, in any letters, so ?room= is env("ROOM")'s, where SLOPPY_X may also be written x, and a bare ?x is "1")

file_error = () -> str

why the last file operation that failed did, in words: "no such file or directory", "permission denied", "it is a directory", "the disk is full"... ("" when none has failed). Checked read_file/read_bytes/read_line(File)/list_dir carry FileError in their own results:

read_line = () -> str?

a line typed in (or piped in), without its end; none when the input has ended

struct File

A file open for reading a piece at a time (a log too big to load whole, the start of a file to hash):

create_file = (path: str) -> File?

A file made (or emptied) for writing a piece at a time (a download, a log written as it goes):

write = (f: mut File, b: u8[]) -> bool

add to a file made by create_file (false when it could not: file_error says why)

write = (f: mut File, s: str) -> bool
open_file = (path: str) -> File?
close = (f: mut File)
input = (prompt: str = "") -> str?

a line typed by the user, after showing the prompt; none at EOF or browser cancellation. In a web page, a box asks for it.

input_int = (prompt: str = "") -> int?

a whole number typed by the user, retrying malformed lines; none at EOF or cancellation

input_float = (prompt: str = "") -> f64?

a number (12, 2.5) typed by the user, retrying malformed lines; none at EOF or cancellation

read_stdin = () -> str

all of standard input (what is piped in), until it ends

page_url = () -> str

a web page's own address, without its ?query (to make a link to it: page_url() + "?invite=" + code); "" in a native program

download_file = (path: str, name: str = "") -> bool

a file the program wrote, given to the person using it: in a web page, the browser downloads it (a picture saved with save_png, an exported save), named name or as the path ends; elsewhere it is already where it was written. True if the file is there

write_file = (path: str, contents: str, sync: bool = false) -> bool

write a whole file (made, or replaced); false if it could not be (file_error() says why). sync = true: on the disk itself when this returns, and whole: written to a new file beside it (path + ".new"), which is put on the disk and then takes the old one's place, the directory put on the disk too, so that neither a crash nor a power cut leaves half a file, or none (for data a program keeps, as a server's: it takes some milliseconds more; a web page's storage keeps what it is given as it does)

write_bytes = (path: str, b: u8[], sync: bool = false) -> bool
is_dir = (path: str) -> bool

a directory (and not a file)

is_symlink = (path: str) -> bool

the path is a symbolic link (to anything, or to nothing); is_dir and the rest follow links, so a walk through directories that should not go round in circles asks this first

file_size = (path: str) -> int?

a file's size in bytes; none if it cannot be opened (or is a directory)

file_exists = (path: str) -> bool
make_executable = (path: str) -> bool
delete_file = (path: str) -> bool
time = () -> f64

seconds since an arbitrary point (monotonic clock): the one to measure how long code takes (elapsed() is the game's clock, which a screenshot run advances 1/60 s a frame)

time_ns = () -> int

nanoseconds since an arbitrary point (monotonic clock)

sleep = (seconds: f64)
write = (s: str)

print without a trailing newline

flush_output = ()

what print and write gave so far, written out now (output to a file or a pipe is collected and written in large pieces; to a terminal it goes at once anyway)

is_terminal = () -> bool

standard output is a terminal (not a file or a pipe)

eprint = (s: str)

print to standard error (for messages about the program, kept apart from its output), and a line break; it takes what print takes: eprint("bad line", i, xs)

exe_path = () -> str

absolute path of the running executable (a script run with sloppy tool.jo is built into a cache first: its own path is args()[0])

exec = (path: str, argv: str[]) -> bool

replace the current process with another program (returns only on failure)

set_env = (name: str, value: str)

an environment variable set, for this program and the programs it starts after this

unset_env = (name: str)

an environment variable taken away, for this program and the programs it starts after this

env_all = () -> {str: str}

every environment variable, by name (in a web page: only those set with set_env)

spawn_detached = (path: str, argv: str[]) -> bool

start a program in the background, detached from this one: its own session, no terminal (input and output go to /dev/null); returns whether it was started

run_program = (program: str, args: str[] = [], show: bool = false, cwd: str = "") -> (int, str)

run a program and wait for it to end: its exit code (-1: it could not be started) and what it wrote to its standard output (its errors go where this program's go). A program named without a / is looked for on the PATH. args are its arguments, after its name. show = true: its output goes straight to this program's as it runs (a build's progress), and the text returned is "". cwd: the directory it runs in ("": this program's; a program named with a relative path is found from there). In a program with tasks the others take their turns meanwhile (on Windows they wait for it), and a task cancelled meanwhile ends it (its code is then 137)

run_shell = (command: str, show: bool = false, cwd: str = "") -> (int, str)

run a command line through the system's shell (sh; cmd on Windows): pipes, *.jo, && work as typed. Its exit code and what it wrote to its standard output; show and cwd as run_program's

chmod = (path: str, mode: int) -> bool
mkdir = (path: str) -> bool
make_dirs = (path: str) -> bool

make a directory and the ones it is in ("out/maps/2"); true if it is there after

delete_dir = (path: str) -> bool

remove a directory, which must be empty (delete_file for a file)

rename_file = (from: str, to: str, replace: bool = true) -> bool

move or rename a file or directory (one already at to is replaced: a file, or an empty directory). replace = false: false instead when something is at to (file_error() says "it is already there"), checked as it moves, so no other program can put one there in between

copy_file = (from: str, to: str) -> bool

copy a file's contents to another (made, or replaced)

append_file = (path: str, contents: str, sync: bool = false) -> bool

add to the end of a file (made if it is not there): a log. sync = true: on the disk itself when this returns (a change a server has made, kept before it answers: a crash or a power cut may cut short a line written as it happened, never one before it)

file_time = (path: str) -> f64?

when a file or directory was last changed, in seconds since 1970 (as unix_time()); none if it is not there

walk_dir = (path: str) -> str[]

every file under a directory, at any depth, as paths from it ("maps/level1.tmx"), sorted; links to directories are not followed

glob = (pattern: str) -> str[]

the files whose paths match a pattern: * is any part of a name, ? one character, and ** any number of directories ("src/.jo", "assets//.png"), sorted. As in the shell, hidden names (.git, .env) match only a pattern that starts them with a dot (".", "/.env"). On Windows letters match in either case, as its file names do (".TXT" matches notes.txt); elsewhere only in the same case. On Windows a pattern's \ is a / ("data\*.txt" gives data/notes.txt)

memory_in_use = () -> int

the memory this program has in use, in bytes (what the system counts as its resident set: on Linux, its pages in RAM; on Windows, its working set; in a web page, the size of its memory, which only grows); 0 where it is not known (macOS)

cwd = () -> str

the current directory

temp_dir = () -> str

a directory for temporary files (TMPDIR, else /tmp; on Windows, the user's temporary directory)

file.jo

Checked file reads. Failures travel with their results; streaming none/empty means EOF. open_file creates a buffered File; close it when finished. Writes still report bool and file_error(). File reads are synchronous and hold up tasks while the operating system reads.

error struct FileError:
    message: str
    path: str
    operation: str

an operating-system read failure, with the path and operation that failed

read_file = (path: str) -> str | FileError

read a whole UTF-8 file, omitting a leading UTF-8 BOM; read failure is never partial success

read_bytes = (path: str) -> u8[] | FileError

read every byte of a file, including a UTF-8 BOM; failures return FileError

read_line = (f: mut File) -> str? | FileError

the next line without its line ending; none only at EOF, FileError on read failure

read_bytes = (f: mut File, n: int) -> u8[] | FileError

up to n more bytes; empty only at EOF (or n=0), FileError on read failure; n must be nonnegative

list_dir = (path: str) -> str[] | FileError

names in a directory, excluding . and ..; a failed listing returns FileError, never a partial list

path.jo

Paths as text: their parts, and joining them (nothing is looked up on the disk). Both / and \ separate (Windows takes either).

print(file_name("art/hero.png"))           # hero.png
print(dir_name("art/hero.png"))            # art
print(extension("art/hero.png"))           # .png
print(without_extension("art/hero.png"))   # art/hero
print(join_path("art", "hero.png"))        # art/hero.png
file_name = (path: str) -> str

the last part: the file's name ("" for a path ending in a separator)

dir_name = (path: str) -> str

all but the last part ("." for a bare name; "/" for one at the root)

extension = (path: str) -> str

the file name's extension with its dot (".png"; "" when it has none, or is like ".bashrc")

without_extension = (path: str) -> str

the path without its file name's extension ("art/hero.png" -> "art/hero")

join_path = (a: str, b: str) -> str

a then b, with one separator between them (b as it is when it starts at the root). The separator is /, but on Windows \ when a is written with \ or is a drive ("C:\Users\me" and "report.txt" give "C:\Users\me\report.txt"; "art" and "hero.png" give "art/hero.png")

home_dir = () -> str

the user's home directory ("" when there is none: in a web page): /home/me, C:\Users\me

documents_dir = () -> str

the user's Documents folder ("" when there is none: in a web page). On Windows wherever it is (OneDrive may hold it); on Linux XDG_DOCUMENTS_DIR from ~/.config/user-dirs.dirs, else ~/Documents; on macOS ~/Documents. It may not be there yet: make_dirs makes it

abs_path = (path: str) -> str

the path from the root: a relative one from the working directory, with . and .. worked out ("../x" in /home/me/src is /home/me/x; links are not followed). On Windows, with \

date.jo

Dates and the wall clock: what time it is (unix_time), and the calendar date and time of day of a moment, where the computer is (its time zone) or in UTC.

d = now()
print("{d.year}-{d.month:02}-{d.day:02} {d.hour:02}:{d.minute:02}")   # 2026-10-14 08:15
print(date_text(now()))                                               # 2026-10-14 08:15:03
started = unix_time()
# ... do the work here
print("took {unix_time() - started:.1} s")

(time() is the clock to measure with in a game: it never jumps, as the wall clock may)

struct Date:
    year: int
    month: int          # 1 (January) to 12
    day: int            # 1 to 31
    hour: int           # 0 to 23
    minute: int         # 0 to 59
    second: int         # 0 to 59
    weekday: int        # 0 (Monday) to 6 (Sunday)
    offset: int         # its time zone: seconds east of UTC (0: UTC; New York in winter: -18000)
unix_time = () -> f64

seconds since 1970-01-01 00:00 UTC, now (the wall clock: it can jump when it is set)

date = (t: f64, utc: bool = false) -> Date

the date and time of day of moment t (unix seconds), in the computer's time zone, or in UTC

now = () -> Date

the date and time of day it is now, where the computer is

unix_time = (d: Date) -> f64

the moment (unix seconds) a date stands for (its offset says where it was: from date(), or 0 for a Date made as UTC); fields past their range carry over (month 13 is January of the next year)

parse_date = (text: str, utc: bool = false) -> Date?

a date written as ISO 8601 has it, or none: "2026-10-14", "2026-10-14 08:15", "2026-10-14T08:15:03Z" (Z: UTC), "2026-10-14T08:15:03.250+02:00". One without a time zone is where the computer is (utc = true: in UTC)

date_text = (d: Date) -> str

"2026-10-14 08:15:03"

month_name = (d: Date) -> str

the names of a date's month and weekday, in English ("October", "Wednesday")

weekday_name = (d: Date) -> str
utc_offset = (t: f64) -> int

how many seconds east of UTC the computer's clock is at moment t (unix seconds): its time zone and daylight saving time then (the TZ variable, or the system's zone). Fractional timestamps are floored to whole seconds, as date does, including before the Unix epoch.

Time zones on Linux and macOS: the TZif file of the zone (zic's format)

parse_date = (text: str, format: str, utc: bool = false) -> Date?

a date read with a strptime-style format. Supported: %Y %y %m %d %e %H %I %M %S %p, %b/%B (English month), %a/%A (English weekday), %j (day of year), %u/%w (weekday), %z (Z or +/-HHMM, +/-HH:MM), %Z (UTC/GMT), %% and %F/%T/%R (date, time, hours:minutes). Unspecified fields start at 1900-01-01 00:00:00. No zone in the text: local, or UTC with utc = true. Invalid text/format gives none.

date_text = (d: Date, format: str) -> str

format a date with the directives of parse_date(text, format). %Z writes UTC or the numeric offset (no abbreviations for local zones); %u: Monday=1, %w: Sunday=0. Unknown directives are an error. Text and English names are independent of the computer's locale.

date_add = (d: Date, seconds: f64, local: bool = false) -> Date

add (or subtract, when negative) elapsed seconds. Keeps d's fixed offset; local = true converts the result to the computer's local zone, including any daylight saving change. Dates have whole-second precision; fractional results are rounded down, as date(t) does.

date_diff = (a: Date, b: Date) -> f64

elapsed seconds from b to a (positive when a is later), respecting both UTC offsets

duration_text = (seconds: f64) -> str

elapsed seconds as "1h 30m", "2d 3s", "-1m 5s"; whole seconds, rounded toward zero (for subsecond measurements, format the seconds directly: "{seconds:.3} s")

cli.jo

A command line's options, read into a struct: its fields are the options, their defaults what an option left out keeps.

struct Options:
    verbose = false         # say each file's name
    out = "report.txt"      # where the counts go
    jobs = 4                # files read at once
    files: str[]            # the files to count

opts = parse_args[Options]("count lines in files")

That reads --verbose (or -v), --out file.txt (--out=file.txt, -o file.txt), --jobs 8 (a whole number) and the arguments that are not options (into the last list field). --help (or -h, and on Windows /?) prints what the options are, each with the comment written beside its field (or on the lines just above it), and ends the program; a mistake (an option it does not have, a word where a number goes) is said with the same help, and ends it with exit code 2. A field dry_run is --dry-run; -x is the one field starting with x (when only one does; -h is help, so a field starting with h is -H). A list field given as an option takes it each time (--tag a --tag b). Enums take a variant's name (--mode slow), optionals a value or nothing. After -- all are arguments.

parse_args[T] = (about: str = "") -> T

the program's command line (after its name) read into a T, as above. about: one line on what the program does, for --help

read_args[T] = (words: str[]) -> T | str

words of a command line read into a T, or what is wrong with them (parse_args without its --help, messages and exit: for tests, or a program's own handling)

args_help[T] = (program: str, about: str = "") -> str

what --help shows: the usage line, about, and each option with its default

stop.jo

Stopping a program that runs until it is stopped (a server, a tool watching something): ctrl-c in its terminal, SIGTERM (what systemd, docker stop and kill send) and, on Windows, ctrl-break or its console closed ask it to stop. A program that cleans up first watches for that:

loop not stopping():
    ...
    net.wait(1.0)              # (or sleep: either ends early when it is asked)
save()

or has an on_quit = (): ..., which runs as any program ends: its window closed, its last line done, exit() called, or asked to stop. A program that does not look at stopping() ends at its next wait (sleep, net.wait, a server's), running on_quit; one busy elsewhere, at a second ctrl-c or SIGTERM (then on_quit does not run).

With tasks (lib/std/task.jo), the sleep or net.wait of a task that has asked stopping() ends early as well, and so does a select with a stopping(): arm. The usual order: main (or the server's loop) sees stopping(), tells its tasks (closing the channels they read, or t.cancel()), waits for them, then saves. A task that goes on is told after a moment, with where it waits; a second ctrl-c ends the program.

stopping = () -> bool

true once the program has been asked to stop (ctrl-c, SIGTERM, its console closed): from the first call on, being asked no longer ends the program at once, it is for the program to stop

Terminal programs

A module (import term): the whole terminal as a screen of characters, as curses, tcell or bubbletea give it: keys (with ctrl, alt and shift), the mouse, resizes and pasted text as events, colors and styles, boxes, and a flush that writes only the cells that changed. The terminal is put back as it was however the program ends. See terminal programs and examples/files.jo.

# example: a terminal program
# an @ moved by the arrows, or put where the mouse clicks; a clock ticking in a task meanwhile
import term

x = 10
y = 5
ticks = 0

show = ():
    w, h = term.size()
    term.clear()
    term.box(0, 0, w, h - 1, fg = term.CYAN, lines = .rounded, title = "arrows or the mouse move it, q quits")
    term.put(x, y, "@", fg = term.YELLOW, style = term.BOLD)
    x2 = term.put(0, h - 1, "at {x}, {y}  ", fg = term.GRAY)
    term.put(x2, h - 1, "{ticks / 10}.{ticks % 10} s", fg = term.color(rgb(1, 0.5, 0)))
    term.flush()

# (a task: it runs while main waits for a key)
clock = ():
    loop:
        sleep(0.1)
        ticks += 1
        show()

main = () -> int:
    global x, y
    if not term.start(mouse = true):
        eprint("not a terminal")
        return 1
    spawn(clock, background = true)
    loop:
        show()
        e = term.read_event() ?? break
        if e.kind == .mouse and e.mouse == .press:
            x = e.x
            y = e.y
        match e.name:
            "q", "escape": break
            "left": x -= 1
            "right": x += 1
            "up": y -= 1
            "down": y += 1
    0

Run it in the playground

term.jo

Terminal programs: the whole terminal as a screen of characters, drawn into and shown (a file browser, an editor, a game in the terminal), as curses, tcell or bubbletea do. import term:

term.start()                            # keys one at a time, a screen of the program's own
loop:
    term.clear()
    term.box(0, 0, 30, 5, title = "hello")
    term.put(2, 2, "q quits", fg = term.YELLOW, style = term.BOLD)
    term.flush()                        # what changed since the last flush, in one write
    if let e = term.read_event():       # a key, the mouse, a resize, text pasted
        if e.name == "q" or e.name == "escape": break

Drawing goes into a screen of cells (a character, its colors and style) that flush compares with what the terminal shows, writing only the cells that changed. Characters of East Asian scripts and emoji take two cells. Columns (x) and rows (y) count from 0 at the top left.

The terminal is put back as it was (its screen, the cursor, keys echoed and read by line) by term.stop(), and as the program ends whichever way: its end, exit(), a panic or a crash, ctrl-c, SIGTERM or the terminal closed. Ctrl-c asks the program to stop as it does elsewhere (stopping() and on_quit, lib/std/stop.jo): a program that does not look ends at its next read_event, flush or sleep. start(ctrl_c_key = true) makes ctrl-c a key the program reads ("ctrl+c") instead. Ctrl-z and ctrl-\ are keys too.

In a program with tasks, a task waiting in read_event lets the others run (on Windows it looks for input every 10 ms meanwhile). Windows: keys, the mouse and resizes come from the console's events (paste comes as keys typed); a web page has no terminal (start gives false).

Colors and styles

const DEFAULT = 0

Colors are numbers: DEFAULT is the terminal's own, the 16 named ones follow the terminal's theme, color(n) is one of the 256 of xterm's palette, and color(rgb(...)) any (24-bit).

const BLACK = 0x100
const RED = 0x101
const GREEN = 0x102
const YELLOW = 0x103
const BLUE = 0x104
const MAGENTA = 0x105
const CYAN = 0x106
const WHITE = 0x107
const GRAY = 0x108
const BRIGHT_RED = 0x109
const BRIGHT_GREEN = 0x10A
const BRIGHT_YELLOW = 0x10B
const BRIGHT_BLUE = 0x10C
const BRIGHT_MAGENTA = 0x10D
const BRIGHT_CYAN = 0x10E
const BRIGHT_WHITE = 0x10F
const BOLD = 1

styles, joined with |: BOLD | UNDERLINE

const DIM = 2
const ITALIC = 4
const UNDERLINE = 8
const REVERSE = 16
const STRIKE = 32
color = (n: int) -> int

one of the 256 colors of xterm's palette: 0-15 the named ones, 16-231 a 6x6x6 cube (16 + 36 r + 6 g + b), 232-255 grays

color = (c: vec4) -> int

a color of 24 bits, from one of the library's (rgb(1, 0.5, 0), hex(0xff8000), ORANGE)

Events

enum EventKind: key, mouse, resize, paste
enum Key: char, enter, tab, backspace, delete, escape, up, down, left, right, home, end, page_up, page_down, insert, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12

a key: a character typed is .char (the character in the event's text)

enum Mouse: press, release, drag, move, wheel_up, wheel_down, wheel_left, wheel_right

what the mouse did

struct Event:
    kind: EventKind
    key: Key                # a key's (.char: a character, in text)
    text = ""               # the character typed (a letter with ctrl is small: "c"), or the text pasted
    name = ""               # a key as text: "a", "A", "space", "enter", "ctrl+c", "alt+x", "shift+tab", "ctrl+up", "f5"
    ctrl = false
    alt = false
    shift = false           # (keys other than characters: a character typed with shift is that character, "A")
    mouse: Mouse            # the mouse's: what it did
    button = 0              # which button: 1 left, 2 middle, 3 right (0: none, as for a move or the wheel)
    x = 0                   # the mouse's column; resize: the new width
    y = 0                   # the mouse's row; resize: the new height

what read_event gives: a key pressed, the mouse (start(mouse = true)), the terminal resized (the screen has its new size already, and shows it all again at the next flush), or text pasted

str = (e: Event) -> str

an event as text: "key ctrl+c", "mouse press 1 at 10,3", "resize 120x40", "paste 12 bytes"

The terminal

start = (mouse: bool = false, mouse_moves: bool = false, ctrl_c_key: bool = false) -> bool

the program takes the terminal over: keys come one at a time and are not shown, its screen is one of its own (the terminal's is back as it was afterwards), the cursor hidden, pasted text one event. mouse: the mouse's presses, releases, drags and wheel come as events (mouse_moves: its moves with no button held too). ctrl_c_key: ctrl-c is a key, not a request to stop. False when standard input or output is not a terminal (a pipe, a file); true if started already

stop = ()

the terminal put back as it was before start (its screen, the cursor, its settings); start takes it over again (around run_program(..., show = true) of an editor, say)

size = () -> (int, int)

the screen's size: its columns and rows (the terminal's, from start on; 80 x 24 before)

set_size = (w: int, h: int)

the screen's size in cells, which start and a resize set: for tests without a terminal. What is drawn stays where it fits, and the next flush shows it all

set_title = (s: str)

the terminal window's title

Reading events

read_event = (wait: f64 = -1.0) -> Event?

the next key pressed, mouse event, resize or paste, waiting at most wait seconds for it (below 0: until one comes). none: none came in that time, the task waiting was cancelled, the terminal was closed, or the program has been asked to stop (ctrl-c: once, for a program that looks at stopping()). A lone escape is told from a key's sequence by 50 ms with nothing after it

decode = (b: u8[]) -> Event[]

the events in a terminal's input bytes, as read_event makes them (an escape at the end is the key): for tests, and for a terminal's bytes from elsewhere

The screen

clear = (fg: int = 0, bg: int = 0)

every cell blank, in the colors given (bg: the background all over)

put = (x: int, y: int, text: str, fg: int = 0, bg: int = 0, style: int = 0) -> int

write text at column x of row y, going right; what is off the screen is left out (x may be below 0). The column after it: put(put(x, y, "name: "), y, name, fg = CYAN)

fill_rect = (x: int, y: int, w: int, h: int, ch: str = " ", fg: int = 0, bg: int = 0, style: int = 0)

fill a rectangle with a character (a space: the background color alone)

enum Lines: single, double, rounded, heavy

the lines a box is drawn with

box = (x: int, y: int, w: int, h: int, fg: int = 0, bg: int = 0, style: int = 0, lines: Lines = .single, title: str = "")

a box's outline, with lines drawing characters: w columns wide, h rows high (the inside is left as it is: fill_rect for a background). title: written on its top line

hline = (x: int, y: int, w: int, fg: int = 0, bg: int = 0, style: int = 0, ch: str = "─")

a line across, w columns long, from x (ch: what it is drawn with)

vline = (x: int, y: int, h: int, fg: int = 0, bg: int = 0, style: int = 0, ch: str = "│")

a line down, h rows long, from y

text_width = (text: str) -> int

how many columns text takes (two for a wide character, none for a mark on the one before)

fit = (text: str, width: int) -> str

text cut to fit width columns (with … at its end when it is cut)

set_cursor = (x: int, y: int)

show the cursor at column x of row y after each flush (where the user types)

hide_cursor = ()

no cursor shown (as from start on)

redraw = ()

the next flush shows every cell, not only those changed (after something else wrote to the terminal: a program run, a message)

flush = () -> int

show what was drawn: the cells changed since the last flush, written in one go with the cursor moved as little as it can be. How many bytes were written (none while stopped)

render = () -> str

what flush would write now, as text, the screen then counting it as shown: for tests without a terminal

screen_text = () -> str

the screen's characters, a line for each row (colors and styles left out): for tests

JSON, CSV, URLs, base64 and SHA-256

to_json(value) and from_json[T](text) turn any value (a struct, an array, a map...) into JSON and back; parse_json reads JSON of any shape as a Json to look inside.

# example: JSON, CSV, URLs, base64 and SHA-256
struct Monster:
    name = ""
    hp = 0
    drops: str[]

# a struct (or any value) to JSON and back
m = Monster("slime", 12, ["gel", "coin"])
text = to_json(m)
print(text)
back = from_json[Monster](text)
if back is Monster: print(back.name, back.hp)

# JSON of any shape: parse it and look inside
r = parse_json(r'{"name": "bat", "drops": ["wing"]}')
if r is Json:
    j: Json? = r
    print(j.get("name").as_str() ?? "?", j.get("drops").get(0).as_str() ?? "?")

# CSV: rows of fields
rows = csv_rows("name,hp\nslime,12\n\"big, bad bat\",40\n")
loop row in rows[1..]: print(row[0], to_int(row[1]) ?? 0)
print(trim(to_csv([["a", "b, c"]])))

# a URL's query, and text from a web page
print("https://example.com/search?" + url_query({"q": "café au lait", "page": "2"}))
print(html_unescape("Tom &amp; Jerry &mdash; &eacute;t&eacute;"))

code = base64_encode(bytes("hello"))
print(code, str_from_bytes(base64_decode(code) ?? []))
print(sha256("hello"))                   # a fingerprint, as sha256sum gives

Run it in the playground

json.jo

JSON: parse_json reads text into a Json value (or a JsonError saying where it is wrong), and to_json writes one. Reading: get (a field or list element) and the as_* functions all take a Json? and give an optional, so they chain, and a missing piece anywhere gives none:

j = parse_json(text)
if j is JsonError: return j
width = j.get("width").as_int() ?? 0
name = j.get("layers").get(0).get("name").as_str() ?? "?"
loop l in j.get("layers").as_list(): print(l.get("name").as_str() ?? "")

For JSON straight into your own structs and back, from_jsonConfig and to_json(value) are in "Saving, and values as text" (they give a TextError, with the same message, line, column). JSON has no infinity or NaN: to_json writes them as null, as JavaScript's JSON.stringify does (from_json reads null into a float as NaN), and the words Infinity, -Infinity and NaN that Python's json writes are read too. Its text is UTF-8: a byte in a string that is not is a mistake where it is, and to_json writes such bytes as U+FFFD, so what it writes always is.

enum Json: null_, boolean(b: bool), integer(i: int), number(n: f64), text(s: str), list(items: Json[]), object(keys: str[], values: Json[])

a whole number in the text is an integer, kept exactly as written while it fits in an int; any other is a number (as_float and as_int read both). print shows a Json as JSON text

error struct JsonError:
    message: str
    line: int
    column: int
parse_json = (s: str) -> Json | JsonError

Reading

get = (j: Json?, key: str) -> Json?

an object's field

get = (j: Json?, i: int) -> Json?

a list's zero-based element, or none for a negative/out-of-range index or non-list

as_float = (j: Json?) -> f64?

a floating number (integer variants convert to f64 too), or none for a non-number

as_int = (j: Json?) -> int?

the whole part of a finite number in the int range, or none. Fractions truncate toward zero; typed from_json[int] instead rejects fractional numbers. Integer variants stay exact.

as_str = (j: Json?) -> str?
as_bool = (j: Json?) -> bool?
as_list = (j: Json?) -> Json[]

list items, or [] for a non-list; inspect the Json variant to distinguish empty from missing

keys = (j: Json?) -> str[]

an object's field names, in order object keys, or [] for a non-object; inspect the variant if empty versus missing matters

is_null = (j: Json?) -> bool

Changing

put = (j: mut Json, key: str, value: Json)

put or replace an object's field (a primitive value is made a Json where a Json goes)

put = (j: mut Json, i: int, value: Json)

replace an existing list element

push = (j: mut Json, value: Json)

append to a Json list

remove = (j: mut Json, key: str) -> bool

remove an object's field; false when it was absent (wrong kind: an error)

set_path = (j: mut Json, path: Json, value: Json)

change a nested field/element: each path part is a string (object key) or integer (list index). Intermediate containers must exist; the last object field may be new. No indexing syntax is needed: j.set_path(["user", "age"], 32), j.push_path(["user", "tags"], "new"). An empty path means j itself.

push_path = (j: mut Json, path: Json, value: Json)

append to a list at a nested path

remove_path = (j: mut Json, path: Json) -> bool

remove an object field at a nested path (an empty path is an error)

Writing

to_json = (j: Json, indent: int = 0) -> str

JSON text for a value (indent > 0: on several lines, indented by that many spaces)

to_json[T] = (x: T, indent: int = 0) -> str

any value as JSON: a struct as an object (by field name: one ending in , as when, without it), an array, tuple or vector as a list, a map as an object (its keys as text), none as null, an enum's variant as its name (one with fields as {"name": [fields]}), and a Json inside it as itself; from_json[T] reads it back. NaN and the infinities are null (JSON has none)

json_value = (j: Json) -> Json

any value as a Json (what to_json writes for it) (a Json as it is: in a Json literal, {"user": j})

json_value[T] = (x: T) -> Json

csv.jo

CSV: rows of fields separated by commas (or another separator), as spreadsheets save them. A field in double quotes may hold the separator, line breaks and "" for a quote.

rows = csv_rows(read_file("sales.csv").unwrap())
loop row in rows[1..]: total += to_float(row[2]) ?? 0.0      # (rows[0]: the header)

Or each row as a struct, its fields found by the header's names:

struct Sale:
    date = ""
    region = ""
    price = 0.0          # (a number: checked; empty or NA is NaN)
    units = 0
    discount: f64? = none   # (empty or NA: none)
sales = from_csv[Sale](read_file("sales.csv").unwrap())
if sales is TextError:
    eprint(sales.message)
    exit(1)
csv_rows = (text: str, sep: u8 = ',') -> str[][]

the rows of a CSV text, each the list of its fields (a header is the first row, like the others)

to_csv = (rows: str[][], sep: u8 = ',') -> str

CSV text of the rows: a field with the separator, a quote or a line break is put in quotes

from_csv[T] = (text: str, sep: u8 = ',') -> T[] | TextError

the rows of a CSV text with a header, each as a T: a column goes to the field of its name ("Unit Price" to unit_price; others are skipped), a field with no column keeps its default. A number is checked (a TextError says the row, after the header, and column where one is not); an empty one, or NA, is NaN in an f64 and none in an optional

url.jo

Text for the web: URLs taken apart and links followed from a page, a URL's parts percent-encoded and back, query strings, cookies, and HTML's entities.

url = "https://api.example.com/search?" + url_query({"q": "café au lait", "page": "2"})
name = url_decode("caf%C3%A9")                        # café
u = parse_url("https://example.com:8080/a/b?q=1")?   # u.host "example.com", u.port 8080
next = url_join("https://example.com/a/b/page.html", "../c.html")   # https://example.com/a/c.html
title = html_unescape("Tom &amp; Jerry &#8212; &lt;b&gt;")  # Tom & Jerry — <b>
url_encode = (s: str, safe: str = "") -> str

text as a part of a URL (a query's value, a path's segment): every byte but letters, digits and - _ . ~ as %XX (a space as %20, é as %C3%A9), as Python's quote(s, safe="") writes it; the characters in safe are kept too: url_encode("/a b/c", safe = "/") is "/a%20b/c" (a path)

url_decode = (s: str, plus: bool = false) -> str

percent-encoded text back as it was: %XX as that byte (a % without two hex digits stays as it is); with plus = true a + is a space too, as an HTML form's query writes one

url_query[T] = (params: {str: T}) -> str

a query string from names and values, each url_encoded: url_query({"q": "x y", "n": "5"}) is "q=x%20y&n=5" (what goes after the ? of a URL; Python's urlencode)

parse_query = (q: str) -> {str: str}

a query string's names and values, decoded: parse_query("q=x%20y&n=5") is {"q": "x y", "n": "5"} (what comes after the ? of a URL, or an HTML form's body; a name given twice: the last)

parse_cookies = (header: str) -> {str: str}

a Cookie header's names and values: parse_cookies("a=1; b=2") is {"a": "1", "b": "2"} (a name given twice: the first, which a browser sends for the longer path or the narrower domain). A value's %XX are decoded, as http.set_cookie (and JavaScript's encodeURIComponent) write what a cookie cannot have: "caf%C3%A9%3B%20x" is "café; x"

struct Url:
    scheme = ""
    user = ""                   # (before an @: a name, or name:password)
    host = ""
    port = -1
    path = ""
    query = ""                  # (after the ?, without it: parse_query(u.query) for its values)
    fragment = ""               # (after the #, without it)

a URL taken apart (parse_url), each part as written (its %XX kept: url_decode(u.path) for the text): https://ann@example.com:8080/a/b?q=1#top has scheme "https", user "ann", host "example.com", port 8080, path "/a/b", query "q=1" and fragment "top". The scheme and host are in small letters; an IPv6 host is without its [ ]. A part not written is "" (the port: -1). str(u) puts it back together.

error struct UrlError:
    message: str
parse_url = (s: str) -> Url | UrlError

a URL's parts, or what is wrong with it (a port that is not a number or is over 65535, a [ without its ], a control character such as a line break in it). Spaces and line breaks around it are left out. A URL with no scheme is a relative one ("/a/b?q=1", "../c": scheme and host "")

url_join = (base: str, link: str) -> str

a link (an href, a redirect's Location) as the URL it leads to from the page at base: "../c?x" from https://example.com/a/b/page.html is https://example.com/a/c?x. As RFC 3986 says (section 5.2: ./ and ../ taken out, a path from / on the same host, //host on the same scheme, a ?query or a #fragment on the same page), as Python's urljoin and Go's ResolveReference do. A link with its own scheme ("mailto:...", "https://...") is the link itself (with its ./ and ../ out); spaces and line breaks around it, and tabs and line breaks inside it (as in HTML written over lines), are left out.

html_unescape = (s: str) -> str

HTML's entities as the characters they stand for: &amp; &lt; &gt; &quot; &#39; &nbsp;, the other named ones of Latin-1 and punctuation (&eacute; &copy; &mdash; &hellip; &euro;...), and numbers (&#233; &#xE9;); one it does not know stays as it is

html_escape = (s: str) -> str

text with & < > " ' as entities, to put inside HTML

base64.jo

Base64: bytes as text (A-Z a-z 0-9 + /, padded with =), and back.

base64_encode = (b: u8[]) -> str
base64_decode = (s: str) -> u8[]?

the bytes, or none if s is not base64 (spaces and line breaks in it are skipped)

hash.jo

SHA-256: a file's or a text's fingerprint, as 64 hex digits (the same as sha256sum prints). Two different contents practically never have the same one: to check a download, or to know whether a file changed since it was last built.

sha256 = (b: u8[]) -> str

the SHA-256 of these bytes, as 64 lowercase hex digits

sha256 = (s: str) -> str

the SHA-256 of a text's UTF-8 bytes: sha256("abc") is ba7816bf...

Bytes and bits

Whole numbers in byte arrays in either byte order (file formats, network messages), counting and turning bits, and bytes from C. A float's bits: f64_bits and f64_from_bits (math).

# example: bytes
# a WAV file's header, written and read back
n = 1000
h: u8[]
loop c in "RIFF": h.push(c)
append_le(h, 36 + n * 2, 4)
loop c in "WAVEfmt ": h.push(c)
append_le(h, 16, 4)
append_le(h, 1, 2)                       # PCM
append_le(h, 1, 2)                       # one channel
append_le(h, 44100, 4)
print(h.len(), get_le(h, 4, 4), get_le(h, 24, 4))
print(popcount(0b1011), leading_zeros(1), trailing_zeros(8), byte_swap(0x1234, 2) == 0x3412)

Run it in the playground

bytes.jo

Bytes and bits: whole numbers in byte arrays (file formats, network messages) in little- or big-endian order, bit counting and turning, and bytes from C.

header: u8[]
append_le(header, 0x46464952, 4)              # "RIFF"
append_le(header, 36 + n, 4)
size = get_le(file, 4, 4)                     # 4 bytes at offset 4, little-endian
rate = get_be(packet, 0, 2)
rate_f = f32_from_bits(u32(get_le(file, 8, 4)))   # a float's bytes

Sizes are 1 to 8 bytes (3 for a 24-bit field); get_le and get_be give the bytes as an unsigned number (8 bytes: its bits as an int), get_le_signed and get_be_signed with their sign. A float's bits are a u64 (f64_bits) and these take an int: append_le(b, int(f64_bits(x)), 8), and back f64_from_bits(u64(get_le(b, at, 8))); plain_bytes(xs) and array_from_bytesf64 do a whole array.

get_le = (b: u8[], at: int, size: int) -> int

the size-byte number at b[at..], least significant byte first

get_be = (b: u8[], at: int, size: int) -> int

the size-byte number at b[at..], most significant byte first (network order)

get_le_signed = (b: u8[], at: int, size: int) -> int
get_be_signed = (b: u8[], at: int, size: int) -> int
put_le = (b: mut u8[], at: int, size: int, v: int)

v as size bytes at b[at..] (b grows to hold them), least or most significant byte first

put_be = (b: mut u8[], at: int, size: int, v: int)
append_le = (b: mut u8[], v: int, size: int)

v as size bytes at the end of b

append_be = (b: mut u8[], v: int, size: int)

Bits

popcount = (x: int) -> int

how many bits are 1

leading_zeros = (x: int) -> int

how many 0 bits come before the highest 1 (64 for 0)

trailing_zeros = (x: int) -> int

how many 0 bits come after the lowest 1 (64 for 0)

rotate_left = (x: int, n: int) -> int

the bits turned by n places (those going out at one end come back at the other)

rotate_right = (x: int, n: int) -> int
popcount = (x: u8) -> int

(each of the above for a number of each size, counting and turning its own bits: a u32's 32)

leading_zeros = (x: u8) -> int
trailing_zeros = (x: u8) -> int
rotate_left = (x: u8, n: int) -> u8
rotate_right = (x: u8, n: int) -> u8
popcount = (x: u16) -> int
leading_zeros = (x: u16) -> int
trailing_zeros = (x: u16) -> int
rotate_left = (x: u16, n: int) -> u16
rotate_right = (x: u16, n: int) -> u16
popcount = (x: u32) -> int
leading_zeros = (x: u32) -> int
trailing_zeros = (x: u32) -> int
rotate_left = (x: u32, n: int) -> u32
rotate_right = (x: u32, n: int) -> u32
popcount = (x: u64) -> int
leading_zeros = (x: u64) -> int
trailing_zeros = (x: u64) -> int
rotate_left = (x: u64, n: int) -> u64
rotate_right = (x: u64, n: int) -> u64
popcount = (x: i8) -> int
leading_zeros = (x: i8) -> int
trailing_zeros = (x: i8) -> int
rotate_left = (x: i8, n: int) -> i8
rotate_right = (x: i8, n: int) -> i8
popcount = (x: i16) -> int
leading_zeros = (x: i16) -> int
trailing_zeros = (x: i16) -> int
rotate_left = (x: i16, n: int) -> i16
rotate_right = (x: i16, n: int) -> i16
popcount = (x: i32) -> int
leading_zeros = (x: i32) -> int
trailing_zeros = (x: i32) -> int
rotate_left = (x: i32, n: int) -> i32
rotate_right = (x: i32, n: int) -> i32
byte_swap = (x: int, size: int = 8) -> int

the bytes of a size-byte number in the other order (0x1234, 2 -> 0x3412)

Plain values

plain_bytes[T] = (x: T) -> u8[]

a plain value's bytes as it is in memory (numbers, bools, vectors, fixed-size arrays and structs of them; no str or T[]): a machine's state saved in one go, write_bytes(path, plain_bytes(cpu)). They are this program's layout of the type, on a little-endian machine (every one Sloppy runs on): for reading back with plain_from_bytes, not a file format for other programs

plain_from_bytes[T] = (b: u8[]) -> T?

the plain value whose bytes are b (from plain_bytes): plain_from_bytes[Cpu](read_bytes(path).unwrap()); none when b is not the size of a T

plain_bytes[T] = (xs: T[]) -> u8[]

an array of plain values: its elements' bytes one after another (n f64s are 8n bytes, as in a C array and NumPy's tobytes): write_bytes(path, plain_bytes(weights))

array_from_bytes[T] = (b: u8[]) -> T[]?

the array whose elements' bytes are b (from plain_bytes): array_from_bytes[f64](read_bytes(path).unwrap()); none when b is not a whole number of them

From C

bytes_from = (p: *u8, n: int) -> u8[]

a copy of the n bytes at p

str_from_c = (p: *u8) -> str

a copy of C's text at p, up to its zero byte ("" for null)

Saving, and values as text

save_value and load_value keep any value (settings, a saved game) as text that reads back even after its structs gain or lose fields. to_bytes and from_bytes do the same in a smaller, quicker binary form, and byte_writer / byte_reader a few milliseconds at a time.

# example: saving
# (a place of the program's own: a folder for the user on the desktop, the page's storage on the web)
struct Settings:
    volume = 0.8
    fullscreen = false
    keys: {str: int} = {"jump": 32}
    best_times: f64[]

settings = load_value("settings", Settings())      # (the defaults the first time)
settings.best_times.push(42.5)
save_value("settings", settings)
print(to_text(settings))

runs = to_int(load_data("runs") ?? "0") ?? 0        # (plain text works too)
save_data("runs", "{runs + 1}")

Run it in the playground

save.jo

Data a program keeps between runs: saved games, settings, high scores.

save_data("progress", "{level}\n{coins}")
if let s = load_data("progress"): ...

Each program has its own place, named after it (PROGRAM_NAME: the build block's name, else the main file's name): on Linux ~/.local/share/<name>/ (or $XDG_DATA_HOME), on Windows %APPDATA%\<name>\, on macOS ~/Library/Application Support/<name>/, in a web page the browser's storage for the page (it survives reloads and restarts of the browser). SLOPPY_SAVE_DIR=/tmp/x puts it in /tmp/x/<name>/ instead (tests). For a file the player names (an editor's levels), write the text yourself: write_file(path, to_text(level)) and from_text[Level](read_file(path).unwrap()).

save_dir = () -> str

the directory a program's data goes to (made when first written; "" in a web page)

save_data = (name: str, contents: str) -> bool

keep contents under name (a file name, as Windows allows them: no / \ : * ? " < > |); false if it could not be written (file_error() says why)

load_data = (name: str) -> str?

what was kept under name; none if nothing was

delete_data = (name: str) -> bool

forget what was kept under name (a saved game, at the player's death); false if nothing was

text.jo

Values as text and back, for saved games and settings. to_text(value) writes a value the way print shows one inside a list (strings in quotes):

Settings(volume=0.8, keys={"jump": 32}, mode=hard, pos=vec2(1.5, 2.0), best=none)

from_textT reads such text back as a T, or says where it is not one (a TextError). Fields go by name, in any order: one the text leaves out keeps its default value, and one the struct does not have (any more) is skipped, so what an older version of a program wrote still reads after its structs change.

save_value("settings", settings)
settings = load_value("settings", Settings())     # (the default when there is none yet)

Numbers, bool, str, arrays (T[] and T[N]), maps, optionals, tuples, structs, enums (with fields too), unions and vectors can be read; function values and pointers cannot.

error struct TextError:
    message: str
    line: int
    column: int
    path = ""       # where in the value: items[2].count (the message names it too)
to_text[T] = (x: T) -> str
from_text[T] = (text: str) -> T | TextError
from_json[T] = (text: str) -> T | TextError

a value of type T from JSON: objects for structs (by field name: a field left out keeps its default, one the struct does not have is skipped) and maps, lists for arrays, tuples and vectors, null for none, an enum's variant by its name in quotes. A field whose name ends in _ is the name without it in JSON: when_: str is "when" (a keyword, which a field cannot be). A float reads null as NaN (to_json writes NaN and the infinities so), and Infinity and NaN as Python's json writes them; a string with bytes that are not UTF-8 is a TextError

save_value[T] = (name: str, x: T) -> bool

keep value under name (save_data) as text; false if it could not be written

load_value[T] = (name: str, default: T) -> T

the value kept under name, or default if there is none or it does not read as one (said on stderr then, and what was kept is copied to name + ".bad" first: the next save_value over it does not lose it)

Each type

error struct ParseError:
    message: str
    start: int
    end: int

a whole-number scan failure; start/end are the offending span's half-open byte offsets

ints = (text: str) -> int[] | ParseError

every whole number in the text, in order: each run of digits, negative when a - is right before it (ints("x=3,y=-4") is [3, -4], ints("1-3 a") is [1, -3]); in one pass, without splitting. A number too big for an int returns ParseError, including its byte span

binary.jo

Values as bytes and back: what to_text and from_text do, in a compact binary form that is quicker to write and read (a saved game, a message):

b = to_bytes(world)                      # u8[]
w = from_bytes[World](b)                 # World | TextError

The bytes start with a schema: each struct and enum type the value's type uses, once, with its fields' names and kinds. Then the value, field after field in that order: so fields go by name, as from_text's do. A field the bytes have that the struct no longer has is skipped, one the struct has that the bytes lack keeps its default, and a field whose kind changed (a str that is an int now) is a TextError naming it; an enum's variants go by name too. The same value gives the same bytes (a map's entries in its own order), to hash or compare.

A big value can be written or read a few milliseconds at a time (a frame's spare time):

w = byte_writer(world)                   # (kept in a mut place: a global, a field)
loop not w.step(0.003): next_frame()     # true when done; w.progress() is 0 to 1
b = w.result()                           # the same bytes as to_bytes(world)

r = byte_reader[World](b)
loop not r.step(0.003): next_frame()
loaded = r.result()                      # World | TextError, as from_bytes

A step stops between array elements, map entries and struct fields; one string, packed array of numbers or flat struct (no arrays or maps inside) is done whole, as are a tuple's elements, an enum variant's fields, a map's keys, a soa array and (reading) a field skipped. Function values and pointers cannot be written. Numbers, bool, str, arrays (T[] and T[N]), maps, optionals, tuples, structs, enums (with fields too), unions and vectors can (from_bytes's T is not an optional itself, as from_text's is not: an optional inside a struct or an array is).

The format: "SLPB", 1 (the version), the schema, then the value. Whole numbers are varints (zigzag for signed ones; i8, u8 and u64 as they are), floats their 4 or 8 bytes, a str and an array their length and then their contents (an array of fixed-size numbers, bools or vectors packed: its elements' bytes as they are in memory, little-endian), a T[N] its N elements, an optional 0 or 1 and then its value, an enum its variant's number and then its fields, a union its member's number and then its value, a map its count and its keys and values in turn.

Writing

struct ByteWriter

a value being written a step at a time (byte_writer)

to_bytes[T] = (x: T) -> u8[]

the value's bytes, read back with from_bytes

byte_writer[T] = (x: T) -> ByteWriter

a ByteWriter for x: step it until it is done, then its result is to_bytes(x). It keeps a copy of x (arrays and maps are shared, not copied): x may change meanwhile

step = (w: mut ByteWriter, seconds: f64) -> bool

go on for about this many seconds; true when done

progress = (w: ByteWriter) -> f64

how far it is, 0 to 1 (by the elements of the arrays and maps being written)

result = (w: mut ByteWriter) -> u8[]

the bytes (to_bytes's); if step has not said done yet, the rest of the work is done first

Reading

from_bytes[T] = (b: u8[]) -> T | TextError

the value of type T in b (to_bytes's), or where it is not one

struct ByteReader[T]

a value being read a step at a time (byte_reader)

byte_reader[T] = (b: u8[]) -> ByteReader[T]

a ByteReader for the bytes b: step it until it is done, then its result is from_bytesT

step[T] = (br: mut ByteReader[T], seconds: f64) -> bool

go on for about this many seconds; true when done

progress[T] = (br: ByteReader[T]) -> f64

how far it is, 0 to 1 (by the bytes read)

result[T] = (br: mut ByteReader[T]) -> T | TextError

the value (from_bytes's); if step has not said done yet, the rest of the work is done first

Pools and handles

Pool[T] holds things that come and go (enemies, bullets), each found again by its Handle, which stays its own while others are removed (an array's index does not) and says so once its thing is gone.

# example: pool
# (homing shots that keep their target: each enemy is found again by its handle, while others
# are shot down and removed; click to fire)
struct Enemy:
    pos: vec2
    hp = 3
struct Shot:
    pos: vec2
    target: Handle
enemies: Pool[Enemy]
shots: Shot[]
loop i in 0..6: enemies.add(Enemy(vec2(f32(200 + i * 160), 120)))

update = (dt: f64):
    if mouse_pressed(.left) and enemies.len() > 0:
        shots.push(Shot(vec2(640, 680), enemies.handles[random_int(0, enemies.len())]))
    loop mut s in shots:
        if not enemies.has(s.target): continue
        to = enemies[s.target].pos - s.pos
        if length(to) < 12.0:
            enemies[s.target].hp -= 1
            s.target = Handle()
        else: s.pos += normalize(to) * f32(500.0 * dt)
    shots.retain((s): enemies.has(s.target))
    enemies.retain((e): e.hp > 0)

draw = ():
    clear()
    loop e in enemies.items: circle(e.pos, 10.0 + f64(e.hp) * 4.0, RED)
    loop s in shots: circle(s.pos, 4, YELLOW)

Run it in the playground

pool.jo

Things that come and go (enemies, bullets, units), each found again by a Handle: an index into an array points at another thing once things before it are removed, a handle stays its own, and says so once its thing is gone. The things themselves are an ordinary array, items, in no particular order, to loop over as any.

enemies: Pool[Enemy]
h = enemies.add(Enemy(pos))
bullet.target = h                     # (a homing bullet keeps its enemy)
if enemies.has(bullet.target): aim = enemies[bullet.target].pos
enemies[h].hp -= 10
loop mut e in enemies.items: e.pos += e.vel * dt
enemies.retain((e): e.hp > 0)         # (handles to those gone: has(h) is false)
struct Handle:
    slot = -1
    gen = 0

a thing's handle in a Pool (Handle() is none: has(h) false)

struct Pool[T]:
    items: T[]                  # the things, in no particular order
    handles: Handle[]           # items[i]'s handle
add[T] = (p: mut Pool[T], x: T) -> Handle

add x: its handle

has[T] = (p: Pool[T], h: Handle) -> bool

whether h's thing is still there

index_of[T] = (p: Pool[T], h: Handle) -> int

the index of h's thing in items now (-1 when it is gone)

([])[T] = (p: Pool[T], h: Handle) -> T

h's thing (panics when it is gone: has(h) first, or get)

([]=)[T] = (p: mut Pool[T], h: Handle, x: T)
get[T] = (p: Pool[T], h: Handle) -> T?

h's thing, or none when it is gone

remove[T] = (p: mut Pool[T], h: Handle) -> bool

take h's thing out (false when it was gone already); the last thing moves into its place in items

retain[T] = (p: mut Pool[T], keep: (T) -> bool)

keep the things keep says yes to; the others' handles are gone

len[T] = (p: Pool[T]) -> int
clear[T] = (p: mut Pool[T])

everything out (every handle gone)

Sets and deques

Set[T] holds values without repeats (x in s asks in about the same time however many it holds); Deque[T] is a queue with two ends, pushed and popped at either in the same short time: a breadth-first search's frontier.

# example: sets
# the rooms one can walk to from the hall, nearest first: a breadth-first search with a Deque
# as its frontier and a Set of the rooms seen
doors = {"hall": ["kitchen", "stairs"], "kitchen": ["pantry", "hall"], "stairs": ["attic", "hall"],
    "pantry": [], "attic": ["roof"], "roof": []}
seen = set(["hall"])
frontier: Deque[(str, int)]
frontier.push(("hall", 0))
loop frontier.len() > 0:
    room, steps = frontier.pop_front()
    print("{room}: {steps} doors away")
    loop next in doors[room]:
        if seen.add(next): frontier.push((next, steps + 1))
upstairs = set(["stairs", "attic", "roof"])
print(seen.difference(upstairs), "roof" in seen, seen.len())

Run it in the playground

set.jo

A set: values without repeats, kept in the order they were first added, asked about in about the same time however many it holds (a map from each to nothing, underneath).

seen: Set[int]                      # (or seen: Set[int] = {}, empty)
seen.add(start)
vowels = {"a", "e", "i", "o", "u"}  # the values written; {loop w in ws: w.lower()} too
if next in seen: print("already visited")   # x in s, or s.contains(x)
words = set(split(text, " "))       # the different words
loop w in words: print(w)
both = a.intersection(b)            # also union, difference, is_subset

Sets compare with == by what they hold, in any order, and print as {1, 2, 3}.

struct Set[T]
set[T] = (xs: T[]) -> Set[T]

a set of the values in xs (each once)

add[T] = (s: mut Set[T], x: T) -> bool

put x in; true when it was not there yet (if seen.add(v): queue.push(v))

remove[T] = (s: mut Set[T], x: T) -> bool

take x out; true when it was there

contains[T] = (s: Set[T], x: T) -> bool

(x in s)

len[T] = (s: Set[T]) -> int
is_empty[T] = (s: Set[T]) -> bool
clear[T] = (s: mut Set[T])
items[T] = (s: Set[T]) -> T[]

the values, in the order they were added (a loop over the set goes over these)

union[T] = (a: Set[T], b: Set[T]) -> Set[T]

what is in a, in b, or in both

intersection[T] = (a: Set[T], b: Set[T]) -> Set[T]

what is in both a and b

difference[T] = (a: Set[T], b: Set[T]) -> Set[T]

what is in a and not in b

is_subset[T] = (a: Set[T], b: Set[T]) -> bool

whether everything in a is in b

(==)[T] = (a: Set[T], b: Set[T]) -> bool

the same values, in any order

hash[T] = (s: Set[T]) -> u64

a number made from the values, in any order: sets that are == hash alike (so a set can be a key)

deque.jo

A double-ended queue: values pushed and popped at either end in the same short time, however many it holds (an array's insert(0, x) and remove(0) move all the others). A breadth-first search's frontier, a sliding window, an undo list with a limit.

q: Deque[int]
q.push(start)                       # at the back
loop q.len() > 0:
    v = q.pop_front()               # the oldest
    q.push(next)
q.push_front(x)                     # at the front; q.pop() takes from the back
print(q.first(), q.last(), q[i])           # (i from the front)

A loop over a deque goes from front to back; it prints as an array does.

struct Deque[T]
len[T] = (d: Deque[T]) -> int
is_empty[T] = (d: Deque[T]) -> bool
push[T] = (d: mut Deque[T], x: T)

put x at the back

push_front[T] = (d: mut Deque[T], x: T)

put x at the front

pop[T] = (d: mut Deque[T]) -> T

take the value at the back out (the deque must not be empty)

pop_front[T] = (d: mut Deque[T]) -> T

take the value at the front out (the deque must not be empty)

first[T] = (d: Deque[T]) -> T

the value at the front, and at the back (the deque must not be empty)

last[T] = (d: Deque[T]) -> T
([])[T] = (d: Deque[T], i: int) -> T

the i-th value from the front

([]=)[T] = (d: mut Deque[T], i: int, x: T)
clear[T] = (d: mut Deque[T])
items[T] = (d: Deque[T]) -> T[]

the values from front to back, in an array (a loop over the deque goes over these)

(==)[T] = (a: Deque[T], b: Deque[T]) -> bool

the same values in the same order

hash[T] = (d: Deque[T]) -> u64

a number made from the values, in order: deques that are == hash alike (so a deque can be a key)

Priority queues

Heap[T] gives back what it holds smallest priority first: A*'s open list, events by time. heap_push and heap_pop keep a plain array as a heap of values that order themselves, as Python's heapq does.

# example: heap
# the shortest way across a small map (Dijkstra): the open list is a Heap, cheapest first
map = ["S..#....", ".#.#.##.", ".#...#..", ".####.#.", "......#E"]
w = len(map[0])
cost: {int: f64} = {}
open: Heap[int]
open.push(0, 0.0)
cost[0] = 0.0
loop open.len() > 0:
    c = open.pop()
    x = c % w
    y = c / w
    if map[y][x] == 'E':
        print("E reached in {cost[c]} steps")
        break
    loop d in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        nx = x + d.0
        ny = y + d.1
        if nx < 0 or ny < 0 or nx >= w or ny >= map.len() or map[ny][nx] == '#': continue
        n = ny * w + nx
        if cost.contains(n) and cost[n] <= cost[c] + 1.0: continue
        cost[n] = cost[c] + 1.0
        open.push(n, cost[n])

Run it in the playground

heap.jo

A priority queue: values taken out smallest priority first, as A*'s open list or events by time. Pushing and popping take time in proportion to the log of how many it holds.

open: Heap[int]
open.push(start, 0.0)
loop open.len() > 0:
    c, d = open.pop_with_priority()    # the one with the least priority, and that priority
    open.push(next, d + cost)

Priorities are f64s, or ints: an int priority keeps its order exactly, past 2^53 too, where f64s of neighboring ints are equal (pop_with_int_priority gives one back exactly). (largest first: push with -priority.) Values that order themselves, as Python's heapq keeps them, need no Heap: pq.heap_push((dist, node)) and pq.heap_pop() on an array keep the smallest at pq[0], tuples compared by their first element, then the next.

struct Heap[T]:
    items: T[]
    keys: f64[]
push[T] = (h: mut Heap[T], x: T, priority: f64)

put x in with this priority

push[T] = (h: mut Heap[T], x: T, priority: int)

put x in with an int priority, kept exactly (an int past 2^53 is not, as an f64)

pop[T] = (h: mut Heap[T]) -> T

take out the value with the least priority (the heap must not be empty)

pop_with_priority[T] = (h: mut Heap[T]) -> (T, f64)

take out the value with the least priority, and give that priority too (the heap must not be empty)

pop_with_int_priority[T] = (h: mut Heap[T]) -> (T, int)

take out the value with the least priority, and give that priority as an int, exactly as pushed with an int (the heap must not be empty)

peek[T] = (h: Heap[T]) -> T

the value pop would take out (the heap must not be empty)

peek_priority[T] = (h: Heap[T]) -> f64

the least priority, the one of the value pop would take out (the heap must not be empty)

peek_int_priority[T] = (h: Heap[T]) -> int

the least priority as an int, exactly as pushed with an int (the heap must not be empty)

len[T] = (h: Heap[T]) -> int
clear[T] = (h: mut Heap[T])

An array as a heap

heap_push[T] = (xs: mut T[], x: T)

put x in the array kept as a heap

heapify[T] = (xs: mut T[])

the array made a heap in place, in time in proportion to its length (Python's heapify): heap_pop then takes out its smallest

heap_pop[T] = (xs: mut T[]) -> T

take the smallest value out of the array kept as a heap (it must not be empty)

Stories and dialogue

A story's script, written as Ren'Py writes one (labels, lines, menus, variables), read into a Story the game steps through: it draws each line and choice its own way (a dialogue box, text_rich) and does each command.

# example: story
# a story's script, stepped through: a game draws each line and choice its own way
script = r"""
character m "Mira" #f4a6c6

label start:
    scene cafe
    m "You came!"
    menu:
        "Of course.":
            $ trust += 1
        "I almost didn't.":
            $ trust -= 1
    if trust > 0:
        m "Then stay a while."
    else:
        m "Oh."
"""
st = story(script)
loop true:
    step = st.next()
    if step.kind == .end: break
    if step.kind == .line: print("{step.speaker}: {step.text}")
    else if step.kind == .command: print("(the game does: {join(step.words, " ")})")
    else:
        print("choices: {step.choices}")
        st.choose(0)
print(st.vars)

Run it in the playground

story.jo

Stories: a script of dialogue, choices and what happens on screen, written as Ren'Py writes one, read into a Story that the game steps through. The game draws each line and choice its own way (a dialogue box, text_rich, portraits) and does each command (show, scene, play...).

# doccheck: illustrative story script, parsed by story() rather than the Sloppy compiler
character m "Mira" #f4a6c6

label start:
    scene cafe
    show mira happy
    "The bell rang twice."                 (narration)
    m "You came! I wasn't sure you would."
    menu:
        "Of course I came.":
            $ mira += 2
        "I almost didn't." if mira < 5:
            $ mira -= 1
            jump doubt
    if mira >= 3:
        m "Then stay a while."
    else:
        jump goodbye

Reading and displaying that script from Sloppy:

st = story(str_from_bytes(embed("story.txt")))
if len(st.error) > 0: print(st.error)
step = st.next()            # (again when the player clicks: the next line, choice or command)
match step.kind:
    .line: text("{step.speaker}: {step.text}", vec2(20, 20)) # step.who: portrait id
    .choice:
        loop i in 0.. and choice in step.choices:
            if ui_button(choice): st.choose(i); step = st.next()
    .command: print(step.words)      # handle show, scene, play, etc. here
    .end: pass                      # the story has ended

Lines: label name: (the story starts at start, else at the top), character id "Name" #color, "narration", id "dialogue", menu: with "options": (and if conditions), if, elif, else, jump label, call label and return, $ name = value (and += -=), end. Anything else is a command for the game. Variables are whole numbers (true is 1, false 0), and "[name]" in a line puts one in. A Story is a value: save_value("story", st.save()) and later st.load(load_value("story", st.save())) take up where it was, even after the script changed in other labels.

enum StoryKind: line, choice, command, end
struct StoryStep:
    kind: StoryKind
    speaker = ""        # a line's speaker ("": narration)
    who = ""            # the speaker's id, as in the script (m)
    color = ""          # the speaker's color, as written (#f4a6c6; "": none given)
    text = ""           # a line's text, with [name]s put in
    choices: str[]      # a choice's options (those whose condition holds)
    words: str[]        # a command's words

what the story does next

struct Story:
    error = ""
    vars: {str: int}

a story read from its script; error says what is wrong with it ("" if nothing)

struct StorySave:
    label = ""
    nth = 0
    stack: (str, int)[]
    vars: {str: int}

where a story is, to save and load: the place by label and statement, so it still loads after the script changes elsewhere

story = (text: str) -> Story

a story from its script (st.error: what is wrong with it, with its line)

next = (st: mut Story) -> StoryStep

what the story does next: a line to show, a choice to make (until choose), a command for the game, or the end

choose = (st: mut Story, i: int)

take option i of the choice next gave (from 0); the story goes on from there

jump = (st: mut Story, label: str) -> bool

go to a label (a chapter select, a new game)

save = (st: Story) -> StorySave

where the story is (for save_value), and back there (a StorySave from an older script finds its label's statement)

load = (st: mut Story, s: StorySave)

Charts

Line charts, scatter plots, bars and histograms with axes and a legend: drawn in a game's draw, or made into a picture with no window (chart_image, then save_png). render_image draws any picture that way.

# example: charts
# a line chart and a histogram, made into pictures (save_png("sales.png", img) keeps one)
r = rng(1)
days = [loop i in 0..60: f64(i)]
sales = [loop d in days: 100.0 + 2.0 * d + 10.0 * r.next_normal()]
c = Chart(title = "Sales", x_label = "day", y_label = "units")
c.line(days, sales, "units sold")
c.line([0.0, 59.0], [100.0, 218.0], "trend")
img = chart_image(c, 640, 400)
print(img.width, img.height)

h = Chart(title = "How sales spread")
h.histogram(sales, 15)
print(chart_image(h, 400, 300).width)

Run it in the playground

chart.jo

Charts: lines, points, bars and histograms over axes with ticks, labels and a legend. A Chart holds what to show; draw_chart draws it into a rectangle (in a game's draw, a live graph), and chart_image makes a picture of it with no window (a script's chart, saved with save_png).

c = Chart(title = "Daily sales", x_label = "day", y_label = "revenue")
c.line(days, revenue, "revenue")
c.line(days, weekly_mean, "7-day mean")
c.points(xs, ys, "orders")
save_png("sales.png", chart_image(c, 800, 500))

c2 = Chart(title = "Units by region")
c2.bars(["north", "south", "east"], [120.0, 95.0, 143.0], "2026")
c3 = Chart(title = "Prices")
c3.histogram(prices, 30)

Each series given no color takes the next of a palette. The axes fit what is shown (from 0 for bars and histograms) unless x_min, x_max, y_min or y_max say otherwise; equal_axes keeps a unit as long across as up (a trajectory's true shape). Whole numbers and f32s (a vec2's parts) may be given as well as f64s. c.annotate(x, y, "apex") writes a word at a point.

struct Chart:
    title = ""
    x_label = ""
    y_label = ""
    series: ChartSeries[]
    categories: str[]           # (bars: the labels along the x axis)
    x_min: f64? = none
    x_max: f64? = none
    y_min: f64? = none
    y_max: f64? = none
    legend = true
    legend_at = LegendAt.top_right      # (the corner of the plot it is in)
    grid = true
    equal_axes = false                  # a unit as long along x as along y
    background = vec4(1, 1, 1, 1)
    ink = vec4(0.15, 0.15, 0.17, 1)     # text and axes
    text_size = 14.0
    log_y = false                       # y on a log scale: each tick ten times the one below
enum LegendAt: top_right, top_left, bottom_right, bottom_left
struct ChartSeries:
    kind: int                   # 0 line, 1 points, 2 bars, 3 histogram, 4 a note (its name)
    xs: f64[]
    ys: f64[]
    name: str
    color: vec4
    size: f64                   # a line's width, a point's radius
    bin_width = 0.0             # (a histogram's)
    dash = 0.0                  # (a line's dashes' length, in pixels; 0: solid)
line = (c: mut Chart, xs: f64[], ys: f64[], name: str = "", color: vec4? = none, width: f64 = 2.0, dash: f64 = 0.0)

a line through the points (x, y), in order; dash: dashes this many pixels long (0: solid)

line = (c: mut Chart, xs: f32[], ys: f32[], name: str = "", color: vec4? = none, width: f64 = 2.0, dash: f64 = 0.0)
line = (c: mut Chart, xs: int[], ys: int[], name: str = "", color: vec4? = none, width: f64 = 2.0, dash: f64 = 0.0)
line = (c: mut Chart, ys: f64[], name: str = "", color: vec4? = none, width: f64 = 2.0, dash: f64 = 0.0)

a line through ys, at x = 0, 1, 2...

line = (c: mut Chart, ys: f32[], name: str = "", color: vec4? = none, width: f64 = 2.0, dash: f64 = 0.0)
line = (c: mut Chart, ys: int[], name: str = "", color: vec4? = none, width: f64 = 2.0, dash: f64 = 0.0)
points = (c: mut Chart, xs: f64[], ys: f64[], name: str = "", color: vec4? = none, radius: f64 = 3.0)

a dot at each point (a scatter plot)

points = (c: mut Chart, xs: f32[], ys: f32[], name: str = "", color: vec4? = none, radius: f64 = 3.0)
points = (c: mut Chart, xs: int[], ys: int[], name: str = "", color: vec4? = none, radius: f64 = 3.0)
bars = (c: mut Chart, labels: str[], values: f64[], name: str = "", color: vec4? = none)

a bar for each category (more bars series stand side by side)

bars = (c: mut Chart, labels: str[], values: int[], name: str = "", color: vec4? = none)
bars = (c: mut Chart, labels: str[], values: f32[], name: str = "", color: vec4? = none)
annotate = (c: mut Chart, x: f64, y: f64, words: str, color: vec4? = none)

words written at the point (x, y), in the ink's color unless given one (not in the legend)

histogram = (c: mut Chart, values: f64[], bins: int = 20, name: str = "", color: vec4? = none)

how the values spread: how many fall in each of bins equal ranges (NaN left out)

chart_image = (c: Chart, w: int, h: int) -> Image

a picture of the chart, w x h pixels (no window needed)

draw_chart = (c: Chart, r: Rect)

draw the chart in a rectangle (its background, axes, series, title and legend)

Cryptography

A module (import crypto): SHA-1, SHA-256, SHA-384 and SHA-512, HMAC, HKDF, TLS 1.2's PRF, AES-128-GCM, P-256 and X25519 keys (ECDH), P-256 signatures (ECDSA), P-384 and RSA signatures checked, self-signed certificates and random bytes from the operating system; checked against the standards' test vectors and Wycheproof's.

crypto.jo

Cryptography: hashes (SHA-1, SHA-256, SHA-384, SHA-512), HMAC, HKDF, TLS 1.2's PRF, AES-128-GCM, the P-256 curve (ECDH keys and ECDSA signatures), X25519 keys, P-384 and RSA signatures checked, a self-signed certificate, and random bytes from the operating system. It is what the library's WebRTC (lib/rtc.jo) and TLS (lib/tls.jo) are made of, and a program may use it too: import crypto.

key = crypto.aes_key(crypto.random_bytes(16))
sealed = crypto.aes_gcm_seal(key, nonce12, aad, message)        # the message and a 16-byte tag
opened = crypto.aes_gcm_open(key, nonce12, aad, sealed)         # none when it was changed
pk = crypto.p256_key()                                          # a private key and its public point
sig = crypto.p256_sign(pk, crypto.sha256(msg))
ok = crypto.p256_verify(pk.public, crypto.sha256(msg), sig)

(P-256's arithmetic does not take the same time whatever the key: fine for keys made for a session, as WebRTC's are; not for long-lived keys on shared machines. X25519's does.)

Random bytes

random_bytes = (n: int) -> u8[]

n bytes from the operating system's random source (for keys and nonces: not seeded, not repeatable)

Bytes

hex_text = (b: u8[]) -> str

bytes as lowercase hex ("a9993e...")

hex_bytes = (s: str) -> u8[]?

"a9993e..." as bytes (none when it is not hex)

MD5

md5 = (m: u8[]) -> u8[]

SHA-1

sha1 = (m: u8[]) -> u8[]

SHA-1 of the bytes (20 bytes); for HMAC-SHA1, which STUN uses, not for anything new

SHA-256

sha256 = (m: u8[]) -> u8[]

SHA-256 of the bytes (32 bytes; std/hash's sha256 gives them as hex)

SHA-512, SHA-384

sha512 = (m: u8[]) -> u8[]

SHA-512 of the bytes (64 bytes)

sha384 = (m: u8[]) -> u8[]

SHA-384 of the bytes (48 bytes: SHA-512 started elsewhere, cut short)

HMAC

hmac_sha256 = (key: u8[], msg: u8[]) -> u8[]
hmac_sha1 = (key: u8[], msg: u8[]) -> u8[]

HKDF (RFC 5869, with SHA-256)

hkdf_extract = (salt: u8[], ikm: u8[]) -> u8[]

a key of 32 bytes made from input keying material and a salt (empty: as 32 zeros)

hkdf_expand = (prk: u8[], info: u8[], n: int) -> u8[]

n bytes of keys made from such a key, for a purpose (info)

Passwords: PBKDF2 (RFC 8018, with HMAC-SHA256)

pbkdf2_sha256 = (password: u8[], salt: u8[], iterations: int, n: int = 32) -> u8[]

n bytes of key from a password and a salt, by iterations rounds of HMAC-SHA256 (on a helper thread where tasks run, as hash_password's)

hash_password = (password: str, iterations: int = 100000) -> str

a password as text to store: a new random salt, and PBKDF2-HMAC-SHA256's hash of it with that many iterations. 100000 takes about a tenth of a second in a release build (a sixth in a debug one: OpenSSL's SHA-256 is twice as fast); OWASP asks for 600000 of programs whose SHA-256 is OpenSSL's: more where sign-ins are few, as an admin's. Where tasks run, it is made on a helper thread (pbkdf2_sha256's)

check_password = (password: str, stored: str) -> bool

whether the password is the one stored by hash_password (false too for text that is not such a hash); it takes as long whichever bytes differ

constant_time_equal = (a: u8[], b: u8[]) -> bool

whether a and b are the same bytes, taking as long whichever bytes differ (a secret compared with what a client sent: a token, a signature, an HMAC), so that the time taken tells nothing about where they differ. Their lengths are not secret: different lengths are false at once

constant_time_equal = (a: str, b: str) -> bool

TLS 1.2's PRF (RFC 5246 5, P_SHA256)

tls12_prf = (secret: u8[], label: str, seed: u8[], n: int) -> u8[]

n bytes of keys made from a secret, for a purpose (label) and a seed

AES-128

struct AesKey:
    w: u8[176]
    rk: u32[44]

an AES-128 key, expanded: the 11 round keys, 176 bytes (and as 44 big-endian words)

aes_key = (key: u8[]) -> AesKey
aes_encrypt_block = (k: AesKey, block: u8[16]) -> u8[16]

one 16-byte block encrypted

GHASH, constant-time

aes_gcm_seal = (key: AesKey, nonce: u8[], aad: u8[], message: u8[]) -> u8[]

the message encrypted, then its 16-byte tag: nonce (12 bytes) must never repeat for one key; aad is bytes the tag covers that travel unencrypted

aes_gcm_open = (key: AesKey, nonce: u8[], aad: u8[], sealed: u8[]) -> u8[]?

the message back from aes_gcm_seal's bytes, or none when they (or aad) were changed

P-256

struct P256Key:
    private: u8[]
    public: u8[]

a P-256 key: the private scalar and the public point (65 bytes: 0x04, x, y)

p256_key = () -> P256Key

a new key, from the system's random bytes

p256_ecdh = (k: P256Key, other: u8[]) -> u8[]?

the shared secret of a key and another's public point (its x, 32 bytes), or none when that is no point on the curve

p256_sign = (k: P256Key, hash: u8[]) -> u8[]

an ECDSA signature of a 32-byte hash: r and s, 32 bytes each

p256_verify = (public: u8[], hash: u8[], sig: u8[]) -> bool

whether sig (r and s, 32 bytes each) signs the 32-byte hash for the public point

X25519 (RFC 7748)

struct X25519Key:
    private: u8[]
    public: u8[]

an X25519 key: the private scalar and the public value, 32 bytes each

x25519_key = () -> X25519Key

a new key, from the system's random bytes

x25519_ecdh = (k: X25519Key, other: u8[]) -> u8[]?

the shared secret of a key and another's public value (32 bytes), or none when it comes out all zeros (the other's value was one of the few that make it so)

RSA signatures (checking only)

rsa_verify_pkcs1 = (n: u8[], e: u8[], hash: u8[], sig: u8[]) -> bool

whether sig is an RSASSA-PKCS1-v1_5 signature of the hash (as certificates are signed)

rsa_verify_pss = (n: u8[], e: u8[], hash: u8[], sig: u8[]) -> bool

whether sig is an RSASSA-PSS signature of the hash, with MGF1 of the same hash and a salt as long as the hash (as TLS 1.3 signs)

P-384 (ECDSA signatures, checking only)

p384_verify = (public: u8[], hash: u8[], sig: u8[]) -> bool

whether sig (r and s, 48 bytes each) signs the hash for the P-384 public point (97 bytes: 0x04, x, y); a hash longer than 48 bytes is cut to its first 48, as ECDSA does

DER

der_signature = (sig: u8[]) -> u8[]

r and s (32 bytes each) as an ECDSA signature in DER (as TLS and certificates carry it)

der_signature_parts = (der: u8[]) -> u8[]?

a DER ECDSA signature as r and s (32 bytes each), or none when it is not one

self_signed_certificate = (k: P256Key, name: str) -> u8[]

a self-signed X.509 certificate for the key (DER), named name: what DTLS (WebRTC's) shows the other side, which knows it by its SHA-256 fingerprint

certificate_p256_key = (cert: u8[]) -> u8[]?

the P-256 public point (65 bytes) a certificate holds, or none when it holds none

CRC-32

crc32 = (b: u8[]) -> u32

CRC-32 (zip's, PNG's, STUN's) of the bytes

crc32c = (b: u8[]) -> u32

CRC-32C (Castagnoli: SCTP's, iSCSI's) of the bytes

Big numbers

A module (use big): numbers past f64's 1.8e308, a mantissa and a power of ten (an idle game's currency), with arithmetic, comparison, min, max, sorting and saving as for numbers; shown as 1.23M or 4.56e+1234.

big.jo

Big numbers: past f64's 1.8e308, as an idle game's currency grows (1e1000, 1e100000). A Big is a mantissa from 1 to 10 and a power of ten, so it keeps about 15 digits, as a float does, whatever its size (BigInt, with no import, keeps every digit of a whole number); arithmetic, comparison, min, max and sort work as for numbers:

use big
dust = big(0)
rate = big(1.5, 120)                  # 1.5e120
dust += rate * dt
if dust >= cost: ...
print(dust)                           # 4.20e+1234 (short_number's form below 1e15)

to_text, to_json and saves write its fields (Big(m=4.2, e=1234)) and read them back.

struct Big:
    m: f64          # 0, or from 1 up to (not including) 10 (negative: from -10)
    e: int          # the power of ten
big = (x: f64) -> Big

x as a Big

big = (x: int) -> Big
big = (m: f64, e: int) -> Big

m times ten to the power e: big(1.5, 120) is 1.5e120

to_f64 = (b: Big) -> f64

the f64 nearest a Big (infinity past 1.8e308, 0 below 1e-308)

(+) = (a: Big, b: Big) -> Big
(-) = (a: Big, b: Big) -> Big
(-) = (a: Big) -> Big
(*) = (a: Big, b: Big) -> Big
(/) = (a: Big, b: Big) -> Big
(+) = (a: Big, x: f64) -> Big
(-) = (a: Big, x: f64) -> Big
(*) = (a: Big, x: f64) -> Big
(/) = (a: Big, x: f64) -> Big
(*) = (x: f64, a: Big) -> Big
(<) = (a: Big, b: Big) -> bool
(==) = (a: Big, b: Big) -> bool
hash = (b: Big) -> u64

a number made from b: the same for Bigs that are == (every zero alike), so a Big can be a key

(<) = (a: Big, x: f64) -> bool
(<) = (x: f64, a: Big) -> bool
log10 = (b: Big) -> f64

the power of ten it is near: log10(big(1, 500)) is 500

pow = (b: Big, p: f64) -> Big

b to the power p (p may be a fraction: a cost that grows 1.15 times for each one bought)

floor = (b: Big) -> Big
abs = (b: Big) -> Big
str = (b: Big) -> str

how it shows: short_number's form below 1e15 (1.23K, 45.6M), else 1.23e+45

Tasks and channels

spawn((): ...) runs a function alongside the rest of the program; a task that waits (a channel, the network, sleep, a line of input) lets the others run meanwhile. Channels carry values between them. Nothing is imported (the compiler reads it for the programs that use it). See tasks.

# example: tasks
# three tasks at once: each sleeps (the others run meanwhile), then sends what it found
found = channel[str]()
loop name in ["ann", "bob", "cy"]:
    spawn(():
        sleep(0.1)
        found.send("{name} is done")
    )
loop _ in 0..3: print(found.receive()!)

# a task's result
total = spawn((): [loop i in 0..1000: i].sum())
print(total.wait())

Run it in the playground

task.jo

Tasks: functions that run alongside the rest of the program, taking turns with it, and channels that carry values from one to another. A task that waits (for a channel, a socket, a fetch, sleep, a line of input) lets the others run meanwhile:

t = spawn((): net.fetch("https://example.com").text)     # starts it; the program goes on
...
page = t.wait()                                      # its result (waiting for it if need be)

jobs = channel[str]()
results = channel[int]()
loop _ in 0..4:
    spawn(():
        loop let url = jobs.receive(): results.send(net.fetch(url).status)
    )
loop u in urls: jobs.send(u)
jobs.close()                     # the workers' loops end once they have taken every one
loop _ in urls: print(results.receive()!)

Tasks take turns on the program's one thread: one runs until it waits, then another. So between two waits nothing else changes the program's variables, and they need no locks; a task that computes for a long time without waiting holds up the others (parallel_map shares work over all of the processor's cores). A channel's send or receive that need not wait goes on at once, letting the others ready take their turns only every 64th time. File reads/writes and C functions hold up tasks. run_program lets other tasks run on native Unix targets (cancellation ends its child); on Windows it holds them up until the child exits. The program ends when main and every task have ended, or at exit(); a game's tasks take their turns at the start of each frame, and end with it.

t.cancel() asks a task to stop: from then on its waits end at once, giving nothing (receive none, sleep returns, the network's calls nothing or status 0), and cancelled() is true in it, for it to clean up and end. A group (task_group) is tasks waited for and cancelled together.

Tasks

struct Task[T]

Copying a Task copies its handle to the same completion/result cell; cancel affects that task.

spawn[T] = (f: () -> T, background: bool = false) -> Task[T]

run f alongside the rest of the program; its result is the Task's wait(). background: the program's end does not wait for it (a server's loop, a task that watches something)

wait[T] = (t: Task[T]) -> T

its result, once it has ended (until then the caller waits, and the others take their turns; also in a task that has been cancelled, as the result is needed: wait_for(seconds) is a wait that cancel ends)

wait_for[T] = (t: Task[T], seconds: f64) -> bool

wait at most seconds for it to end: true once it has (wait() then gives its result at once), false if it has not (or the task waiting has been cancelled)

done[T] = (t: Task[T]) -> bool

it has ended

wait_all[T] = (ts: Task[T][]) -> T[]

the results of all of them, in their order

cancel[T] = (t: Task[T])

ask it to stop: its waits end at once from now on, the one it is in too, giving nothing (a channel's receive none, a send gives up, sleep returns, select takes its after or else arm, the network's calls give nothing or status 0), and cancelled() is true in it, for it to clean up and end. Nothing if it has ended. A task that never waits or looks is not stopped

cancelled = () -> bool

true in a task that has been cancelled (t.cancel(), or its group's): time for it to end

task_count = () -> int

how many tasks have started and not ended (main not counted, those in the background counted)

report_tasks = ()

write to standard error what each task is doing (what it waits for, where, and where it was spawned): for a program that seems stuck

Groups

struct TaskGroup
task_group = () -> TaskGroup

a group, with no tasks yet

spawn[T] = (g: TaskGroup, f: () -> T) -> Task[T]

run f alongside the rest of the program, in group g (cancelled at once if g has been)

wait = (g: TaskGroup) -> bool

wait until every task of the group has ended; false if one of them panicked (why() says what; the others were cancelled then). In a task that has been cancelled, the group's are cancelled first

cancel = (g: TaskGroup)

cancel every task of the group (t.cancel()), and those spawned into it from now on

why = (g: TaskGroup) -> str

the message of the first panic in the group's tasks ("": none has panicked)

Channels

struct Channel[T]

Values sent from one task to another, in order. send waits until a receiver takes the value (capacity 0), or while capacity values wait to be taken; receive waits until one comes, and gives none once the channel is closed and every value has been taken. Copies of a Channel are the same channel; send/close mutate that shared resource without mut. Optional element types are rejected: receive uses none for closed/empty. To send an optional, wrap it in a struct with an optional field (optionals flatten).

channel[T] = (capacity: int = 0) -> Channel[T]

a channel of T: channel[str](), or channelint for one that holds up to 100 values before send waits

send[T] = (c: Channel[T], v: T)

send v: normally waits until a receiver takes it (capacity 0), or a buffer slot is available. Cancellation ends the wait, not the send's side effect: if v was enqueued, it remains queued for a later receiver, even on an unbuffered channel. If already cancelled before enqueueing, v is enqueued only when a buffer slot or waiting receiver is available, otherwise not sent. This void form cannot report which happened; use timed/try_send to observe local acceptance. Accepted means enqueued, not processed. Send after close panics. Void-send cancellation is experimental; cancellation never promises to retract an enqueued value.

send[T] = (c: Channel[T], v: T, wait: f64) -> bool

send v if it can go within wait seconds (a receiver takes it, or there is room); false: it was never enqueued (including cancellation). True means local acceptance, not processing. An accepted item is not retracted by later cancellation; send after close panics.

try_send[T] = (c: Channel[T], v: T) -> bool

send v if that needs no wait (a receiver waits for it, or there is room); false: not sent. When it is full and other tasks are ready (a receiver just woken), they take their turns first

receive[T] = (c: Channel[T]) -> T?

the next value; none once the channel is closed and every value sent has been taken (or the task has been cancelled)

receive[T] = (c: Channel[T], wait: f64) -> T?

the next value, waiting at most wait seconds for it; none when none came (or the channel is closed and empty: closed() tells which)

try_receive[T] = (c: Channel[T]) -> T?

the next value if one waits; none if not

close[T] = (c: Channel[T])

no more values will be sent: receivers take what is left, then get none (and loops over it end)

closed[T] = (c: Channel[T]) -> bool

it has been closed (values may still wait in it)

len[T] = (c: Channel[T]) -> int

the values waiting in it

Waiting

next_frame = ()

wait until the next frame (a game's), letting the others take their turns; outside a game, the same as sleep(0)

yield_now = ()

let the other tasks ready take their turns, then go on: for a task that computes for long without waiting, now and then

Threads

# example: threads
slow_square = (n: int) -> int:
    total = 0
    loop i in 0..n: total += n
    total

nums = [loop i in 0..16: 1000000 + i]
squares = parallel_map(nums, slow_square)      # spread over every core
print(cpu_count(), "cores", squares[0], squares[15])

halves = parallel_range(8, (i): i / 2.0)  # f(0) .. f(7), in parallel
print(halves)

Run it in the playground

thread.jo

Data parallelism on a pool of worker threads (fork-join).

squares = parallel_map(nums, (x): x * x)
parallel_update(particles, (p): step(p, dt))      # xs[i] = f(xs[i]), in place
rows = parallel_range(height, (y): render_row(y))

The function runs on several threads at once: read immutable/copy-safe inputs, and return results instead of changing globals or captured variables. Use documented atomics/shared primitives for communication; arbitrary library calls are not necessarily thread-safe. Parallel callback safety remains experimental beyond the compiler's documented checks. On the web target everything runs on the calling thread.

cpu_count = () -> int

number of hardware threads available to this process

parallel_map[T, U] = (xs: T[], f: (T) -> U) -> U[]

[loop x in xs: f(x)], computed in parallel (f must not change globals or what it captured)

parallel_update[T] = (xs: mut T[], f: (T) -> T)

xs[i] = f(xs[i]) for every element, in parallel

parallel_range[U] = (n: int, f: (int) -> U) -> U[]

[loop i in 0..n: f(i)], computed in parallel

Atomics

struct Atomic

A whole number threads change together: parallel code may change it (and no other variable), as a count of work done or a flag that tells the other threads to stop. Copies of an Atomic are the same number: set/add mutate the shared cell without a mut receiver; assignment of the handle does not make an independent counter. Use atomic(v) for an independent cell.

atomic = (v: int = 0) -> Atomic
get = (a: Atomic) -> int

its value now

add = (a: Atomic, v: int) -> int

add v (negative: subtract) and give the value after

set = (a: Atomic, v: int)

set it to v

compare_swap = (a: Atomic, expected: int, v: int) -> bool

set it to v if it is expected (true), or leave it (false): one thread wins

set_max = (a: Atomic, v: int)

make it at least v (the largest of what the threads give)

Numeric arrays

Elementwise operators (.+ .* .^...), f.(xs) and n-dimensional arrays are part of the language: see arrays for numeric work. These are the functions on them.

# example: numeric arrays
xs = linspace(0.0, 1.0, 5)               # [0.0 0.25 0.5 0.75 1.0]
ys = 3.0 .* xs .^ 2.0 .+ 1.0             # element by element, as one loop
print(ys, sqrt.(xs), xs .> 0.5)
print(mean(ys), dot(xs, ys))

m = [1.0 2.0; 3.0 4.0]                   # a 2 x 2 matrix
print(m.shape, m[1, 0], m * [1.0, 1.0], m * transpose(m))
grid = zeros(3, 4)
grid[1, 2] = 5.0
print(grid)

Run it in the playground

nd.jo

Arrays for numeric work, in the spirit of numpy and MATLAB.

T[,] is an n-dimensional array (NDArray[T]): its elements in row-major order, and its shape. How many dimensions it has is part of the value, as in numpy (T[,,] is the same type; the commas are only for the reader). Write a 2-D one as [1 2; 3 4] (rows separated by ';' or line breaks), stack arrays with [a; b], or make one with zeros(2, 3, 4), ones, eye, rand, reshape. m[i, j] (with as many indexes as dimensions) reads and writes an element; m.shape is its shape. Ranges select parts: m[i, ..] is row i, m[.., j] column j, m[1..3, 0..] a block (a..b leaves b out, as everywhere; missing indexes at the end mean whole axes). A part is an array of its own: m[i, ..] is a 1-D T[,], which goes where a T[] is expected (row(m, i) gives the T[] itself, the fast way in a loop). Assigning to one (m[.., 0] = xs, m[0, ..] = 0.0) writes into m. An array of indexes or a mask picks parts along its axis: x[idx, ..] is the rows idx, in that order.

The dotted operators work element by element on arrays of any shape, and broadcast like numpy (a dimension of length 1, or a missing leading one, stretches to fit): a .* b, m .+ 1.0, v .^ 2, xs .< 0.5, and f.(xs) applies f to each element. A whole dotted expression runs as one loop. On 2-D arrays the plain operators follow linear algebra: a * b is the matrix product.

type Array[T] = T[]

another spelling of T[]

struct NDArray[T]:
    data: T[]
    shape: int[]

Shapes

ndarray[T] = (data: T[], shape: int[]) -> T[,]
ndim[T] = (m: T[,]) -> int
size[T] = (m: T[,]) -> int
len[T] = (m: T[,]) -> int
rows[T] = (m: T[,]) -> int
cols[T] = (m: T[,]) -> int
flatten[T] = (m: T[,]) -> T[]

Indexing

([])[T] = (m: T[,], i: int) -> T
([])[T] = (m: T[,], i: int, j: int) -> T
([])[T] = (m: T[,], i: int, j: int, k: int) -> T
([])[T] = (m: T[,], i: int, j: int, k: int, l: int) -> T
([]=)[T] = (m: mut T[,], i: int, v: T)
([]=)[T] = (m: mut T[,], i: int, j: int, v: T)
([]=)[T] = (m: mut T[,], i: int, j: int, k: int, v: T)
([]=)[T] = (m: mut T[,], i: int, j: int, k: int, l: int, v: T)

Picking along an axis

take[T] = (m: T[,], idx: int[], axis: int = 0) -> T[,]

the parts of m at these indexes along an axis, in their order (NumPy's take): take(x, idx) is the rows idx of x, as x[idx, ..] and x[idx] are (a mini-batch); with a mask (a bool[] as long as the axis), the parts where it is true

take[T] = (m: T[,], mask: bool[], axis: int = 0) -> T[,]
([])[T] = (m: T[,], idx: int[]) -> T[,]
([])[T] = (m: T[,], mask: bool[]) -> T[,]

Joining

concat[T] = (a: T[,], b: T[,], axis: int = 0) -> T[,]

the arrays joined along an axis (NumPy's concatenate): their other dimensions must be the same. concat(a, b) puts b's rows under a's, concat(a, b, 1) b's columns after a's

concat[T] = (parts: T[,][], axis: int = 0) -> T[,]
vstack[T] = (parts: T[,][]) -> T[,]

NumPy's vstack and hstack: rows under rows, a 1-D array being a row (so [a; b] for two), and columns after columns (1-D arrays joined end to end)

vstack[T] = (rows: T[][]) -> T[,]
hstack[T] = (parts: T[,][]) -> T[,]

Making arrays

zeros = (n: int) -> f64[]
zeros = (a: int, b: int) -> f64[,]
zeros = (a: int, b: int, c: int) -> f64[,]
zeros = (a: int, b: int, c: int, d: int) -> f64[,]
zeros[T] = (n: int) -> T[]

of another type (NumPy's dtype): zeros[int](rows, cols) is an int[,] of zeros

zeros[T] = (a: int, b: int) -> T[,]
zeros[T] = (a: int, b: int, c: int) -> T[,]
ones = (n: int) -> f64[]
ones = (a: int, b: int) -> f64[,]
ones = (a: int, b: int, c: int) -> f64[,]
ones = (a: int, b: int, c: int, d: int) -> f64[,]
eye = (n: int) -> f64[,]

the identity matrix

rand = (n: int) -> f64[]

uniformly random in [0, 1)

rand = (a: int, b: int) -> f64[,]
rand = (a: int, b: int, c: int) -> f64[,]
rand = (a: int, b: int, c: int, d: int) -> f64[,]
randn = () -> f64

normally distributed (mean 0, standard deviation 1)

randn = (n: int) -> f64[]
randn = (a: int, b: int) -> f64[,]
randn = (a: int, b: int, c: int) -> f64[,]
randn = (a: int, b: int, c: int, d: int) -> f64[,]
linspace = (a: f64, b: f64, n: int) -> f64[]

n evenly spaced values from a to b (both included)

reshape[T] = (xs: T[], shape: int[]) -> T[,]
reshape[T] = (xs: T[], a: int, b: int) -> T[,]
reshape[T] = (xs: T[], a: int, b: int, c: int) -> T[,]
reshape[T] = (m: T[,], shape: int[]) -> T[,]
reshape[T] = (m: T[,], a: int, b: int) -> T[,]
reshape[T] = (m: T[,], a: int, b: int, c: int) -> T[,]
transpose[T] = (m: T[,]) -> T[,]

the axes in reverse order (rows and columns swapped, for a 2-D array)

row[T] = (m: T[,], i: int) -> T[]
col[T] = (m: T[,], j: int) -> T[]

Reductions

sum[T] = (m: T[,]) -> T
min[T] = (m: T[,]) -> T
max[T] = (m: T[,]) -> T
sum = (xs: f64[]) -> f64

the sum of the elements (floats: added in pairs of halves, so the rounding errors stay small however long the array is: a million 0.1s make 100000.0, as NumPy's sum does)

max = (xs: f64[]) -> f64

(floats: NaN, not a number, wins: one NaN makes the answer NaN, as in NumPy)

min = (xs: f64[]) -> f64
sort = (xs: mut f64[], descending: bool = false)

(floats: NaN after every number, in either order; the numbers in order, equal ones as they were)

mean = (xs: f64[]) -> f64

the average (0 for none)

mean = (xs: int[]) -> f64
mean = (m: f64[,]) -> f64
median = (xs: f64[]) -> f64

the middle value once sorted (the mean of the two middle ones for an even count; 0 for none)

median = (xs: int[]) -> f64
std_dev = (xs: f64[]) -> f64

how far the values are from their mean, on average (the standard deviation of these values: the population's, as numpy's std; Python's statistics.stdev divides by n - 1 instead)

std_dev = (xs: int[]) -> f64
sum[T] = (m: T[,], axis: int, keepdims = false) -> T[,]

along one axis: the array without that axis, each element combining the ones along it (sum(m, 0) adds up the rows of a 2-D array: one sum per column). keepdims = true keeps the axis, with length 1, so that the result broadcasts against m: m .- max(m, 1, keepdims = true) takes each row's largest from the row (NumPy's keepdims)

min[T] = (m: T[,], axis: int, keepdims = false) -> T[,]
max[T] = (m: T[,], axis: int, keepdims = false) -> T[,]
mean = (m: f64[,], axis: int, keepdims = false) -> f64[,]
argmax[T] = (m: T[,], axis: int, keepdims = false) -> int[,]

where the largest (smallest) value along an axis is: its index there, the first of equal ones (argmax(scores, 1): each row's best column, as NumPy's argmax(axis=1))

argmin[T] = (m: T[,], axis: int, keepdims = false) -> int[,]
softmax = (m: f64[,], axis: int) -> f64[,]

e^x of each element over the sum of those along the axis: each row of softmax(scores, 1) is positive and adds up to 1. The largest along the axis is taken away first, so that no e^x overflows (NumPy-style code writes the same, scipy's softmax)

softmax = (xs: f64[]) -> f64[]
logsumexp = (m: f64[,], axis: int, keepdims = false) -> f64[,]

log(sum(exp(m), axis)), without exp overflowing or underflowing: the largest along the axis is taken out first (scipy's logsumexp)

logsumexp = (xs: f64[]) -> f64
dot = (a: f64[], b: f64[]) -> f64

the sum of a[i] * b[i] (kept in four running sums, about twice as fast: rounded a little differently from adding in order, the same for the same input every time)

norm = (a: f64[]) -> f64
variance = (xs: f64[]) -> f64

the variance: the mean of the squared distances from the mean (NumPy's var; std_dev squared)

variance = (xs: int[]) -> f64
percentile = (xs: f64[], p: f64) -> f64

the value p percent of the way through the sorted values (0: the smallest, 50: the median, 100: the largest), between two of them where it falls between (NumPy's percentile)

quantile = (xs: f64[], q: f64) -> f64

the same with q from 0 to 1

percentile = (xs: int[], p: f64) -> f64
argmax[T] = (xs: T[]) -> int

where the largest (smallest) value is: its index, the first of equal ones (-1: empty)

argmin[T] = (xs: T[]) -> int
argsort[T] = (xs: T[]) -> int[]

the indexes of xs in the order that sorts it (equal values keep their order)

cumsum = (xs: f64[]) -> f64[]

running totals: [a, a + b, a + b + c ...]

cumsum = (xs: int[]) -> int[]
diff = (xs: f64[]) -> f64[]

the differences of neighbors: [b - a, c - b ...] (one fewer)

diff = (xs: int[]) -> int[]
prod = (xs: f64[]) -> f64

all of them multiplied

prod = (xs: int[]) -> int
histogram = (xs: f64[], bins: int, lo: f64 = 0.0, hi: f64 = 0.0) -> (int[], f64[])

how many values fall in each of bins equal parts of lo..hi (the values' range when lo and hi are equal), and where the parts begin and end (bins + 1 edges; the last part takes hi itself)

covariance = (a: f64[], b: f64[]) -> f64

how a and b vary together: the covariance (divided by n - 1, as NumPy's cov), and the correlation, from -1 to 1 (Pearson's r: NumPy's corrcoef)

correlation = (a: f64[], b: f64[]) -> f64

Linear algebra

outer = (a: f64[], b: f64[]) -> f64[,]

the matrix of every a[i] * b[j]

diag = (m: f64[,]) -> f64[]

the diagonal of a square (or any 2-D) matrix, and its sum

trace = (m: f64[,]) -> f64
solve = (a: f64[,], b: f64[]) -> f64[]

x with a * x = b, a square (Gaussian elimination, choosing the largest pivot); a matrix with no inverse panics

inverse = (a: f64[,]) -> f64[,]

the inverse (a * inverse(a) is eye(n)); a matrix with none panics

det = (a: f64[,]) -> f64

the determinant (0 for a matrix with no inverse)

Matrix products

(*)[T] = (a: T[,], b: T[,]) -> T[,]

matrix product

(*)[T] = (a: T[,], v: T[]) -> T[]

matrix times column vector

(*)[T] = (k: T, m: T[,]) -> T[,]
(*)[T] = (m: T[,], k: T) -> T[,]
(/)[T] = (m: T[,], k: T) -> T[,]
(+)[T] = (a: T[,], b: T[,]) -> T[,]
(-)[T] = (a: T[,], b: T[,]) -> T[,]

As bytes

plain_bytes[T] = (m: T[,]) -> u8[]

an n-dimensional array of plain values as bytes: how many dimensions it has and each of them (8 bytes each, little-endian), then its elements' (as plain_bytes of its data): read back with ndarray_from_bytes

ndarray_from_bytes[T] = (b: u8[]) -> T[,]?

the array whose bytes are b (from plain_bytes): ndarray_from_bytes[f64](read_bytes(path).unwrap()); none when b is not one

From CSV

csv_array = (text: str, sep: u8 = ',') -> f64[,] | TextError

the numbers of a CSV text as a 2-D array, a row of the array for each row of the text (NumPy's loadtxt(path, delimiter=",")): x = csv_array(read_file("data.csv").unwrap()). A first row that is not all numbers (a header) is left out; an empty field, or NA, is NaN. A TextError says where a field is not a number, or a row has another number of fields than the first

The window, the game loop and input

A program that defines update(dt: f64) or draw() opens a window and calls them every frame. More on windows, screen sizes and the game loop: the language.

# example: the window, the game loop and input
window("Input", 960, 540)               # the title, and the size of the 2D area

pos = vec2(480, 270)
trail: vec2[] = []

update = (dt: f64):                      # every frame; dt: the seconds since the last one
    global pos
    pos += input_axis() * 320 * dt  # arrows, W A S D, or a gamepad's stick
    if mouse_down(.left): pos = mouse_pos()
    if key_pressed(.space): trail.clear()
    if key_pressed(.f): toggle_fullscreen()
    if key_pressed(.tab): show_stats(not stats_shown())     # frame times, and the zones' below
    zone("trail")                         # a part of the frame, timed in the statistics
    trail.push(pos)
    if trail.len() > 60: trail.remove_at(0)
    zone_end()

draw = ():                               # every frame, after update
    clear(rgb(0.08, 0.09, 0.12))
    loop i in 0.. and p in trail: circle(p, 4, rgba(0.3, 0.7, 0.9, i / 60.0))
    circle(pos, 18, ORANGE)
    text("move: arrows, W A S D or click   space: clear   F: fullscreen   Tab: statistics", vec2(20, 20), 20)
    text("{fps():.0} fps, {elapsed():.1} s", vec2(20, 500), 18, GRAY)

Run it in the playground

window.jo

Windows, the frame loop and input. Linux: Wayland (or X11), drawn with Vulkan (or OpenGL ES 3, or the software renderer: SLOPPY_SOFTWARE=1); Windows: Win32 and Vulkan or OpenGL; macOS: Cocoa and OpenGL. The system's libraries are loaded at runtime. Web: a <canvas> with WebGL2.

enum Key:
    unknown, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,
    n0, n1, n2, n3, n4, n5, n6, n7, n8, n9,
    space, enter, escape, tab, backspace, delete, insert, home, end, page_up, page_down,
    left, right, up, down, shift, ctrl, alt, super,
    f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
    minus, equals, comma, period, slash, semicolon, quote, lbracket, rbracket, backslash, grave,
    kp0, kp1, kp2, kp3, kp4, kp5, kp6, kp7, kp8, kp9, kp_period, kp_plus, kp_minus, kp_star, kp_slash
enum Mouse: left, middle, right
key_down = (k: Key) -> bool

true while the key is held

key_pressed = (k: Key) -> bool

true only in the frame the key was pressed

key_released = (k: Key) -> bool
key_presses = (k: Key) -> int

how many times the key was pressed this frame: 2 for two taps that came in one frame, which key_pressed counts as one (in a fixed step, 1 at most)

key_press_time = (k: Key, i: int = 0) -> f64

when the key was pressed this frame (its i-th press, from 0), on elapsed()'s clock, -1 if it was not: the time the desktop gives the event, finer than the frame, to judge a hit by (audio_time_at(key_press_time(.d)) is the music's time then). Without one (gamepads, Windows to about 16 ms), when the frame read it; in a screenshot run its frame's time, or SLOPPY_INPUT's (5.5:d+ is half way through frame 5, seen in frame 6)

key_release_time = (k: Key) -> f64

when the key was let go this frame (the last time), as key_press_time, -1 if it was not

key_typed = (k: Key) -> bool

true in the frame the key was pressed, and again each time it repeats while held down, as the desktop repeats keys (for moving through text); characters typed arrive through text_input()

shortcut = (k: Key, shift: bool = false) -> bool

true in the frame Ctrl and k are pressed together, and as it repeats (on a Mac and in a browser Cmd too), for a tool's keys: if shortcut(.s): save(); shift: with Shift held too, as Ctrl+Shift+Z (without it, Shift must not be held). Browsers keep some for themselves (Ctrl+N, Ctrl+W, Ctrl+T) and the page never sees them.

mouse_pos = () -> vec2

(in the 2D units of the screen: see screen_size and screen.jo)

mouse_delta = () -> vec2
mouse_wheel = () -> f64
set_wheel_scale = (s: f64)

how much a notch of the mouse wheel counts in mouse_wheel (1.0, the default: one; less, slower), for everything that reads it: hud_scroll lists, text boxes, ui_ and layout lists, a game's own zoom. A setting for players who find the wheel too fast: set_wheel_scale(settings.wheel)

wheel_scale = () -> f64

(set_wheel_scale's)

mouse_down = (b: Mouse) -> bool
mouse_pressed = (b: Mouse) -> bool
mouse_released = (b: Mouse) -> bool
mouse_presses = (b: Mouse) -> int

how many times the button was pressed this frame, and when (as key_presses, key_press_time)

mouse_press_time = (b: Mouse, i: int = 0) -> f64
text_input = () -> str

characters typed this frame

pasted_text = () -> str

the text pasted this frame (ctrl+V, cmd+V on a Mac, a web page's paste, a text field's Paste button on a phone): the clipboard's text then; "" in other frames. For a widget of a game's own (the hud_ text fields take it themselves)

A fixed time step

fixed_update = (dt: f64, step: (f64) -> void, rate: f64 = 60.0) -> f64

step(dt) at a fixed rate, rate times a second whatever the frame rate: as many times as the time since the last frame holds (none in some frames of a 144 Hz screen, two in some at 30), the rest kept for the next frame. Physics and jumps come out the same at any frame rate (Godot's _physics_process, Unity's FixedUpdate): In step, a press (key_pressed, mouse_pressed, gamepad_pressed, action_pressed, and their released) is seen in one step only, the first after it, even one that came in a frame with no step. It gives back how far the time is into the next step (0 to 1): to draw what moves between where the last two steps put it, mix(prev_pos, pos, f32(k)).

input_axis = () -> vec2

arrows/WASD (or a gamepad's left stick and d-pad) as a direction vector (y down)

screen_width = () -> int

The screen's size in 2D drawing units: the size given to window() (the design size), whatever the window's real size; screen.jo says how it maps to the window (screen_fit). pixel_size() is the window's real size.

screen_height = () -> int
screen_size = () -> vec2
pixel_size = () -> vec2
aspect_ratio = () -> f64

width / height of the picture 3D draws into (for a projection: perspective(fov, aspect_ratio(), ...)): the window's, or the design area's when the screen fit shows just that (screen.jo)

visible_rect = () -> Rect

the part of the 2D plane the screen shows, as a Rect (x, y, w, h): with screen_fit(.expand) (the default) the design area centered in a window of any shape and what is around it (draw backgrounds over this to fill the window); with bars, just the design area

frame_time = () -> f64
time_scale = (s: f64)

how fast the game's time runs: update gets dt times this (0.5: slow motion, 0: paused, while drawing, input and sound go on); frame_time() is the scaled dt, fps() and elapsed() are not

time_scale = () -> f64

the scale set with time_scale (1 to start with)

fps = () -> f64
elapsed = () -> f64
frame_number = () -> int
quit = ()

end the game (the window closes once this frame is done). A web page cannot close itself: there it does nothing (can_quit() is false, so a menu can leave its Quit button out)

can_quit = () -> bool

Frames drawn on demand: tools, editors, forms

redraw_on_input = (on: bool = true)

A game draws 60 frames a second; a tool that waits for its user need not. With redraw_on_input(), a frame is drawn only when something may have changed: a key, the mouse moving, a click or the wheel, text typed, the window resized or focused, files dropped, a file dialog's answer (and two frames after each, for what a frame's drawing sets off), at the time redraw_after asked for, or after request_redraw(). In between the program sleeps (sound still plays). update's dt is the time since the last frame (0.1 s at most). Something that moves on its own (an animation, a timer shown, a tween) calls request_redraw() in each frame it is not done in (tweens, hud_scroll's gliding and a text field's blinking caret do so themselves). While the program fetches from the network or has tasks, a frame comes at least 10 times a second, so that their answers are seen. Screenshot runs draw every frame as usual. On the web too: the page asks for no animation frames while it waits.

request_redraw = ()

draw another frame soon, even with nothing typed or moved (redraw_on_input): while an animation runs, once in each frame

redraw_after = (seconds: f64)

draw a frame seconds from now at the latest (redraw_on_input): a clock that shows the time, a message that goes away, a caret that blinks

set_fullscreen = (on: bool = true)
toggle_fullscreen = ()
is_fullscreen = () -> bool
can_fullscreen = () -> bool

whether set_fullscreen can fill the screen: false in an iPhone's Safari, which has no fullscreen for a page's canvas (a game can leave its Fullscreen button out there)

clipboard = () -> str

the text on the system clipboard ("" if none, or not text). In a web page the browser lets a page read it only as it is pasted: this is the text last pasted (ctrl+V, or a text field's Paste button on a phone) into the page.

set_clipboard = (s: str)
can_share = () -> bool

the system's menu for sending text to another app (a chat, Messages, mail), where there is one: a web page on a phone, and in some desktop browsers. In a page the menu opens as the tap or click that asked ends (browsers allow it only then)

share = (text: str)
sideways_hint = (on: bool)

a phone held upright, playing a game made for a screen wider than tall: a note over the game to turn the phone sideways (on to start with; the game goes on under it). Off for a game laid out for a phone either way up (visible_rect says what shows).

upright_hint = (on: bool)

the other way: a phone held sideways, playing a game made for a screen taller than wide (as window("...", 360, 640)): a note to turn the phone upright (on to start with); off for a game laid out for both

mouse_lock = (on: bool = true) -> bool

lock the mouse pointer to the window and hide it, for mouse look: the pointer stays put and its motion keeps arriving through mouse_delta(). false where the platform cannot. (A web page gets the lock at the next click into it, as browsers require; Escape releases it there.)

run_hidden = (on: bool = true)

keep running while the window is hidden (a web page in a tab not shown, or in a window covered by another): its frames go on, called by a timer, which a browser may slow to one a second. For a game online: hidden, it would stop sending, and the others would take it for gone. (Not in a web page: frames go on anyway.)

is_mouse_locked = () -> bool

(in a screenshot run, what the game asked for: the desktop's focus coming and going would make the run differ from one time to the next)

window_focused = () -> bool

the window (or the web page) has the keyboard's focus: false while the player is in another window or tab, as after a click outside an itch.io frame (a game may pause then)

touches = () -> vec2[]

the fingers on a touch screen (a phone's, in a web page): where each is, in the screen's units as mouse_pos, in the order they landed. The first finger also is the mouse, its left button held while it is down, so a game made for the mouse works with one finger; more fingers (on screen buttons: left, right, jump) are only here. Empty without a touch screen.

touch_ids = () -> int[]

each finger's number, in the order of touches(): the same for as long as that finger stays down, and another for the next one to land, so a game can follow each finger from frame to frame (what it landed on, how far it moved since the last frame: a drag that turns a camera)

touch_input = () -> bool

whether the pointer is a finger: the last pointer input was a touch, not the mouse (a finger lifted leaves mouse_pos where it was: hover highlights mean nothing then)

touch_device = () -> bool

whether the screen is a touch screen, its main pointer a finger (a phone or a tablet: a page asks the browser), known before the first touch: on-screen buttons from the start, say. touch_input() says whether the last input was a finger

A press of the left button (or of the first finger): taps, drags, swipes

claim_press = ()

the press now held (of the left button, or a finger) is the game's own, for a drag of its own: a hud_scroll list it went down in does not move with it, and letting go of it clicks no button. Call it in the frame it goes down (on mouse_pressed), as the drag starts:

press_claimed = () -> bool

whether the press now held was claimed (claim_press), or moved a hud_scroll list

swipe = () -> vec2?

a drag of a finger (or the mouse) that just ended, 30 points long or more: which way it went most, vec2(-1, 0) left, vec2(1, 0) right, vec2(0, -1) up or vec2(0, 1) down, in the frame it lets go; none otherwise, and for a drag begun on a hud_ box or one a scrolling list moved with

long_press = (seconds: f64 = 0.5) -> bool

true once, in the frame a finger (or the left mouse button) has been held down seconds without moving: what it is on, said more about, say. Letting go after it is no tap of a button

Points, a phone's notch, the design size: one layout for screens of any size

pixel_ratio = () -> f64

how many of the window's pixels make a point (a page's CSS pixel: about 1/160 inch on a phone, 1/96 on a desktop screen): the page's devicePixelRatio as it is drawn, or the desktop's scale (Wayland's, a Retina Mac's, Windows'), 1 without one

css_pixel = () -> f64

a point's size in 2D units: what must be the same size to a finger or an eye on any screen, a phone's or a desktop's, is sized in these (a button 48 * css_pixel() tall fits a finger; text 16 * css_pixel() high reads as a page's)

safe_rect = () -> Rect

the part of visible_rect() clear of a phone's notch, rounded corners and home bar (in a page on such a phone; all of visible_rect() elsewhere): what must be seen or tapped goes inside it, backgrounds over all of visible_rect()

design_size = (w: int, h: int)

change the design size (the 2D units, as given to window()) while the game runs: one layout for a phone held upright, another for a screen wider than tall, say (the window keeps its size; screen_fit says how the new units fill it), at once: in update, before drawing (with a letterbox fit or a fixed resolution, from the next frame)

show_cursor = (on: bool)

show or hide the mouse pointer over the window (hidden: a game drawing its own crosshair or cursor); unlike mouse_lock, it still moves and mouse_pos() follows it

set_cursor = (c: Cursor)

the mouse pointer's shape over the window, from the end of this frame on: .arrow (the usual), .ibeam over text to type in, .hand over a link, .crosshair, .move over what drags, .resize_ew, .resize_ns, .resize_nwse and .resize_nesw over an edge or a corner that resizes, .not_allowed, .wait while busy; .hidden is show_cursor(false), and any other shape shows it again. While it is .arrow, a hud_text_field or ui_text_field under the pointer shows an I-beam. (In a web page, the browser's cursors; on Wayland, where the compositor has cursor shapes)

enum Cursor: arrow, ibeam, hand, crosshair, move, resize_ew, resize_ns, resize_nwse, resize_nesw, not_allowed, wait, hidden
window = (title: str = "", width: int = 1280, height: int = 720)

Open the game window (called automatically when the program defines update/draw).

set_title = (title: str)

change the window's title while the game runs (a level's name, the score); in a web page, the page's title

files.jo

A user's files: dropped onto the window, or chosen in the system's file dialog. The same calls everywhere; what a path is differs. Natively a path is where the file is on the disk. In a web page the browser gives the page a copy of the file, not where it is: the page keeps it in its own files, which read_file, read_bytes and load_image read, under the file's name.

loop path in dropped_files(): open_doc(read_file(path).unwrap())

if key_pressed(.o) and key_down(.ctrl): asked = open_file_dialog([".txt", ".md"])
if asked >= 0:
    if let paths = file_dialog_result(asked):        # (each frame: none while it is open)
        asked = -1
        if paths.len() > 0: open_doc(read_file(paths[0]).unwrap())      # ([]: cancelled)

Dialogs: on Windows the system's (the program waits while it is open); on Linux zenity's or kdialog's, when one of them is installed (else the answer is at once: no files); on macOS AppleScript's (osascript). In a web page, the browser's file picker: it opens only as a click, a tap or a key ends (browsers allow it only then; asked for at another time, it opens at the next one). Drops: Windows, X11, Wayland and web pages (not yet macOS).

Testing aids: SLOPPY_FILE_DIALOG="a.txt|b.txt" answers every dialog with those paths, at once ("": cancelled); SLOPPY_INPUT's 5:drop=a.txt drops a file in frame 5.

dropped_files = () -> str[]

the files dropped onto the window since the last frame: their paths (in a web page, the names of the page's copies, which read_file reads), in this frame only; [] in most frames

open_file_dialog = (types: str[] = [], multiple: bool = false, title: str = "") -> int

ask the user for a file to open, in the system's dialog: an id for file_dialog_result, which gives the answer once the user has chosen. types: the extensions to show (".png", "jpg"), [] for any file; multiple: more than one may be chosen; title: the dialog's own

save_file_dialog = (name: str = "", types: str[] = [], title: str = "") -> int

ask the user where to save a file: as open_file_dialog, with a name to start with. The answer is the path to write to. In a web page the answer is name at once, a file of the page's own: write it there, then download_file(path) hands it to the browser, which saves it where the user says (natively download_file does nothing more; the same code works everywhere)

file_dialog_result = (d: int) -> str[]?

a file dialog's answer (open_file_dialog's or save_file_dialog's id), once the user has chosen: the paths chosen, [] if the dialog was cancelled; none while it is open. Given once: asking again stops the program (a mistake: keep the answer when it comes)

stats.jo

A frame statistics overlay: frame times as a graph, CPU time, time handing frames to the screen, frames that took much longer than usual (stutter), and the time each zone of the frame takes (zone("physics") ... zone_end(): update and draw are zones already, as are the 3D scene, its shadows and post-processing), on the CPU and, through Vulkan, on the GPU. show_stats() turns it on, as do SLOPPY_STATS=1 and, in a web page, ?stats in the URL. SLOPPY_STATS=log (?stats=log) prints the same numbers every two seconds instead, and each long frame as it happens. For a game's own log: record_stats() times the zones with nothing shown, and frame_stats_line() gives the frames since it was last called as one line of text.

show_stats = (on: bool = true)
stats_shown = () -> bool
record_stats = (on: bool = true)

time the frames and their zones with nothing shown, for frame_stats_line (a log of how a game runs on the players' machines)

frame_stats_line = () -> str

the frames since the last call (at most 240), as one line: how many, their average and slowest time and how many took much longer than usual; the CPU's time in a frame (most: the longest), handing it to the screen, the GPU's (through Vulkan); each zone's average and longest, in ms. Zones are timed only after record_stats() or show_stats()

graphics_info = () -> str

how frames reach the screen, and on what: "vulkan (its GPU)", "egl window surface"..., in a web page "webgl" and the browser's name for the GPU, and the browser

Zones: named parts of a frame, timed

zone = (name: str)

start timing a part of the frame, until zone_end() (zones nest; their times show in the overlay; a zone entered several times in a frame shows their total); costs a check when the statistics are off

zone_end = ()
zone = (name: str, f: () -> void)

f, timed as a zone

Controls and gamepads

# example: controls and gamepads
window("Controls", 960, 540)

# actions with their default keys and buttons; the player can change them (ui_controls)
action("jump", [.key(.space), .key(.w), .button(.a)])
action("left", [.key(.a), .key(.left), .stick(0, -1), .button(.left)])
action("right", [.key(.d), .key(.right), .stick(0, 1), .button(.right)])

x = 480.0
y = 0.0
vy = 0.0
settings = false

update = (dt: f64):
    global settings, vy, y
    if key_pressed(.tab): settings = not settings
    if settings: return
    x += action_axis("left", "right") * 300 * dt        # -1 to 1 (a stick gives in between)
    if action_pressed("jump") and y == 0.0: vy = 500.0
    vy -= 1200 * dt
    y = max(0.0, y + vy * dt)

draw = ():
    global settings
    clear(rgb(0.1, 0.1, 0.14))
    rect(0, 440, 960, 100, rgb(0.25, 0.3, 0.25))
    rect(x - 20, 400 - y, 40, 40, ORANGE)
    text("move: A D or arrows   jump: space or W   Tab: change the controls   ({gamepads().len()} gamepads)", vec2(20, 20), 20)
    if settings:
        ui_begin("controls", vec2(480, 100))
        ui_controls()                    # choose an action, then press its new key or button
        if ui_button("Back") or ui_back(): settings = false
        ui_end()

Run it in the playground

controls.jo

Controls the player can change. The game names its actions and gives each its default inputs, then asks for actions, never for keys; ui_controls() is a settings screen where the player rebinds them (choose one, press the new key or button), and the bindings are saved.

action("jump", [.key(.space), .button(.a)])
action("left", [.key(.a), .key(.left), .stick(0, -1), .button(.left)])
action("right", [.key(.d), .key(.right), .stick(0, 1), .button(.right)])
...
if action_pressed("jump"): jump()
x = action_axis("left", "right")            # -1..1, analog on a stick

# in the settings menu:
ui_begin("settings", vec2(640, 140))
ui_controls()
if ui_button("Back") or ui_back(): ...
ui_end()

Local multiplayer: a player number reads that gamepad (keys and the mouse count for player 0). Players sharing one keyboard each have actions of their own, declared for their number: its keys are theirs, and its buttons their gamepad's

action("p2 jump", [.key(.up), .button(.a)], player = 1)
if action_pressed("p2 jump"): ...               # the up arrow, or gamepad 1's A
enum Input: key(k: Key), button(b: PadButton), mouse(m: Mouse), stick(axis: int, dir: int)

an input: a key, a gamepad button, a mouse button, or a stick or trigger pushed one way (axis: 0 left x, 1 left y, 2 right x, 3 right y, 4 left trigger, 5 right trigger; dir: 1 or -1)

action = (name: str, defaults: Input[], player: int = -1)

declare an action and its default inputs (once, before reading it: again, nothing changes); a binding the player saved replaces the defaults. player: the one it is for (its keys count for them, its buttons are their gamepad's), -1 anyone's

input_value = (x: Input, player: int = -1) -> f64

how far input x is pushed, 0 to 1, for player (-1: anyone)

action_value = (name: str, player: int = -1) -> f64

how far the action is pushed, 0 to 1 (the most of its inputs)

action_down = (name: str, player: int = -1) -> bool
action_pressed = (name: str, player: int = -1) -> bool

true in the frame the action was pressed (a stick: when it goes past halfway)

action_presses = (name: str, player: int = -1) -> int

how many times the action was pressed this frame (two taps of its key in one frame: 2), and when, on elapsed()'s clock, -1 if it was not (as key_press_time: its keys' and mouse buttons' times from the desktop, a gamepad's when the frame read it)

action_press_time = (name: str, i: int = 0, player: int = -1) -> f64
action_released = (name: str, player: int = -1) -> bool
action_axis = (neg: str, pos: str, player: int = -1) -> f64

from -1 (neg) to 1 (pos): action_axis("left", "right")

action_vec = (left: str, right: str, up: str, down: str, player: int = -1) -> vec2

a direction (y down), at most 1 long

Bindings

bindings = (name: str) -> Input[]
set_bindings = (name: str, inputs: Input[])
reset_controls = ()

every action back to its defaults

input_name = (x: Input) -> str

what an input is called, for showing it ("Space", "Pad A", "Left stick right")

Rebinding

input_pressed = () -> Input?

the input the player pressed first this frame (a key, a button, a click, a stick pushed most of the way), if any

rebinding = () -> bool

whether ui_controls is waiting for a new input (the game's own keys should wait too), or took one this frame

ui_controls = (names: str[] = [], labels: str[] = [], rows: int = 0)

a row per action (its name, and its inputs), in a menu (between ui_begin and ui_end), and a row to put the defaults back. Choosing an action waits for its new input: a key replaces its first key (or the mouse), a gamepad's button or stick its first gamepad input; Escape cancels. names: the actions shown (and what they are called), in order: all of them if none given. rows: how many are shown at once (0: as many as fit on the screen, with room for two items after); the list scrolls to the chosen one, and with the mouse wheel.

gamepad.jo

Gamepads and joysticks: up to eight at once, each by its number, with a standard layout (Xbox-style names), and every device's own buttons and axes as they are (flight sticks, wheels).

if gamepad_pressed(.a): jump()            # any gamepad
move = left_stick()                        # vec2 in -1..1, y down, with a dead zone
loop pad in gamepads():                    # (local multiplayer: one player per pad)
    players[pad].move = left_stick(pad)

A controller keeps its number while it is plugged in (players stay who they are); one plugged in later takes a free number. input_axis() also follows the sticks and d-pads, so keyboard games work with a pad. Linux builds read the joystick devices (/dev/input/js0..7), Windows builds XInput and Raw Input HID (PlayStation, Switch Pro, D-input and generic pads), web builds the browser's Gamepad API, macOS builds Apple's GameController framework.

enum PadButton: a, b, x, y, lb, rb, back, start, home, lstick, rstick, up, down, left, right
const MAX_GAMEPADS = 8
gamepads = () -> int[]

the numbers of the gamepads connected

gamepad_connected = () -> bool
gamepad_connected = (pad: int) -> bool
gamepad_name = (pad: int) -> str

what the device calls itself ("" if it does not say; in a web page, the browser's Gamepad.id, which names the device and often its vendor and product numbers)

gamepad_standard = (pad: int) -> bool

whether pad is a standard-layout gamepad (two sticks, two triggers, the face buttons and a d-pad, as gamepad_down and gamepad_axis read them), and not a flight stick, wheel or pedals, whose own controls only joystick_axis and joystick_button read as they are (their throttle can look like a trigger to gamepad_axis); false if it is not connected. Web: the browser's "standard" mapping. Windows: XInput, the HID pads whose layout is known (PlayStation, Switch Pro, 8BitDo) and any HID device that says it is a gamepad (not a joystick). macOS: every pad (GameController's extended gamepad). Linux: the kernel's gamepad class (its buttons are BTN_SOUTH..., a joystick's BTN_TRIGGER...). SLOPPY_INPUT's pads: true unless the script sets their own axes or buttons or names them (or pad1_standard=0/1 says)

gamepad_down = (pad: int, b: PadButton) -> bool

a button of pad, or (without a pad) of any gamepad

gamepad_pressed = (pad: int, b: PadButton) -> bool
gamepad_released = (pad: int, b: PadButton) -> bool
gamepad_down = (b: PadButton) -> bool
gamepad_pressed = (b: PadButton) -> bool
gamepad_released = (b: PadButton) -> bool
gamepad_axis = (pad: int, i: int) -> f64

axis value in -1..1 (triggers 0..1): 0 left x, 1 left y, 2 right x, 3 right y, 4 left trigger, 5 right trigger; without a pad, the gamepad that has it furthest from rest

gamepad_axis = (i: int) -> f64
left_stick = (pad: int) -> vec2
right_stick = (pad: int) -> vec2
left_stick = () -> vec2

(without a pad: the one pushed furthest)

right_stick = () -> vec2
joystick_buttons = (pad: int) -> int

any device's own buttons and axes, as it numbers them (a flight stick's hat and throttle, a wheel's pedals): how many it has, and their state. In tests SLOPPY_INPUT sets them (5:pad1_axis3=-0.4, 5:pad1_button7+ and -, 1:pad1_name=T.16000M), and a scripted standard pad's mirror its sticks, triggers and buttons as Linux's xpad numbers them

joystick_axes = (pad: int) -> int
joystick_button = (pad: int, i: int) -> bool
joystick_pressed = (pad: int, i: int) -> bool
joystick_axis = (pad: int, i: int) -> f64

keyrepeat.jo

Key repeats as a game wants them (PICO-8's btnp): key_repeat, gamepad_repeat, action_repeat.

key_repeat = (k: Key, delay: f64 = 0.25, period: f64 = 1.0 / 15.0) -> bool

true in the frame the key was pressed, then again while it is held: after delay seconds, each period seconds (PICO-8's btnp: a quarter second, then 15 times a second); for moving through a menu or a grid a step at a time. It counts the game's time, the same in a SLOPPY_INPUT run; in a fixed_update step, the steps'. gamepad_repeat and action_repeat are the same for a button and an action.

gamepad_repeat = (pad: int, b: PadButton, delay: f64 = 0.25, period: f64 = 1.0 / 15.0) -> bool

true as the button is pressed, then again while it is held, as key_repeat

gamepad_repeat = (b: PadButton, delay: f64 = 0.25, period: f64 = 1.0 / 15.0) -> bool
action_repeat = (name: str, player: int = -1, delay: f64 = 0.25, period: f64 = 1.0 / 15.0) -> bool

true as the action is pressed, then again while it is held, as key_repeat (a menu's up and down)

Drawing in 2D

# example: drawing in 2D
window("Shapes", 960, 540)

t = 0.0
update = (dt: f64): t += dt

draw = ():
    clear(rgb(0.1, 0.1, 0.14))
    rect(40, 40, 200, 120, rgb(0.9, 0.3, 0.3))            # x, y (top left), width, height
    rect_outline(270, 40, 200, 120, 4, WHITE)
    circle(vec2(600, 100), 60, hsv(t * 0.1, 0.7, 1.0))    # a color that changes
    ring(vec2(800, 100), 60, 8, YELLOW)
    arc(vec2(800, 100), 40, 8, 0.0, t % TAU, CYAN)
    line(vec2(40, 220), vec2(460, 300), 6, GREEN)
    polygon([vec2(560, 220), vec2(680, 260), vec2(620, 340)], PURPLE)
    circle_gradient(vec2(820, 300), 80, rgba(1, 0.8, 0.3, 1), rgba(1, 0.4, 0.1, 0))

    # transforms: what follows is moved, turned and scaled
    push_transform()
    translate(240, 430)
    rotate(t)
    rect(-50, -50, 100, 100, BLUE)
    pop_transform()
    text("text at any size", vec2(420, 420), 40, WHITE)

Run it in the playground

draw2d.jo

2D drawing: batched shapes, textured sprites, SDF text, transforms, blend modes and render targets. Coordinates are in the screen's units (1280 x 720 unless the program says otherwise, whatever the window's real size), with (0, 0) at the top-left and y down; on a render target, its pixels.

struct Texture:
    id: int
    width: int
    height: int
struct RenderTarget:
    texture: Texture
    fbo: int
    depth: int                                  # (its depth renderbuffer; 0 with depth_texture)
    depth_texture: Texture = Texture(0, 0, 0)   # render_target(..., depth_texture = true): its depth
    colors: Texture[4]                          # its colors: render_target(..., colors = n) fills 0 to
                                                # n - 1, the rest are empty; colors[0] is texture
enum Blend: alpha, add, multiply, premultiplied, screen, none

Draw state: how a draw's colors go into the picture (blend), whether it is drawn only where it is nearer than what is there (depth_test) and leaves its own depth (depth_write), which faces are left out (cull), whether colors are written at all (color_write). See docs/GRAPHICS.md.

enum DepthTest: off, nearer, nearer_or_equal, farther, farther_or_equal, equal, always
enum Cull: none, back, front
clear = (c: vec4 = vec4(0, 0, 0, 1))
clear_depth = ()

only the depth of what is drawn into is cleared (to far); its colors stay

blend = (b: Blend)

how what is drawn next goes over what is there, for 2D drawing and draw/draw_instanced alike: .alpha (the default), .add (glows), .multiply (shadows, tints), .premultiplied (colors already multiplied by their alpha), .screen (1 - (1 - a)(1 - b): lightens, never past white), .none (no blending: the colors and alpha replace what is there)

depth_test = (t: DepthTest)

which fragments are drawn by their depth against the depth already there: .off (all of them, and none leaves its depth), .nearer, .nearer_or_equal, .farther, .farther_or_equal, .equal, .always (all, each leaving its depth when depth_write is on)

depth_write = (on: bool)

whether a draw leaves its depth (where depth_test is not .off)

cull = (c: Cull)

which triangles are left out: .none, .back (those whose corners go clockwise on the screen), .front (counter-clockwise)

color_write = (on: bool)

whether colors are written (false: a depth-only pass)

clip = (pos: vec2, size: vec2)

2D drawing after this shows only inside the rectangle, until no_clip(), the next frame or another target (draw_to); for a scrolling list, a panel, a minimap. The rectangle is in the units of the 2D transform, as what is drawn is (under translate, scale or camera2d_fit it is where a rect() of it shows; turned, the box around that); the clip is then kept where it is on the screen, whatever transform comes after

clip = (r: Rect)

the same, with a Rect: clip(r) around a scrolling list's box

no_clip = ()

drawing shows everywhere again (and a hud_scroll list's bar, drawn over its rows, is drawn now, as they are done)

push_transform = ()
pop_transform = ()
translate = (x: f64, y: f64)
rotate = (angle: f64)
scale = (sx: f64, sy: f64)
reset_transform = ()
camera2d = (target: vec2, zoom: f64 = 1.0, angle: f64 = 0.0)

2D camera: target appears at the screen center, scaled by zoom

camera2d_fit = (world: Rect, on: Rect)

a 2D camera showing the area world (in the world's units) as large as it fits inside on (a part of the screen: visible_rect() for all of it), centered there, its shape kept: a board above the buttons on a phone held upright,

screen_to_world = (p: vec2) -> vec2

convert a screen position to world coordinates under the current transform; in update (before draw sets one), under the last camera2d: screen_to_world(mouse_pos()) is where the mouse points

world_to_screen = (p: vec2) -> vec2

where a world position appears on the screen under the current transform (the other way; in update, the last camera2d's)

Effects: a shader of your own on 2D drawing

struct Pixel2D:
    pos: vec4               # where on the screen, in pixels from the bottom left (z, w: 0 and 1)
    uv: vec2                # where in the texture (0 to 1)
    color: vec4             # the color it is drawn with
    mode: f32               # (1 for text: its texture holds distances to the letters' edges)

An effect is a fragment function run for each pixel of what is drawn while it is on (sprites, shapes, text): it gets the pixel (where it is, its place in the texture, the color it is drawn with) and the uniforms, Effect2D[P] holding your parameters P; base_color gives what drawing would have made of the pixel without it.

struct Effect2D[P]:
    proj: mat4
    texture: Texture        # what is being drawn (white for shapes)
    params: P
effect_vs[P] = (v: __Vert2D, u: Effect2D[P]) -> Pixel2D

the vertex function of every effect: shader(effect_vs, your_fragment_function)

base_color[P] = (p: Pixel2D, u: Effect2D[P]) -> vec4

the pixel's color as 2D drawing makes it without an effect

use_effect[P] = (sh: Shader, params: P)

2D drawing from here on goes through effect sh (made with shader(effect_vs, ...)), with params, until no_effect() or the end of the frame

no_effect = ()

back to drawing without an effect (palette swaps go on: palette_reset ends them)

Textures

smooth_textures = true

whether a texture is smoothed (sampled linearly) when drawn larger, smaller or between pixels, where texture() and load_texture().unwrap() are not told: yes, until pixel_art() makes it no (sharp pixels, no blur and no dark fringes around transparent ones). It is read when a texture is made.

texture = (img: Image, smooth: bool = smooth_textures) -> Texture

upload an image to the GPU (smooth: see smooth_textures)

set_repeat = (t: Texture, on: bool)

a texture that repeats past its edges, for sprite_region (and a shader's sample) beyond them: a source rectangle wider than the texture shows it again and again. Off (the default), what is past an edge is that edge's pixels, stretched. A whole texture repeats, not a part of a sheet: sprite_tiled repeats any part, on every texture.

update_texture = (t: Texture, img: Image)
load_texture = (file: u8[], smooth: bool = smooth_textures) -> Texture | ImageError

a texture from a PNG or JPEG file's bytes: load_texture(embed("hero.png")).unwrap(); smooth: false for sharp pixels when it is drawn larger (pixel art), as every texture is after pixel_art()

free_texture = (t: Texture)

give back a texture's memory (it may not be drawn after): for textures made while the game runs, a save's thumbnail, a level's tiles

Render targets

render_target = (w: int, h: int, smooth: bool = true, depth_texture: bool = false, colors: int = 1) -> RenderTarget

A picture to draw into (draw_to) and then draw (draw_target) or sample in a shader (rt.texture). depth_texture = true: its depth is a texture too, rt.depth_texture, 32-bit float, sampled as any other (sample(t, uv).x, 0 near .. 1 far) by a later pass; a draw into the target may not sample its own color or depth (it panics: copy_depth the depth into another target first). colors = 2 to 4: that many color textures, rt.colors[i] (rt.texture is rt.colors[0]), for a fragment function returning a struct of as many vec4s (one per color); a shader of one color drawn into it (2D drawing too) writes rt.colors[0] and leaves the others as they are.

copy_depth = (from: RenderTarget, to: RenderTarget)

Copy the depth of one render target into another of the same size (both made with depth_texture = true): for a pass that tests against a scene's depth while sampling it, drawn into to and sampling from.depth_texture. A blit on OpenGL and WebGL, an image copy on Vulkan and Metal, a copy in the software renderer.

copy_depth = (from: Texture, to: RenderTarget)

the same, from a depth texture of a render target: rt.depth_texture, or scene_depth()

render_image = (w: int, h: int, draw: () -> void) -> Image

a picture of w x h pixels drawn by draw (with what draw = (): uses, in pixels from its top left corner), at any time: a chart a script saves, a texture made at the start, a 3D scene's thumbnail (camera3d and draw_mesh inside draw are drawn into it). Before any window is open it needs none: the software renderer draws it.

free_render_target = (rt: RenderTarget)

give back a render target's memory (it may not be used after)

draw_to = (rt: RenderTarget)

draw into a render target until draw_to_screen() is called

draw_to_screen = ()

Batching

flush = ()

Shapes

rect = (x: f64, y: f64, w: f64, h: f64, c: vec4)
rect = (pos: vec2, size: vec2, c: vec4)
rect = (r: Rect, c: vec4)
rect_gradient = (x: f64, y: f64, w: f64, h: f64, top: vec4, bottom: vec4)

rectangle with a vertical color gradient

rect_outline = (x: f64, y: f64, w: f64, h: f64, thickness: f64, c: vec4)
rect_outline = (r: Rect, thickness: f64, c: vec4)
triangle = (a: vec2, b: vec2, c: vec2, col: vec4)
triangle_gradient = (a: vec2, b: vec2, c: vec2, ca: vec4, cb: vec4, cc: vec4)

triangle with a color per corner (colors blend across it)

quad_gradient = (a: vec2, b: vec2, c: vec2, d: vec2, ca: vec4, cb: vec4, cc: vec4, cd: vec4)

quad (a, b, c, d in order around it) with a color per corner

circle = (center: vec2, radius: f64, c: vec4, segments: int = 0)
ellipse = (center: vec2, radii: vec2, c: vec4, segments: int = 0)

an ellipse: radii.x across, radii.y up and down (a shadow under a card or a character)

rect_rounded = (x: f64, y: f64, w: f64, h: f64, radius: f64, c: vec4)

a rectangle with rounded corners, each a quarter circle of this radius (a card, a button)

rect_rounded_outline = (x: f64, y: f64, w: f64, h: f64, radius: f64, thickness: f64, c: vec4)

its outline, thickness wide inside it

circle_gradient = (center: vec2, radius: f64, inner: vec4, outer: vec4, segments: int = 48)

circle that fades from inner color at the center to outer at the edge (glows, soft lights)

ring = (center: vec2, radius: f64, thickness: f64, c: vec4, segments: int = 48)
arc = (center: vec2, radius: f64, thickness: f64, start: f64, stop: f64, c: vec4, segments: int = 0)

part of a ring: from angle start to stop (radians, clockwise on screen)

line = (a: vec2, b: vec2, thickness: f64, c: vec4)
polyline = (points: vec2[], thickness: f64, c: vec4, closed: bool = false)

lines through the points, one band without gaps at the bends (mitred: a sharp bend's point cut off at three times the thickness)

polygon = (points: vec2[], c: vec4)

a filled polygon, its points in order around it (either way round); a concave one (a star, an L) is cut into triangles

Sprites

sprite = (t: Texture, pos: vec2, size: vec2 = vec2(0, 0), tint: vec4 = vec4(1, 1, 1, 1), angle: f64 = 0.0, origin: vec2 = vec2(0, 0))

(where each puts a picture, and origin: the table in sprites.jo) draw a texture with its top left corner at pos (origin: another point of it), optionally scaled (size: in the screen's units; vec2(0, 0): its own), turned and tinted. origin is a normalized placement anchor before rotation, not its pivot; rotation is about the offset center.

sprite_region = (t: Texture, src: vec4, center: vec2, size: vec2, tint: vec4 = vec4(1, 1, 1, 1), angle: f64 = 0.0, origin: vec2 = vec2(0.5, 0.5))

draw part of a texture (src = x, y, w, h in its pixels) with its middle at center (origin: another point of it), size big. A src past the texture's edges shows the edge pixels stretched, unless set_repeat(t, true) (the texture again); sprite_tiled repeats a part of one. center means the draw point: actual center = center + (0.5 - origin) * abs(size). Angle turns around that actual center; origin does not stay at the draw point during rotation.

sprite_tiled = (t: Texture, area: Rect, offset: vec2 = vec2(0, 0), scale: f64 = 1.0, tint: vec4 = vec4(1, 1, 1, 1), src: vec4 = vec4(0, 0, 0, 0))

fill area with copies of a texture side by side (or of a part of it, src: x, y, w, h in its pixels), each scale times its size, the copies shifted by offset; those at area's edges are cut. A background that scrolls and repeats (Godot's motion_mirroring), drawn without a camera, here a third as fast as the camera: A strip repeats one way when area is as tall (or wide) as a copy. Any texture, any part of one: no set_repeat needed.

draw_target = (rt: RenderTarget, pos: vec2 = vec2(0, 0), size: vec2 = vec2(0, 0), tint: vec4 = vec4(1, 1, 1, 1), color: int = 0)

draw a render target's texture (flipped: render targets are stored bottom-up); color: which of a target of several colors (render_target(..., colors = n)), rt.colors[color]

Text

set_font = (f: Font)

the font text() and text_width() use (load_font makes one); set_font() goes back to the built-in

set_font = ()
text_width = (s: str, size: f64 = 20.0, mono: bool = false) -> f64

how wide text is drawn (the widest of its lines)

fit_text = (s: str, width: f64, size: f64 = 20.0) -> str

s as it fits in a line width wide: cut short, ending in …, when it is wider (a long name on a button, a table's cell)

text_height = (s: str, size: f64 = 20.0) -> f64

how tall text is drawn: its lines, each size * 1.25 below the one before (pixel_font's: its characters' pixels, each line a pixel apart)

enum Align:
    left
    center
    right
wrap_text = (s: str, width: f64, size: f64 = 20.0) -> str[]

s broken into lines no wider than width, at spaces, and between the characters of Chinese, Japanese and Korean (a word wider than that has a line of its own; a line break in s starts a new line; 。、」 and the like stay at the end of a line, not the start of the next)

text_wrapped = (s: str, pos: vec2, width: f64, size: f64 = 20.0, color: vec4 = vec4(1, 1, 1, 1), align: Align = .left, shadow: vec4 = vec4(0, 0, 0, 0), chars: int = -1) -> f64

text in a column width wide from pos (its top-left corner), broken into lines at spaces, each line to the left, centered or to the right; the height it took (LÖVE's printf). chars: only the first that many characters, laid out where the whole text puts them (dialogue that types itself out does not jump to the next line midway through a word)

text = (s: str, pos: vec2, size: f64 = 20.0, color: vec4 = vec4(1, 1, 1, 1), shadow: vec4 = vec4(0, 0, 0, 0), mono: bool = false, chars: int = -1)

draw text with its top-left corner at pos. The built-in font has ASCII, the accented letters of European languages (é ñ ü ł ő č ş ș), symbols (° ² ½ ± × ÷), Cyrillic (Привет), Greek (θ ω π Δ λ μ), − √ ≈ ≠ ≤ ≥ ∞ ∑ ∫ ∂ ∝ ⋅ ∇ ∈, arrows (→ ← ↑ ↓ ↔), sub- and superscript digits (v₀, x⁴, 10⁻⁹), ′ ″ and ✓ ✗; characters a font does not have show as ? (load_font: others); shadow: a color drawn under it, a little down and right, to read over a busy scene (shadow = rgba(0, 0, 0, 0.7)). mono: each character in a cell of the same width, so columns made with "{name:<12} {score:>5}" line up (a scoreboard, a table, a roguelike's map). chars: only the first that many characters (dialogue appearing letter by letter: where the rest will be does not move); -1: all

text_rich = (s: str, pos: vec2, size: f64 = 20.0, color: vec4 = vec4(1, 1, 1, 1), width: f64 = 0.0, chars: int = -1, shadow: vec4 = vec4(0, 0, 0, 0)) -> f64

text with parts of it styled where they are: [color=#ff8040]...[/color] (or a name: red, green, blue, yellow, orange, purple, cyan, magenta, gray, white, black), [b]...[/b] bold, [i]...[/i] slanted, [[ for a [. width above 0: lines broken to fit it (as wrap_text). chars: only the first that many characters (dialogue typing itself out). The height it took.

text_centered = (s: str, center: vec2, size: f64 = 20.0, color: vec4 = vec4(1, 1, 1, 1), shadow: vec4 = vec4(0, 0, 0, 0), mono: bool = false)

text centered on center (horizontally and vertically; each of its lines centered). The built-in font is proportional ("i" is narrower than "@"): a grid of characters, a roguelike's map, draws each one centered in its cell

font.jo

Fonts: load_font reads a TrueType or OpenType font (.ttf, .otf, or the first font of a .ttc) and makes the characters text() draws with, sharp at any size (signed distance fields). set_font chooses the font text() and text_width() use; set_font() goes back to the built-in one.

title_font = load_font(embed("PressStart2P.ttf")).unwrap()
draw = ():
    set_font(title_font)
    text_centered("GAME OVER", vec2(640, 300), 64)
    set_font()

It has the printable ASCII characters, Latin-1 and Latin Extended-A (accented letters), common punctuation (quotes, dashes, the euro sign), and any others listed in extra. A character the font does not have is drawn with the built-in one (Latin in a Japanese font), else as ?.

Japanese, Chinese or Korean text needs a font with them (Noto Sans CJK, which most systems have), and its characters in extra: give it all the text that will be shown (load_font(file, extra = story).unwrap()). wrap_text breaks lines between their characters. (Variable fonts with CFF2 outlines are not read: a static .otf or .ttf of the same font is.)

struct Font:
    texture: Texture
    slots: {int: int}           # a character (its code point) -> its cell in the atlas
    ascii: int[]                # (the same for the first 128, faster; -1: none)
    adv: f64[]                  # each cell's advance, in pixels at `px`
    cols: int                   # cells in a row of the atlas
    cell: f64                   # a cell's size, in atlas pixels
    px: f64                     # the size the characters were made at
    base: f64                   # the baseline's height in a cell
    spread: f64                 # distance (in atlas pixels) the field fades over
    bitmap = false              # (pixel_font: hard pixels at whole-number scales, not distances)
    kerning: __FontKern[]       # optional shared pair tables/cache; empty for built-in/bitmap fonts

Making the atlas

error struct FontError:
    message: str

Font bytes were unsupported or damaged.

load_font = (file: u8[], extra: str = "") -> Font | FontError

a font from TrueType/OpenType bytes; FontError describes unsupported or damaged input. Horizontal kerning comes from GPOS's kern feature (pairs, classes and extension lookups), or the legacy kern table. Drawing, measuring, wrapping and text-field carets use the same advances. mono = true and the built-in/pixel fonts keep their fixed metrics. This is pair positioning, not script shaping: contextual substitutions, mark attachment and variable font/device adjustments are not applied.

screen.jo

How a game's picture fits windows of any size and shape.

A game is drawn in 2D units: the size given to window() (its design size; design_size changes it while the game runs), so the same coordinates work in any window. Two settings decide how that maps to the window's pixels:

screen_fit chooses what another window shape shows: .expand keeps the design area and adds space around it (the default; visible_rect says what is shown); .letterbox keeps just the design area with bars (letterbox_color); .crop fills the window and cuts off the edges; .stretch fills it by stretching shapes; .native makes one unit one desktop point (on a screen at 200%, two screen pixels). screen_size gives the window's size in these units.

screen_fit(.letterbox)
render_resolution(320, 180)   # sharp pixels, whole steps (2x, 3x...), letterboxed by default
render_resolution(0, 0)       # return to the window's resolution
pixel_art()                  # render at the design size; also choose pixel_font and sharp shapes
render_scale(0.5)            # half each dimension: a quarter as many pixels, scaled smoothly
full_resolution()            # in draw: finish the frame at full resolution, e.g. a sharp HUD

render_resolution keeps 2D units at the design size; give both resolutions the same shape. The picture uses the screen fit chosen above. pixel_art also makes later textures sharp (smooth_textures changes that), and draws lines, circles, rings and rects without smoothed edges, so a palette has no shades between its colors. set_font overrides its pixel_font. A window designed small opens a whole number of times larger.

Drawing that needs it goes to an offscreen canvas, put on the window when the frame ends; the mouse is mapped back the same way (mouse_pos is in 2D units).

enum Fit: expand, letterbox, crop, stretch, native
screen_fit = (mode: Fit)
letterbox_color = (c: vec4)
render_resolution = (w: int, h: int, smooth: bool = false, whole: bool = true)
render_scale = (s: f64)
full_resolution = ()

the rest of this frame's drawing at the window's own resolution, over what was drawn at the low one of pixel_art() (or render_resolution, render_scale), in the same 2D units: a HUD whose text stays sharp, where text a few pixels tall at 320 x 180 is unreadable (in the built-in font: pixel_font() and whole-pixel shapes are for pixel_art's resolution). Without a low resolution it does nothing.

pixelart.jo

Pixel art: pixel_art(), PICO-8's kind of font, palette swaps (PICO-8's pal) and pictures written as text.

pixel_art = (smooth: bool = false)

one 2D unit is one sharp pixel: render_resolution at the design size (screen.jo). Textures made after it are sharp too (smooth_textures); lines, rects, circles, rings, arcs and ellipses are whole pixels in exactly their colors, and text() draws in pixel_font() unless set_font says

The pixel font

pixel_font = () -> Font

PICO-8's kind of font, for tiny resolutions: each character 3 x 5 pixels, 4 apart, drawn in hard pixels at a whole-number scale: 1 at size 6 (a line 6 pixels high), 2 at 12, ... (a size between is drawn at the whole number below; under 6, at 1). It has the printable ASCII characters, the lowercase letters drawn as capitals, as PICO-8 draws them; others show as ?. Under pixel_art() text() draws with it, unless set_font gave another:

Palette swaps

palette_swap = (from: vec4, to: vec4, screen: bool = false)

What is drawn in one color is drawn in another, as with PICO-8's pal(c0, c1): an enemy of another color from the same sprite, a flash as something is hit, a fade through a palette's colors. Swaps stay from frame to frame until palette_reset(), up to 16 at once (a color swapped again changes its swap; swapped to itself, it has none). A pixel is in the color from when its red, green and blue are each within one 255th of from's; its alpha is kept. screen = true swaps the color in the whole picture as it is shown, all the frame drew (PICO-8's pal(c0, c1, 1)), once as the frame ends. The swaps of drawing are an effect (use_effect): one of the game's own is used in their place until no_effect().

palette_reset = ()

no palette swaps (of drawing and of the screen) from here on

Pictures written as text

pixel_image = (rows: str, palette: vec4[]) -> Image

a picture written as text, a character a pixel and a line a row (blank lines and the lines' indentation left out): 0 to 9 and a to f are the colors of palette with those numbers, as PICO-8's sprite editor numbers its 16 (g to z: 16 to 35; capitals the same), and "." is clear. For sprites drawn in the code:

softgl.jo

soft_rendering = () -> bool

Images, sprites and tilemaps

# example: images, textures and sprites
window("Sprites", 960, 540)

# an image made pixel by pixel (load_image(embed("hero.png")).unwrap() reads one from a file)
img = image(16, 16)
loop y in 0..16:
    loop x in 0..16:
        d = length(vec2(x - 7.5, y - 7.5))
        if d < 7.0: img.set(x, y, hsv(y / 40.0, 0.8, 1.0))
        if d < 3.0: img.set(x, y, WHITE)
ball = texture(img, false)               # on the GPU; false: sharp pixels when scaled

t = 0.0
update = (dt: f64): t += dt

draw = ():
    clear(rgb(0.12, 0.12, 0.16))
    sprite(ball, vec2(100, 100))                                   # its own size
    sprite(ball, vec2(200, 100), vec2(128, 128))                   # scaled up
    sprite(ball, vec2(400, 100), vec2(128, 128), rgb(0.4, 1, 0.6), t)   # tinted and turned
    loop i in 0..12:
        a = i / 12.0 * TAU + t
        sprite(ball, vec2(700 + 120 * cos(a), 300 + 120 * sin(a)), vec2(32, 32))

Run it in the playground

image.jo

Images: RGBA8 pixel buffers, PNG decoding (with a built-in inflate; JPEG: jpeg.jo), procedural helpers.

struct Image:
    width: int
    height: int
    pixels: u8[]          # RGBA, row-major, top row first
image = (w: int, h: int, fill: vec4 = vec4(0, 0, 0, 0)) -> Image
set = (img: mut Image, x: int, y: int, c: vec4)
get = (img: Image, x: int, y: int) -> vec4
resized = (img: Image, w: int, h: int) -> Image

the image at another size (a save's thumbnail, an icon): each new pixel the average of the pixels it covers when smaller, smoothly between them when larger

Inflate (RFC 1951)

inflate = (src: u8[], start: int = 0) -> u8[]?

read a raw deflate stream (as deflate writes, or zlib's after its 2-byte header: start = 2); none if it is damaged or cut short

struct Inflater

inflate a few milliseconds at a time, as a Deflater deflates: a big one (a level, a song) in the frames while the game goes on. Start it, step it each frame, and take the bytes when done:

inflater = (src: u8[], start: int = 0) -> Inflater

an Inflater for this stream, to step until it is done

step = (s: mut Inflater, seconds: f64) -> bool

go on for about this many seconds (it looks at the clock after each 64 KB it writes); true when it is done (or has found the stream damaged)

progress = (s: Inflater) -> f64

how much of the stream it has been through, 0 to 1

result = (s: mut Inflater) -> u8[]?

the inflated bytes, none if the stream is damaged or cut short (if step has not said done yet, this does the rest of the work first)

PNG

error struct ImageError:
    message: str

A PNG/JPEG could not be decoded. message describes the unsupported or damaged input.

load_png = (file: u8[]) -> Image | ImageError

decode a PNG file; ImageError for unsupported or damaged data

load_image = (file: u8[]) -> Image | ImageError

decode PNG/JPEG bytes; ImageError for unsupported or damaged input. embed checks that a file exists, not that it decodes: load_image(embed("hero.png")).unwrap() asserts trusted content.

Deflate (RFC 1951)

deflate = (src: u8[]) -> u8[]

compress bytes into a raw deflate stream (inflate reads it back)

struct Deflater

deflate a few milliseconds at a time: a big one (a game's save, megabytes) in the frames while the game goes on, giving the same bytes as deflate. Start it when saving, step it each frame, and write when it says it is done:

deflater = (src: u8[]) -> Deflater

a Deflater for these bytes, to step until it is done

step = (d: mut Deflater, seconds: f64) -> bool

go on for about this many seconds (it looks at the clock after each 4 KB of the input); true when it is done

progress = (d: Deflater) -> f64

how much of the input it has been through, 0 to 1

result = (d: mut Deflater) -> u8[]

the deflated bytes (if step has not said done yet, this does the rest of the work first)

PNG writing

encode_png = (img: Image) -> u8[]
save_png = (path: str, img: Image) -> bool

write a PNG to path (false: file_error describes write failure), destination first as write_bytes

screenshot = () -> Image

read what has been drawn into an image: the window's pixels (on a scaled display more than the size asked for in window(): resized(img, w, h) makes it smaller), or the render target being drawn to (draw_to)

jpeg.jo

JPEG images: load_jpeg (and load_image, which tells PNG and JPEG apart). Baseline and progressive JPEGs (Huffman coded, 8-bit), any sampling (4:4:4, 4:2:2, 4:2:0...), grayscale, RGB and Adobe's CMYK, restart markers. As libjpeg decodes them by default: its integer inverse DCT, smooth upsampling of halved color, its color conversion. Not read: arithmetic coding, lossless and 12-bit JPEGs (rare): none, as for a damaged file.

load_jpeg = (file: u8[]) -> Image | ImageError

decode a JPEG file into RGBA pixels; ImageError for damaged or unsupported data

sprites.jo

Sprite sheets and animations. A sheet is a texture cut into frames: a grid of equal frames (sprite_sheet), or the frames and animations Aseprite exports (load_aseprite: File > Export Sprite Sheet with "JSON Data" on; each tag becomes an animation). Pixel art wants its texture loaded unsmoothed: load_texture(file, false).unwrap(), as every texture is after pixel_art().

Where each puts a picture: the point given is its top left corner or its middle, and origin (vec2(0, 0): the top left corner, vec2(0.5, 0.5): the middle, vec2(0.5, 1): the middle of the bottom edge, a character's feet) puts another point of the picture there. An angle turns it around its middle, after the origin offset; origin is an unrotated placement anchor, not a fixed rotation pivot. For a draw point P and drawn size S, the center is P + (vec2(0.5, 0.5) - origin) * abs(S), and the corners rotate about that center. A bottom-center origin therefore does not keep the feet at P when angle is nonzero. Negative size / flip_x / flip_y mirror the image without mirroring this anchor offset.

sprite(t, pos)   # pos: its top left corner (origin = vec2(0, 0))
sprite_region(t, src, center, size)   # center: its middle (origin = vec2(0.5, 0.5))
draw_frame(sheet, i, center)   # its middle
draw_anim(sheet, clip, elapsed(), center)   # its middle
anim.draw(center)   # its middle (an AnimPlayer)
draw_tile(map, id, center)   # its middle
sprite_tiled(t, area)   # fills area (x, y: its top left corner)
draw_target(rt, pos)   # its top left corner
text(s, pos)   # the top left corner; text_centered(s, center): the middle

hero = sprite_sheet(load_texture(embed("hero.png"), false).unwrap(), 32, 32)
walk = animation(4, 7, 10.0)                    # frames 4 to 7, ten a second
draw = ():
    draw_anim(hero, walk, elapsed(), pos, 3.0)  # three times as big

An AnimPlayer plays the sheet's animations by name, each from its start when it changes:

hero.anims["idle"] = animation(0, 1, 2.0)
hero.anims["run"] = animation(2, 5, 12.0)
anim = anim_player(hero)
# in update:
anim.play(if moving: "run" else: "idle")   # (the same one again goes on)
# in draw:
anim.draw(feet, origin = vec2(0.5, 1), flip_x = facing < 0.0)
struct Animation:
    frames: int[]               # the sheet's frames, in order
    durations: f64[]            # how long each one shows (seconds)
    looping = true
struct SpriteSheet:
    texture: Texture
    frames: vec4[]              # each frame's rectangle in the texture: x, y, width, height
    anims: {str: Animation}     # its animations by name (load_aseprite: its tags)
sprite_sheet = (t: Texture, frame_w: int, frame_h: int, count: int = 0, spacing: int = 0, margin: int = 0) -> SpriteSheet

a sheet of equal frames in a grid, numbered from 0 left to right, then down (count: how many there are, if the last row is not full; spacing: pixels between frames; margin: around them)

animation = (frames: int[], fps: f64 = 10.0, looping: bool = true) -> Animation

an animation through these frames, fps a second

animation = (first: int, last: int, fps: f64 = 10.0, looping: bool = true) -> Animation

frames first..last (inclusive)

anim_length = (a: Animation) -> f64

how long it takes to go through once (seconds)

anim_frame = (a: Animation, t: f64) -> int

the frame showing t seconds after it started (a non-looping one stays on its last frame)

anim_done = (a: Animation, t: f64) -> bool

has a non-looping animation finished, t seconds after it started?

draw_frame = (s: SpriteSheet, frame: int, center: vec2, scale: f64 = 1.0, tint: vec4 = vec4(1, 1, 1, 1), angle: f64 = 0.0, flip_x: bool = false, flip_y: bool = false, origin: vec2 = vec2(0.5, 0.5))

frame i of the sheet, its middle at center (scale: its size times this; flip_x: mirrored, to face the other way; origin: the point of it at center, vec2(0.5, 1) its bottom edge's middle)

draw_anim = (s: SpriteSheet, a: Animation, t: f64, center: vec2, scale: f64 = 1.0, tint: vec4 = vec4(1, 1, 1, 1), angle: f64 = 0.0, flip_x: bool = false, flip_y: bool = false, origin: vec2 = vec2(0.5, 0.5))

the frame an animation shows t seconds after it started

draw_anim = (s: SpriteSheet, name: str, t: f64, center: vec2, scale: f64 = 1.0, tint: vec4 = vec4(1, 1, 1, 1), angle: f64 = 0.0, flip_x: bool = false, flip_y: bool = false, origin: vec2 = vec2(0.5, 0.5))

the same, with the sheet's animation of this name (sheet.anims: Aseprite's tags, or set with sheet.anims["run"] = animation(2, 5))

struct AnimPlayer:
    sheet: SpriteSheet
    name = ""                   # the animation playing ("": none yet)
    start = 0.0                 # when it started (elapsed())

plays a sheet's animations by name: the one playing, and when it started. Changing to another starts that one from its first frame; play with the one playing goes on with it. Its clock is elapsed(), so it goes on while a game's own pause screen shows (draw_anim(sheet, p.name, t, ...) draws it on a clock of the game's own).

anim_player = (sheet: SpriteSheet, name: str = "") -> AnimPlayer
play = (p: mut AnimPlayer, name: str, restart: bool = false)

play the sheet's animation of this name: from its start if another was playing (or restart: even if it was this one)

anim_time = (p: AnimPlayer) -> f64

how long the animation playing has played (seconds)

anim_frame = (p: AnimPlayer) -> int

the frame it shows now

anim_done = (p: AnimPlayer) -> bool

has a non-looping animation played to its end (an attack, a jump's take-off)?

draw = (p: AnimPlayer, center: vec2, scale: f64 = 1.0, tint: vec4 = vec4(1, 1, 1, 1), angle: f64 = 0.0, flip_x: bool = false, flip_y: bool = false, origin: vec2 = vec2(0.5, 0.5))

draw the frame it shows now, as draw_frame does

load_aseprite = (t: Texture, json: str) -> SpriteSheet | JsonError

a sheet from Aseprite's export: its texture, and the JSON it wrote beside it (as an array or a hash of frames). Tags become animations (forward, reverse or ping-pong), with each frame's own duration.

tilemap.jo

Tilemaps: layers of tiles drawn from a tileset image. Make one from text (tile_layer: each character is a tile), or load a map made in Tiled (load_tiled("level.tmx", embed_dir("assets")): .tmx or .tmj, with its tilesets and their images found by their paths). Draw it with draw_tilemap, and move boxes through it with tilemap_move, which stops them at solid tiles. Every tile is solid unless set_tile_shape says otherwise: a one-way platform (landed on from above, passed through from below and the sides), a slope (a floor that rises or falls across the tile), or empty (scenery). Past the map's edges there is nothing (a box walks off its side and falls) unless edges says there are walls. Tiles can have properties of any name (hurts, coin), set in Tiled or with set_tile_prop, and tilemap_touches asks whether a box touches one (hazards); tilemap_tiles says which tiles a box is in.

tiles = tileset(load_texture(embed("tiles.png"), false).unwrap(), 16, 16)
level = tilemap(tiles, [tile_layer("walls", WALLS, "#=")])     # '#': tile 1, '=': tile 2
update = (dt: f64):
    global box
    m = tilemap_move(level, 0, box, vel * f32(dt))
    box = m.rect
    if m.hit_y: vel.y = 0.0
draw = (): draw_tilemap(level)

In Tiled, a tile's custom property shape (a string) is its shape for tilemap_move, as set_tile_shape would set it: solid, empty, platform, or slope 0 1 (its floor's height at the tile's left and right sides, 0 to 1). Every other custom property of a tile is kept as text: tile_prop(level, id, "hurts") is "true" for a bool property ticked. The map's own custom properties are level.props, a layer's layer.props, an object's o.props. A tile object (Insert Tile) has its tile in o.tile and its rect from its top left corner, as every object's.

struct Tileset:
    texture: Texture
    tile_w: int
    tile_h: int
    columns: int
    first = 1                   # the id of its first tile (Tiled's firstgid)
    count = 0                   # tiles in it
    spacing = 0                 # pixels between tiles in the image
    margin = 0                  # around them
struct TileLayer:
    name: str
    width: int                  # in tiles
    height: int
    tiles: int[]                # tile ids, a row at a time from the top; 0: no tile
    visible = true
    offset = vec2(0, 0)         # drawn this far from the map's corner (Tiled's layer offset; tile_at and tilemap_move do not move with it)
    parallax = vec2(1, 1)       # how fast it scrolls with the camera: 1 with the map, 0.5 half as fast (far away), 0 not at all
    opacity = 1.0
    props: {str: str}           # its custom properties in Tiled, as text
    image: Texture? = none      # an image layer's picture (Tiled's image layer: no tiles), its top left corner at offset
    repeat_x = false            # (an image layer: repeated across, down)
    repeat_y = false
struct MapObject:
    name: str
    kind: str                   # its class (Tiled's "type")
    layer: str                  # the object layer it is on
    rect: Rect                  # where (a point: width and height 0); a tile object's too, top left
    props: {str: str}           # its custom properties, as text
    tile = 0                    # a tile object's tile (Tiled's Insert Tile), an id as tile_at gives; 0: not one
    flip_x = false              # (a tile object: drawn mirrored)
    flip_y = false
    id = 0                      # its id in Tiled (what an object property refers to)
    rotation = 0.0              # degrees, clockwise (around its top left corner; a tile object's, its bottom left)

an object placed in Tiled (an object layer's): a spawn point, a door, a coin...

enum TileShape:
    solid
    empty
    platform
    slope(left: f64, right: f64)

how a tile stops what moves through the map (tilemap_move): solid; empty (scenery); platform (one-way: landed on from above, passed through from below and the sides); slope(left, right), a floor whose height (0: the tile's bottom, 1: its top) goes from left at the tile's left side to right at its right side: slope(0, 1) rises to the right, slope(0, 0.5) then slope(0.5, 1) gently over two tiles (passed through from below)

enum MapEdges: open, sides, closed

what is past the map's edges, for tilemap_move: nothing (open: a box walks off the side and falls); walls at its left and right sides (sides: from far above to far below it); or walls all round (closed)

struct Tilemap:
    tile_w: int
    tile_h: int
    width: int                  # in tiles
    height: int
    tilesets: Tileset[]
    layers: TileLayer[]
    objects: MapObject[]
    shapes: TileShape[]         # by tile id (set_tile_shape); solid past its end
    props: {str: str}           # the map's custom properties in Tiled, as text
    tile_props: {int: {str: str}}   # each tile's custom properties, by tile id (tile_prop, set_tile_prop)
    tile_anims: {int: Animation}    # a tile's animation (Tiled's tile animations): its frames are tile ids
    edges = MapEdges.open       # tilemap_move: solid walls at the map's edges (`level.edges = .sides`)
    parallax_origin = vec2(0, 0)    # where the view's middle is when layers with a parallax are where their offset puts them
struct TileCell:
    x: int
    y: int
    id: int

a tile a box touches (tilemap_tiles): its column, its row, and its id

struct TileMove:
    rect: Rect                  # where the box ended up
    hit_x: bool                 # it was stopped going sideways
    hit_y: bool                 # ... or up or down (moving down: it landed)
    platform = -1               # the one of `platforms` it stands on after the move (-1: none)
    solid = -1                  # ... of `solids`
tileset = (t: Texture, tile_w: int, tile_h: int, spacing: int = 0, margin: int = 0) -> Tileset

a tileset: an image of equal tiles in a grid, numbered from first (1) left to right, then down

tile_layer = (name: str, rows: str, chars: str) -> TileLayer

a layer from rows of text: the character at position i of chars is tile i + 1, and any other character (a space, a dot) is no tile; a character the rows never use skips a number ("_#": '#' is tile 2). Tiles count from 1, 0 being no tile: tile 1 is the tileset's top-left tile, which a sprite_sheet of the same picture calls frame 0, so tile n is frame n - 1 (with chars "123456ab", 'a' is tile 7, frame 6). Rows of spaces are rows of the map (open sky); only an empty first line (the line break after the opening quote) and a last line of spaces (before the closing quote) are left out. For tilemap_move every tile is solid, floor tiles too: a tile walked over is set_tile_shape(map, id, .empty), or a character left out of chars (no tile).

tilemap = (ts: Tileset, layers: TileLayer[]) -> Tilemap

a map of these layers, drawn with one tileset

layer_index = (m: Tilemap, name: str) -> int

the index of the layer with this name (-1: none)

tile_at = (m: Tilemap, layer: int, x: int, y: int) -> int

the tile at column x, row y of a layer (0 outside the map)

tile_at = (m: Tilemap, layer: int, p: vec2) -> int

the tile under a point (in pixels)

set_tile = (m: mut Tilemap, layer: int, x: int, y: int, id: int)
set_tile_shape = (m: mut Tilemap, id: int, shape: TileShape)

how tile id stops what moves (every tile is solid until this says otherwise)

tile_shape = (m: Tilemap, id: int) -> TileShape
tilemap_size = (m: Tilemap) -> vec2

the map's size in pixels

draw_tilemap = (m: Tilemap, layer: int = -1, at: vec2 = vec2(0, 0), tint: vec4 = vec4(1, 1, 1, 1))

draw a layer (-1: every visible layer, bottom first), with the map's top left corner at at. Only the tiles on the screen are drawn, wherever the camera is. A layer is drawn at its offset, and one with a parallax other than 1 moves with the camera at that fraction of its speed (as Tiled shows it: where the view's middle is at the map's parallax_origin, at its offset); an image layer draws its picture there (repeated, if it repeats); tiles with an animation in Tiled go through its frames.

draw_tile = (m: Tilemap, id: int, center: vec2, size: vec2 = vec2(0, 0), tint: vec4 = vec4(1, 1, 1, 1))

draw tile id (from the map's tilesets; Tiled's flip bits mirror it), its middle at center, its size the map's tiles' (or size): a tile object (draw_tile(level, o.tile, center(o.rect), vec2(o.rect.w, o.rect.h))), a tile picked up, an editor's palette

tilemap_hits = (m: Tilemap, layer: int, r: Rect) -> bool

does a box (in pixels) touch a tile of the layer? Any tile, whatever its shape: an .empty one (scenery, spikes) too; tilemap_touches asks for tiles with a property, tilemap_tiles says which tiles they are

tilemap_tiles = (m: Tilemap, layer: int, r: Rect) -> TileCell[]

the tiles of the layer a box touches (no empty cells), row by row from the top: what a player stands in, loop c in tilemap_tiles(level, 0, box): if tile_prop(level, c.id, "coin") != none: set_tile(level, 0, c.x, c.y, 0)

tilemap_touches = (m: Tilemap, layer: int, r: Rect, prop: str) -> bool

does a box touch a tile with this custom property (set in Tiled, or by set_tile_prop), one not "false", "0" or empty? Hazards: if tilemap_touches(level, 0, box.grow(-2), "hurts"): die()

tilemap_touches = (m: Tilemap, layer: int, r: Rect, id: int) -> bool

does a box touch tile id?

tile_prop = (m: Tilemap, id: int, name: str) -> str?

a custom property of tile id, as text (a Tiled tile's, or set_tile_prop's); none: it has none of that name

set_tile_prop = (m: mut Tilemap, id: int, name: str, value: str)
tilemap_move = (m: Tilemap, layer: int, r: Rect, d: vec2, drop: bool = false, platforms: Rect[] = [], solids: Rect[] = []) -> TileMove

move a box by d, stopping it against the layer's tiles: sideways first, then up or down, so it slides along walls and floors. However far it moves in one step, it does not pass through a solid tile. Platforms stop it only coming down onto them (drop: not even then, to drop through one); on a slope it walks up and down the slope's floor, staying on it going down. Past the map's edges there is nothing, unless its edges say there are walls (level.edges = .sides): a box walks off the side and falls. Boxes that are not tiles stop it too: platforms (one-way, as platform tiles: moving platforms, landed on from above) and solids (stopping it from every side: a crate, a door); the result's platform (or solid) says which one it stands on after the move, for a moving one to carry it in the next frame (see "Platformers" in the docs).

Tiled

load_tiled = (path: str, files: {str: u8[]}) -> Tilemap | JsonError

a map made in Tiled, with its tilesets and their images, from files built into the program: The map may be Tiled's XML (.tmx) or JSON (.tmj), its tilesets inside it or in files of their own (.tsx, .tsj), found as Tiled does: next to the file that names them. Tile layers (also inside groups) become layers, with their offsets, parallax factors, opacity and properties (a group's passed on to its layers); image layers become layers with a picture (image, drawn by draw_tilemap, repeated if Tiled repeats it); object layers become objects; tile animations play in draw_tilemap; tiles stay sharp (no smoothing). Not read: infinite maps, maps that are not orthogonal, tilesets made of separate images, a layer's tint color, Wang sets.

load_tiled = (text: str, textures: Texture[]) -> Tilemap | JsonError

a map saved by Tiled (its text: XML, .tmx, or JSON, .tmj), with its tilesets embedded in it (Tiled: in the Tilesets view, "Embed Tileset"), and a texture for each tileset, in the map's order (load_tiled(path, files) finds tileset files and images by itself). Layer data can be plain, CSV or base64 (uncompressed, zlib or gzip). Image layers are layers with no picture here (load_tiled(path, files) loads theirs).

Platformers

How the pieces fit for a platformer (the program here is one): tilemap_move for running and landing (one-way platforms, slopes, drop to fall through a platform), level.edges = .sides for walls at a level's ends, platforms (and solids) for moving platforms (move them first, then carry what stood on one by what it moved: the move's platform says which), hazards as a tile's property (tilemap_touches(level, 0, box, "hurts"); in Tiled, a custom property of the tile), a wall slide from hit_x, coyote time and a jump buffer as two timers, a camera held inside the level with clamp, and fixed_update for the same jumps at any frame rate. sloppy new mygame platformer starts a project with slopes, coins and a camera; AnimPlayer (sprites) plays a character's animations by name, and sprite_tiled repeats a background as the camera moves.

# example: platformers
# a level with spikes, walls at its sides, and a platform that carries the player across a pit;
# running, jumping (with coyote time and a jump buffer), sliding down walls and jumping off them,
# and a camera that stays inside the level. Arrows or A/D to run, space to jump.
window("Platformer", 960, 540)
const T = 32

LEVEL = r"
......................................
......................................
......................................
......................................
......................................
......................................
......................................
......................................
......................................
...............................o......
.............................=====....
...........o..........................
..........===.....................#...
..........................#.......#...
...@......................#.......#...
########............#######^^^^####...
########^^^^^^^^^^^^##################
"

# the tiles: ground, a one-way platform, spikes (drawn here; a tileset image does as well)
img = image(3 * T, T)
loop y in 0..T:
    loop x in 0..T:
        img.set(x, y, rgb(0.42, 0.3, 0.22))
        if y < 8: img.set(T + x, y, rgb(0.7, 0.5, 0.3))
        if y > T - 2 * abs(x % 16 - 8) * 2: img.set(2 * T + x, y, rgb(0.85, 0.25, 0.25))
level = tilemap(tileset(texture(img), T, T), [tile_layer("ground", LEVEL, "#=^")])
set_tile_shape(level, 2, .platform)
set_tile_shape(level, 3, .empty)            # spikes: passed into, not stood on...
set_tile_prop(level, 3, "hurts", "true")    # ...and they hurt (in Tiled: a custom property of the tile)
level.edges = .sides                        # walls at the level's left and right ends

# a moving platform: where it is, and how far it moved in the last step (to carry its rider)
struct Mover:
    rect: Rect
    from: vec2
    to: vec2
    t = 0.0
    moved = vec2(0, 0)
movers = [Mover(Rect(8 * T, 15 * T, 3 * T, 10), vec2(8 * T, 15 * T), vec2(17 * T, 15 * T))]

const RUN = 300.0
const JUMP = 760.0
const GRAVITY = 2200.0
start = vec2(3 * T, 14 * T)
box = Rect(start.x, start.y, 22, 30)
vel = vec2(0, 0)
on_ground = false
coyote = 0.0        # time left to jump after running off a ledge
buffered = 0.0      # time left for a jump pressed just before landing
wall = 0.0          # -1: a wall on the left is touched, 1: on the right
riding = -1         # the mover stood on
cam = start
action("jump", [.key(.space), .key(.up), .button(.a)])

# the game in steps of 1/60 s, whatever the frame rate (a press is seen in one step only)
update = (dt: f64): fixed_update(dt, step)

step = (dt: f64):
    global box, buffered, cam, coyote, on_ground, riding, vel, wall
    # the movers move first, and carry what stands on them
    loop mut mv in movers:
        mv.t += dt
        p = mix(mv.from, mv.to, f32(0.5 - 0.5 * cos(mv.t * 0.8)))
        mv.moved = p - vec2(mv.rect.x, mv.rect.y)
        mv.rect.x = p.x
        mv.rect.y = p.y
    if riding >= 0: box = tilemap_move(level, 0, box, movers[riding].moved).rect
    move = input_axis().x
    vel.x = approach(vel.x, move * RUN, 14.0, dt)
    vel.y += GRAVITY * dt
    if vel.y < 0.0 and not action_down("jump"): vel.y += GRAVITY * dt      # let go early: a short hop
    # sliding down a wall pushed into
    if wall != 0.0 and move == wall and not on_ground: vel.y = min(vel.y, 120.0)
    coyote -= dt
    buffered -= dt
    if on_ground: coyote = 0.1
    if action_pressed("jump"): buffered = 0.12
    if buffered > 0.0 and (coyote > 0.0 or wall != 0.0):
        if coyote <= 0.0: vel.x = -wall * RUN          # off a wall: away from it
        vel.y = -JUMP
        buffered = 0.0
        coyote = 0.0
    hit = tilemap_move(level, 0, box, vel * f32(dt), drop = input_axis().y > 0.5, platforms = movers.map((mv): mv.rect))
    box = hit.rect
    wall = 0.0
    if hit.hit_x:
        wall = sign(vel.x)
        vel.x = 0.0
    on_ground = hit.hit_y and vel.y > 0.0
    if hit.hit_y: vel.y = 0.0
    riding = hit.platform
    # spikes, or a fall out of the level: back to the start
    if tilemap_touches(level, 0, box.grow(-4), "hurts") or box.y > tilemap_size(level).y:
        box = Rect(start.x, start.y, box.w, box.h)
        vel = vec2(0, 0)
    # the camera follows, and stops at the level's edges
    size = tilemap_size(level)
    cam = follow(cam, center(box), dt, 6.0, vec2(80, 60))
    cam = clamp(cam, vec2(480, 270), vec2(max(size.x - 480.0, 480.0), max(size.y - 270.0, 270.0)))

draw = ():
    clear(rgb(0.5, 0.72, 0.92))
    camera2d(cam)
    draw_tilemap(level)
    loop mv in movers: rect(mv.rect, rgb(0.55, 0.4, 0.3))
    rect(box, rgb(0.95, 0.85, 0.3))

Run it in the playground

Colors, vectors and matrices

vec2, vec3, vec4, ivec2 and mat4 are built-in types, with + - * and fields .x .y .z .w (and swizzles: v.xz). Colors are vec4s: red, green, blue and alpha, from 0 to 1.

# example: colors, vectors and matrices
a = vec2(3, 4)
b = vec2(1, 0)
print(length(a), normalize(a), dot(a, b), a + b * 2.0, a.x)
print(distance(a, b), lerp(a, b, 0.5), angle(a), from_angle(PI / 2.0))

v = vec3(1, 2, 3)
print(cross(vec3(1, 0, 0), vec3(0, 1, 0)), v.xz, length(v))

m = translation(vec3(10, 0, 0)) * rotation_y(PI / 2.0)    # turn, then move
print(transform_point(m, vec3(1, 0, 0)))                   # about (10, 0, -1)

# colors are vec4s: red, green, blue, alpha from 0 to 1
print(rgb(1, 0.5, 0), hex(0x3399ff), hsv(0.33, 1.0, 1.0), with_alpha(RED, 0.5))

Run it in the playground

vmath.jo

Vector and matrix math for the built-in vec2/vec3/vec4/mat4 types (f32 components). mat4 is column-major: m[i] is column i.

dot = (a: vec2, b: vec2) -> f32
dot = (a: vec3, b: vec3) -> f32
dot = (a: vec4, b: vec4) -> f32
cross = (a: vec3, b: vec3) -> vec3
cross = (a: vec2, b: vec2) -> f32
length = (v: vec2) -> f32
length = (v: vec3) -> f32
length = (v: vec4) -> f32
length_sq = (v: vec2) -> f32
length_sq = (v: vec3) -> f32
distance = (a: vec2, b: vec2) -> f32
distance = (a: vec3, b: vec3) -> f32
normalize = (v: vec2) -> vec2
normalize = (v: vec3) -> vec3
normalize = (v: vec4) -> vec4
lerp = (a: f32, b: f32, t: f32) -> f32
lerp = (a: vec2, b: vec2, t: f32) -> vec2
lerp = (a: vec3, b: vec3, t: f32) -> vec3
lerp = (a: vec4, b: vec4, t: f32) -> vec4
mix = (a: f32, b: f32, t: f32) -> f32
mix = (a: vec2, b: vec2, t: f32) -> vec2
mix = (a: vec3, b: vec3, t: f32) -> vec3
mix = (a: vec4, b: vec4, t: f32) -> vec4
abs = (v: vec2) -> vec2
abs = (v: vec3) -> vec3
min = (a: vec2, b: vec2) -> vec2
max = (a: vec2, b: vec2) -> vec2
min = (a: vec3, b: vec3) -> vec3
max = (a: vec3, b: vec3) -> vec3
clamp = (v: vec2, lo: vec2, hi: vec2) -> vec2
clamp = (v: vec3, lo: f32, hi: f32) -> vec3
clamp = (v: vec3, lo: vec3, hi: vec3) -> vec3
floor = (v: vec2) -> vec2
sin = (v: vec2) -> vec2

GLSL's math on each part of a vector, as a shader writes it (there, GLSL's own)

cos = (v: vec2) -> vec2
ceil = (v: vec2) -> vec2
pow = (v: vec2, e: vec2) -> vec2
step = (edge: vec2, x: vec2) -> vec2
step = (edge: f32, x: vec2) -> vec2
smoothstep = (e0: vec2, e1: vec2, x: vec2) -> vec2
smoothstep = (e0: f32, e1: f32, x: vec2) -> vec2
mix = (a: vec2, b: vec2, t: vec2) -> vec2
sin = (v: vec3) -> vec3
cos = (v: vec3) -> vec3
floor = (v: vec3) -> vec3
fract = (v: vec3) -> vec3
ceil = (v: vec3) -> vec3
pow = (v: vec3, e: vec3) -> vec3
step = (edge: vec3, x: vec3) -> vec3
step = (edge: f32, x: vec3) -> vec3
smoothstep = (e0: vec3, e1: vec3, x: vec3) -> vec3
smoothstep = (e0: f32, e1: f32, x: vec3) -> vec3
mix = (a: vec3, b: vec3, t: vec3) -> vec3
sin = (v: vec4) -> vec4
cos = (v: vec4) -> vec4
floor = (v: vec4) -> vec4
fract = (v: vec4) -> vec4
ceil = (v: vec4) -> vec4
abs = (v: vec4) -> vec4
min = (a: vec4, b: vec4) -> vec4
max = (a: vec4, b: vec4) -> vec4
pow = (v: vec4, e: vec4) -> vec4
step = (edge: vec4, x: vec4) -> vec4
step = (edge: f32, x: vec4) -> vec4
smoothstep = (e0: vec4, e1: vec4, x: vec4) -> vec4
smoothstep = (e0: f32, e1: f32, x: vec4) -> vec4
mix = (a: vec4, b: vec4, t: vec4) -> vec4
smoothstep = (e0: f32, e1: f32, x: f32) -> f32
reflect = (d: vec3, n: vec3) -> vec3
reflect = (d: vec2, n: vec2) -> vec2
perp = (v: vec2) -> vec2
angle = (v: vec2) -> f64
from_angle = (a: f64) -> vec2
rotate = (v: vec2, a: f64) -> vec2
move_toward = (a: vec2, b: vec2, step: f32) -> vec2

a moved toward b by at most step (reaching it, not passing it): a steady speed, where approach eases in

move_toward = (a: vec3, b: vec3, step: f64) -> vec3
move_toward = (a: f64, b: f64, step: f64) -> f64

Random points, directions and colors

random_direction = () -> vec2

a direction at a random angle (length 1)

random_direction_3d = () -> vec3

a direction in 3D, all equally likely (length 1)

random_point = (low: vec2, high: vec2) -> vec2

a point in the rectangle between corners low and high

random_in_circle = (center: vec2, radius: f64) -> vec2

a point inside the circle around center (spread evenly over it)

random_color = (saturation: f64 = 0.7, value: f64 = 1.0) -> vec4

a color of a random hue (less saturation: paler; less value: darker)

Colors

rgb = (r: f32, g: f32, b: f32) -> vec4
rgba = (r: f32, g: f32, b: f32, a: f32) -> vec4
gray = (v: f32) -> vec4
hex = (c: int) -> vec4

a color from the low 24 bits, as RGB (0xRRGGBB); alpha is 1

hex = (s: str) -> vec4?

a color from CSS RGB/RGBA hex digits: "#ff8000", "#f80", "#ff800080" (with alpha); none for invalid text. Three, four, six or eight digits, with an optional leading #.

hsv = (h: f64, s: f64, v: f64) -> vec4
with_alpha = (c: vec4, a: f32) -> vec4
lighten = (c: vec4, k: f32) -> vec4
darken = (c: vec4, k: f32) -> vec4
const WHITE = vec4(1, 1, 1, 1)
const BLACK = vec4(0, 0, 0, 1)
const RED = vec4(0.9, 0.2, 0.2, 1)
const GREEN = vec4(0.2, 0.8, 0.3, 1)
const BLUE = vec4(0.2, 0.4, 0.9, 1)
const YELLOW = vec4(1, 0.85, 0.2, 1)
const ORANGE = vec4(1, 0.55, 0.15, 1)
const PURPLE = vec4(0.6, 0.3, 0.8, 1)
const CYAN = vec4(0.2, 0.85, 0.9, 1)
const MAGENTA = vec4(0.9, 0.25, 0.75, 1)
const GRAY = vec4(0.5, 0.5, 0.5, 1)
const TRANSPARENT = vec4(0, 0, 0, 0)

Matrices

mat4_identity = () -> mat4
translation = (t: vec3) -> mat4
scaling = (s: vec3) -> mat4
scaling = (s: f64) -> mat4

the same in every direction

rotation = (axis0: vec3, a: f64) -> mat4
rotation_x = (a: f64) -> mat4
rotation_y = (a: f64) -> mat4
rotation_z = (a: f64) -> mat4
facing = (dir: vec3, up: vec3 = vec3(0, 1, 0)) -> mat4

the turn that points a model's front (-z, the way a camera looks) along dir, its top toward up: a turret aimed at its target, a beam from a to b (translation(a) * facing(b - a))

perspective = (fov_y: f64, aspect: f64, near: f64, far: f64) -> mat4
perspective_reversed = (fov_y: f64, aspect: f64, near: f64) -> mat4

an infinite reversed perspective, for reversed depth (reversed_depth): clip z is near and w the distance along the view, so the depth (z / w) is near / distance: 1 at the near plane, going to 0 far away, and exact at any distance (no far plane: nothing is cut off behind)

orthographic = (left: f64, right: f64, bottom: f64, top: f64, near: f64, far: f64) -> mat4
look_at = (eye: vec3, target: vec3, up: vec3) -> mat4
transpose = (m: mat4) -> mat4
transform_point = (m: mat4, p: vec3) -> vec3
transform_dir = (m: mat4, d: vec3) -> vec3
inverse = (m: mat4) -> mat4

Quaternions

quat_axis_angle = (axis: vec3, a: f64) -> vec4
quat_euler = (pitch: f64, yaw: f64, roll: f64) -> vec4

Euler angles in radians: applied as roll about z, then pitch about x, then yaw about y (as Unity's Euler angles; quat_euler(0, 90deg, 0))

quat_facing = (dir: vec3, up: vec3 = vec3(0, 1, 0)) -> vec4

the turn that points -z along dir (facing's, as a quaternion)

quat_inverse = (q: vec4) -> vec4

the turn back

quat_from_mat4 = (m0: mat4) -> vec4

a rotation matrix's turn (its scaling left out)

quat_mul = (a: vec4, b: vec4) -> vec4
quat_rotate = (q: vec4, v: vec3) -> vec3
quat_to_mat4 = (q: vec4) -> mat4
slerp = (a: vec4, b0: vec4, t: f32) -> vec4

3D

# example: 3D
window("3D", 960, 540)

cube = cube_mesh(1.0)
ball = sphere_mesh(0.5)
ground = plane_mesh(40.0)
cam = orbit_camera(vec3(0, 0.5, 0), 7.0)      # drag the mouse to turn, scroll to zoom
t = 0.0

update = (dt: f64):
    t += dt
    cam.update(dt)

draw = ():
    sky(vec3(0.25, 0.45, 0.8), vec3(0.75, 0.82, 0.9))
    sun(vec3(-0.5, 1.0, -0.3))                # where the sun is: up and to the left, behind
    shadows(true)
    camera3d(cam)
    draw_mesh(ground, mat4(), rgb(0.45, 0.5, 0.4))
    draw_mesh(cube, translation(vec3(0, 0.5, 0)) * rotation_y(t), rgb(0.9, 0.4, 0.3))
    loop i in 0..6:
        a = i / 6.0 * TAU + t * 0.5
        p = vec3(3 * cos(a), 0.5 + 0.3 * sin(t * 2.0 + i), 3 * sin(a))
        draw_mesh(ball, translation(p), hsv(i / 6.0, 0.6, 1.0), emissive = 0.4)
    text("drag to turn, scroll to zoom", vec2(20, 20), 20)

Run it in the playground

draw3d.jo

3D rendering: camera, sun + sky lighting, fog, shadows, instancing and post effects. Draw calls made during draw() are recorded and rendered (shadow pass, then the lit pass) before any 2D drawing that follows them, so a HUD can be drawn on top.

Directions: y is up, in meters. A turn by a about y (transform(pos, a), rotation_y(a)) turns +z toward +x, so something turned by a faces vec3(sin(a), 0, cos(a)); glTF models face +z unturned, so a model faces a direction d turned by atan2(d.x, d.z). facing(d) turns -z, a camera's front, to d. The cameras (fly, follow, orbit) share one yaw: 0 looks along -z, more turns left, and the way ahead is vec3(-sin(yaw), 0, -cos(yaw)).

struct Vertex3D:
    pos: vec3
    normal: vec3
    uv: vec2
    color: vec4
    tangent: vec4 = vec4(0, 0, 0, 1) # xyz: along +u; w: bitangent handedness
    uv1: vec2 = vec2(0, 0)
struct SkinVertex3D:
    pos: vec3
    normal: vec3
    uv: vec2
    color: vec4
    joints: vec4
    weights: vec4
    tangent: vec4 = vec4(0, 0, 0, 1)
    uv1: vec2 = vec2(0, 0)

a vertex of a skinned mesh: also the 4 joints that bend it (their places in the skin, as numbers) and how much each does

struct Instance3D:
    model: mat4
    color: vec4
enum AlphaMode: opaque, mask, blend

How a PBR material treats alpha.

struct Material:
    base_color: vec4 = vec4(1, 1, 1, 1)
    base_texture: Texture = Texture(0, 0, 0)
    metallic: f32 = 1.0
    roughness: f32 = 1.0
    metallic_roughness: Texture = Texture(0, 0, 0)
    normal_map: Texture = Texture(0, 0, 0)
    normal_scale: f32 = 1.0
    occlusion_map: Texture = Texture(0, 0, 0)
    occlusion_strength: f32 = 1.0
    emissive_color: vec3 = vec3(0, 0, 0)
    emissive_map: Texture = Texture(0, 0, 0)
    alpha_mode: AlphaMode = .opaque
    alpha_cutoff: f32 = 0.5
    double_sided: bool = false
    unlit: bool = false         # glTF KHR_materials_unlit: base color without lighting
    base_uv: int = 0            # maps may select TEXCOORD_0 or TEXCOORD_1
    metallic_roughness_uv: int = 0
    normal_uv: int = 0
    occlusion_uv: int = 0
    emissive_uv: int = 0

Metallic-roughness PBR. Color factors are linear; base/emissive textures are sRGB, the other maps linear. Packed metallic_roughness: G roughness, B metal; occlusion: R. Opaque ignores alpha; mask discards below alpha_cutoff (including shadows); blend is drawn back to front without writing depth. Maps default to TEXCOORD_0.

struct LitParams:
    view_proj: mat4
    model: mat4
    shadow_vp: mat4
    color: vec4
    cam_pos: vec3
    sun_dir: vec3
    sun_color: vec3
    sky_color: vec3
    ground_color: vec3
    fog_color: vec3
    fog_density: f32
    fog_height: f32
    emissive: f32
    specular: f32
    use_tex: f32
    shadow_strength: f32
    shadow_texel: f32           # (one texel of the shadow map, across)
    shadow_taps: f32            # (9 on a GPU; 4 in the software renderer)
    time: f32
    wind: f32
    tex: Texture
    shadow_map: Texture
    lights: vec4[8]             # point lights: position and radius
    light_colors: vec4[8]
    light_count: f32
    bones: vec4[192]            # skinned meshes: each joint's matrix, its first three rows
    pbr: f32 = 0.0
    metal: f32 = 1.0
    rough: f32 = 1.0
    mr_map: Texture = Texture(0, 0, 0)
    normal_map: Texture = Texture(0, 0, 0)
    ao_map: Texture = Texture(0, 0, 0)
    em_map: Texture = Texture(0, 0, 0)
    map_flags: vec4 = vec4(0, 0, 0, 0)
    normal_scale: f32 = 1.0
    ao_strength: f32 = 1.0
    em_color: vec3 = vec3(0, 0, 0)
    alpha_mode: f32 = 0.0
    alpha_cutoff: f32 = 0.5
    both_sides: f32 = 0.0
    uv_sets: vec4 = vec4(0, 0, 0, 0) # base, MR, normal, occlusion
    em_uv: f32 = 0.0
    unlit: f32 = 0.0
    environment: Texture = Texture(0, 0, 0)
    environment_rough: Texture = Texture(0, 0, 0)
    environment_diffuse: Texture = Texture(0, 0, 0)
    environment_on: f32 = 0.0
    environment_intensity: f32 = 1.0
    environment_rotation: f32 = 0.0
struct LitOut:
    pos: vec4
    world: vec3
    normal: vec3
    uv: vec2
    color: vec4
    shadow_pos: vec4
lit_vs = (v: Vertex3D, u: LitParams) -> LitOut
lit_vs_inst = (v: Vertex3D, inst: Instance3D, u: LitParams) -> LitOut
lit_vs_skin = (v: SkinVertex3D, u: LitParams) -> LitOut

(a skinned vertex: bent by its joints, then placed by the model matrix)

shadow_factor = (u: LitParams, sp: vec4, ndl: f32) -> f32
aces = (c: vec3) -> vec3
lit_fs = (i: LitOut, u: LitParams) -> vec4
camera3d = (pos: vec3, target: vec3, fov_degrees: f64 = 60.0, near: f64 = 0.1, far: f64 = 500.0, up: vec3 = vec3(0, 1, 0))

place the camera; call once per frame before drawing 3D objects. up is the way that is up on the screen (tilt it to roll the picture: a camera behind a plane, banking with it). fov_degrees is the vertical field of view in degrees (60, not 60deg); perspective uses radians.

world_to_screen = (p: vec3) -> vec2?

where a point in 3D appears on the screen, in 2D drawing units (for a name or a health bar over someone's head); none when it is behind the camera. As the camera was last placed.

screen_ray = (p: vec2) -> (vec3, vec3)

the ray from the camera through a point on the screen (2D units, as mouse_pos): where it starts and its direction (length 1), for picking what the mouse is on (with a physics3d raycast)

sun = (direction: vec3, color: vec3 = vec3(1, 0.95, 0.85), disc: f64 = 1.0)

the sunlight: direction points toward the sun (y > 0: above the horizon), color is its light; disc is how bright the sun's disc and its glow are in the sky (0: none, as for light from a moon or a sky with no sun, the light the same)

sky = (top: vec3, horizon: vec3, ground: vec3 = vec3(0.3, 0.27, 0.24))
sky_image = (texture: Texture, intensity: f64 = 1.0, rotation: f64 = 0.0, refresh: bool = false)

An equirectangular sky (usually a 2:1 PNG/JPEG, sRGB), at infinity behind the 3D scene. intensity scales its linear light; rotation turns it about +Y, in radians. PBR materials also sample it for ambient light and reflections. sky(...) returns to the gradient. Keep the texture alive while selected. refresh rebuilds its light maps after update_texture. hide_sky hides the backdrop, retaining its light.

hide_sky = ()
night_stars = (amount: f64)
fog = (color: vec3, density: f64 = 0.01, height_falloff: f64 = 0.05)

fog: thicker with distance (density per meter), thinner with height (height_falloff); far away everything becomes color, shown as the sky's horizon color is (give it that to fade things into the sky). The simple lighting and PBR materials are fogged alike.

shadows = (on: bool, strength: f64 = 0.8, area: f64 = 30.0)
post_effects = (bloom: f64 = 0.6, threshold: f64 = 0.7, vignette: f64 = 0.35, saturation: f64 = 1.0, tint: vec3 = vec3(1, 1, 1), include_hud: bool = false, scene_depth: bool = false)

bloom + color grading for the frame: all of a 2D game; in a 3D one, the 3D and the 2D drawn before it, while 2D drawn after the 3D (a HUD, text) stays as drawn, unless include_hud scene_depth = true: the picture the 3D is drawn into keeps its depth in a texture, scene_depth(), for a later pass of the game's own (fog, clouds, soft particles) drawn into another target

no_post_effects = ()
point_light = (pos: vec3, color: vec3, radius: f64 = 6.0, intensity: f64 = 1.0)

a light at a point for this frame (muzzle flashes, glowing shots, lamps): it reaches radius meters, fading out on the way. Up to 8 light a frame (the ones nearest the camera); they cast no shadows.

draw_mesh = (m: Mesh, transform: mat4 = mat4(), color: vec4 = vec4(1, 1, 1, 1), texture: Texture = Texture(0, 0, 0), emissive: f64 = 0.0, specular: f64 = 0.3, cast_shadow: bool = true, in_front: bool = false, double_sided: bool = false)

A color whose alpha is below 1 is see-through, drawn after the solid ones (rgba(1, 0, 0, 0.5); much emissive makes it near white, which hides that). in_front = true: drawn after everything else and over it, casting no shadow (a first-person weapon, which would otherwise poke into walls the player stands against). material selects metallic-roughness PBR; without it the original lighting, specular and color handling are retained. color multiplies its factor; texture is the fallback when it has no base_texture. See Material for map channels.

draw_mesh = (m: Mesh, transform: mat4 = mat4(), color: vec4 = vec4(1, 1, 1, 1), texture: Texture = Texture(0, 0, 0), emissive: f64 = 0.0, specular: f64 = 0.3, cast_shadow: bool = true, in_front: bool = false, double_sided: bool = false, material: Material?)

Select PBR with a Material (or optional Material); omitted material keeps classic lighting.

draw_line3d = (a: vec3, b: vec3, color: vec4 = vec4(1, 1, 1, 1), width: f64 = 0.03)

a line from a to b, width thick: for seeing paths, rays, normals and boxes while making a game

draw_grid3d = (size: f64 = 10.0, step: f64 = 1.0, height: f64 = 0.0, color: vec4 = vec4(1, 1, 1, 0.35))

lines on the ground (y = height), step apart out to size from the center: to see distances

draw_mesh_instanced = (m: Mesh, instances: Instance3D[], color: vec4 = vec4(1, 1, 1, 1), emissive: f64 = 0.0, specular: f64 = 0.3, cast_shadow: bool = true, wind: f64 = 0.0)

many copies of a mesh in one draw call (crowds, forests, particles...)

draw_mesh_instanced = (m: Mesh, instances: InstanceBuffer[Instance3D], color: vec4 = vec4(1, 1, 1, 1), emissive: f64 = 0.0, specular: f64 = 0.3, cast_shadow: bool = true, wind: f64 = 0.0)

the same, of instances kept on the GPU: for copies that do not move (a forest, a town), made once with instance_buffer(instances) (an array is sent to the GPU again every frame)

draw_custom = (render: () -> void, transparent: bool = false, additive: bool = false)

draw with your own shader inside the 3D pass; render runs with depth testing on. Use scene_view_proj(), scene_camera(), scene_sun(), scene_shadow_vp(), scene_shadow_map()... transparent = true: run after the sky with alpha blending on and depth writes off; additive = true: like transparent, but colors add up (glows, beams, light shafts)

For shaders

hash21 = (p: vec2) -> f32

a number in [0, 1) that looks random, made from the cell a 2D point is in (its whole parts: noise, stars, sparkle in a shader). Integers, so every GPU and the CPU give the same one

Mipmaps

auto_mipmaps = true

Textures drawn on 3D meshes (draw_mesh's texture, a material's maps, a model's) get mipmaps the first time they are drawn: smaller copies, each half the size of the one before, which the GPU blends between (trilinear filtering) for what is far away or seen at a slant, so it does not shimmer. A third more memory for those textures. Textures made with smooth = false (pixel art: pixel_art() makes them so), 2D sprites and render targets are left as they are. false before drawing: no automatic mipmaps (set_mipmaps still makes them)

set_mipmaps = (t: Texture, on: bool)

make t's mipmaps now and sample it trilinearly (a texture for your own 3D shader, or one to prepare while loading rather than at its first 3D draw), or, on = false, no mipmaps for it, also on 3D meshes: sharp but shimmering far away. After update_texture, a 3D draw makes them again (or call this again). A render target's texture has none.

warm_up = (material: Material)

Prepare shared material programs explicitly from a custom loading path.

mesh = (vertices: SkinVertex3D[], indices: u32[] = [], mode: int = GL_TRIANGLES) -> Mesh

Upload skinned vertices, preparing skeletal GL/WebGL programs on the first load.

3D particles

struct Particle3D:
    pos: vec3
    vel: vec3
    life: f32
    max_life: f32
    size: f32
    color: vec4

sparks, smoke, dust and magic: soft dots that always face the camera

struct Particles3D:
    items: Particle3D[]
    gravity: vec3
    drag: f32 = 1.0
emit = (ps: mut Particles3D, pos: vec3, count: int, speed: f64, color: vec4, life: f64 = 1.0, size: f64 = 0.15, spread: f64 = PI, direction: vec3 = vec3(0, 1, 0))

count particles from pos, at up to speed (m/s), within spread radians of direction (PI: every way), lasting up to life seconds, up to size meters across

update = (ps: mut Particles3D, dt: f64)
draw = (ps: Particles3D, glow: bool = true)

draw them with the 3D scene: glowing (colors add up: sparks, fire, magic) or not (blended: smoke, dust); they fade and shrink as they age

scene_view_proj = () -> mat4
scene_camera = () -> vec3
scene_sun = () -> vec3
scene_sun_color = () -> vec3
scene_sky_color = () -> vec3
scene_ground_color = () -> vec3
scene_fog_color = () -> vec3
scene_fog = () -> vec2
scene_shadow_vp = () -> mat4
scene_shadow_map = () -> Texture
scene_depth = () -> Texture

The depth of the 3D scene drawn this frame (0 near .. 1 far, in .x), with post_effects(..., scene_depth = true); an empty texture otherwise. Sample it in a pass drawn into a target of your own (not while drawing into the scene, the screen under post effects: copy_depth(scene_depth(), rt) gives a pass there a copy to test against).

scene_shadow_strength = () -> f32
instance = (transform: mat4, color: vec4 = vec4(1, 1, 1, 1)) -> Instance3D
transform = (pos: vec3, rot_y: f64 = 0.0, scale: f64 = 1.0) -> mat4

transform helpers

Meshes

tangents3d = (vertices: Vertex3D[], indices: u32[] = [], uv_set: int = 0) -> Vertex3D[]

Generate tangent frames for missing tangents. Angle-weighted UV derivatives, orthogonalized against the vertex normal, with the glTF/MikkTSpace handedness convention (+Y normal maps). UV and normal seams must have separate vertices (as glTF exporters normally produce). Degenerate UVs get a stable perpendicular; supplied nonzero tangents are preserved.

cube_mesh = (size: f64 = 1.0) -> Mesh
add_box = (vs: mut Vertex3D[], center: vec3, size: vec3, color: vec4 = vec4(1, 1, 1, 1), transform: mat4 = mat4())

a box: center, and its size along x, y and z

add_cylinder = (vs: mut Vertex3D[], base: vec3, radius: f64, height: f64, color: vec4 = vec4(1, 1, 1, 1), segments: int = 16, top_radius: f64 = -1.0, transform: mat4 = mat4())

a cylinder standing on base (a cone when top_radius is 0)

add_sphere = (vs: mut Vertex3D[], center: vec3, radius: f64, color: vec4 = vec4(1, 1, 1, 1), segments: int = 16, rings: int = 8, transform: mat4 = mat4())

a sphere (segments around, rings from top to bottom: few of each give a faceted look)

sphere_mesh = (radius: f64 = 0.5, segments: int = 32, rings: int = 16) -> Mesh
capsule_mesh = (radius: f64 = 0.5, height: f64 = 2.0, segments: int = 24, rings: int = 16) -> Mesh

a capsule standing on end: height from end to end, centered (physics3d's add_capsule and a character are this shape)

terrain_mesh = (size: f64, divisions: int, height: (f64, f64) -> f64, color: (f64, f64, f64) -> vec4) -> Mesh

a grid in the XZ plane, centered on the origin and size across (x and z from -size/2 to size/2), in divisions x divisions squares; height gives the elevation at (x, z), and color each corner's color from (x, y, z). To stand on it with import physics3d: w.add_mesh(physics3d.terrain_triangles(size, divisions, height)), the same triangles

plane_mesh = (size: f64 = 10.0, tile: f64 = 0.0) -> Mesh

a flat square in the XZ plane, centered on the origin and size across, facing up. A texture drawn on it covers it once; with tile, it repeats every tile meters (a floor of stones a meter across: plane_mesh(200, tile = 1), and set_repeat(t, true) on the texture)

cylinder_mesh = (radius: f64 = 0.5, height: f64 = 1.0, segments: int = 24, top_radius: f64 = -1.0) -> Mesh

a cylinder standing on its base at y = 0 (the cube, sphere and capsule meshes are centered instead), up to y = height; top_radius 0 makes a cone

cone_mesh = (radius: f64 = 0.5, height: f64 = 1.0, segments: int = 24) -> Mesh
custom_mesh = (vertices: Vertex3D[], indices: u32[] = []) -> Mesh

a mesh of your own: triangles, three vertices each (or three indices each into vertices). A triangle's front is the side its normals point to, and only fronts are drawn (a box seen from inside is clear): a triangle wound the other way (its corners clockwise as seen from its front) is turned around to face where its normals do. With no normals (all zero), corners go counter-clockwise as seen from the front. draw_mesh(..., double_sided = true) draws both sides

camera3d.jo

Cameras that the player moves (3D): an orbit camera, around a point (to look at a model, a board, a level from above), and a fly camera (to move through a scene). Each is a value the game keeps: update it with the frame's input, then make it the camera.

cam = orbit_camera(vec3(0, 1, 0), 12.0)
update = (dt: f64): update(cam, dt)
draw = ():
    camera3d(cam)
    draw_mesh(cube_mesh())
struct OrbitCamera:
    target: vec3
    distance: f64 = 10.0
    yaw: f64 = 0.0                 # around the vertical axis, in radians (0: from +z)
    pitch: f64 = 0.4               # above the horizon, in radians
    min_distance: f64 = 1.0
    max_distance: f64 = 200.0
    turn_speed: f64 = 0.006        # radians per pixel the mouse moves
    smooth: f64 = 14.0             # how quickly it follows (0: at once)
    drag_left = true               # a left-button drag turns it (false: only the right, the left left to the game)
    shown_yaw: f64 = 0.0           # (where it is now, on its way to yaw, pitch and distance)
    shown_pitch: f64 = 0.4
    shown_distance: f64 = 10.0
    invert_x = false              # reverse horizontal mouse and right-stick look
    invert_y = false              # reverse vertical mouse and right-stick look

Around target, at distance: dragging with the left or right mouse button (or the right stick) turns it, the wheel (or the left stick up and down) brings it closer or further.

orbit_camera = (target: vec3 = vec3(0, 0, 0), distance: f64 = 10.0, yaw: f64 = 0.0, pitch: f64 = 0.4) -> OrbitCamera
update = (c: mut OrbitCamera, dt: f64, input: bool = true)

input = false follows/smooths the camera without reading mouse, sticks or wheel.

position = (c: OrbitCamera) -> vec3

where the camera is

camera3d = (c: OrbitCamera, fov_degrees: f64 = 60.0, near: f64 = 0.1, far: f64 = 500.0)

vertical fov_degrees is in degrees (60, not 60deg); unlike perspective, which takes radians

struct FollowCamera:
    target: vec3                   # what it follows (update sets it)
    distance: f64 = 6.0
    height: f64 = 1.5              # how far above the target it aims
    yaw: f64 = 0.0                 # 0: behind the target, looking along -z; more: turned left
    pitch: f64 = 0.35              # looking down from above, in radians
    min_pitch: f64 = -0.3
    max_pitch: f64 = 1.3
    min_distance: f64 = 2.0
    max_distance: f64 = 20.0
    turn_speed: f64 = 0.004        # radians per pixel the mouse moves
    smooth: f64 = 12.0             # how quickly it follows the target (0: at once)
    chase: f64 = 4.0               # how quickly it swings round behind a heading given to update
    reach: f64 = 1.0               # (the share of its distance it may be out this frame: pull_in)
    shown_target: vec3
    shown_reach: f64 = 1.0
    placed = false
    invert_x = false              # reverse horizontal mouse and right-stick look
    invert_y = false              # reverse vertical mouse and right-stick look

Behind a target the game moves (a third-person camera): the mouse while it is locked (mouse_lock()) or the right button is held, or the right stick, turns it around the target, and the wheel brings it closer. Walk the player along flat_forward and flat_right, so that ahead is where the camera looks: Its yaw is the other cameras': 0 looks along -z, more turns it left. Behind a vehicle (a chase camera), give update the way it faces, in the same terms: it swings round behind it, smoothly (chase: how quickly), update(cam, kart.pos, dt, heading = kart.yaw).

follow_camera = (distance: f64 = 6.0, yaw: f64 = 0.0, pitch: f64 = 0.35, height: f64 = 1.5) -> FollowCamera
update = (c: mut FollowCamera, target: vec3, dt: f64, heading: f64? = none, input: bool = true)

input = false still follows the target/heading and recovers from walls, without look or zoom.

pull_in = (c: mut FollowCamera, fraction: f64)

a wall between aim(c) and position(c): only this share of the way out (a cast's fraction)

aim = (c: FollowCamera) -> vec3

the point it looks at (above the target), and where it is

position = (c: FollowCamera) -> vec3
flat_forward = (c: FollowCamera) -> vec3

the way it looks along the ground, and its right (for walking where it looks)

flat_right = (c: FollowCamera) -> vec3
camera3d = (c: FollowCamera, fov_degrees: f64 = 60.0, near: f64 = 0.1, far: f64 = 500.0)

vertical fov_degrees is in degrees (60, not 60deg); unlike perspective, which takes radians

struct FlyCamera:
    pos: vec3
    yaw: f64 = 0.0                 # 0: looking toward -z
    pitch: f64 = 0.0
    speed: f64 = 8.0               # units per second (Shift: four times that)
    turn_speed: f64 = 0.004

Through the scene: W A S D (or the arrows, or the left stick) move, Space and Q go up and down, Shift is faster; the mouse looks around while the right button is held, or always when the mouse is locked (mouse_lock()), as does the right stick.

fly_camera = (pos: vec3, yaw: f64 = 0.0, pitch: f64 = 0.0) -> FlyCamera
forward = (c: FlyCamera) -> vec3

the way it looks (a unit vector), and its right

right = (c: FlyCamera) -> vec3
update = (c: mut FlyCamera, dt: f64)
camera3d = (c: FlyCamera, fov_degrees: f64 = 60.0, near: f64 = 0.1, far: f64 = 500.0)

vertical fov_degrees is in degrees (60, not 60deg); unlike perspective, which takes radians

Models (glTF)

gltf.jo

3D models from glTF 2.0 files (.glb, or .gltf with its .bin and images), the format Blender and most tools export: metallic-roughness materials (PNG/JPEG maps), vertex colors, placed by the scene's nodes; skins (meshes bent by a skeleton of nodes, up to 64 joints) and their animations, plus weighted morph targets.

ship = load_model(embed("ship.glb")).unwrap()
draw = ():
    camera3d(vec3(0, 1, 5), vec3(0, 0, 0))
    draw_model(ship, translation(pos) * rotation_y(angle))

An animated model is drawn in a pose: an animation at a time, or two blended.

run = find_animation(hero, "Run")
draw_model(hero, transform(pos, facing), pose = pose_at(hero, run, elapsed()))

A .gltf names its other files: give them in files, relative to the .gltf's directory (load_model(embed("assets/hero.gltf"), embed_dir("assets")).unwrap()). This works in web builds too; the loader does not read neighboring files from disk. URI escapes are decoded while keeping subdirectories, so textures/fox%20fur.png finds textures/fox fur.png in the map. Exact URI keys take precedence; a basename-only map also works. A .glb usually contains its own buffers and images, and needs no files map. Not read: compressed meshes (Draco, meshopt), sparse base/animation accessors (float morph deltas can be sparse), and material extensions other than KHR_materials_unlit.

struct ModelPart:
    mesh: Mesh
    transform: mat4             # where the scene's nodes put it, in the model
    color: vec4                 # the material's base color (times the vertices' colors)
    texture: Texture            # its base color texture (Texture(0, 0, 0): none)
    emissive: f64               # how much it glows (from the material's emissive color)
    node: int = -1              # the node it hangs from (in Model.nodes)
    skin: int = -1              # the skin that bends it (in Model.skins; -1: none)
    material: Material? = none
    morph: MeshData? = none     # CPU source retained only for a part with morph targets
struct ModelNode:
    name: str
    parent: int
    t: vec3
    r: vec4
    s: vec3
    weights: f32[] = []         # this node's default morph weights (node, mesh, then zeros)

a node of the model's scene: its name, its parent (-1: none), and where it rests, from its parent: a translation, a rotation (a quaternion) and a scale

struct Skin:
    joints: int[]
    inverse_bind: mat4[]

the joints (nodes) that bend a skin's vertices, and the inverse of where each was when the mesh was bound to them

struct AnimChannel:
    node: int
    path: int
    step: bool
    times: f32[]
    values: f32[]
    components: int = 0         # path 3: morph weights, this many scalars per key
    tangents: f32[] = []        # cubic weights: incoming then outgoing derivatives per key

keys moving one node: translation (path 0), rotation (1), scale (2), morph weights (3). 3 values a key, 4 for rotations, components for weights; steps or interpolated keys

struct ModelAnimation:
    name: str
    length: f64                 # (seconds)
    channels: AnimChannel[]
struct Pose:
    t: vec3[]
    r: vec4[]
    s: vec3[]
    weights: f32[][] = []       # morph weights by node; weights need not sum to one

every node's translation, rotation, scale and morph weights (by node, as in Model.nodes)

struct Model:
    parts: ModelPart[]
    min: vec3                   # the corners of a box around it (in its resting pose)
    max: vec3
    nodes: ModelNode[] = []
    order: int[] = []           # (the nodes, each after its parent)
    skins: Skin[] = []
    animations: ModelAnimation[] = []
error struct ModelError:
    message: str
struct MorphTarget:
    positions: vec3[] = []
    normals: vec3[] = []
    tangents: vec3[] = []

Per-vertex deltas from one glTF morph target. Empty attributes keep their base values. Tangent deltas are XYZ only: handedness stays the base vertex's W.

struct MeshData:
    vertices: Vertex3D[]
    indices: u32[]              # (none: the vertices are the triangles)
    transform: mat4
    color: vec4
    image: int                  # its texture's image in ModelData.images (-1: none)
    emissive: f64
    node: int = -1
    skin: int = -1
    joints: vec4[] = []         # (skinned: per vertex, 4 joints (by their place in the skin)
    weights: vec4[] = []        # and how much each bends it)
    material: Material? = none  # CPU factors; the five maps name ModelData.images below
    material_images: int[] = [] # base, metallic-roughness, normal, occlusion, emissive
    targets: MorphTarget[] = []
    flat_normals: bool = false  # the base asset had no normals
    generated_tangents: bool = false # the base tangents were absent or ignored

A model's data before it goes to the GPU (read_gltf): the vertices (in each part's own space) for collision, or to change them, and the images of its textures.

struct ModelData:
    meshes: MeshData[]
    images: Image[]
    smooth: bool[]              # (per image: filtered, or nearest pixels)
    min: vec3
    max: vec3
    nodes: ModelNode[] = []
    order: int[] = []
    skins: Skin[] = []
    animations: ModelAnimation[] = []
model = (d: ModelData) -> Model

the model on the GPU: a mesh and a texture for each part

draw_model = (m: Model, transform: mat4 = mat4(), tint: vec4 = vec4(1, 1, 1, 1), cast_shadow: bool = true, pose: Pose = Pose([], [], []), in_front: bool = false)

Draw each part (see draw_mesh), the model placed by transform and its colors times tint. An animated model is drawn in the pose given (pose_at, blend_poses), or as it rests.

morph_vertices = (m: MeshData, weights: f32[], uv_set: int = -1) -> Vertex3D[]

Blend CPU vertices before skinning. Missing weights are zero; extra ones are ignored. Authored normals/tangents are normalized after blending. If absent in the asset, flat normals and tangent frames are rebuilt for the deformed geometry, using its normal UV set.

Poses

rest_pose = (m: Model) -> Pose

every node as it rests

find_animation = (m: Model, name: str) -> int

the animation with this name (or whose name ends "|name", as Blender's "Armature|Run"); -1: none

animation_length = (m: Model, anim: int) -> f64
pose_at = (m: Model, anim: int, time: f64, looping: bool = true) -> Pose

ModelAnimation anim at a time (seconds): looping, or held at its end. Nodes it does not move rest.

An animation player

struct Animator:
    current = -1            # the animation playing (find_animation's number; -1: none)
    time = 0.0              # how far into it, in seconds
    looping = true
    speed = 1.0
    finished = false        # one played once has come to its end (it holds its last pose)
    last_time = 0.0         # (time before the last update)
    prev = -1               # (the one fading out, where it was, and how far the fade has come)
    prev_time = 0.0
    prev_looping = true
    fade = 0.0
    faded = 0.0

plays a model's animations by name, fading from one to the next:

play = (a: mut Animator, m: Model, name: str, looping: bool = true, fade: f64 = 0.2, speed: f64 = 1.0, restart: bool = false)

play the animation named name (already playing: it goes on; restart = true starts it over), fading in over fade seconds

update = (a: mut Animator, m: Model, dt: f64)
passed = (a: Animator, m: Model, t: f64) -> bool

the last update went past time t of the animation (once per loop, for a looping one)

pose = (a: Animator, m: Model) -> Pose

the pose to draw (the fade from the one before, while it lasts)

blend_poses = (a: Pose, b: Pose, k: f64) -> Pose

between two poses of the same model: k = 0 is a, 1 is b (to fade from one animation to the next)

find_node = (m: Model, name: str) -> int

the node with this name (or whose name ends ":name", as Mixamo's "mixamorig:Head"); -1: none

node_transform = (m: Model, p: Pose, node: int) -> mat4

where a node is in the model, posed (to hold something in a hand: transform * this)

turn_node = (m: Model, p: mut Pose, node: int, axis: vec3, angle: f64)

turn a node of a pose by angle (radians) round an axis in the model's space (a spine bent to aim up or down, a head turned to look)

model_size = (m: Model) -> vec3

the model's size (the box around it) and its middle

model_center = (m: Model) -> vec3
load_model = (file: u8[], files: {str: u8[]} = {}) -> Model | ModelError

a .glb (binary glTF) or .gltf (its JSON) file, on the GPU; files: the ones it names, by name. ModelError describes read/decode failures; embed validates file existence, not model content.

read_gltf = (file: u8[], files: {str: u8[]} = {}) -> ModelData | ModelError

the same, its data only (see ModelData)

Sound and music

Music in time with a game (a rhythm game's notes, a beat): the audio clock, sounds started on it to the sample, presses timed finer than a frame and calibration, in rhythm games and music sync.

# example: sound
window("Sound", 960, 540)

beep = tone(440.0, 0.2, .square, 0.3)                      # a note, made by the program
zap = tone(900.0, 0.3, .saw, 0.3, slide = 0.3)             # sliding down to 0.3 of its pitch
chord = mix([tone(262.0, 0.6), tone(330.0, 0.6), tone(392.0, 0.6)])
song = melody_loop("C4 E4 G4 E4 F4 A4 C5 A4", 140.0)
music = play(song, 0.5, looping = true)

update = (dt: f64):
    if key_pressed(.a): play(beep)
    if key_pressed(.s): play(zap, pan = -0.8)                # more to the left
    if key_pressed(.d): play(chord)
    if key_pressed(.f): play(sfx_coin())
    if key_pressed(.m): set_volume(music, 0.0)
    # (from where the mouse is, heard from the middle: to the left or right, fainter further away)
    if mouse_pressed(.left): play_at(beep, mouse_pos(), vec2(480, 270), reach = 600)

draw = ():
    clear(rgb(0.1, 0.1, 0.14))
    text("A: beep   S: zap   D: chord   F: coin   M: quiet   click: a beep from there", vec2(20, 20), 24)
    text("(in a browser, click the page first: pages may not play sound before)", vec2(20, 60), 18, GRAY)

Run it in the playground

audio.jo

Audio: a software mixer written in Sloppy. Sounds are float sample buffers (stereo, interleaved, at the mixer rate). Each frame the mixer renders just enough samples to keep the output device fed: on Linux through ALSA, on Windows waveOut, on macOS AudioQueue, in a web page Web Audio (silent where there is none, or with SLOPPY_NO_AUDIO=1). Web: WebAudio.

error struct AudioError:
    message: str

A sound/music file could not be decoded; message describes the input failure.

struct Sound:
    samples: f32[]      # interleaved stereo

A Sound is its samples: make one from your own, Sound(samples), for synthesis (left and right in turn, at MIX_RATE a second, from -1 to 1). The mix: each voice's samples times its volume, its pan taken from the other side (pan 1: the left channel silent, the right as loud as at 0), times master_volume; what goes past 0.75 is bent smoothly toward 1.

enum Wave: sine, square, triangle, saw, noise
const MIX_RATE = 48000
frames = (s: Sound) -> int
duration = (s: Sound) -> f64
play = (s: Sound, volume: f64 = 1.0, pan: f64 = 0.0, pitch: f64 = 1.0, looping: bool = false, delay: f64 = 0.0, at: f64? = none) -> int

play a sound; returns a voice id for stop()/set_volume(). It starts with the mixer's next samples (made each frame, heard audio_latency() later), or delay seconds after them, to the sample; a negative delay starts it that far into the sound. at starts it when audio_time() is at (plus delay), to the sample, whatever the frame rate: for music, play(kick, at = beat_at) a beat or so ahead keeps each note on time; an at already past starts it with the next samples, as far into it as it would be by then (a song resumed at at = audio_time() - 30.0: 30 seconds in, in time with the clock)

audio_time = () -> f64

the audio clock: seconds of sound heard so far, as the system reports it (the mixer is audio_latency() ahead). It runs smoothly, read from the monotonic clock between mixes and kept in step with the output's reports, averaged (off a straight line by about 0.2 ms where a device reports a 10 ms period at a time); it never goes back, and never passes the sound mixed. In step with the sound, not the frames, a beat kept by it does not drift when frames are slow or dt is capped; play's at counts on it. It starts with the sound: the first play, or the first audio_time() or audio_started(). With no sound device (or SLOPPY_NO_AUDIO=1) it moves with the frames' time, a frame at a time; in a screenshot run exactly 1/60 s a frame.

audio_started = () -> bool

whether sound has started: a web page's waits for the first click or key (browsers allow no sound before), and audio_time stays at 0 until then; a "click to start" screen asks this

audio_latency = () -> f64

how long a sound played now takes to be heard, in seconds: the samples the output holds and the delay the system reports past them (Bluetooth headphones may add more than it knows: a game that judges timing has a calibration setting too); 0 with no sound device

audio_time_at = (t: f64) -> f64

audio_time() as it was at elapsed() time t: when a key was pressed, by the music (audio_time_at(key_press_time(.d)))

stop = (id: int)
stop_all = ()
is_playing = (id: int) -> bool
set_volume = (id: int, volume: f64)
fade_volume = (id: int, volume: f64, seconds: f64)

change a voice's volume gradually, over seconds

fade_out = (id: int, seconds: f64 = 1.0)

fade a voice to silence over seconds, then stop it

crossfade = (old: int, s: Sound, seconds: f64 = 1.0, volume: f64 = 1.0, looping: bool = true) -> int

fade out the voice old while s starts silent and fades in to volume: from one music or ambience loop to the next (returns the new voice; old may be 0 or already stopped)

set_pitch = (id: int, pitch: f64)
set_pan = (id: int, pan: f64)
pause = (id: int)

hold a voice where it is (a sound, music, a stream), silent, until resume(id); it is still playing (is_playing), and stop() still ends it

resume = (id: int)
voice_time = (id: int) -> f64

where a voice is in its sound, in seconds, as heard now (by audio_time, so it runs as smoothly): a song's position, for a chart. Negative before it is heard (play's delay, and audio_latency); 0 for one that has stopped

seek = (id: int, t: f64)

a voice goes on from t seconds into its sound (music too: decoded from the page before t), with the mixer's next samples; one that loops, from t in its turn

Sounds in a place

play_at = (s: Sound, pos: vec2, listener: vec2, volume: f64 = 1.0, reach: f64 = 1200.0, pitch: f64 = 1.0, looping: bool = false) -> int

play a sound from a place in 2D: to the left or right of listener (who hears it: the player, or the camera's target), and quieter further away, silent beyond reach (2D units)

play_at = (s: Sound, pos: vec3, volume: f64 = 1.0, reach: f64 = 40.0, pitch: f64 = 1.0, looping: bool = false) -> int

play a sound from a place in 3D: heard from the camera (camera3d), to its left or right, and quieter further away, silent beyond reach (meters); looping: again and again, till stop(id) (an engine: move_sound(id, kart.pos) each frame, set_pitch(id, ...) with its speed)

move_sound = (id: int, pos: vec3, volume: f64 = 1.0, reach: f64 = 40.0)

a sound already playing (play_at's voice, or any play's) moved to another place in 3D: a looping engine, a fire that the player walks past (call it every frame)

Volume

master_volume = (v: f64)

the volume of everything played, from 0 (silent) to 1

master_volume = () -> f64

the volume set with master_volume (0.8 to start with)

Samples made as it runs

sound_stream = (rate: int = MIX_RATE, channels: int = 2, volume: f64 = 1.0, pan: f64 = 0.0) -> int
push_samples = (id: int, samples: f32[])
queued_samples = (id: int) -> int

Making sounds

tone = (freq: f64, seconds: f64, wave: Wave = .sine, volume: f64 = 0.5, attack: f64 = 0.005, release: f64 = 0.1, slide: f64 = 1.0, vibrato: f64 = 0.0) -> Sound

a single synthesized note: frequency slides from freq to freq * slide over the duration. The volume rises over attack seconds and falls over the last release seconds, each at most half the note (a short blip keeps its volume). Noise has a pitch too: a new random level 16 times a cycle, so a low one rumbles (an explosion at 60) and a high one hisses (5000)

mix = (sounds: Sound[]) -> Sound

mix several sounds into one (useful for chords and layered effects)

sfx_jump = () -> Sound

sound effect presets

sfx_coin = () -> Sound
sfx_hit = () -> Sound
sfx_explosion = () -> Sound
sfx_laser = () -> Sound
sfx_powerup = () -> Sound
sfx_click = () -> Sound
sfx_whoosh = () -> Sound
sfx_chime = () -> Sound
note_freq = (name: str) -> f64

note name ("C4", "F#3", "Bb5") to frequency in Hz

midi_freq = (n: f64) -> f64

the frequency of a MIDI note number: 69 is A4, 440 Hz; 60 middle C

melody = (notes: str, bpm: f64 = 120.0, wave: Wave = .triangle, volume: f64 = 0.3, step: f64 = 0.5) -> Sound

render a melody: notes separated by spaces, "-" holds the previous note, "." is a rest; each lasts step beats (0.5: eighth notes at bpm)

melody_loop = (notes: str, bpm: f64 = 120.0, wave: Wave = .triangle, volume: f64 = 0.3, step: f64 = 0.5) -> Sound

a melody made to be played with looping = true: exactly as long as its notes, with the end of the last ones (and their release) carried round to the start, so the loop has no seam

WAV files

load_wav = (file: u8[]) -> Sound | AudioError

a WAV file's sound: integer samples of 8, 16, 24 or 32 bits or floats of 32 or 64, any number of channels (the first two are used; mono plays on both), any rate (resampled to MIX_RATE). Other files are an error that says what they are.

encode_wav = (s: Sound) -> u8[]

a sound as a WAV file's bytes: 16-bit stereo at MIX_RATE (what load_wav reads back), to keep or to listen to a sound made in code

save_wav = (path: str, s: Sound) -> bool

write a WAV to path (false: file_error describes write failure), destination first as write_bytes

vorbis.jo

OGG Vorbis: load_ogg decodes a whole .ogg file into a Sound. Vorbis is the usual format for game music: about a tenth of the size of a WAV. (Written from the Vorbis I specification.)

music = load_ogg(embed("music.ogg")).unwrap()
play(music, 0.6, looping = true)
load_ogg = (file: u8[]) -> Sound | AudioError

a whole Ogg Vorbis file, at the mixer's rate, in stereo (mono is copied to both sides; files with more channels give their front left and right). AudioError describes decode failures.

Music: decoded while it plays

struct Music:
    file: u8[]
    channels: int
    rate: int
    seconds: f64                # how long it is (0: unknown)

A long piece of music played as it is decoded, a little ahead of where it is playing: no wait when it loads and little memory (a three-minute song decoded whole is about 70 MB).

load_music = (file: u8[]) -> Music | AudioError
play_music = (m: Music, volume: f64 = 1.0, pan: f64 = 0.0, looping: bool = true, delay: f64 = 0.0, at: f64? = none) -> int

play music from its start; returns a voice id for stop(), set_volume(), is_playing(), pause(), seek() and voice_time(). delay and at as for play(), to the sample: at = audio_time() + 1.0 starts it a second from now on the audio clock, a negative delay that far into it. Shared options follow Sound play: volume, pan, then looping (Music has no pitch option). Music loops by default; Sound play defaults to a single play.

crossfade = (old: int, m: Music, seconds: f64 = 1.0, volume: f64 = 1.0, looping: bool = true) -> int

fade out the voice old while music m starts silent and fades in to volume (returns the music's voice; old may be 0 or already stopped)

music_error = (id: int) -> AudioError?

take a streaming decode error for this play_music voice, once (none: none recorded). Errors survive the voice ending; accepted samples before the damaged packet may have played. Opening errors come from load_music instead. Query after is_playing(id) becomes false.

struct OggAudio:
    channels: int
    rate: int
    samples: f32[]
    error = ""                  # why it could not be read ("": it could)

the samples as the file has them (interleaved, d.channels of them, at d.rate)

GPU programs

# example: GPU programs
window("Shader", 960, 540)

struct Vertex:
    pos: vec2
struct Params:
    time: f32
    size: vec2
struct Out:
    pos: vec4                            # (the first field: where on the screen)
    uv: vec2

vs = (v: Vertex, u: Params) -> Out: Out(vec4(v.pos, 0, 1), v.pos * 0.5 + 0.5)
fs = (i: Out, u: Params) -> vec4:        # runs for every pixel, on the GPU
    p = (i.uv - 0.5) * vec2(u.size.x / u.size.y, 1.0)
    d = length(p)
    rgb(0.5 + 0.5 * sin(d * 30.0 - u.time * 4.0), 0.3, 0.6 + 0.4 * cos(u.time + p.x * 3.0))

prog = make_shader(shader(vs, fs))
quad = mesh([Vertex(vec2(-1, -1)), Vertex(vec2(1, -1)), Vertex(vec2(1, 1)),
             Vertex(vec2(-1, -1)), Vertex(vec2(1, 1)), Vertex(vec2(-1, 1))])
t = 0.0
update = (dt: f64): t += dt
draw = (): draw(prog, quad, Params(t, vec2(960, 540)))

Run it in the playground

gpu.jo

GPU programs written in Sloppy: meshes, shaders and uniform binding.

struct Vertex: pos: vec3; color: vec4          # vertex attributes
struct Params: mvp: mat4                        # uniforms
struct Out:    pos: vec4; color: vec4           # first field is the clip position
vs = (v: Vertex, u: Params) -> Out: Out(u.mvp * vec4(v.pos, 1), v.color)
fs = (i: Out, u: Params) -> vec4: i.color
prog = make_shader(shader(vs, fs))
m = mesh(vertices)
draw(prog, m, Params(mvp))

Uniform fields are numbers, vectors, mat4 and Texture, or fixed-size arrays of them (bones: mat4[64], lights: vec4[8]), and GPU buffers (gpubuffer.jo: u.particles[i]). Shader code can use fixed-size arrays, loop over them, and sample(), sample_lod(), texel(), texture_size(), discard() and set_depth() (fragment) and vertex_id(), instance_id() (vertex).

struct ShaderSource:
    vs: str
    fs: str
    layout: str
    cpu_vs: *u8           # the shader functions, for the software renderer
    cpu_fs: *u8
    out_size: int         # bytes of the vertex function's result
    vs_args: int          # 2: vs(vertex, uniforms), 3: vs(vertex, instance, uniforms)
    flat: str             # per 4 bytes of that result: 'f' interpolated, 'i' passed on unchanged
    vs_spirv: str         # the stages as SPIR-V, for Vulkan (compiler/spirv.jo; "" on the web)
    fs_spirv: str
    where: str            # the stages' functions and where they are in the source, for error
                          # reports ("vertex: vs at src/main.jo:12:1\nfragment: ..."; the GLSL
                          # text leaves them out, so that it stays the same when code moves)
    outputs: int          # the fragment function's colors: 0 for a vec4, else a struct's fields
                          # (1 to 4), one for each color of a render target (colors = n)

produced by the compiler from shader(vs, fs)

struct ShaderAttrib:
    comps: int
    offset: int
struct ShaderUniform:
    loc: int              # (OpenGL; from make_shader: where the library keeps its location)
    kind: u8
    offset: int
    count: int            # an array (T[N] field): N, and the bytes per element
    stride: int
    loc2: int = -1        # a GPU buffer: its length's location (loc: its texture's)
struct Shader:
    prog: int
    stride: int
    attribs: ShaderAttrib[]
    uniforms: ShaderUniform[]
    usize: int
    istride: int
    iattribs: ShaderAttrib[]
    ibase_loc: int = -1   # (OpenGL) where instance_id() starts: see draw_indirect (as loc)
    lid: int              # (OpenGL) this shader's number (0: one made by hand, never matched;
                          # its locations are OpenGL's own)
    ucache: *u8 = null    # (OpenGL) the uniform bytes last uploaded to its program
    outputs: int          # the colors its fragment function writes past one (0: a vec4; else a
                          # struct's fields: render_target's colors)
struct Mesh:
    vao: int
    vbo: int
    ibo: int
    count: int
    index_count: int
    stride: int
    mode: int
    instances: int
    center: vec3                # a sphere around the vertices (radius < 0: not known), for
    radius: f32 = -1.0          # leaving out what the camera cannot see (draw3d.jo)
    gbuf: int                   # the vertices are a GPU buffer's (gpu_mesh): its number
    keep: u8[]                  # (and what keeps that buffer alive)
warm_up = ()

Prepare what is loaded, during a loading screen: OpenGL and WebGL link every shader queued and not linked yet (warm_up_shaders()); Vulkan prepares the pipelines of the programs and layouts loaded.

warm_up = (sh: Shader, mode: int = GL_TRIANGLES)

Prepare one shader now: OpenGL and WebGL link it (one made with warm = false too); Vulkan prepares its pipeline for the drawing state selected now (blend, color_write, depth_test, depth_write, the target) and primitive mode.

shaders_pending = () -> int

how many shaders are queued for warm-up and not linked yet (0 on Vulkan, Metal and the software renderer)

warm_up_later = (sh: Shader)

Queue a shader made with warm = false for warm_up_shaders (with parallel compiling, its linking starts now); one queued or linked already stays as it is.

warm_up_shaders = (max_count: int = -1, max_ms: f64 = -1.0) -> int

Link queued shaders, oldest first: at most max_count of them (-1: no limit), starting no new one after max_ms milliseconds (-1: no limit; at least one is linked). With no limit, all of them (warm_up() does that too). Returns how many are still waiting. With parallel compiling, a limited call finishes only the programs whose linking is done, never waiting for one.

make_shader = (src: ShaderSource, warm: bool = true) -> Shader

a shader from shader(vs, fs); on OpenGL and WebGL its program is linked at its first draw (or by warm_up_shaders, unless warm is false), and compile or link errors are reported there. Made again from the same source, it is the program made before.

mesh[V] = (vertices: V[], indices: u32[] = [], mode: int = GL_TRIANGLES) -> Mesh

upload vertices (any struct type matching the shader's vertex input) and optional indices

update_mesh[V] = (m: mut Mesh, vertices: V[])
draw[U] = (sh: Shader, m0: Mesh, params: U)

draw a mesh with a shader; params is the uniforms struct the shader functions take

draw_instanced[U, I] = (sh: Shader, m: Mesh, instances: I[], params: U)

draw many copies of a mesh in one call; instances holds the per-instance shader input (uploaded on every call: for instances that change rarely, keep them on the GPU with instance_buffer)

struct InstanceBuffer[I]:
    vbo: int
    count: int

per-instance shader input kept on the GPU: uploaded once (and again by set_instances), drawn any number of times with draw_instanced

instance_buffer[I] = (instances: I[]) -> InstanceBuffer[I]
set_instances[I] = (b: mut InstanceBuffer[I], instances: I[])

replace what an instance buffer holds

draw_instanced[U, I] = (sh: Shader, m: Mesh, b: InstanceBuffer[I], params: U, first: int = 0, count: int = -1)

draw instances first .. first + count of a buffer (count -1: to the end)

sample = (t: Texture, uv: vec2) -> vec4

texture lookup inside shader functions (maps to GLSL texture()); outside the software renderer, calling it on the CPU returns white

sample_lod = (t: Texture, uv: vec2, lod: f32) -> vec4

texture lookup at a given mipmap level (maps to GLSL textureLod; a texture without mipmaps: the full-size image. See set_mipmaps)

texel = (t: Texture, p: ivec2) -> vec4

the texel at integer coordinates p (0 to size - 1; y = 0 is the first row of the image data): no filtering or wrapping (maps to GLSL texelFetch)

texture_size = (t: Texture) -> ivec2

a texture's size in texels (maps to GLSL textureSize)

discard = ()

in a fragment shader: drop this fragment (no color, no depth), e.g. for alpha-tested leaves: if c.a < 0.5: discard(). The rest of the function still runs on the CPU; its result is unused.

set_depth = (d: f32)

in a fragment shader: write this fragment's depth (0 to 1; under reversed_depth, 1 is near) instead of the interpolated one, e.g. logarithmic depth for a view of hundreds of kilometres: set_depth(log2(1.0 + 1.0 / i.pos.w) * k) (i.pos.w is 1/w: 1 over the distance along the view). A path that does not call it keeps the interpolated depth (i.pos.z). A shader that calls it loses the GPU's early depth test: its fragments are all shaded before being tested.

reversed_depth = (on: bool = true) -> bool

Reversed depth: depth 1 near and 0 at an infinitely far plane, in float, so that a kilometre and a millimetre are told apart at a million metres (with the usual depth everything past a few kilometres is one depth). Returns whether it is on: false where this renderer has no way to do it (OpenGL without glClipControl, a browser without EXT_clip_control), and then nothing changed. Turn it on once, before the first frame (it opens the window if none is open yet). With it: depth is cleared to 0; depth_test(.nearer) is GL's GREATER (the renderers' glDepthFunc flips LESS to GREATER and LEQUAL to GEQUAL, so a raw glDepthFunc(GL_LESS) does too); depth textures hold 1 near, 0 far; 3D's camera is an infinite reversed perspective (perspective_reversed: clip z is near, always, and w the distance); a vertex shader's clip z goes to the depth unit as it is, from 0 (far) to w (near), not -w to w. Shadow maps keep the usual depth. A sky or backdrop at the far plane: clip z far_depth() * w.

far_depth = () -> f32

the clip z / w of the far plane with the depth drawn with now: 0.9999 (just inside it), or 0 with reversed depth (the infinitely far plane). For a sky or backdrop behind everything, drawn with depth_test(.nearer_or_equal): pass it in the uniforms and write vec4(p.xy, u.far, 1) as the clip position.

vertex_id = () -> int

in a vertex shader: the index of the vertex being shaded (GLSL gl_VertexID) and of the instance (gl_InstanceID: 0 for draw, the index into the instances for draw_instanced)

instance_id = () -> int
fwidth = (x: f32) -> f32

in a fragment shader: how much x changes from one pixel to the next (GLSL fwidth), e.g. for edges that stay sharp at any size; 0 on the CPU

fract = (v: vec2) -> vec2
step = (edge: f32, x: f32) -> f32

GPU arrays

# example: GPU arrays
xs = gpu(linspace(0.0, 1.0, 1000000))    # a million numbers, on the GPU
ys = xs .* xs .+ 1.0                     # one GPU program, run on all of them
print(gpu_available(), sum(ys), mean(ys), max(ys))
print(cpu(ys).data[999999])              # back on the CPU

Run it in the playground

gpuarray.jo

GPU arrays: numbers kept in GPU memory and computed on by GPU programs.

g = gpu(xs)                       # upload (up to 4 dimensions)
h = g .* 2.0 .+ sin.(g)           # one GPU program, made from the expression at compile time
ys = cpu(h)                       # download: an array of the same shape
total = sum(h)                    # reductions too

Values are f32, or i32 for arrays made from integers (gpu(int_array)): integer arithmetic keeps integer semantics (7 / 2 is 3), and mixing with floats gives floats. A dotted expression whose arrays are GPU arrays runs on the GPU as one program (the functions applied with f.(g) are translated like shader functions; numbers in the expression become its parameters). Shapes broadcast as on the CPU. Native programs use Vulkan where they can: an array is a buffer, the program a compute program (compiler/spirv.jo, spirv_kernel), with or without a window. Otherwise they use OpenGL ES (without a window, through a windowless EGL context), and web builds WebGL 2: an array is a float texture holding four values per texel, the program a fragment program drawn over it. Where none of these can (no driver, SLOPPY_SOFTWARE=1, an old browser, node) the same expressions run on the CPU, so programs work everywhere; gpu_available() tells which.

struct GpuArray[T]:
    n: int
    w: int
    h: int
    tex: int          # the texture holding the values (0: there is no GPU; they are in host)
    host: T[]
    token: u8[]       # shared by all copies of this value; see __gpu_alloc
    shape: int[]
gpu_available = () -> bool

Moving data

gpu = (xs: f32[]) -> GpuArray[f32]
gpu = (xs: f64[]) -> GpuArray[f32]
gpu = (xs: i32[]) -> GpuArray[i32]
gpu = (xs: int[]) -> GpuArray[i32]
gpu = (xs: bool[]) -> GpuArray[f32]
gpu = (m: f32[,]) -> GpuArray[f32]
gpu = (m: f64[,]) -> GpuArray[f32]
gpu = (m: i32[,]) -> GpuArray[i32]
gpu = (m: int[,]) -> GpuArray[i32]
cpu[T] = (g: GpuArray[T]) -> T[,]

the values (an array of the GPU array's shape)

len[T] = (g: GpuArray[T]) -> int

Reductions

sum = (g: GpuArray[f32]) -> f64

Floats are reduced on the GPU (64 values at a time, until few are left), then added up in f64; integers are added up exactly, in 64 bits, on the CPU (their min and max are found on the GPU with Vulkan).

sum = (g: GpuArray[i32]) -> int
mean = (g: GpuArray[f32]) -> f64
mean = (g: GpuArray[i32]) -> f64
min = (g: GpuArray[f32]) -> f32
max = (g: GpuArray[f32]) -> f32
min = (g: GpuArray[i32]) -> i32
max = (g: GpuArray[i32]) -> i32

GPU buffers and compute

For programs that keep their data on the GPU: buffers of any struct, functions run once per element (compute, dispatch) and draws the GPU decides (draw_indirect). Through Vulkan these run on the GPU; elsewhere on the CPU, so programs work everywhere.

# example: GPU buffers and compute
window("Swarm", 960, 540)

struct Bug:
    pos: vec2
    vel: vec2
struct Step:
    bugs: GpuBuffer[Bug]
    dt: f32
    time: f32

# runs on the GPU, once for each bug
step = (id: int, u: Step):
    b = u.bugs[id]
    a = id * 0.000314 + u.time * 0.3
    r = 0.45 + 0.3 * sin(a * 5.0 + u.time)
    goal = vec2(cos(a) * r * 0.5625, sin(a) * r)
    b.vel = b.vel * 0.94 + (goal - b.pos) * u.dt * 12.0
    b.pos += b.vel * u.dt
    u.bugs[id] = b

struct Corner:
    at: vec2
struct Look:
    bugs: GpuBuffer[Bug]
struct Out:
    pos: vec4
    color: vec4

vs = (c: Corner, u: Look) -> Out:
    b = u.bugs[instance_id()]
    Out(vec4(b.pos + c.at * vec2(0.004, 0.007), 0, 1), vec4(0.3 + length(b.vel) * 3.0, 0.7, 1.0 - length(b.vel) * 2.0, 1))
fs = (i: Out, u: Look) -> vec4: i.color

bugs = gpu_buffer([loop i in 0..20000: Bug(vec2(sin(f32(i)), cos(f32(i * 1.7))) * 0.9, vec2(0, 0))])
stepper = compute(step)
prog = make_shader(shader(vs, fs))
quad = mesh([Corner(vec2(-1, -1)), Corner(vec2(1, -1)), Corner(vec2(0, 1))])
t = 0.0
update = (dt: f64):
    t += dt
    dispatch(stepper, len(bugs), Step(bugs, dt, t))
draw = ():
    clear(rgb(0.05, 0.06, 0.1))
    draw_instanced(prog, quad, len(bugs), Look(bugs))

Run it in the playground

gpubuffer.jo

GPU buffers and compute programs: arrays kept in GPU memory, and functions written in Sloppy that run on the GPU once per element.

struct Particle: pos: vec2; vel: vec2
struct Step: parts: GpuBuffer[Particle]; dt: f32
step = (id: int, u: Step):                    # a compute function: (id, parameters)
    p = u.parts[id]
    p.pos += p.vel * u.dt
    u.parts[id] = p
parts = gpu_buffer(particles)                 # upload (gpu_buffer[Particle](n): n zeros)
stepper = compute(step)                       # the program (the compiler makes it)
dispatch(stepper, len(parts), Step(parts, dt))    # step(id, ...) for each id in [0, len(parts))
ps = cpu(parts)                               # download

A compute function over a grid takes id: ivec2 (dispatch(k, ivec2(w, h), params)).

Shaders read buffers among their uniforms (u.parts[instance_id()]); a buffer can also be a mesh's vertices (gpu_mesh), a draw's instances (draw_instanced) and the counts of draws the GPU decides (draw_indirect with DrawArgs; draw_indirect_count: how many draws, too). Only compute functions write buffers; atomic_add() and the others change an element of a GpuBuffer[i32] or GpuBuffer[u32] that many invocations change at once. What a dispatch writes is seen by every dispatch and draw after it.

Through Vulkan a buffer is GPU memory read by its address and a compute function a compute program (compiler/spirv.jo); elements are laid out as the CPU lays them out. Elsewhere (OpenGL, the software renderer, the web) buffers are in CPU memory and compute functions run on the CPU, on every core; shaders read buffers through a copy in an integer texture. So programs run everywhere: gpu_compute() tells which way.

struct GpuBuffer[T]:
    addr: int             # its address in GPU memory (Vulkan): what GPU programs read
    n: int
    id: int               # its entry in __gb
    host: *T              # its elements, when they are in CPU memory (else null)
    token: u8[]           # shared by every copy of this value: see __gb_reclaim
gpu_compute = () -> bool

whether buffers are in GPU memory and compute functions run on the GPU (Vulkan: the window's, or one with no window), or else in CPU memory and on the CPU

Making, reading and writing buffers

gpu_buffer[T] = (n: int) -> GpuBuffer[T]

a buffer of n elements, all zero: gpu_bufferParticle. Elements are plain data (numbers, bools, vectors and structs of them; no strings, arrays or functions)

gpu_buffer[T] = (xs: T[]) -> GpuBuffer[T]

a buffer holding a copy of xs

len[T] = (b: GpuBuffer[T]) -> int
cpu[T] = (b: GpuBuffer[T]) -> T[]

all the elements, or count of them from first (after what the GPU was given to do has run)

cpu[T] = (b: GpuBuffer[T], first: int, count: int) -> T[]
upload[T] = (b: GpuBuffer[T], xs: T[], at: int = 0)

xs written into the buffer from element at on (before the dispatches and draws that follow)

([])[T] = (b: GpuBuffer[T], i: int) -> T

one element (in GPU memory, outside compute functions: a slow round trip; cpu() reads many). In compute functions, as on the GPU, reading past either end reads the nearest element and writing there does nothing; elsewhere it is an error.

([]=)[T] = (b: GpuBuffer[T], i: int, v: T)
words[T] = (b: GpuBuffer[T]) -> GpuBuffer[u32]

the same memory as 32-bit words, e.g. for atomic_add on a field of DrawArgs: atomic_add(u.arg_words, 1, u32(1)) counts instances (u.arg_words: words(args))

Compute programs

struct Compute[P]:
    spirv: str                # the program for Vulkan (compiler/spirv.jo; "" on the web)
    textures: str             # where P holds Textures: byte offsets, "8,40" (Vulkan: given slots)
    run: (int, P) -> void     # f itself, for the CPU

what compute(f) makes of a compute function f(id: int, params: P)

struct Compute2[P]:
    spirv: str
    textures: str
    run: (ivec2, P) -> void

what compute(f) makes of a compute function over a grid, f(id: ivec2, params: P)

struct Compute3[P]:
    spirv: str
    textures: str
    run: (ivec3, P) -> void

... and over a 3D grid, f(id: ivec3, params: P)

dispatch[P] = (k: Compute[P], n: int, params: P)

k's function run for each id in [0, n) with these parameters, in any order and many at once; the dispatches and draws after it see what it wrote

dispatch[P] = (k: Compute2[P], size: ivec2, params: P)

k's function run for each cell of a size.x by size.y grid, id from ivec2(0, 0) to size - 1 (in groups of 8 by 8 on the GPU), as dispatch(k, n, params) runs it for each id in [0, n)

dispatch[P] = (k: Compute3[P], size: ivec3, params: P)

k's function run for each cell of a size.x by size.y by size.z grid (in groups of 4 by 4 by 4 on the GPU)

atomic_add = (b: GpuBuffer[i32], i: int, v: i32) -> i32

Atomic operations on element i of a buffer, for compute functions whose invocations change the same element: each returns the element's old value (past the ends: does nothing, returns 0).

atomic_add = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_sub = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_sub = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_and = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_and = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_or = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_or = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_xor = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_xor = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_exchange = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_exchange = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_min = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_min = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_max = (b: GpuBuffer[i32], i: int, v: i32) -> i32
atomic_max = (b: GpuBuffer[u32], i: int, v: u32) -> u32
atomic_compare_exchange = (b: GpuBuffer[i32], i: int, expected: i32, desired: i32) -> i32

(the element becomes desired if it was expected)

atomic_compare_exchange = (b: GpuBuffer[u32], i: int, expected: u32, desired: u32) -> u32

Subgroups

subgroup_size = () -> int

In a compute function, the invocations the GPU runs together (a subgroup: 32 of them on NVIDIA, 64 on AMD, fewer on some; 1 on the CPU) combine values without going through memory: subgroup_add(x) is the sum of x over those of them that reach the call together. A program written for any size runs the same everywhere, e.g. one atomic for a subgroup's elements instead of one each: These take numbers and vectors (and, or and xor integers and bools too).

subgroup_invocation_id = () -> int
subgroup_elect = () -> bool
subgroup_all = (b: bool) -> bool
subgroup_any = (b: bool) -> bool
subgroup_broadcast_first[T] = (x: T) -> T
subgroup_add[T] = (x: T) -> T
subgroup_inclusive_add[T] = (x: T) -> T
subgroup_exclusive_add[T] = (x: T) -> T
subgroup_min[T] = (x: T) -> T
subgroup_max[T] = (x: T) -> T
subgroup_and[T] = (x: T) -> T
subgroup_or[T] = (x: T) -> T
subgroup_xor[T] = (x: T) -> T

Drawing with buffers

gpu_mesh[V] = (vertices: GpuBuffer[V], mode: int = GL_TRIANGLES) -> Mesh

a mesh whose vertices are a buffer's (a compute function may change them between draws)

draw_instanced[U, I] = (sh: Shader, m: Mesh, instances: GpuBuffer[I], params: U, first: int = 0, count: int = -1)

instances drawn with their data in a buffer: count of them from first (count -1: to the end)

draw_instanced[U] = (sh: Shader, m: Mesh, count: int, params: U)

count instances with no data of their own (their shaders tell them apart with instance_id(), e.g. reading a buffer among their uniforms: u.parts[instance_id()])

struct DrawArgs:
    count: u32            # how many vertices (or, for a mesh with indices, indices) are drawn
    instances: u32 = 1
    first: u32            # the first vertex (or index)
    base_vertex: i32      # added to each vertex number
    first_instance: u32   # where instance_id() starts (and the instances' data with it)

what one draw of draw_indirect draws (as Vulkan's VkDrawIndexedIndirectCommand)

draw_indirect[U] = (sh: Shader, m: Mesh, args: GpuBuffer[DrawArgs], params: U, at: int = 0, draws: int = 1)

draws whose counts are in a buffer, where a compute function can decide them (GPU-driven drawing): draws draws of mesh m, each as args[at + k] says

draw_indirect[U, I] = (sh: Shader, m: Mesh, instances: GpuBuffer[I], args: GpuBuffer[DrawArgs], params: U, at: int = 0, draws: int = 1)

the same with instance data in a buffer

draw_indirect_count[U] = (sh: Shader, m: Mesh, args: GpuBuffer[DrawArgs], count: GpuBuffer[u32], params: U, at: int = 0, max_draws: int = -1, count_at: int = 0)

draws whose number is in a buffer too: as many as count[count_at] says (at most max_draws, -1: all of args from at on), so a compute function can decide it, e.g. counting the draws it writes with atomic_add(u.count, 0, u32(1))

draw_indirect_count[U, I] = (sh: Shader, m: Mesh, instances: GpuBuffer[I], args: GpuBuffer[DrawArgs], count: GpuBuffer[u32], params: U, at: int = 0, max_draws: int = -1, count_at: int = 0)

the same with instance data in a buffer

Responsive layout

An explicit module (import layout as ui): rows and columns, content and weighted grow sizes, wrapping text, scroll containers and floating boxes. See responsive layout.

layout.jo

Responsive immediate-mode boxes. Import explicitly: import layout as ui. Describe children in a closure; the root solves widths, wraps text, solves heights, then positions and draws. Events use the preceding description's boxes. Keys are local to a parent; changing a keyed row's position does not change its identity.

enum SizingKind: fit, grow, fixed, percent
struct Sizing:
    kind: SizingKind = .fit
    min = 0.0
    max = 1e30
    value = 1.0
type Size = Sizing | int | f64
fit = (min: f64 = 0.0, max: f64 = 1e30) -> Sizing

Content size, bounded by min/max. A number passed for width or height means fixed(number).

grow = (weight: f64 = 1.0, min: f64 = 0.0, max: f64 = 1e30) -> Sizing

Share the available space by weight, respecting min/max and the contents' minimum size.

fixed = (n: f64) -> Sizing
percent = (p: f64) -> Sizing

Fraction of the parent's inner size, before gaps. Percent children contribute zero to fit.

struct Insets:
    left = 0.0
    top = 0.0
    right = 0.0
    bottom = 0.0
type Padding = Insets | int | f64
insets = (left: f64 = 0.0, top: f64 = 0.0, right: f64 = 0.0, bottom: f64 = 0.0) -> Insets

Per-side padding; one number for pad applies to all four sides.

struct Border:
    color: vec4 = vec4(0, 0, 0, 0)
    thickness = 1.0
enum MainAlign: start, center, end, space_between
enum CrossAlign: start, center, end, stretch
enum Axis: vertical, horizontal
enum Corner: top_left, top, top_right, left, center, right, bottom_left, bottom, bottom_right
struct State:
    rect: Rect
    hovered = false
    pressed = false
    clicked = false
    focused = false
    editing = false
    submitted = false

A container/slot's state from its previous solved box. clicked includes keyboard activation; pressed is a pointer press held on the box. rect is zero the first time the element exists. A text field also reports editing, and submitted for the frame Enter/A submits it.

struct Input:
    pointer: vec2 = vec2(-1e20, -1e20)
    origin: vec2?
    down = false
    pressed = false
    released = false
    tap = true
    claimed = false
    touch = false
    wheel = 0.0
    dt = 1.0 / 60.0
    nav: vec2
    activate = false
    next = 0
    cancel = false

Optional scripted input for headless layout tests. Pointer coordinates are screen units when rendering, and the units of at() otherwise. nav is a direction, activate is Enter/A.

debug = false

Outline every solved box while drawing.

profile = false

Opt-in solver timing, in seconds, excluding tree description, drawing and box recording.

solve_seconds = 0.0

Last solve's duration when profile is enabled.

at = (r: Rect, children: () -> void, pad: Padding = 0, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, key: str = "", render: bool = true, input: Input? = none) -> State

Root in any Rect. render=false solves without a window and still runs slot callbacks. Give different roots distinct keys. Rebuild each root once per frame; keys inside it are scoped to their parent. input overrides live input for headless tests.

screen = (children: () -> void, pad: Padding = 0, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, key: str = "") -> State

Root covering the visible area in the current drawing transform's units.

get = (key: str, root: str = "root 0") -> State?

Last solved state for a key, or none if absent. Keys may repeat under different parents: use a unique key for queries (identity itself always includes the parent).

bounds = (key: str, root: str = "root 0") -> Rect?

Last solved rectangle by key. During description this is the previous frame's rectangle.

clip_bounds = (key: str, root: str = "root 0") -> Rect?

Last solved clipping rectangle by key (for headless inspection of scroll containers).

hovered = () -> bool

True over any layout box from the last description. Rendered boxes also count in hud_hovered.

reset = ()

Forget cached roots and release their buffers (for a UI that is closed permanently).

scroll_to = (key: str, offset: f64, root: str = "root 0")

Programmatically scroll a keyed container, clamped against its current content on solving.

row = (children: () -> void, width: Size = fit(), height: Size = fit(), pad: Padding = 0, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, color: vec4 = vec4(), radius: f64 = 0.0, border: Border = Border(), key: str = "", focusable: bool = false) -> State

Children from left to right. focusable: the whole row is a control (keys and a gamepad reach it; it lights up under the pointer), for a card whose State.clicked is used.

column = (children: () -> void, width: Size = fit(), height: Size = fit(), pad: Padding = 0, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, color: vec4 = vec4(), radius: f64 = 0.0, border: Border = Border(), key: str = "", focusable: bool = false) -> State

Children from top to bottom (focusable: as row's).

panel = (children: () -> void, width: Size = fit(), height: Size = fit(), pad: Padding = 16, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, color: vec4 = hud_style.panel, radius: f64 = hud_style.panel_radius, border: Border = Border(hud_style.panel_edge), key: str = "", focusable: bool = false) -> State

A column with padding and the current HUD panel's background, corners and edge (focusable: as row's).

scroll = (children: () -> void, width: Size = fit(), height: Size = fit(), pad: Padding = 0, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, color: vec4 = vec4(), radius: f64 = 0.0, border: Border = Border(), key: str = "", axis: Axis = .vertical) -> State

A clipped container with wheel, drag and gliding, on its axis. Offset is kept by id.

over = (children: () -> void, width: Size = fit(), height: Size = fit(), pad: Padding = 0, gap: f64 = 0.0, align: MainAlign = .start, cross: CrossAlign = .start, color: vec4 = vec4(), radius: f64 = 0.0, border: Border = Border(), key: str = "", anchor: Corner = .top_left, at: Corner = .top_left, offset: vec2 = vec2(), clip: bool = false) -> State

Floating children attached to the parent: anchor is its point, at is this box's point. Drawn last, outside scroll clips. clip = true keeps it inside the scroll containers around it, as a badge on a list's row is.

label = (s: str, size: f64 = hud_style.text_size, color: vec4 = hud_style.text, wrap: bool = false, align: Align = .left, width: Size = fit(), height: Size = fit(), key: str = "") -> void

Text at its measured size; wrap breaks words at the final width, then determines height. A wrapping label's minimum width is its longest unbreakable word (CJK characters may break).

button = (text: str, width: Size = fit(), height: Size = fit(), enabled: bool = true, selected: bool = false, key: str = "") -> bool

A HUD-styled button. Answers from the preceding frame; false the first time it exists.

space = (width: Size = fit(), height: Size = fit(), key: str = "") -> void

An empty box. A grow spacer takes the room left between its siblings.

bar = (amount: f64, color: vec4 = hud_style.accent, width: Size = grow(), height: Size = 12, back: vec4 = hud_style.track, key: str = "") -> void

Filled from zero to one, over the HUD style's track color.

image = (t: Texture, width: Size = fit(), height: Size = fit(), tint: vec4 = vec4(1, 1, 1, 1), key: str = "") -> void

A texture stretched into its solved box. Fits to the texture's pixel dimensions by default.

slot = (draw: (Rect) -> void, width: Size = fit(), height: Size = fit(), focusable: bool = false, key: str = "") -> State

Run draw at draw time with the solved Rect. Captured variables can be changed by hud_ widgets inside it. focusable includes it in direction navigation (with the focus ring drawn around it); get(key) exposes its focus/click.

slider = (value: f64, low: f64, high: f64, step: f64 = 0.0, label: str = "", width: Size = grow(), height: Size = fit(), enabled: bool = true, key: str = "") -> f64

A value in low..high. Left/Right adjust by step (0: continuous pointer, 1% with keys). The focused value control reserves Left/Right even at an endpoint; Tab/LB/RB leave a row. The value is shown at the right: with step's decimals, or as a percentage from 0 to 1.

switch = (on: bool, label: str = "", width: Size = grow(), height: Size = fit(), enabled: bool = true, key: str = "") -> bool

On or off, toggled by a click/tap, Enter, Space or A. Left/Right stay on this control.

choice = (options: str[], index: int, label: str = "", width: Size = grow(), height: Size = fit(), enabled: bool = true, key: str = "") -> int

One option, wrapping at either end. Left/Right or the left/right half of its value changes it; Enter/Space/A chooses the next. Empty options return zero.

text_field = (value: str, hint: str = "", max_chars: int = 64, width: Size = grow(), height: Size = fit(), enabled: bool = true, key: str = "", label: str = "") -> str

A single line using the HUD editor (selection, undo, clipboard, touch keyboard and Paste). Click/tap or Enter/A starts typing; Enter/A submits, Escape/B cancels typing, Up/Down or Tab/LB/RB leave it. get(key).editing/submitted describe this frame after the field call. label sits at the left, with the editable value at the right, as in slider/switch/choice.

Paths

# example: paths
window("Paths", 960, 540)

grid = path_grid(24, 13, 40.0)           # 24 by 13 cells, 40 units across
loop y in 2..11: set_open(grid, 8, y, false)     # two walls
loop y in 0..9: set_open(grid, 16, y, false)
chaser = vec2(60, 260)

update = (dt: f64):
    goal = mouse_pos()
    way = path_step(grid, chaser, goal)  # the next point on the way round the walls
    if distance(way, chaser) > 1.0: chaser += normalize(way - chaser) * 200 * dt

draw = ():
    clear(rgb(0.1, 0.1, 0.13))
    loop y in 0..13:
        loop x in 0..24:
            if not is_open(grid, x, y): rect(x * 40, y * 40, 40, 40, GRAY)
    circle(mouse_pos(), 10, YELLOW)
    circle(chaser, 14, RED)
    text("the red one follows the mouse", vec2(20, 500), 20)

Run it in the playground

paths.jo

Paths over a grid, for enemies finding their way round walls: the grid's cells are open or blocked, and path_step() gives, from anywhere, the next point to walk to on the way to a goal. The steps to each goal are worked out once (a flood over the open cells, eight ways round: diagonally only where both sides are open, about 1 ms for 128 x 128) and kept, for up to 256 goals, until the grid changes (any set_open forgets them all). Many units sharing a few goals is what it is for; each unit with a goal of its own floods the grid for each.

grid = path_grid(40, 30, 16.0)                  # 40 by 30 cells, 16 units across
set_open(grid, 3, 4, false)                     # a wall there
way = path_step(grid, enemy, player)            # walk toward this

Positions are vec2: x and y in a 2D game; on the ground of a 3D one, x and z. origin is where the grid's first cell starts (its corner with the least x and y). A game played on the cells themselves (a roguelike) gives them as ivec2: path_step(grid, monster, player, taken = others) is the next cell. field_of_view and line_cells are below.

struct PathGrid:
    width: int
    height: int
    cell: f64
    origin: vec2
    open: bool[]                # by cell: x + y * width
    fields: {int: int[]} = {}   # (steps to a goal from every cell, by the goal's cell)
path_grid = (width: int, height: int, cell: f64 = 1.0, origin: vec2 = vec2(0, 0)) -> PathGrid

a grid with every cell open

set_open = (g: mut PathGrid, x: int, y: int, open: bool)
is_open = (g: PathGrid, x: int, y: int) -> bool

whether a cell is open (outside the grid: no)

path_cell = (g: PathGrid, p: vec2) -> ivec2

the cell a point is in (kept within the grid), and the middle of a cell

cell_center = (g: PathGrid, c: ivec2) -> vec2
nearest_open = (g: PathGrid, c: ivec2, reach: int = 4) -> ivec2

the open cell nearest c, looking up to reach cells away (c itself when nothing is open)

path_distance = (g: mut PathGrid, from: vec2, to: vec2) -> int

how many steps from one point to another over open cells (-1: there is no way)

path_step = (g: mut PathGrid, from: vec2, to: vec2) -> vec2

Where to head from from on the way to to: the middle of the next cell, or to itself when it is in the same or the next cell (or cannot be reached). Off the open cells (pushed into a corner, or a goal on a crate), the nearest open cell stands in.

In cells, for games on a grid (a roguelike's monsters)

path_step = (g: mut PathGrid, from: ivec2, to: ivec2, taken: ivec2[] = []) -> ivec2

the next cell on the way from one cell to another: to itself when it is next to from (a step onto it: a bump, an attack), from when there is no way. taken: cells it may not step to (other monsters): it takes the best of the free cells that still get closer, so a crowd goes round each other

path_distance = (g: mut PathGrid, from: ivec2, to: ivec2) -> int

how many steps from one cell to another (-1: there is no way)

path_field = (g: mut PathGrid, goal: ivec2) -> int[]

the steps to a goal cell from every cell (x + y * width), as path_step follows them: a Dijkstra map (a million where there is no way). For several goals at once, or to flee (step to where the number is larger), read it directly

What can be seen: field of view and lines over a grid

field_of_view = (width: int, height: int, opaque: bool[], from: ivec2, radius: int) -> bool[]

the cells seen from a cell (x + y * width): those within radius cells that a line from it reaches past no opaque cell (the opaque cells it reaches are seen too: walls show). Shadows are cast as a roguelike's are (recursive shadowcasting)

field_of_view = (g: PathGrid, from: ivec2, radius: int) -> bool[]

the same over a path grid, its blocked cells opaque (walls block sight as they block the way)

line_cells = (a: ivec2, b: ivec2) -> ivec2[]

the cells a straight line from a to b goes through, both ends in (Bresenham's): for line of sight, a thrown item's flight, a beam

Particles, noise, easing, collisions and smooth paths

# example: helpers: particles, noise, easing, collisions, a camera that follows and shakes
window("Helpers", 960, 540)

sparks = Particles(gravity = vec2(0, 300))
player = Rect(100, 400, 40, 40)
wall = Rect(500, 380, 60, 120)
t = 0.0
cam = vec2(480, 270)
shake = Shake()

update = (dt: f64):
    global cam
    t += dt
    if mouse_pressed(.left):
        sparks.emit(screen_to_world(mouse_pos()), 40, 250, ORANGE)
        shake.add(0.5)
    player.x = 100 + 700 * ease_in_out((sin(t) + 1.0) / 2.0)
    if every(1, 0.5) and overlaps(player, wall): sparks.emit(center(player), 10, 120, RED)
    sparks.update(dt)
    shake.update(dt)
    # (the camera keeps the player in view: it moves once the player is 200 units off center)
    cam = follow(cam, center(player), dt, 4.0, vec2(200, 1000))

draw = ():
    clear(rgb(0.08, 0.08, 0.1))
    camera2d(cam + shake.offset())
    loop x in 0..48:                    # a row of smooth noise
        h = fbm(x * 0.15, t * 0.3)
        rect(x * 20, 300 - 100 * h, 18, 100 * h + 4, rgb(0.3, 0.5, 0.4))
    rect(wall.x, wall.y, wall.w, wall.h, GRAY)
    rect(player.x, player.y, player.w, player.h, if overlaps(player, wall): RED else: CYAN)
    sparks.draw()
    camera2d(vec2(480, 270))
    text("click for sparks (and a shake)", vec2(20, 20), 20)

Run it in the playground

gameutil.jo

Common game helpers: noise, collision shapes, easing, timers and 2D particles.

Noise

noise = (x: f64, y: f64) -> f64

smooth value noise in [0, 1]

noise = (x: f64) -> f64

along a line: smooth value noise in [0, 1] (a wobble, a flicker, wind)

noise = (x: f64, y: f64, z: f64) -> f64

in 3D: smooth value noise in [0, 1] (clouds, caves; or 2D noise that changes with time as z)

fbm = (x: f64, y: f64, octaves: int = 4) -> f64

fractal noise (several octaves) in roughly [0, 1]

Easing

linear = (t: f64) -> f64

curves from 0 (t = 0) to 1 (t = 1): in = slow at the start, out = slow at the end; back goes a little past, elastic springs, bounce bounces (easings.net shows each)

ease_in = (t: f64) -> f64
ease_out = (t: f64) -> f64
ease_in_out = (t: f64) -> f64
ease_in_cubic = (t: f64) -> f64
ease_out_cubic = (t: f64) -> f64
ease_in_out_cubic = (t: f64) -> f64
ease_in_sine = (t: f64) -> f64
ease_out_sine = (t: f64) -> f64
ease_in_out_sine = (t: f64) -> f64
ease_in_back = (t: f64) -> f64
ease_out_back = (t: f64) -> f64
ease_out_elastic = (t: f64) -> f64
ease_out_bounce = (t: f64) -> f64
angle_difference = (a: f64, b: f64) -> f64

how far to turn from angle a to angle b the short way, in radians (from -PI to PI)

turn_toward = (angle: f64, target: f64, max_step: f64) -> f64

turn an angle toward another the short way, at most max_step (radians) this time

approach_angle = (current: f64, target: f64, speed: f64, dt: f64) -> f64

frame-rate independent smoothing of an angle toward another, the short way round (as approach)

approach = (current: f64, target: f64, speed: f64, dt: f64) -> f64

frame-rate independent smoothing toward a target (higher speed = snappier)

approach = (current: vec2, target: vec2, speed: f64, dt: f64) -> vec2
approach = (current: vec3, target: vec3, speed: f64, dt: f64) -> vec3

Tweens

enum TweenMode: once, repeat, pingpong

once (then it stays at to), repeat (from the start again), pingpong (to and back, again and again)

struct Tween[T]:
    from: T
    to: T
    duration: f64
    ease: (f64) -> f64 = linear            # (read back from text: this; the text cannot hold a function)
    mode: TweenMode
    t = 0.0                     # seconds since it started (below 0: still waiting)
tween[T] = (from: T, to: T, duration: f64, ease: (f64) -> f64 = ease_in_out, delay: f64 = 0.0, mode: TweenMode = .once) -> Tween[T]

a value going from from to to over duration seconds along an easing curve: a number, a position (vec2, vec3) or a color (vec4); delay: seconds before it starts. For example pop = tween(0.0, 1.0, 0.4, ease_out_back), then pop.update(dt) each frame and pop.value() where it is (grown in 0.4 s, a little past the end, then back).

tween = (from: f64, to: f64, duration: f64, ease: (f64) -> f64 = ease_in_out, delay: f64 = 0.0, mode: TweenMode = .once) -> Tween[f64]

(numbers: tween(0, 10, 0.5) goes through the fractions between)

update[T] = (tw: mut Tween[T], dt: f64)

move it on by dt seconds (with redraw_on_input, it asks for frames until it is done)

progress[T] = (tw: Tween[T]) -> f64

where along the curve it is, from 0 to 1 (before the easing)

value[T] = (tw: Tween[T]) -> T
done[T] = (tw: Tween[T]) -> bool

finished (a tween that repeats never is)

restart[T] = (tw: mut Tween[T])

start again from the start

retarget[T] = (tw: mut Tween[T], to: T)

go on from where it is now to a new target, taking duration again

done[T] = (tws: Tween[T][]) -> bool

all of them finished (a set of tweens started together: cards dealt, then the next turn)

struct Chain[T]:
    steps: Tween[T][]
    t = 0.0

tweens played one after another, as one: hop = chain([tween(a, b, 0.2), tween(b, a, 0.3, ease_out_bounce)]), then hop.update(dt) each frame, hop.value() where it is, hop.done() once the last has ended (each step's delay counts: a pause between two). A step that repeats keeps the chain on it

chain[T] = (steps: Tween[T][]) -> Chain[T]
update[T] = (c: mut Chain[T], dt: f64)
value[T] = (c: Chain[T]) -> T
done[T] = (c: Chain[T]) -> bool
restart[T] = (c: mut Chain[T])

start again from the first step

The camera: following and shaking

follow = (cam: vec2, target: vec2, dt: f64, speed: f64 = 8.0, deadzone: vec2 = vec2(0, 0)) -> vec2

where a camera that follows target is next: it waits while target stays inside deadzone (half its size, in 2D units, around the camera's center), then catches up smoothly (higher speed: snappier). For camera2d(follow(...)).

struct Shake:
    trauma = 0.0
    strength = 24.0             # how far it moves at the most (2D units)
    fade = 1.5                  # trauma lost each second
    t = 0.0

A screen shake: add(trauma) on a hit or a blast (0 to 1; more adds up), update(dt) every frame, and move the camera by offset() (in 3D, offset3d(right)): it shakes hard at first, fading as the trauma wears off.

add = (s: mut Shake, trauma: f64)
update = (s: mut Shake, dt: f64)
offset = (s: Shake) -> vec2
offset3d = (s: Shake, right: vec3, up: vec3 = vec3(0, 1, 0), meters: f64 = 0.25) -> vec3

the same shake for a 3D camera: up to meters along the camera's right and up (add it to where the camera is: camera3d(eye + shake.offset3d(right), target))

Collision

struct Rect:
    x: f32
    y: f32
    w: f32
    h: f32

a box: its top left corner and its size, in the screen's units (any numbers go in: Rect(x, y, 120, 40) with x an f64 is fine, as f64 converts to f32 by itself)

overlaps = (a: Rect, b: Rect) -> bool
contains = (r: Rect, p: vec2) -> bool
center = (r: Rect) -> vec2
right = (r: Rect) -> f32

its right edge, x + w, and its bottom one, y + h (the left is x, the top y)

bottom = (r: Rect) -> f32
move = (r: Rect, by: vec2) -> Rect

the same rect moved by by

grow = (r: Rect, by: f64) -> Rect

each side moved out by by (in, when it is negative: a hitbox a little smaller than its sprite is r.grow(-2)); it stays centered where it was

clamp = (r: Rect, bounds: Rect) -> Rect

r moved (not resized) to be inside bounds: a player kept on the screen, player.rect = player.rect.clamp(Rect(0, 0, 1280, 720)); one larger than bounds is centered on it

union = (a: Rect, b: Rect) -> Rect

the smallest rect around both

first_overlap = (r: Rect, rects: Rect[]) -> int?

the first of rects that r overlaps, by its position in the array, or none

circles_overlap = (a: vec2, ra: f64, b: vec2, rb: f64) -> bool
circle_rect = (c: vec2, r: f64, rect: Rect) -> bool

2D particles

struct Particle:
    pos: vec2
    vel: vec2
    life: f32
    max_life: f32
    size: f32
    color: vec4
struct Particles:
    items: Particle[]
    gravity: vec2           # added to their velocity each second (vec2(0, 400): they fall)
    drag: f32 = 1.0         # how fast they slow down: their speed shrinks by e^-drag a second (0: never)
    colors: vec4[]          # the colors each goes through as it ages, drawn solid (see draw); none: emit's, fading
emit = (ps: mut Particles, pos: vec2, count: int, speed: f64, color: vec4, life: f64 = 1.0, size: f64 = 4.0, spread: f64 = TAU, direction: f64 = 0.0)

count particles from pos, at up to speed (pixels a second), lasting up to life seconds, of up to size pixels' radius; spread is the angle they go out in (radians, TAU: every way) around direction (radians, 0: right, as from_angle)

update = (ps: mut Particles, dt: f64)
draw = (ps: Particles, glow: bool = true)

draw particles as soft glowing dots (additive blending), or with glow = false as solid ones (blended as the drawing before them); each fades out and shrinks as it ages. With colors, each is a solid dot of its size in the color its age is at, as pixel art wants:

Timing

every = (id: int, period: f64) -> bool

true once every period seconds, the first time on the first call: each timer is told apart by its id, any number of the game's own (every(1, 0.5) and every(2, 3.0) run apart)

struct Actions

things to do one after another, each a wait after the one before: an enemy's turn, the hits of an attack, a cutscene. Steps are added with then, and update runs those whose time came.

then = (a: mut Actions, wait: f64, f: () -> void)

do f, wait seconds after the step before it (or after now, when there is none)

update = (a: mut Actions, dt: f64)

the steps whose time has come, run in order (a step may add more)

busy = (a: Actions) -> bool

steps still to come

clear = (a: mut Actions)

drop the steps still to come

curves.jo

Smooth paths through points (vec2 or vec3): a road, a race track, a rail for a camera or a moving platform. A path is its points in order; closed, it goes back to the first (a track).

track = spline_points(corners, per_segment = 12, closed = true)    # the smooth track, as points
d, at = nearest_on_path(track, kart.pos, closed = true)            # how far round, and where
lap_progress = d / path_length(track, closed = true)
ahead = point_along(track, d + 8.0, closed = true)                 # a point to steer for
spline[T] = (points: T[], t: f64, closed: bool = false) -> T

the point at t, from 0 (the first point) to 1 (the last; a closed path's first again), on the smooth curve through the points (Catmull-Rom: through each point, with no corners)

spline_points[T] = (points: T[], per_segment: int = 8, closed: bool = false) -> T[]

the smooth curve through the points as points: per_segment from each point to the next (for drawing it, or as a path to follow; the last point is there too, unless it is closed)

path_length[T] = (path: T[], closed: bool = false) -> f64

how long the path is (closed: back to the start too)

nearest_on_path[T] = (path: T[], p: T, closed: bool = false) -> (f64, T)

where p is nearest to the path: how far along it that is (from its start) and the point there

point_along[T] = (path: T[], distance: f64, closed: bool = false) -> T

the point distance along the path from its start (a closed one goes round again; an open one stops at its ends)

2D physics

A module (import physics): rigid bodies (circles, boxes, convex polygons) that collide, bounce, slide and stack, joined by pins, rods, ropes and springs. Distances are in the screen's units with y down, as in drawing. See examples/physics.jo.

# example: physics
import physics

w = physics.World()                                       # gravity: 980 pixels/s² down
w.add_box(vec2(640, 700), vec2(1280, 40), kind = .fixed)  # the floor
crates: physics.Body[]
loop i in 0..5: crates.push(w.add_box(vec2(600 + 8 * i, 600 - 45 * i), vec2(40, 40)))
ball = w.add_circle(vec2(200, 300), 25, bounce = 0.5)
w.push(ball, vec2(600, -200) * w.mass(ball))          # thrown at the stack
lamp = w.add_box(vec2(1000, 220), vec2(30, 60))
w.rod(physics.ground, lamp, vec2(1000, 80), vec2(1000, 190), rope = true)

update = (dt: f64):
    w.step(dt)
    loop c in w.contacts(ball):
        if c.new and c.impulse > 500.0: print("hit, {c.impulse:.0}")

draw = ():
    clear(rgb(0.1, 0.1, 0.14))
    physics.draw_debug(w)

Run it in the playground

physics.jo

2D physics: rigid bodies that fall, collide, bounce, slide and stack, held together by pins, rods, ropes, springs, welds, sliders and wheels. import physics, then:

w = physics.World()                                     # gravity down, in pixels (as drawing)
floor = w.add_box(vec2(640, 700), vec2(1280, 40), kind = .fixed)
ball = w.add_circle(vec2(640, 100), 24, bounce = 0.6)
update = (dt: f64): w.step(dt)
draw = ():
    circle(w.pos(ball), 24, WHITE)                      # (or physics.draw_debug(w))

Bodies are .dynamic (moved by forces and collisions), .fixed (never move: floors, walls) or .moving (moved only by the velocity the game gives them: platforms, doors). Each has a shape: a circle, a box or a polygon (a concave one is cut into convex parts), or several of them held together (w.add_body(pos, [.circle(vec2(0, -30), 12), physics.box_part(vec2(0, 0), vec2(40, 20))])). A Body is a handle; ask the world about it (w.pos(b), w.angle(b), w.velocity(b)) and change it (w.push(b, impulse)).

Units: pixels, seconds, radians. A body's mass is its density times its area / 100 (a 40 x 40 box of density 1 weighs 16; mass = gives it outright), an impulse is mass times pixels a second: a contact's .impulse divided by the lighter body's mass is the speed it took out. Two bodies touching use the square root of their frictions multiplied, and the larger bounce. A body that would cross more than half its size in a step is swept: it stops at what it would have passed through (no tunneling at any speed). Circles roll on without slowing (there is no rolling resistance): w.set_damping(b, 1.0) lets one come to rest.

Joints: w.hinge(a, b, at) (a hinge at a point), w.rod(a, b, at_a, at_b) (a fixed distance; spring = 4.0 makes it a spring of that many oscillations a second, rope = true lets it go slack), w.weld(a, b, at) (one piece), w.slider(a, b, at, axis) (along a line: a piston, a lift), w.wheel(car, wheel, at) (sprung, turning, with a motor), w.drag(b, at) and w.drag_to(j, target) (pulling a body by a point: the mouse). physics.ground is a fixed body to attach things to the world. Two bodies joined by a joint do not collide with each other (the links of a chain overlap where they are pinned).

Each step is the same for the same inputs (a fixed internal step, a fixed order), so a game that steps it with a fixed dt can replay or roll back. Contacts: w.contacts() lists the pairs touching after the step (.new on the step they met, .impulse how hard), w.separated() those that stopped touching, and sensors (sensor = true) report contacts without colliding: pickups, triggers. Collision layers: bodies a and b collide when a.layer & b.mask and b.layer & a.mask are not 0.

enum BodyKind: dynamic, fixed, moving
struct Body:
    id: int
    gen: int

(a handle: a body's place, and which body has had it: a removed body's handle is not taken for the next one put there)

struct Joint:
    id: int
    gen: int
struct Contact:
    a: Body
    b: Body
    point: vec2
    normal: vec2            # from a toward b
    impulse: f32            # how hard they pushed on each other in the last step (0 for sensors)
    new: bool               # they started touching in the last step

a pair of bodies touching after the last step

struct Hit:
    body: Body
    point: vec2
    normal: vec2
    fraction: f32           # how far along the ray, 0 to 1
enum Part: circle(center: vec2, radius: f64), polygon(points: vec2[])

one of the shapes a body of several is made of (add_body), placed around the body's position

box_part = (center: vec2, size: vec2, angle: f64 = 0) -> Part

a box among a body's parts

struct World:
    gravity = vec2(0, 980)
    iterations = 8          # solver passes each step (more: stiffer stacks and chains)
    sleep = true            # bodies that have come to rest are left out until something touches them
    substep = 1.0 / 120.0   # the longest internal step, in seconds

Making bodies

add_circle = (w: mut World, pos: vec2, radius: f64, kind: BodyKind = .dynamic, density: f64 = 1.0, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body
add_box = (w: mut World, pos: vec2, size: vec2, angle: f64 = 0, kind: BodyKind = .dynamic, density: f64 = 1.0, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body
add_polygon = (w: mut World, pos: vec2, points: vec2[], angle: f64 = 0, kind: BodyKind = .dynamic, density: f64 = 1.0, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body

points around pos, in order: a concave polygon is cut into convex parts (points not in order, or crossing themselves: their convex hull)

add_body = (w: mut World, pos: vec2, parts: Part[], angle: f64 = 0, kind: BodyKind = .dynamic, density: f64 = 1.0, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body

a body made of several shapes, held together as one: .circle(center, radius), .polygon(points) and box_part(center, size), placed around pos (turned by angle). Its frame is then at its center of mass, not at pos: w.pos(b), to_world and to_local use that point (w.to_world(b, p - (w.pos(b) - pos)) places p as given around pos, before it turns)

set_mass = (w: mut World, b: Body, m: f64)

give a dynamic body another mass (its turning inertia changes with it)

remove = (w: mut World, b: Body)

take b out of the world (and the joints it is in); its handle then means nothing (a handle used after this panics; removing twice does nothing)

remove = (w: mut World, j: Joint)
joint_alive = (w: World, j: Joint) -> bool

the joint is still there (not removed, nor one of its bodies)

Asking and changing

pos = (w: World, b: Body) -> vec2
angle = (w: World, b: Body) -> f64
velocity = (w: World, b: Body) -> vec2
spin = (w: World, b: Body) -> f64
mass = (w: World, b: Body) -> f64
kind = (w: World, b: Body) -> BodyKind
alive = (w: World, b: Body) -> bool
tag = (w: World, b: Body) -> int

a number of the game's own, kept with the body (what it is: a coin, an enemy's index...)

set_tag = (w: mut World, b: Body, t: int)
bodies = (w: World) -> Body[]

every body there is (not ground)

radius = (w: World, b: Body) -> f64

a circle's radius (0 for a polygon)

to_world = (w: World, b: Body, local: vec2) -> vec2

a point of the body, in the world (from the body's own frame), and back

to_local = (w: World, b: Body, p: vec2) -> vec2
set_pos = (w: mut World, b: Body, p: vec2)
set_angle = (w: mut World, b: Body, a: f64)
set_velocity = (w: mut World, b: Body, v: vec2)
set_spin = (w: mut World, b: Body, s: f64)
sleeping = (w: World, b: Body) -> bool

it is asleep: at rest with all it touches, left out of each step until something touches it

set_damping = (w: mut World, b: Body, d: f64)

slowing down by itself (as through air or water): the share of its speed lost each second

set_fixed_rotation = (w: mut World, b: Body, on: bool)

it never turns (a character's body)

set_friction = (w: mut World, b: Body, f: f64)
set_bounce = (w: mut World, b: Body, f: f64)
set_layers = (w: mut World, b: Body, layer: int, mask: int = -1)
push = (w: mut World, b: Body, impulse: vec2)

a sudden change of motion (a jump, a hit), at a point of the world (its center: no turning)

push = (w: mut World, b: Body, impulse: vec2, at: vec2)
apply_force = (w: mut World, b: Body, f: vec2)

a steady force for the next step (thrust, wind): give it every frame it acts

apply_torque = (w: mut World, b: Body, t: f64)

Joints

hinge = (w: mut World, a: Body, b: Body, at: vec2, lower: f64 = -1e9, upper: f64 = 1e9, motor_speed: f64 = 0, max_torque: f64 = 0) -> Joint

a hinge: a and b turn about the point at (in the world, now) lower, upper: how far b may turn against a (radians, from how they are now); motor_speed: b turned against a at that many radians a second, with up to max_torque (0: no motor)

weld = (w: mut World, a: Body, b: Body, at: vec2) -> Joint

a and b held together at at, as one: neither moves or turns against the other (a joint that can be undone, unlike one body of both shapes)

slider = (w: mut World, a: Body, b: Body, at: vec2, axis: vec2, lower: f64 = -1e9, upper: f64 = 1e9, motor_speed: f64 = 0, max_force: f64 = 0) -> Joint

b slides against a along a line through at in the direction axis (in the world, now) and does not turn against it: a piston, a sliding door, a lift. lower, upper: how far b may go along the line from where it is now; motor_speed: driven along it at that many units a second, with up to max_force (0: no motor)

wheel = (w: mut World, a: Body, b: Body, at: vec2, axis: vec2 = vec2(0, 1), spring: f64 = 4, damping: f64 = 0.7, motor_speed: f64 = 0, max_torque: f64 = 0) -> Joint

a car's wheel: b (the wheel) held to a (the car) at at, free to move only along axis (the suspension, in the world, now: up and down by default) on a spring of that many oscillations a second (damping: 0 bounces on, 1 settles at once), and free to turn; motor_speed turns it at that many radians a second, with up to max_torque (0: it rolls freely)

joint_translation = (w: World, j: Joint) -> f64

how far b is along a slider's or wheel's line from where it started

set_motor = (w: mut World, j: Joint, speed: f64, limit: f64)

change a hinge's or wheel's angular motor (speed in radians/second, limit is torque), or a slider's linear motor (speed in world units/second, limit is force). 0 disables it.

set_limits = (w: mut World, j: Joint, lower: f64, upper: f64)

change how far a hinge lets b turn against a (from lower to upper radians), or a slider lets it move along its line

joint_angle = (w: World, j: Joint) -> f64

how far b has turned against a since the joint was made, in radians

rod = (w: mut World, a: Body, b: Body, at_a: vec2, at_b: vec2, spring: f64 = 0, damping: f64 = 0.5, rope: bool = false) -> Joint

the points at_a of a and at_b of b (in the world, now) kept as far apart as they are; with spring > 0 a spring of that many oscillations a second (damping: 0 bounces on, 1 settles at once); with rope, only as far apart at most

drag = (w: mut World, b: Body, at: vec2, strength: f64 = 1000) -> Joint

pulls the point at of b toward a target (drag_to), as a stiff spring: grabbing with the mouse

drag_to = (w: mut World, j: Joint, target: vec2)
ends = (w: World, j: Joint) -> (vec2, vec2)

where a joint's two ends are now: on a and on b (a rope or rod is drawn between them; a pin's are its hinge as each body has it, one point unless it is stretched; a drag's: its target, and the point it pulls)

set_length = (w: mut World, j: Joint, l: f64)

set a rod's length (a winch)

Stepping

step = (w: mut World, dt: f64)

move the world on by dt seconds (in steps of at most w.substep)

contacts = (w: World) -> Contact[]

the pairs touching after the last step

separated = (w: World) -> (Body, Body)[]

the pairs that touched before the last step and no longer do (a ball leaving a trigger, a foot leaving the ground)

contacts = (w: World, b: Body) -> Contact[]

those that b is one of (each turned so that .a is b)

Queries

raycast = (w: World, a: vec2, b: vec2, mask: int = -1) -> Hit?

the first nonsensor body a ray from a to b meets (only those whose layer & mask is not 0). Sensors are excluded; overlap_circle/overlap_box include them.

Overlaps

overlap_circle = (w: World, center: vec2, radius: f64, mask: int = -1) -> Body[]

the bodies (sensors too) a circle or a box overlaps: what an explosion reaches, the zones something stands in (bodies_at(p): those at a point)

overlap_box = (w: World, center: vec2, size: vec2, angle: f64 = 0, mask: int = -1) -> Body[]
circle_cast = (w: World, a: vec2, b: vec2, r: f64, mask: int = -1) -> Hit?

sweep a circle from a to b against nonsensor bodies (filtered by layer & mask). Sensors are excluded; use overlap_circle to query sensors at a position.

bodies_at = (w: World, p: vec2) -> Body[]

the bodies at the point p (the topmost first: the last made)

outline = (w: World, b: Body) -> vec2[]

a body's outline in the world (a circle's as 24 points; a concave polygon as it was given; a body of parts from add_body: around all of them, so draw those with outlines)

outlines = (w: World, b: Body) -> vec2[][]

the outline of each of a body's parts (one, for a body of one shape)

draw_debug = (w: World, thickness: f64 = 2)

every body's outline and every joint, for seeing what the physics does

3D physics

A module (import physics3d): rigid bodies (spheres, boxes, capsules) and a level's triangles, joints (ball, hinge, rod, rope, spring), rays, and a character controller that walks slopes and steps. Meters, y up. See examples/physics3d.jo.

# example: physics3d
import physics3d

w = physics3d.World()                                          # gravity: 9.81 m/s² down
w.add_box(vec3(0, -0.5, 0), vec3(30, 1, 30), kind = .fixed)    # the ground (a size: full lengths)
crates: physics3d.Body[]
loop i in 0..5: crates.push(w.add_box(vec3(0.05 * i, 0.5 + 1.01 * i, 0), vec3(1, 1, 1), density = 200))
ball = w.add_sphere(vec3(-6, 1, 0), 0.5, density = 3000)
w.set_velocity(ball, vec3(9, 3, 0))                            # thrown at the tower
cube = cube_mesh(1.0)
orb = sphere_mesh(0.5)

update = (dt: f64): w.step(dt)

draw = ():
    camera3d(vec3(0, 4, 12), vec3(0, 2, 0))
    draw_mesh(cube, translation(vec3(0, -0.5, 0)) * scaling(vec3(30, 1, 30)), rgb(0.4, 0.5, 0.4))
    loop c in crates: draw_mesh(cube, w.transform(c), rgb(0.7, 0.5, 0.3))
    draw_mesh(orb, w.transform(ball), rgb(0.8, 0.8, 0.85))

Run it in the playground

physics3d.jo

3D physics: rigid bodies (spheres, boxes, capsules) that fall, collide, slide, roll and stack, a level's triangles to stand on, joints, rays, and a character controller for walking. import physics3d, then:

w = physics3d.World()                                   # meters, y up, gravity 9.81 down
w.add_box(vec3(0, -0.5, 0), vec3(40, 1, 40), kind = .fixed)        # (a size: full lengths)
crate = w.add_box(vec3(0, 3, 0), vec3(1, 1, 1))
ball = w.add_sphere(vec3(0.3, 6, 0), 0.5, bounce = 0.4)
update = (dt: f64): w.step(dt)
draw = (): draw_mesh(cube, w.transform(crate))         # (position and turn, as a mat4)

Masses come from sizes and density (kilograms per cubic meter: 1000 is water's, so a ball of radius 0.5 weighs 524 kg), or are given: w.add_sphere(pos, 0.5, mass = 1), w.set_mass(b, 2). Bodies are .dynamic, .fixed or .moving (moved only by the velocity the game gives them), with one shape each; w.add_mesh(triangles) adds fixed triangles (a level, from a model: physics3d.triangles(model_data); a terrain_mesh: physics3d.terrain_triangles). Joints: w.ball(a, b, at) (a ball and socket), w.hinge(a, b, at, axis), w.rod(a, b, at_a, at_b) (a distance, or a spring, or a rope). Rays: w.raycast. A character: w.character(pos, radius, height) and w.walk(c, velocity, dt), a capsule that walks up slopes and steps, slides down steeper ones, and is pushed by nothing but the level. Contacts: w.contacts(b) after a step, each with .new on the step they met; a sensor (sensor = true: a pickup, a trigger zone) collides with nothing but is in them too. As in 2D, stepping is the same for the same inputs (for replays and rollback). A small, fast body can pass through a thin wall in one step (there is no continuous collision yet): for bullets, use w.raycast from where they were to where they are.

enum BodyKind: dynamic, fixed, moving
enum Shape: none, sphere, box, capsule, triangles
struct Body:
    id: int
    gen: int

(a handle: a body's place, and which body has had it: a removed body's handle is not taken for the next one put there)

struct Joint:
    id: int
    gen: int
struct Contact:
    a: Body
    b: Body
    point: vec3
    normal: vec3            # from a toward b
    impulse: f32
    new: bool
struct Hit:
    body: Body
    point: vec3
    normal: vec3
    fraction: f32
ground = Body(0)

the world itself, for joints to it: w.ball(ground, lamp, at) hangs a lamp from a fixed point

The world

struct World:
    gravity = vec3(0, -9.81, 0)
    iterations = 10
    sleep = true            # bodies that have come to rest are left out until something touches them
    substep = 1.0 / 120.0

Making bodies

add_sphere = (w: mut World, pos: vec3, radius: f64, kind: BodyKind = .dynamic, density: f64 = 1000, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body
add_box = (w: mut World, pos: vec3, size: vec3, rot: vec4 = vec4(0, 0, 0, 1), kind: BodyKind = .dynamic, density: f64 = 1000, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body

size: the box's full width, height and depth

add_capsule = (w: mut World, pos: vec3, radius: f64, height: f64, rot: vec4 = vec4(0, 0, 0, 1), kind: BodyKind = .dynamic, density: f64 = 1000, friction: f64 = 0.5, bounce: f64 = 0.0, sensor: bool = false, mass: f64 = 0) -> Body

a capsule standing up: height from the bottom to the top of its round ends

add_mesh = (w: mut World, triangles: vec3[], friction: f64 = 0.6) -> Body

fixed triangles (three corners each, in the world): a level, the ground

triangles = (md: ModelData) -> vec3[]

a model's triangles, where its parts are (for add_mesh)

terrain_triangles = (size: f64, divisions: int, height: (f64, f64) -> f64) -> vec3[]

the triangles of terrain_mesh(size, divisions, height, ...), for add_mesh: the ground of the terrain drawn with the same size, divisions and height

set_mass = (w: mut World, b: Body, m: f64)

give a dynamic body another mass, in kilograms (its turning inertia changes with it)

remove = (w: mut World, b: Body)

take b out of the world (and the joints it is in); its handle then means nothing (a handle used after this panics; removing twice does nothing)

remove = (w: mut World, j: Joint)
joint_alive = (w: World, j: Joint) -> bool

the joint is still there (not removed, nor one of its bodies)

Asking and changing

bodies = (w: World) -> Body[]
shape = (w: World, b: Body) -> Shape

its shape, and (for drawing it) its size: a box's full width, height and depth, a sphere's or a capsule's width (and a capsule's height, end to end, in y)

size = (w: World, b: Body) -> vec3
radius = (w: World, b: Body) -> f64
pos = (w: World, b: Body) -> vec3
rotation = (w: World, b: Body) -> vec4
velocity = (w: World, b: Body) -> vec3
spin = (w: World, b: Body) -> vec3
mass = (w: World, b: Body) -> f64
kind = (w: World, b: Body) -> BodyKind
alive = (w: World, b: Body) -> bool
tag = (w: World, b: Body) -> int
set_tag = (w: mut World, b: Body, t: int)
transform = (w: World, b: Body) -> mat4

where and how it is turned, as a matrix for drawing (a box's or capsule's size not included)

to_world = (w: World, b: Body, local: vec3) -> vec3
to_local = (w: World, b: Body, p: vec3) -> vec3
set_pos = (w: mut World, b: Body, p: vec3)
set_rotation = (w: mut World, b: Body, q: vec4)
set_velocity = (w: mut World, b: Body, v: vec3)
set_spin = (w: mut World, b: Body, s: vec3)
sleeping = (w: World, b: Body) -> bool

it is asleep: at rest with all it touches, left out of each step until something touches it

set_damping = (w: mut World, b: Body, d: f64)
set_fixed_rotation = (w: mut World, b: Body, on: bool)

it never turns, whatever hits it (an upright enemy, a character's body)

set_friction = (w: mut World, b: Body, f: f64)
set_bounce = (w: mut World, b: Body, f: f64)
set_layers = (w: mut World, b: Body, layer: int, mask: int = -1)

which layer a body is on (a bit: 1, 2, 4, 8...; every body starts on 1) and which layers it touches (mask: bits or'ed together; -1, the start: all). Two bodies touch when each one's layer is in the other's mask; rays, casts and overlaps take a mask too. For a collider only the camera sees: w.set_layers(crown, 4) and w.sphere_cast(a, b, r, mask = 1 | 4), the player kept out of it with player.mask = 1 | 2 (a character's mask is its own)

push = (w: mut World, b: Body, impulse: vec3)
push = (w: mut World, b: Body, impulse: vec3, at: vec3)
apply_force = (w: mut World, b: Body, f: vec3)
apply_torque = (w: mut World, b: Body, t: vec3)

Joints

ball = (w: mut World, a: Body, b: Body, at: vec3) -> Joint

a ball and socket at the point at (in the world, now)

hinge = (w: mut World, a: Body, b: Body, at: vec3, axis: vec3, lower: f64 = -1e9, upper: f64 = 1e9, motor_speed: f64 = 0, max_torque: f64 = 0) -> Joint

a hinge at at, turning about axis (in the world, now); lower, upper: how far b may turn against a (radians, from how they are now; about axis, by the right hand); motor_speed: b turned against a at that many radians a second, with up to max_torque (0: no motor)

set_motor = (w: mut World, j: Joint, speed: f64, max_torque: f64)

change a hinge's motor: b turns against a at speed radians a second, with up to max_torque (0: no motor)

set_limits = (w: mut World, j: Joint, lower: f64, upper: f64)

change how far a hinge lets b turn against a: from lower to upper radians

joint_angle = (w: World, j: Joint) -> f64

how far b has turned against a since the joint was made, in radians

rod = (w: mut World, a: Body, b: Body, at_a: vec3, at_b: vec3, spring: f64 = 0, damping: f64 = 0.5, rope: bool = false) -> Joint

the points at_a of a and at_b of b kept as far apart as they are (spring: a spring of that many oscillations a second; rope: only as far at most)

ends = (w: World, j: Joint) -> (vec3, vec3)

Stepping

step = (w: mut World, dt: f64)
contacts = (w: World) -> Contact[]
contacts = (w: World, b: Body) -> Contact[]

Overlaps

overlap_sphere = (w: World, center: vec3, radius: f64, mask: int = -1) -> Body[]

the bodies (sensors too) a sphere, a box or a character overlaps: the trigger zones and pickups a character is in (it is not a body, so it makes no contacts), what an explosion reaches

overlap_box = (w: World, center: vec3, size: vec3, rot: vec4 = vec4(0, 0, 0, 1), mask: int = -1) -> Body[]
overlaps = (w: World, c: Character) -> Body[]

Rays

raycast = (w: World, a: vec3, b: vec3, mask: int = -1) -> Hit?

the first body a ray from a to b meets (only those whose layer & mask is not 0; sensors are passed through)

sphere_cast = (w: World, a: vec3, b: vec3, r: f64, mask: int = -1) -> Hit?

the first body a ball of radius r, moved from a to b, would touch: the hit's point is where it touches, and fraction how far along the ball's center is then (a thick ray: bullets that are not points, a camera kept out of walls, what is under a character's feet)

A character

struct Character:
    feet: vec3                      # the bottom of the capsule
    radius = 0.3
    height = 1.8
    velocity: vec3                  # as it moves (falling builds up here)
    on_ground = false
    ground_normal = vec3(0, 1, 0)
    standing_on = Body(0, 0)        # the body it stands on (a moving platform carries it)
    max_slope = 50deg
    step = 0.35
    layer = 1
    mask = -1
    mass = 80.0                     # (kilograms: what it shoves)
    push = 1.0

A capsule that walks: it stands on what it can (slopes up to max_slope, steps up to step high), slides down steeper slopes, stops at walls, and keeps to the ground going down slopes and steps. It is not a body: the level and fixed and moving bodies stop it, and it shoves dynamic ones out of its way (as hard as its mass against theirs, times push), which stops it as much as they do not give way.

character = (w: World, feet: vec3, radius: f64 = 0.3, height: f64 = 1.8) -> Character
walk = (w: mut World, c: mut Character, move: vec3, dt: f64, jump: f64 = 0)

move c for dt seconds, at the velocity move along the ground (its y is not used), and jumping at jump meters a second when on the ground and jump > 0

Networking

A module (import net): messages between programs over WebSockets, so a native build and a web page can play together (a server is a native program; a web page connects to one: examples/netpong), UDP datagrams between native programs, TCP and TLS streams, and fetch for what is at an http:// or https:// address.

# example: networking
import net

window("Chat", 960, 540)

# HOST=1: a server here; else a client of localhost (or ?join=address in a web page)
hosting = env("HOST") != none
if hosting: net.listen(4000)
else: net.connect(env("JOIN") ?? "localhost", 4000)
said: str[]

update = (dt: f64):
    loop e in net.receive():
        if e.kind == .joined: said.push("({e.peer} is here)")
        else if e.kind == .left: said.push("({e.peer} left)")
        else:
            said.push("{e.peer}: {e.text}")
            if hosting: net.send_all(e.data)       # (a server passes each message on)
    if key_pressed(.space): net.send_all("hello at {elapsed():.1} s")

draw = ():
    clear(rgb(0.08, 0.09, 0.12))
    text("Space: say hello", vec2(20, 20), 22)
    loop i in 0.. and line in said[max(said.len() - 18, 0)..]: text(line, vec2(20, 70 + 24 * i), 20)

Run it in the playground

net.jo

Networking: messages between programs, over WebSockets, so that the same game reaches others from a native build and from a web page. import net, then:

net.listen(4000)                        # a server: others connect to this machine's port 4000
p = net.connect("192.168.1.20", 4000)   # a client: a peer (it connects in the background)
loop e in net.receive():                # what happened since the last call (every frame)
    if e.kind == .joined: ...           # a peer connected (to a server, or the server, to a client)
    if e.kind == .message: print(e.text)
    if e.kind == .left: ...             # it went away (or could not be reached)
net.send(p, "hello")                    # a str or u8[]; net.send_all(...) to every peer

Messages arrive whole and in order (WebSockets over TCP). A web page can only connect, not listen: the server is a native program (a game that hosts, or a small server of its own). A page served over https can only reach a wss:// server (TLS: put a proxy that has a certificate, such as Caddy, in front of the server); net.connect("wss://game.example.com") takes a URL as well, from a web page or a native program.

error struct NetError:
    message: str

A network operation that could not be started; the reason travels with its result.

enum NetKind: joined, message, left
struct NetEvent:
    kind: NetKind
    peer: int
    data: u8[]              # a message's bytes ...
    text = ""               # ... and as text; a left event's: why it left (why(peer))
    code = 0                # a left event's: the WebSocket's close code (close's: 1000 a normal
                            # close, 1001 a page that went away, 4000-4999 a program's own), 1005
                            # a close that gave none, 1006 none at all (the connection was lost);
                            # 0 over WebRTC

The peers

struct Handshake:
    path = ""               # the address's path, as "/play" (its query apart)
    query: {str: str}       # ?room=4&name=ann: {"room": "4", "name": "ann"}
    headers: {str: str}     # names in small letters
    cookies: {str: str}
    origin = ""             # the site of the web page connecting ("https://example.com"; "" when not a page)
    address = ""            # where it connected from: "1.2.3.4"

how a peer that connected to this program's server asked to (net.listen's, or an http server's that took a WebSocket): for a server that lets in only its own web pages (origin), or players who have signed in (a cookie, or a token in the query)

Straight to another player, with no server (WebRTC)

invite = (reliable: bool = true) -> int

One side invites: invite_code gives a short code to send the other player any way (a chat message). They join with it, and invite_code then gives them a reply code to send back, which the first side accepts. Then the peer is as any other: joined, messages, left. Web pages and native programs connect so, each to the other too; a STUN server (Google's, rtc.rtc_stun_servers) says how each looks from the internet, and nothing else is in between. reliable = false: messages may be lost or come in another order, never late (a fast game's state)

join_invite = (code0: str) -> int

join a game with the code its host sent, or a link with the code in it (…?invite=code): a peer, whose invite_code(p) is then the reply to send back

invite_code = (peer: int) -> str

this side's code for a peer from invite or join_invite: "" while it is being made (a moment, as this machine's addresses are found)

webrtc_missing = () -> str

why this game cannot connect straight to another player (invite, join_invite), in words for players: a web browser with WebRTC turned off (Firefox's media.peerconnection.enabled, a privacy setting); "" when it can

code_kind = (code: str) -> str

what a code is: "invite" (from net.invite: for join_invite), "reply" (from join_invite: for accept_reply), or "" (not a code: cut short, or something else pasted); a link to an invite is one

accept_reply = (peer: int, reply: str) -> bool

the other player's reply to this side's invite; false when it is not a reply code

turn_server = (url: str, user: str, password: str)

a TURN server ("turn:host:port", or "host:port") with the user name and password it gives: the invites made after this also offer a path through it, a relay, for players whose networks allow none straight to each other (some mobile data, schools, offices). Your own (coturn), or a service's (some have a free tier); its password goes into every copy of the game. UDP only

listen = (port: int, host: str = "", largest: int = 16 << 20) -> bool

start a server on port (0: one the system picks; port() reads it); false if the port cannot be had. largest: the biggest message taken from the peers that connect (one bigger ends its connection, with code 1009: a public server's guard), and a peer that has not finished connecting in 10 seconds is let go. host: the address it is reached at, "" every one this machine has ("127.0.0.1": from this machine only). handshake(peer) tells how each peer asked to connect (its path, cookies, the web page's site); an http server (import http) takes WebSockets on its own port too. An exact address:port conflict fails everywhere. macOS permits ""/specific-address overlap (SO_REUSEADDR); Linux and Windows reject it. Linux/macOS use SO_REUSEADDR to rebind while old connections are in TIME_WAIT. Windows uses SO_EXCLUSIVEADDRUSE: TIME_WAIT can delay restart only if the server actively closed accepted connections. Closing the listener alone does not create TIME_WAIT.

port = () -> int

the server's port, including the one the system chose for listen(0); -1 when not listening

stop_listening = ()

stop taking new connections (the peers connected stay); listen starts again

connect = (host: str, port: int = 0) -> int

connect to a server: a peer, connecting in the background (joined or left arrive by receive); host is a name or address and port its port, or host is a ws:// or wss:// URL (port then unused)

send = (peer: int, msg: u8[])

send a message to a peer (nothing if it is not connected, or has gone): text goes as a text message (a string to a page's WebSocket), bytes as a binary one

send = (peer: int, msg: str)
send_all = (msg: u8[])

send a message to every connected peer

send_all = (msg: str)
peers = () -> int[]

the peers connected now

close = (peer: int, code: int = 1000, reason: str = "")

end a connection (a left event follows). Over a WebSocket, the other side's left event has the code and the reason (its code, and its text and why(peer)); a web page's WebSocket has them in its close event (event.code, event.reason). code: 1000 a normal close, 4000-4999 the program's own (4001 a full room, 4003 a sign-in refused...), as a browser's own WebSocket takes; reason: a few words, up to 123 bytes

route = (peer: int) -> str

how a peer is reached: "direct" (WebRTC, straight between the two), "relay" (WebRTC through a TURN server), "websocket" (a connection to a server, or one a server took), or "" (not known yet, or gone; in a web page, until the browser says, a moment after the first call)

backlog = (peer: int) -> int

how much waits to reach a peer: over WebRTC, the pieces sent and not acknowledged yet and those waiting for room (in a web page, the bytes its data channel holds); over a WebSocket, the bytes not sent yet (0 in a web page)

dropped = (peer: int) -> int

the messages to a peer dropped so far for want of room (one invited with reliable = false, whose messages may be lost: while the other side is slow to take them, newer ones are not held up)

why = (peer: int) -> str

why a peer could not connect, or the reason its close gave (net.close(p, code, reason)), once it has left ("": it did not say; a web page's browser does not tell why it could not connect)

local_address = () -> str

this machine's address on its network (as 192.168.1.20): what another machine there connects to, and what a host tells the players joining it; "" when it has none (no network, or a web page)

receive = () -> NetEvent[]

what happened since the last call: peers joining and leaving, and their messages, in order

receive = (only: int[]) -> NetEvent[]

the same, for the given peers only (the others' events wait for another call): parts of a program that each have peers of their own, as a game hosting a relay and playing through it

receive = (only: int[], wait: f64) -> NetEvent[]

the same, waiting up to wait seconds for the first of their events: a task's, for the peers it serves (a server's connection each, from accept). The peers waited for are its own from then on: receive() and receive_server() leave their events. In a web page, in a task only

accept = (wait: f64 = 0.0) -> int

a peer that connected to this program's server (listen's port, or an http server's websocket()), waiting up to wait seconds for one; -1 if none came. It is the caller's own, its joined event taken: its events come from receive([peer], ...), not receive() or receive_server(), so that a task can serve each one

gone = (peer: int) -> bool

the peer has gone (or never was), and its events have all been received, its .left last: a task looping not net.gone(p) sees every one

receive_server = () -> NetEvent[]

the same, for the peers that connected to this program's server (listen) only (netplay's packets on the peers a session plays over stay the session's)

wait = (seconds: f64) -> bool

wait until something comes for the program, or seconds pass: a message or a peer (receive), a connection's bytes or one to accept (the tcp_ functions), a fetch's answer (fetch_result), a request for its http server; true when something came (false: the time passed, or the program was asked to stop, as stopping() then says, or the task was cancelled). Meanwhile what waits to go out is sent as the connections take it. For a program with no window, which has nothing else to do: a game's frames come anyway

unsent = (peer: int) -> int

how many bytes sent to a peer still wait to go out to it (a peer that reads slowly, or has stopped: one with more than 8 MB waiting is let go, so that it does not hold the server's memory)

handshake = (peer: int) -> Handshake

how a peer asked to connect to this program's server (an empty Handshake for others)

Rooms: peers by name

join_room = (peer: int, room: str)

peer p is in room from now on (once, however often it joins)

leave_room = (peer: int, room: str)

peer p is not in room any more (a room with no one left is no more)

send_room = (room: str, msg: str, except: int = -1)

a message to everyone in room (but except, as the one who sent it)

send_room = (room: str, msg: u8[], except: int = -1)
members = (room: str) -> int[]

the peers in room, in the order they joined it

rooms = () -> str[]

the rooms with anyone in them; rooms(p): those peer p is in

rooms = (peer: int) -> str[]

UDP (native programs)

struct Datagram:
    host: str               # where it came from: an address, "1.2.3.4"
    port: int
    data: u8[]
udp = (port: int = 0) -> int

a UDP socket on port (0: one the system picks), or -1 (in use, or in a web page)

udp_send = (sock: int, host: str, port: int, data: u8[]) -> bool

false if host is not known or it could not be sent (a datagram may also be lost on the way)

udp_send = (sock: int, host: str, port: int, text: str) -> bool
udp_receive = (sock: int) -> Datagram[]

the datagrams that have arrived since the last call

udp_port = (sock: int) -> int

the port a UDP socket is on (as one made with udp(0), which the system picked), or -1

udp_close = (sock: int)

TCP: a stream of bytes to one other program

tcp_connect = (host: str, port: int, timeout: f64 = 5.0) -> int | NetError

a connection to host's port, waiting up to timeout seconds; NetError carries failure details. This deadline covers connecting only; tcp_receive/tcp_send have independent wait deadlines.

tls_connect = (host: str, port: int = 443, timeout: f64 = 10.0) -> int | NetError

a connection to host's port over TLS (443: https's); NetError carries connect, handshake or certificate failure details. timeout covers connecting plus the TLS handshake; send/receive wait deadlines are independent. Successful handles use tcp_send, tcp_receive and tcp_close.

trust_certificate = (pem: str) -> int

a certificate authority to trust from now on, besides those the system trusts: its certificate as PEM text (what a .pem or .crt file holds, -----BEGIN CERTIFICATE----- ...), for servers whose certificates it signed (a test server's, a private network's); how many certificates were taken. The SLOPPY_CA_FILE environment variable names such a file for any program

tcp_listen = (port: int, host: str = "", backlog: int = 511) -> int

a server on port: connections come from tcp_accept; -1 if the port cannot be had. host: the address it is reached at, "" every one this machine has ("127.0.0.1": from this machine only); backlog: how many connections may wait to be accepted. An exact address:port conflict fails everywhere. macOS permits ""/specific-address overlap (SO_REUSEADDR); Linux and Windows reject it. Linux/macOS use SO_REUSEADDR to rebind while old connections are in TIME_WAIT. Windows uses SO_EXCLUSIVEADDRUSE: TIME_WAIT can delay restart only if the server actively closed accepted connections. Closing the listener alone does not create TIME_WAIT.

tcp_port = (server: int) -> int

the port of a tcp_listen server (0 asks the system to choose), or -1 if closed/not a server

tcp_accept = (server: int, wait: f64 = 0.0) -> int

a connection made to the server (waiting up to wait seconds for one), or -1 if none came (or the server was closed meanwhile)

tcp_address = (c: int) -> str

the address a connection accepted by tcp_accept came from ("1.2.3.4"; "" for others)

tcp_send = (c: int, data: u8[], wait: f64 = 30.0) -> bool

all of data sent, waiting while the other side is slow to take it (up to wait seconds while it takes none); false if the connection has failed or closed, or nothing went for that long

tcp_send = (c: int, text: str, wait: f64 = 30.0) -> bool
tcp_write = (c: int, data: u8[]) -> bool

data sent without waiting: what the other side has not taken yet goes later, as it takes it (in this connection's later tcp_ calls, and in net.wait); false if the connection has failed or closed. A server's way to send: one slow reader holds up nothing else (tcp_unsent says how much waits for it)

tcp_write = (c: int, text: str) -> bool
tcp_unsent = (c: int) -> int

how many bytes sent with tcp_write still wait for the other side to take them

tcp_receive = (c: int, wait: f64 = 0.0) -> u8[]

the bytes that have arrived (waiting up to wait seconds for the first); empty when none has (or the connection has ended: tcp_closed says; or it was closed meanwhile, by another task)

tcp_closed = (c: int) -> bool

the other side has closed the connection (or it failed), and everything sent has been received

tcp_close = (c: int, wait: f64 = 5.0)

end a connection (or stop a server of tcp_listen's), after sending what tcp_write left waiting (for up to wait seconds). A task waiting in another tcp_ call on it is woken, and finds it closed

HTTP: what is at a web address

struct HttpReply:
    status: int             # the server's answer: 200 when all went well (404: no such page...);
                            # 0 when there was none (why says why; a redirect not followed, after
                            # five, is given as it came, with a why too)
    data: u8[]              # what it sent ...
    text = ""               # ... as text
    headers: {str: str} = {}    # its headers, their names in small letters (one sent more than
                                # once: its values joined by ", ")
    why = ""
    size = 0                # how many bytes it sent (saved to a file: data and text are empty)
    all_headers: (str, str)[] = []  # every header as it came, in order (each Set-Cookie)
header_values = (r: HttpReply, name: str) -> str[]

every value of a header the answer has (as each Set-Cookie), in order; name in any letters

struct CookieJar

a shared cookie jar for native fetches: make with cookie_jar(), then pass cookies = jar to fetch, fetch_start or fetch_all. Copies share the cookies (including answers still on their way); clear_cookies changes that shared jar without mut. CookieJar() means no jar. A web page's browser manages its own cookies instead

cookie_jar = () -> CookieJar

a new, empty cookie jar (independent of every other jar)

clear_cookies = (jar: CookieJar)

forget all cookies in a jar; the jar can be used again

fetch = (url: str, wait: f64 = 30.0, method: str = "GET", headers: {str: str} = {}, body: str = "", save_to: str = "", progress: (int, int) -> void = (got: int, all: int): pass, follow: bool = true, cookies: CookieJar = CookieJar()) -> HttpReply

a request to an http:// or https:// address, and its answer (following where it redirects, five times at most), waiting up to wait seconds in all; https is checked as a browser checks it (tls_connect). A GET unless method says otherwise; headers are sent besides the usual ones (as "Authorization": "Bearer ..."), and body after them (its Content-Type, unless given: JSON when it starts with { or [, else text). With save_to, a successful answer (2xx) goes to that file as it comes, not into data; progress(bytes so far, all of them or -1 when not said) is called as they come. follow = false: a redirect is the answer, its Location and Set-Cookie to look at (a test of a server's sign-in; native programs: a web page's browser follows them) cookies: an opt-in cookie_jar(), shared by requests and updated at every redirect. Matching host/domain, path, Secure and expiry decide what goes back; an explicit Cookie header wins. Without it no cookies are kept. Native programs only (a web page's browser keeps its own)

fetch_start = (url: str, wait: f64 = 30.0, method: str = "GET", headers: {str: str} = {}, body: str = "", save_to: str = "", progress: (int, int) -> void = (got: int, all: int): pass, follow: bool = true, cookies: CookieJar = CookieJar()) -> int

the same request, started: an id for fetch_result, which gives the answer once it has come. Nothing waits for it meanwhile (in a web page, the browser asks; its server must allow the page's site, CORS). save_to and CookieJar give status 0 in a page; the browser manages cookies itself. follow = false gives status 0 for a redirect, whose details browsers hide.

fetch_result = (f: int) -> HttpReply?

a fetch's answer (fetch_start's id), once it has come (status 0 when it failed: why says why); none while it is on its way. Given once: the fetch is done with after that, and asking again stops the program (a mistake: keep the answer when it comes)

fetch_cancel = (f: int)

stop a fetch on its way (its answer is not given)

fetch_all = (urls: str[], at_once: int = 8, retries: int = 2, wait: f64 = 30.0, method: str = "GET", headers: {str: str} = {}, body: str = "", done: (int, HttpReply) -> void = (i: int, r: HttpReply): pass, cookies: CookieJar = CookieJar()) -> HttpReply[]

many requests, at most at_once of them on their way at a time (Go's worker pool around http.Get, an errgroup with SetLimit): their answers, in the order of urls. One that fails (status 0: no answer, or none in wait seconds) or whose server is busy or broken (429, 500, 502, 503, 504) is asked again, retries more times at most, after half a second, then 1, 2, 4... (or after the Retry-After the server asks for, a minute at most), unless it is a POST or a PATCH (which may have been done: those are not asked again); the other options are fetch's, for each one. done(i, r) is called as each answer comes (r is that of urls[i]): for a program that shows how far it is, or goes on with each answer at once. A program that asks stopping() and is asked to stop (ctrl-c) gets the answers that came, the rest with status 0. In a page this waits in a task through JSPI; outside tasks use fetch_start/fetch_result. (A program with more to do as they come, a game's frames or a server's requests, uses fetch_start and fetch_result itself, as this does)

HTTP servers

A module (import http): a web site, an API or a game's page served from a native program: routes with :names, JSON, cookies (signed ones too), files, server-sent events, WebSockets on the same port (as net's peers), rate limits, and its own answers (404, 413...) as the program says. It waits with net.wait, so a slow client holds up no other; behind Caddy it serves https (writing a server). sloppy new my_site server starts one.

# example: HTTP servers
# a to-do list's API on http://localhost:8080 (curl localhost:8080/todos), until ctrl-c
import http

struct Todo:
    id = 0
    title = ""
    done = false

struct TodoIn:
    title = ""

todos: Todo[]

http.get("/todos", (r: http.Request) -> http.Response: http.json(todos))
http.get("/todos/:id", (r: http.Request) -> http.Response:
    id = to_int(r.params["id"]) ?? -1
    loop t in todos:
        if t.id == id: return http.json(t)
    http.json_error(404, "no todo {id}"))
http.post("/todos", (r: http.Request) -> http.Response:
    t = TodoIn()
    if let bad = http.read_json(r, t): return bad
    if len(trim(t.title)) == 0: return http.json_error(422, "a todo needs a title")
    todos.push(Todo(todos.len() + 1, trim(t.title)))
    http.json(todos.last(), 201))
http.files("/", "public")                   # the rest: the files in public/

http.log_requests = true
if not http.serve(8080): print("port 8080 is taken")

Run it in the playground

http.jo

HTTP servers: a web site, an API, a game's page with its WebSockets on the same port. import http, then routes (a method and a path, with :names for parts that vary), each answered by a function from a Request to a Response:

http.get("/", (r: http.Request) -> http.Response: http.html("<h1>Hello</h1>"))
http.get("/todos/:id", (r: http.Request) -> http.Response:
    if let t = todos.get(to_int(r.params["id"]) ?? -1): return http.json(t)
    http.status(404))
http.post("/todos", add_todo)
http.files("/", "public")                   # the files under public/ (index.html for /)
http.serve(8080)                            # answers until ctrl-c (or SIGTERM)

A program that does more than answer (a chat whose WebSockets come through net, a job that fetches meanwhile) answers what has come each time round its own loop:

http.listen(8080)
loop not stopping():
    http.answer()
    loop e in net.receive(): ...
    net.wait(1.0)                           # until something comes (a request, a message)

Each request's handler runs as a task of its own (lib/std/task.jo): one that waits (a net.fetch, sleep, a channel) lets the others be answered meanwhile; one connection's requests are answered in order. Tasks take turns on the program's one thread, so handlers change the program's variables (a map of todos, a count) with no locks: nothing else runs between two waits. One that computes for long or reads a big file holds up the others. run_program lets tasks continue on native Unix targets (cancellation ends its child), but holds them up on Windows. A client slow to send or to read holds up no other (what waits to go out to it goes as it takes it). A handler that panics is answered 500 and the server goes on (the panic and its backtrace are written to standard error; what the handler had changed stays changed). Behind a proxy that has the certificate (Caddy: docs/START.md's "Writing a server"), the same program serves https (trust_proxy: the clients' addresses; secure_cookies). Native programs only.

Asked to stop (ctrl-c, SIGTERM), serve takes no more requests, gives the handlers running up to drain seconds to answer, and returns: the program then ends what it runs besides (closing the channels its tasks read), and saves. A program with its own loop calls shutdown() itself.

Trying the routes from the same program (a test, Flask's test_client): handle() answers with no server; or, over a real connection (Go's httptest), serve in a task on a port the system picks, and fetch from it:

assert(http.handle("GET", "/todos/1").status == 200)
http.listen(0, host = "127.0.0.1")
spawn((): http.serve(http.port()), background = true)
assert(net.fetch("http://127.0.0.1:{http.port()}/todos/1").status == 200)
struct Request:
    method = ""             # "GET", "POST", ...
    path = ""               # "/todos/3": decoded (%20 a space), without the query
    query: {str: str}       # ?done=true&q=a%20b: {"done": "true", "q": "a b"} (a name given twice:
                            # the last; query_all(r, name) has each)
    params: {str: str}      # the route's :names: /todos/:id gives {"id": "3"}
    headers: {str: str}     # names in small letters (a header sent twice: its values joined by ", ")
    cookies: {str: str}     # (a name sent twice: the first, the one for the longer path)
    body: u8[]              # what was sent with it ...
    text = ""               # ... as text (read_json reads it into a struct)
    target = ""             # the path and query as sent: "/todos?done=true"
    version = "HTTP/1.1"
    address = ""            # where it came from: "1.2.3.4" (behind a proxy, the proxy's, unless
                            # trust_proxy names it: then the client's, from X-Forwarded-For)
    conn = 0                # its connection (a stream's: send_event and send_chunk go to it)
struct Response:
    status = 200
    headers: {str: str}     # (Content-Length, Date and Connection are added)
    body: u8[]
    cookies: str[]          # each a Set-Cookie header (set_cookie makes them)
    file = ""               # a file sent as the body, a piece at a time (file() sets it)
    stream = false          # the body is sent later, by send_chunk or send_event (stream(), events())
    upgrade = false         # (websocket(): the connection becomes a net peer ...)

Routes

route = (method: str, pattern: str, handler: (Request) -> Response)

a route for requests of that method ("*": any) to paths of the pattern

get = (pattern: str, handler: (Request) -> Response)
post = (pattern: str, handler: (Request) -> Response)
put = (pattern: str, handler: (Request) -> Response)
patch = (pattern: str, handler: (Request) -> Response)
delete = (pattern: str, handler: (Request) -> Response)
files = (prefix: str, dir: str)

the files under dir, at the paths under prefix ("/": the site's root): GET and HEAD, with each file's type, index.html for a directory (a directory asked for without its / is sent there), and what lets a browser keep a copy (ETag, Last-Modified: a file unchanged since is answered 304). Names starting with a dot (.git, .env) and paths with .. are not served

Answers

text = (s: str, status: int = 200, type: str = "text/plain; charset=utf-8") -> Response

text (as text/plain, unless type says otherwise)

html = (s: str, status: int = 200) -> Response

a web page's HTML

json = (value, status: int = 200) -> Response

any value as JSON (to_json's): a struct, an array, a map...; JSON text already made goes with text(s, type = "application/json"). A literal of values of several types is a Json: http.json({"ok": true, "id": id, "tags": tags}). A float that is infinite or NaN is null, as JavaScript's JSON.stringify writes it

json = (value: Json, status: int = 200) -> Response
binary = (b: u8[], status: int = 200, type: str = "application/octet-stream") -> Response

bytes, of a type ("image/png"...)

status = (code: int, message: str = "") -> Response

a status with its reason as the text ("404 Not Found"), or with the text given

json_error = (code: int, message: str) -> Response

an error for an API's client: {"error": message} as JSON

redirect = (to0: str, status: int = 302) -> Response

to another address (302: for now; 301: for good; 303: after a form's POST, a GET of it)

file = (r: Request, path: str) -> Response

a file, sent a piece at a time (a big one is never all in memory), with its type and what lets a browser keep a copy (as files() does); on_error's 404 when there is no such file

read_json[T] = (r: Request, into: mut T) -> Response?

the request's body, as JSON, read into into (a struct, an array...: what from_json reads): none when it went well, else the answer to give (400, saying what is wrong with it), and into is as it was. The fields the body has are set, the others keep the values they had (a struct in it too, field by field; an array or a map in it is replaced), so the same reads a new one and changes one, a PATCH. The request must say it sends JSON (Content-Type: application/json, or a type ending in +json, as net.fetch, a page's fetch() with that header and curl --json send it), else it is answered 415: what a page of another site can send with the browser's cookies and no CORS preflight (a form's post, text/plain) never reaches the handler.

set_cookie = (res: mut Response, name: str, value: str, max_age: int = -1, path: str = "/", http_only: bool = true, secure: bool = false, same_site: str = "Lax", domain: str = "")

a Set-Cookie on the answer: the client sends the cookie back with its requests from then on (r.cookies), for max_age seconds (-1: until the browser closes). The value is any text: what a cookie's value cannot have (spaces, ; , " \, line breaks, letters past ASCII) and % are percent-encoded (%3B for ;), and r.cookies has it decoded. http_only: not for the page's JavaScript; secure: over https only (secure_cookies: every cookie); same_site: "Lax" (sent with the site's own requests, and when a link from another site is followed), "Strict" (the site's own only) or "None" (any site's requests too: then Secure, as browsers require)

secure_cookies = false

every cookie Secure: sent by the browser over https only. For a site served over https (behind Caddy), where a cookie that went over http too could be read on the way:

clear_cookie = (res: mut Response, name: str, path: str = "/", domain: str = "")

a Set-Cookie that has the client forget a cookie (path and domain as it was set with)

set_signed_cookie = (res: mut Response, name: str, value: str, secret: str, max_age: int = 7 * 86400, path: str = "/", http_only: bool = true, secure: bool = false, same_site: str = "Lax", domain: str = "")

a cookie the client can read but not change or make up (a session's user, a cart): its value signed with secret (HMAC-SHA256 over its name, value and when it ends), signed_cookie reads it back. As set_cookie's (HttpOnly, SameSite=Lax), and good for max_age seconds, a week unless said (-1: until the browser closes, its signature good for as long). The value is in it to read (base64), not hidden: no password in it. secret: 16 bytes or more, kept out of the code (env("SESSION_SECRET"), or crypto.hex_text(crypto.random_bytes(32)) made once and saved); a new secret undoes every cookie signed with the old one (everyone signed out)

signed_cookie = (r: Request, name: str, secret: str) -> str?

the value of a cookie set_signed_cookie set; none when the request has none, or one whose signature is not secret's (changed, made up, another cookie's moved), or one past its max_age

struct Flash:
    message: str
    kind = "info"

a message for the next page (flash sets it, flashes reads it)

flash = (res: mut Response, message: str, secret: str, kind: str = "info") -> bool

add a one-time message to an answer, usually redirect(...). secret is set_signed_cookie's secret (16 bytes or more). Messages on this answer share a signed, HttpOnly cookie, good for five minutes; false if their JSON would exceed 2048 bytes (the answer is unchanged).

flashes = (r: Request, res: mut Response, secret: str) -> Flash[]

read the messages on this request, clearing their cookie on res (return that response to the client). [] for none, expired or forged messages. Read before adding new flashes to res.

query_all = (r: Request, name: str) -> str[]

every value a name has in the request's query, in order: ?tag=a&tag=b gives ["a", "b"] (r.query has the last); [] when it has none

Forms

form = (r: Request) -> {str: str}

the fields of the form the request's body is (as text; a file's field: uploads)

form_all = (r: Request, name: str) -> str[]

every value a field of the form has, in order (<input type="checkbox" name="tag"> checked twice: both); [] when it has none

struct Upload:
    name = ""
    filename = ""
    type = ""
    data: u8[]

a file a form sent (<input type="file" name="photo">): its field's name, the file's name on the client's machine (without its directories; the client's to write: not a path to save to as it is), its type as the client says, and its bytes

uploads = (r: Request) -> Upload[]

the files a form sent (<form method="post" enctype="multipart/form-data">), in order; [] for another body. They come whole with the request, so listen's largest bounds them (1 MB unless said: http.serve(8080, largest = 20 << 20) takes 20 MB)

Rate limits

allow = (key: str, per_minute: int, burst: int = 0) -> bool

allow(key, per_minute) says whether one more request of key (a client's address, a user's name, what they do: "login " + r.address) may go on: per_minute of them a minute, in a burst of up to burst (0: per_minute) at once. Each key's count fills back as time passes (a token bucket). Memory is bounded: past 100,000 keys, those nearest to full are forgotten (a key not seen starts full).

Streams: server-sent events and chunks

heartbeat = 15.0

seconds an events() stream may be sent nothing before a comment goes to it (0: none go)

most_streams = 1000

the most streams (stream(), events()) open at once; one more is answered 503 (on_error's). Each holds a connection open, and the connections a program may have are shared by all

most_streams_per_address = 16

the most open streams from one client address; one more is answered 429. As allow(r.address, ...), uses the client's forwarded address only when its proxy is in trust_proxy

stream_open = (conn: int) -> bool

whether a stream (the r.conn of a stream() or events() answer) is open: false once its client has gone, end_stream ended it, or the server stopped

stream = (type: str = "text/plain; charset=utf-8") -> Response

an answer whose body is sent later, a chunk at a time (send_chunk, then end_stream)

events = () -> Response

a stream of server-sent events, what a web page's EventSource reads (send_event)

send_chunk = (conn: int, b: u8[]) -> bool

a chunk of a stream's body; false when the client has gone (or has 8 MB waiting for it, a reader that stopped: then it is let go)

send_chunk = (conn: int, text: str) -> bool
send_event = (conn: int, data: str, event: str = "", id: str = "") -> bool

an event to an events() stream: its data (lines of text: each a data: line, whether it ends in \n, \r\n or \r), its name when not "message" (a page's EventSource: addEventListener(event, ...)), and its id (what the page's next connection says it had last: Last-Event-ID). A line break in event or id is left out (it would start a field of its own)

end_stream = (conn: int)

the end of a stream: its body is complete (the connection may carry other requests)

WebSockets

websocket = (r: Request, largest: int = 16 << 20) -> Response

the answer that makes the request's connection a WebSocket (a request that is not one's: 426). largest: the biggest message taken from it (a bigger one ends the connection, with code 1009)

Every request: before and after its route

before = (f: (mut Request) -> Response?)

a function each request is given before its route

before = (prefix: str, f: (mut Request) -> Response?)

a function the requests to the paths under prefix are given before their route

after = (f: (Request, Response) -> Response)

a function each request's answer goes through after its route (a WebSocket's too, as its 101)

after = (prefix: str, f: (Request, Response) -> Response)

a function the answers to the paths under prefix go through after their route

What the server answers itself

on_error: (Request, int, str) -> Response

The answers no handler made: 404 (no route has the path), 405 (routes have it for other methods: Allow says which), 500 (a handler panicked), and a request refused before it gets to a route (400 not HTTP's, 408 too slow to come, 413 its body too big, 431 its headers, 501 a Transfer-Encoding not taken, 503 too many streams). They are on_error's: given the request (as much of it as was read), the status and why ("" for 404, 405 and 500), and they go through after() as any answer. As text unless changed: an API answers JSON with

CORS: requests from web pages of other sites

cors = (origins: str[] = ["*"], methods: str = "GET, HEAD, POST, PUT, PATCH, DELETE", headers: str = "Content-Type, Authorization", credentials: bool = false, max_age: int = 600, prefix: str = "/")

A browser lets a page of another site (another origin: scheme, host and port) read this server's answers only when they say it may: cors(origins) says so for those sites ("": any site), and answers the browser's preflight (an OPTIONS request it sends first, for a PUT, a DELETE, or a request with JSON or an Authorization header) before any before() or route sees it. credentials: the page's cookies (and Authorization) go along (with the sites listed only: a browser sends none to ""); max_age: how many seconds a browser may keep a preflight's answer

Gzip

gzip = true

Answers of text (HTML, CSS, JavaScript, JSON, SVG...) and WebAssembly of 1 KB or more are sent gzip'd to the clients that take it (Accept-Encoding: gzip): a third or less of the bytes. A file's is made once, while the file is unchanged (up to 64 MB of them kept). false: none are (as behind a proxy that does it, Caddy's encode gzip)

Serving

serve = (port: int, host: str = "", largest: int = 1 << 20, backlog: int = 511, drain: f64 = 10.0) -> bool

answer requests on port until the program is asked to stop (ctrl-c, SIGTERM: stopping()), then give the handlers running up to drain seconds to answer (shutdown); false at once when the port cannot be had. host, largest, backlog: as listen's

shutdown = (wait: f64 = 10.0) -> bool

stop serving: no more requests are taken, the handlers running are waited for (up to wait seconds) and their answers sent, and the connections are closed (streams too, ended first as end_stream ends one, so a client sees them complete). true when every one was answered in time (a handler still running then goes on, but its answer goes nowhere)

listen = (port: int, host: str = "", largest: int = 1 << 20, backlog: int = 511) -> bool

start taking requests on port (answer() answers them); false when the port cannot be had (another program has it). host: the address it is reached at, "" every one this machine has ("127.0.0.1": from this machine only, as behind a proxy on it); largest: the biggest body taken (a bigger one is answered 413); backlog: how many connections may wait to be taken

stop_listening = ()

stop taking requests (those of connections open are still answered)

answer = () -> int

answer the requests that have come, and send what waits to go out; how many were answered. It does not wait: net.wait does (until there is something to answer)

log_line = (r: Request, res: Response, seconds: f64) -> str

the line a request makes in a log: when (the machine's time), who, what, the answer's status and size, how long it took

log_requests = false

write each request's log_line to standard error

trust_proxy: str[]

the addresses of the proxies in front of the server (Caddy on the same machine: ["127.0.0.1"]): a request from one of them has as r.address (log_line's, a WebSocket's handshake's) the client's, from X-Forwarded-For: the last address in it that is not a proxy listed (each proxy adds the one it was reached from at the end; what comes before is the client's to write). None unless set: a server reached with no proxy in front would take a client's word for where it is

http_date = (t: f64) -> str

a time (unix_time's seconds) as HTTP writes one: "Sun, 06 Nov 1994 08:49:37 GMT"

parse_http_date = (s: str) -> f64?

an HTTP date ("Sun, 06 Nov 1994 08:49:37 GMT") as unix_time's seconds; none when it is not one

reason = (code: int) -> str

a status's reason: 404 "Not Found"

mime_type = (path: str) -> str

the type of a file by its extension, as a Content-Type ("text/html; charset=utf-8" for .html); application/octet-stream for one not known

Trying the routes, without a server

handle = (r: Request) -> Response

the answer the server gives a request

handle = (method: str, target: str, body: str = "", headers: {str: str} = {}) -> Response

the answer the server gives a request of that method, target, body and headers

request = (method: str, target: str, body: str = "", headers: {str: str} = {}) -> Request

a request as the server reads one a client sent: method, target ("/todos?done=true"), body and headers (as written: "Content-Type"), from 127.0.0.1

port = (listener: int = 0) -> int

the port the server listens on: listen's, or the one the system chose for listen(0) (a test's server, on a port no other program has). listener selects a listen() call, starting at 0; -1 when that listener does not exist

SQLite databases

A module (import sqlite): a database in one file, through the system's SQLite (it comes with macOS and Windows; on Linux, libsqlite3). db.run(sql, [values]) changes, db.query[T](sql, [values]) reads rows into a struct by its fields' names, and ? in the SQL takes each value, so text that looks like SQL is only text. Not in web pages.

# example: SQLite databases
# a shop's orders kept in shop.db: one added each run, then all of them, newest first
import sqlite

struct Order:
    id = 0
    item = ""
    qty = 0
    paid = false

main = ():
    db = unwrap(sqlite.open("shop.db"))
    if let e = db.exec("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, item TEXT NOT NULL, qty INT, paid BOOL)"): panic(e.message)
    r = db.run("INSERT INTO orders (item, qty, paid) VALUES (?, ?, ?)", ["rope", 2, false])
    if r is sqlite.SqlError: panic(r.message)
    print("order {r.last_id} added")
    loop o in unwrap(db.query[Order]("SELECT * FROM orders ORDER BY id DESC LIMIT ?", [10])): print(o)
    print("{db.value("SELECT sum(qty) FROM orders").as_int() ?? 0} items ordered in all")

Run it in the playground

sqlite.jo

SQLite databases, through the system's SQLite (libsqlite3 on Linux, macOS's own, winsqlite3 on Windows): for a program's data that outgrows a JSON file, one file however much is in it, read and changed a row at a time. import sqlite, then:

db = unwrap(sqlite.open("shop.db"))            # (a SqlError when it cannot be: `?`, `is`, unwrap)
if let e = db.exec("CREATE TABLE IF NOT EXISTS bookings (id INTEGER PRIMARY KEY, name TEXT, spots INT, paid BOOL)"): panic(e.message)
r = unwrap(db.run("INSERT INTO bookings (name, spots, paid) VALUES (?, ?, ?)", [name, 3, false]))
print(r.last_id)
struct Booking:
    id = 0
    name = ""
    spots = 0
    paid = false
bs = unwrap(db.query[Booking]("SELECT * FROM bookings WHERE spots > ?", [0]))
n = db.value("SELECT count(*) FROM bookings").as_int() ?? 0

The values for the ?s are a list of any types ([name, 3, 2.5, none, true], bytes for a BLOB). Never put them in the SQL's text, where a name such as x'); DROP TABLE bookings; -- would be SQL: as a value it is only text. A row's columns go into the fields of the same names (a field with no column keeps its default, a column with no field is left out; a BOOL column is a bool, a BLOB a u8[]; count(*) AS total names a column for a field); query_json gives the rows as Json objects. Dates go in as text, date_text(d), and come out with parse_date. run and query take one statement each; exec, a script of several. Changes that belong together go between db.begin() and db.commit() (or db.rollback()), or in db.transaction(f), as one: all of them or none, even if the program is stopped halfway, and much faster (1000 inserts: a few ms in one, each one by itself waits for the disk). One Db is shared by a server's handlers: a transaction is the task's that began it (the others' statements wait for it to end), and one whose handler panics is rolled back. The file is opened in WAL mode (readers do not wait for a writer) and waits up to 5 s for another program's lock. Not in web pages.

error struct SqlError:
    message: str
    code = 0                        # SQLite's (19: a constraint, as UNIQUE or NOT NULL, 5: busy)
struct Db:
    path = ""
struct Changed:
    rows = 0                        # how many rows were inserted, changed or deleted
    last_id = 0                     # the id (rowid) of the latest row inserted

what run changed

open = (path: str) -> Db | SqlError

the database in the file at path, made when there is none (":memory:": one in memory only, gone at the end)

close = (db: mut Db)

done with it (what it holds is written already)

exec = (db: Db, script: str) -> SqlError?

SQL statements, as many as there are, with no values for ?s: a schema, a migration (none: done; a SqlError: the first that failed, and those after it not done)

run = (db: Db, sql: str, args: Json = []) -> Changed | SqlError

one statement that changes something: INSERT, UPDATE, DELETE, CREATE..., with the values for its ?s

query[T] = (db: Db, sql: str, args: Json = []) -> T[] | SqlError

the rows a query gives, each a T: its columns in the fields of the same names

query_one[T] = (db: Db, sql: str, args: Json = []) -> T? | SqlError

the first row a query gives, as a T (none: it gives none)

query_json = (db: Db, sql: str, args: Json = []) -> Json | SqlError

the rows a query gives, each a Json object of its columns, in a Json list

value = (db: Db, sql: str, args: Json = []) -> Json

the first column of the first row a query gives (Json's null when there is none, or on an error, which is said on stderr): db.value("SELECT count(*) FROM t").as_int() ?? 0

begin = (db: Db) -> SqlError?

a transaction: the changes from here to commit are made all together, or none of them (rollback, or the program stopped before commit) or the program stopped before commit). It is the task's that began it: another task's statements on the same Db wait for it to end, and a panic in it (a server's handler) rolls it back

commit = (db: Db) -> SqlError?
rollback = (db: Db) -> SqlError?
transaction = (db: Db, f: () -> SqlError?) -> SqlError?

the changes f makes, as one transaction: committed when it gives none, rolled back when it gives a SqlError (which is given back) or panics

Invite a friend

A module (import invite): the screens that connect two players with invite codes and no server: a link to send in a chat (it opens the game in a browser), a code sent back, copying, sharing and pasting (on phones too), and why when no connection was made. A game's menu calls invite.start() or invite.join(), and draw shows invite.screen() until it gives the other player. See examples/duel.

# example: invite
# (two players, anywhere: Invite a friend gives a link to send; once connected, each moves a dot
# with the arrows and sees the other's)
import net
import invite

friend = -1
mine = vec2(640, 360)
theirs = vec2(640, 360)
invite.from_link()

update = (dt: f64):
    global friend, theirs
    if friend < 0: return
    mine += input_axis() * f32(300.0 * dt)
    net.send(friend, "{mine.x} {mine.y}")
    loop e in net.receive():
        if e.kind == .message:
            w = split(e.text, " ")
            theirs = vec2(f32(to_float(w[0]) ?? 0.0), f32(to_float(w[1]) ?? 0.0))
        else if e.kind == .left: friend = -1

draw = ():
    global friend
    clear()
    if friend >= 0:
        circle(mine, 20, rgb(0.4, 0.8, 1.0))
        circle(theirs, 20, rgb(1.0, 0.6, 0.3))
        return
    if invite.active():
        if let c = invite.screen("the example"): friend = c.peer
        return
    ui_begin("menu", vec2(640, 300))
    if ui_button("Invite a friend"): invite.start(reliable = false)
    if ui_button("Join a friend"): invite.join()
    ui_end()

Run it in the playground

invite.jo

struct Invited:
    peer: int                   # (a net peer: net.send, net.receive; -1: this side hosts the room Play with anybody found, with no one yet)
    inviter: bool               # this side invited (and the other joined)

the other player, once connected

start = (reliable: bool = true, players: int = 2)

show Invite a friend: an invite is made at once (reliable = false: lost messages are not sent again, nor do they hold up later ones; for fast games and rollback). With a matchmaking server, this computer's room opens instead, for players in all (this side too: 0 for any number, until close_room); the screen has Invite with a code instead

start_codes = (reliable: bool = true)

show Invite a friend with codes (a link to send, a code sent back), with a matchmaking server too: for a game's own Invite with a code instead

anybody = (reliable: bool = true)

Play with anybody (with a matchmaking server): the server finds a public room of this game that has room, or makes this side the host of a new one, which others who ask then join. The screen says how it goes; it gives the host Invited(-1, true) at once (the others then come by arrivals, as to a room), and the others the host (Invited(peer, false)). room_busy(true) sends those who come to another room

join = (code: str = "")

show Join a friend, with their link or code if given (joined at once): an invite's, or a room's (with a matchmaking server: the short code, or a link with ?room= in it)

from_link = () -> bool

the program was opened from an invite link (a web page's ?invite=... or ?room=..., or INVITE=code or ROOM=code): Join a friend with it, and true

active = () -> bool

one of the screens is up

code = () -> str

this side's code: the invite, or the reply to one ("" until it is made, a moment after start or join): for a game that shows it in its own way

reply = (code: str) -> bool

the friend's reply to this side's invite, as Connect takes it from the box: false if it is not one

cancel = ()

leave the screens (Back does it too), dropping the invite if it has not connected (and the room, if no friend has come through it)

screen = (game: str = "the game", web_page: str = "") -> Invited?

draw the screen that is up (in draw), and follow the connection: none until the other player is connected, then them (the screens are gone then). game names the game in what it says; web_page is where it is on the web, for a computer's invite to link to

Rooms, through a matchmaking server (tools/rendezvous.jo)

server = (url: str)

the matchmaking server for rooms (tools/rendezvous.jo: docs/MATCHMAKING.md runs one), as wss://match.example.com (web pages and native programs both reach it there; a page served over https may only reach wss://). "" for none. SLOPPY_SERVER (a web page's ?server=) sets it for any game, over the game's own ("none": no server): for trying a server of one's own

has_server = () -> bool

there is a matchmaking server (rooms: start opens one, join takes a room's code)

room_code = () -> str

this computer's room code while its room is open ("" when it is not): to show in a game's lobby

room_link = (web_page: str = "") -> str

a link to the open room: this page's address (or web_page) with ?room= ("" with neither, or no room)

open_room = (reliable: bool = true, players: int = 0)

open this computer's room, as start does, but with no screen: for a game that shows its code (room_code, room_link) and how it is going (room_status) in a lobby of its own. Friends come by arrivals(). Nothing without a matchmaking server (has_server); room_status says why when it cannot open

room_public = () -> bool

the open room is a public one, which Play with anybody (anybody) found or made

room_status = () -> str

what the room is doing, in words ("" when it is not open; why not, when open_room could not open it)

arrivals = () -> Invited[]

friends who have connected through the open room since the last call (the first, while the screen is up, comes from screen): each a peer, as screen's. Call it every frame while hosting

room_busy = (on: bool)

while on, friends who come to the room wait (told so) until it is off (to a public room: they are sent to another): for a game whose fight has started (call it every frame, with whether that is so)

close_room = ()

close the room: friends can no longer join with its code (until start opens it again)

new_room_code = ()

a new code for this computer's room (the old one, and links with it, no longer lead here)

Netplay

A module (import netplay): players on different machines in one game. With rollback (session), only inputs travel, and a late one is made up for by playing the last ticks again; with a server (server, client), the server runs the game and clients predict their own moves and draw others a little in the past. Sloppy's math is its own (no system math library, no fused multiply-add), so a tick comes out the same on Linux, Windows, macOS and the web. See examples/duel and examples/arena, and playing over a network for choosing between them.

# example: netplay
# (two machines in one program, over a simulated network with 150 ms latency: the top half is what
# player 1's machine shows, the bottom half player 2's; steer player 1 with the arrows)
import netplay

struct Pad:
    x = 0
struct Game:
    xs: f32[] = [400, 800]

tick = (g: Game, pads: Pad[]) -> Game:
    let g = g
    loop i in 0..2: g.xs[i] = clamp(g.xs[i] + 6 * pads[i].x, 20, 1260)
    g

a = netplay.session(Game(), tick, players = 2, me = 0)
b = netplay.session(Game(), tick, players = 2, me = 1)
link = netplay.Link(latency = 0.15)
now = 0.0

update = (dt: f64):
    now += 1.0 / 60.0
    a.play(Pad(int(round(input_axis().x))))
    b.play(Pad(int(sign(sin(now * 1.3)))))                 # (player 2 plays by itself)
    loop o in a.outgoing(): link.send(o.0, o.1, now)
    loop o in b.outgoing(): link.send(o.0, o.1, now)
    loop d in link.deliver(now):
        if d.0 == 0: a.receive(d.1)
        else: b.receive(d.1)

draw = ():
    clear(rgb(0.08, 0.09, 0.12))
    loop half in 0.. and g in [a.state, b.state]:
        y = 180 + 360 * half
        circle(vec2(g.xs[0], y), 24, rgb(0.35, 0.7, 1.0))
        circle(vec2(g.xs[1], y), 24, rgb(1.0, 0.6, 0.3))
    line(vec2(0, 360), vec2(1280, 360), 2, gray(0.3))
    text("rollbacks: {a.rollbacks} and {b.rollbacks}", vec2(20, 20), 22, gray(0.6))

Run it in the playground

netplay.jo

struct Session[S, I]:
    step: (S, I[]) -> S
    players: int
    me: int
    version = PROGRAM_BUILD_ID      # set before play: a shared release name for separate entry points
    delay = 2
    max_ahead = 10                  # (no more than __NP_HIST / 2)
    tick = 0                        # the tick state is at
    state: S
    waiting = false                 # play could not move on (too far ahead of someone's inputs)
    rollbacks = 0                   # how many times a tick was played again, so far
    longest_rollback = 0
    desync = -1                     # the first tick at which two machines' games differed (-1: none)
    problem = ""                    # what is wrong, said once on stderr too: packets that cannot be
                                    # read (another build?), two players with one number, a
                                    # player not heard from for 5 s, the games differing
    rejoin_token = ""               # this player's token from the host, to come back with after a restart (save it)
    rejoin_grace = 0.0              # (the host) seconds a player it plays for may come back in, once last heard from
    rejoin_limit = 4 << 20          # the most a returning player is sent: the game, compressed, in bytes
    rejoining = false               # this machine is coming back into a game: asking, then catching up
    rejoined: int[]                 # (the host) players who came back, in the latest play
    admit_expired: int[]            # (the host) peers closed without a valid rejoin request, in the latest play
session[S, I] = (start: S, step: (S, I[]) -> S, players: int, me: int, delay: int = 2) -> Session[S, I]

a session of players players, this machine's being player me (from 0)

confirmed[S, I] = (s: Session[S, I]) -> int

ticks below this have every player's input: they will not change again (some may not have been played here yet: those from s.tick on)

inputs_at[S, I] = (s: Session[S, I], t: int) -> I[]

everyone's inputs at tick t, one of those confirmed (below s.confirmed(), and not more than 100 ticks before it): a replay keeps them as they come, to play the game again from its start (tick of the start, each one in turn), or a spectator is sent them

heard[S, I] = (s: Session[S, I], p: int) -> bool

Whether player p has been heard from at least once (directly or through the host). Use s.heard(p) and s.silent(p) > seconds before standing in for a silent player: a page still loading has not spoken yet. This machine's own player is always heard.

silent[S, I] = (s: Session[S, I], p: int) -> f64

player p has not been heard from for this many seconds (from session start before its first packet; check s.heard(p) first when a loading player should keep its place)

stats_line[S, I] = (s: mut Session[S, I]) -> str

one line on how play has gone since the last call, for a log (the game writes it where it likes, once a second, say): ticks played, frames spent waiting for someone's inputs, rollbacks and the longest, and for each other player the round trip, how long since heard from, and over net's peers how they are reached and what waits to go to them

ping_ms[S, I] = (s: Session[S, I], p: int) -> f64

the round trip to player p and back, in milliseconds (smoothed; 0 before it is known)

play[S, I] = (s: mut Session[S, I], input: I)

this frame's input from this machine's player; the game moves on a tick (unless waiting)

outgoing[S, I] = (s: mut Session[S, I]) -> (int, u8[])[]

what to send to whom since the last call: (player, bytes) (without s.udp)

receive[S, I] = (s: mut Session[S, I], data: u8[])

bytes that arrived from another player (the packet says which)

stand_in[S, I] = (s: mut Session[S, I], p: int, input: I)

this machine plays for player p from now on, with this input every tick (a game's "the computer flies it": the game's tick makes it so): for one who has left. Their inputs that reached this machine are kept, and the rest are this, so the others must have had none of theirs that this one did not: over net's peers, the host, who passes on all of them, can (or either of two players).

stands_in[S, I] = (s: Session[S, I], p: int) -> bool

this machine plays for player p (s.stand_in)

lag_ms[S, I] = (s: mut Session[S, I], ms: f64, jitter_ms: f64 = 0, loss: f64 = 0)

simulate a slow network on what this session sends: ms more latency, up to jitter_ms more at random, and a share of packets lost (0 to 1)

Over net's peers (invite codes: web pages and native programs)

over[S, I] = (s: mut Session[S, I], peers: int[])

play with the other players over peers from net: peers[p] is player p's (this machine's own entry is not used), from net.invite or net.join_invite (with no server: a page and a native program alike), or net.connect. The session's packets on them are its own (marked: the game's net.receive() leaves them); the game's own messages (a chat, "again?") and their joining and leaving are the game's, through net.send and net.receive as ever. For two, invited with net.invite(reliable = false) (packets lost are not resent: newer ones carry the same inputs, and nothing waits for an old one): Player 0: friend = net.invite(reliable = false), then s.over([-1, friend]). Player 1: host = net.join_invite(code), then s.over([host, -1]). For more players, one hosts: it invites each of the others (each an invite and a reply), tells each its number (a message of the game's), and plays over all of them; the others play over the host alone (the rest -1), who batches the inputs each still lacks: [-1, a, b] for the host, [host, -1, -1] for player 1.

Over UDP (native programs)

udp[S, I] = (s: mut Session[S, I], port: int, addrs: (str, int)[]) -> void | net.NetError

play over UDP: this machine listens on port, and each player p is at addrs[p] (this one's own entry is not used)

port[S, I] = (s: Session[S, I]) -> int

this session's UDP port, including one chosen by udp(0); -1 when it has no UDP socket

Through a relay (web pages too)

join_relay[S, I] = (s: mut Session[S, I], host: str, port: int, room: str, stun: str = "stun:stun.l.google.com:19302")

play through the relay at host and port (or a ws:// or wss:// URL), with the players who name the same room

direct[S, I] = (s: Session[S, I], p: int) -> bool

player p's packets come and go straight (WebRTC between web pages), not through the relay

Rejoining: a player whose program restarts comes back

allow_rejoin[S, I] = (s: mut Session[S, I], token: str = "", grace: f64 = 30.0)

This session takes part in rejoining: every player's, before play. token: the one this player was given before its program restarted (s.rejoin_token, saved by the game), to come back into the game with; "" for a player new to it. grace: on the host, how many seconds a player who has gone quiet may come back in. The host gives each player a token (s.rejoin_token, once it comes: save it), and plays for a returning player until it has caught up (s.rejoining while it does).

admit[S, I] = (s: mut Session[S, I], peer: int, timeout: f64 = 10.0)

On the host, over net's peers (s.over): a new connection that may be a returning player's. Its rejoin request is read, and with the token that player was given, the session plays over it as that player from then on (in their place in the peers given to s.over). After timeout seconds without a valid request it is closed, and listed in s.admit_expired for that play. Call after allow_rejoin; admitting the same peer again does not extend its deadline. 0 expires next play.

Spectators

feed[S, I] = (s: Session[S, I], from: int) -> u8[]

the inputs confirmed from tick from on (what confirmed() gave when the last was sent), for a spectator's Watch; with -1 (a spectator new to the game), or a tick no longer kept, the game as it is at a confirmed tick comes first, then the inputs from there

struct Watch[S, I]:
    step: (S, I[]) -> S
    state: S
    tick = 0                        # the tick state is at
    behind = 6                      # ticks kept in hand (about 0.1 s), so a late packet does not stop play
    ticks_per_second = 60.0
    waiting = true                  # no inputs for the next tick yet: the game holds still
    problem = ""                    # what is wrong with the feed, said once on stderr too

a spectator's game, played from a feed

watch[S, I] = (start: S, step: (S, I[]) -> S) -> Watch[S, I]
ahead[S, I] = (w: Watch[S, I]) -> int

ticks the spectator has inputs for and has not played yet

receive[S, I] = (w: mut Watch[S, I], data: u8[])

a feed's bytes, as they arrive

update[S, I] = (w: mut Watch[S, I], dt: f64)

plays the ticks due in dt seconds, each with its inputs; it holds still (w.waiting) when they have not come, until behind have, then plays on (a tick more each frame while far behind)

relay = (port: int) -> void | net.NetError

a relay on port: call it every frame (in a game that hosts others), or relay_forever

relay_forever = (port: int) -> void | net.NetError

a program that is only a relay

A simulated network, for trying netplay in one program

clock = (now: f64)

netplay's own timing in one program (sending again what was lost, how long a player has been quiet, a returning player's grace; sessions', clients' and servers') on the caller's clock too, when it is given here each frame: the now given to a Link, so a test runs the same every time, as fast as it can, with no sleep. A negative one: elapsed() again (the default).

struct Link:
    latency = 0.05
    jitter = 0.0
    loss = 0.0
    seed: u64 = 1

packets between numbered ends, each arriving after latency (plus up to jitter at random), some lost; time is the caller's (seconds), so a test runs the same every time

send = (l: mut Link, to: int, data: u8[], now: f64)
deliver = (l: mut Link, now: f64) -> (int, u8[])[]

what has arrived by now: (to, data), in the order it arrives

Client and server

struct Server[W, I]:
    world: W
    apply: (W, int, I, W) -> W
    step: (W) -> W
    tick = 0
    version = PROGRAM_BUILD_ID      # set before joining: a shared release name for separate entry points
    rejoin_grace = 0.0              # seconds to keep a dropped player (0: leave immediately)
    dropped: int[]                  # connections lost; player and world retained during the grace period
    rejoined: int[]                 # retained players who returned in the last update
    errors: (int, str)[]            # rejected connections: transport peer and reason, in the last update
    send_every = 2                  # (30 worlds a second)
    ticks_per_second = 60.0         # how often update is called (run sets it): its clients learn it
    joined: int[]                   # the players who came, and went, in the last update
    left: int[]
    messages: (int, str)[]          # the game's own messages that came in the last update, and who sent each (say)
    compress = true                 # the worlds deflated (false: as text, cheaper to make, bigger)
    problem = ""                    # why listening could not start; cleared on a successful retry
server[W, I] = (world: W, apply: (W, int, I, W) -> W, step: (W) -> W) -> Server[W, I]
per_player[W, I] = (s: mut Server[W, I], view: (W, int) -> W)

what each player is sent: view(world, player) for the whole world, as what that player can see (the others near them, their side's), so that a big world goes out to each a part of it. The client's state and view are then that part

encoding[W, I] = (s: mut Server[W, I], encode: (W, int, W?) -> u8[])

The worlds in the game's own bytes, made against what each client already has: encode(world, player, base) gives the bytes for player, where base is the world that player's client last got (none at first, or when it is too far behind), and the client's decode(bytes, base) makes the world again from them and the same base. Only what changed since base need go: a delta, as small as the game can make it (varints, the soldiers that moved). With per_player, world is what view gave for the player. The bytes go as they are (not deflated). The client says c.decoding(decode).

join[W, I] = (s: mut Server[W, I], player: int)

A transport peer connected, or disconnected. join starts the build/token handshake; joined reports a new player only after acceptance. leave retains an accepted player for rejoin_grace seconds (dropped), then left reports its final departure. The parameter named player is a transport peer ID (as before). Feed outgoing's transport peer IDs back through receive/leave; after a rejoin they can differ from the game's player numbers.

leave[W, I] = (s: mut Server[W, I], player: int, rejoin: bool = true)

rejoin=false makes a departure final immediately and revokes its token (a kick or logout).

peer[W, I] = (s: Server[W, I], p: int) -> int?

The connection currently serving player p, or none while dropped. Use this with net.close and other transport APIs, whose IDs can change on a rejoin; say takes the stable player.

receive[W, I] = (s: mut Server[W, I], player: int, data: u8[])

bytes from a transport peer (not necessarily the player's stable number after a rejoin)

say[W, I] = (s: mut Server[W, I], player: int, text: str)

The game's own messages beside the worlds, on the same connection: a chat line, "round over", a score; text, in order, never lost (as the worlds are not either). The server says to one player or to all, and gets the clients' in srv.messages (who, text) after each update; a client says to the server, and gets the server's in c.messages after each play.

say_all[W, I] = (s: mut Server[W, I], text: str)
hello[W, I] = (s: Server[W, I], p: int) -> str

what player p's client gave connect as hello (its name or other game metadata), available when joined reports the player; the rejoin token is separate

waiting[W, I] = (s: Server[W, I], p: int) -> int

how many of player p's inputs are waiting to be applied (1 or 2 normally; more: they come faster than the server ticks, which shows as lag)

lag_ms[W, I] = (s: mut Server[W, I], ms: f64, jitter_ms: f64 = 0)

simulate a slow network on what the server sends: ms more latency, up to jitter_ms more at random (kept in order, as over TCP); the client's lag does the same both ways

run[W, I] = (s: mut Server[W, I], ticks_per_second: f64 = 60.0)

run the server: update 60 times a second, on time (each tick's start set from the first, so a slow sleep does not make it fall behind), until the program ends

outgoing[W, I] = (s: mut Server[W, I]) -> (int, u8[])[]

what to send to whom since the last call (without listen; with it, to the players below 0)

listen[W, I] = (s: mut Server[W, I], port: int) -> void | net.NetError

serve over WebSockets on port: native and web clients connect (players are net's peers)

update[W, I] = (s: mut Server[W, I])

one tick: each player's next input applied, the rest of the tick, and the world sent out

world_at[W, I] = (s: Server[W, I], tick: int) -> W

the world as it was at an earlier tick (the latest kept, if that one is gone)

struct Client[W, I]:
    apply: (W, int, I, W) -> W
    state: W                        # the latest world from the server, with this player's newer inputs applied
    server: W                       # the latest world from the server, as it sent it
    me = -1                         # this player's number (once the server has said: connected())
    version = PROGRAM_BUILD_ID      # set before connecting; defaults to this program's source identity
    rejoin_token = ""               # save per server/room, restore before connect after a program restart
    server_tick = -1                # the tick of server
    interpolation = 0.1             # how far in the past others are drawn (view), in seconds: two
                                    # worlds' time apart or more (send_every ticks), more on a network
                                    # that is uneven
    ticks_per_second = 60.0         # the server's (from its worlds): play once a tick at this rate
    ping_ms = 0.0                   # milliseconds from an input sent to the world that answers it (smoothed)
    messages: str[]                 # the server's own messages that came in the last play (say)
    problem = ""                    # what is wrong, said once on stderr too: could not connect, the
                                    # server gone or not heard from for 5 s, worlds that cannot be read
    reconnect = false               # true: a connection lost, or not made, is made again by itself
                                    # (after 1, 2, 4... up to 30 seconds), not one the server closed
                                    # on purpose (net.close: problem says its reason)
client[W, I] = (start: W, apply: (W, int, I, W) -> W) -> Client[W, I]
decoding[W, I] = (c: mut Client[W, I], decode: (u8[], W?) -> W)

the worlds from a server with encoding: decode(bytes, base) makes the world from the server's encode bytes and the world base this client already had (none when it had none)

connect[W, I] = (c: mut Client[W, I], host: str, port: int, hello: str = "")

connect to the server; hello is game metadata, available as srv.hello(player) at joined. A saved rejoin_token is offered during the build handshake: within the server's rejoin_grace, the player keeps their number and world entry. Clear rejoin_token to join as a new player. With c.reconnect=true a lost connection is retried automatically.

disconnect[W, I] = (c: mut Client[W, I])

close the connection (connect again later, to the same server or another)

lag_ms[W, I] = (c: mut Client[W, I], ms: f64, jitter_ms: f64 = 0)

simulate a slow network on what the client sends and gets: ms more latency each way, up to jitter_ms more at random (kept in order, as over TCP)

connected[W, I] = (c: Client[W, I]) -> bool

connected, and the server has sent a world (and is still heard from)

say[W, I] = (c: mut Client[W, I], text: str)

a message of the game's own to the server (srv.messages), held until the build is accepted

play[W, I] = (c: mut Client[W, I], input: I)

this tick's input: applied here at once (prediction) and sent

receive[W, I] = (c: mut Client[W, I], data: u8[])

bytes from the server

outgoing[W, I] = (c: mut Client[W, I]) -> u8[][]

what to send since the last call (without connect)

view_tick[W, I] = (c: Client[W, I]) -> f64

the server's tick being drawn for the others: interpolation seconds in the past (fractional, going on by the time between plays too, so a view drawn each frame moves each frame)

view[W, I] = (c: Client[W, I]) -> (W, W, f32)

the two worlds around view_tick and how far between them (0 to 1): draw the others at mix(a's, b's, f)