Programming Macaw OS

Programming Macaw OS

Every program in Macaw OS is a Lua file, from the Calculator to the level editor to the games. You can open any of them in Code to see how it works. Your own programs run the same way. Each gets a window on the desktop and uses the same drawing, sound and 3D calls.

This guide shows you how to write your own. If you've never written a program before, start at the top. If you already know Lua, skip to the page for what you want to make.

Start here

  • Your first program shows you how to make a window, draw in it and move something with the keys. It also explains how a program runs and what to do when it goes wrong.
  • Make a game builds a small game called Seed Catcher, one step at a time.

What you can make

PageWhat's in it
DrawingShapes, text, colours, pictures, drawing into pictures, the screen's size and colours
Input and soundThe keyboard and mouse, sound effects, notes, and songs from the Music app
Game cartsA game in a folder with its sprites, map, sounds and music, and the editors for each
3DTextured meshes, a camera and lights, and scenes of objects that move, collide and can be clicked
The graphics chipOpenGL-style 3D with matrices, draw calls, lighting and reflecting water
LevelsLevels built in Brushwork that you walk round in your own program
AppsButtons, text boxes and lists, menus, dialogs, drag and drop
Files and the systemThe disk, what Lua can do here, busy programs, saved passwords, System Extensions
MemoryYour program's own memory, with addresses, peek and poke, malloc and free, and the window's picture
CWriting programs in C, with pointers, structs, the C library and Macaw OS's calls
C referenceEvery one of Macaw OS's C calls, what it does and what each parameter is for
NetworkingTalking to other people's computers on the Macaw network

Where to look

  • The programs that come with Macaw OS are in /system/apps. The games are in /games. Each game is a cart folder, so right-click it in Files and choose Show Contents to look inside.
  • Examples are in /home/examples. There's Seed Catcher (the game the tutorial builds), Worm (a game written in C), a greeter, a to-do list, a program that shows every UI widget, and a System Extension.
  • The Read Me on the desktop is the short version of this guide. It lists every call.
  • In Terminal, new mygame.lua starts a program, newcart mygame starts a cart and newapp myapp.lua starts an app with buttons.

The machine

Screen640x360 to start with, or 640x480, 800x600 or 1024x768. It shows 256 colours, 8 colours or thousands
Sound4 effect voices, plus the S16 music chip with 16 voices of synth or recorded instruments
InputKeyboard and mouse
LanguageLua 5.4, and C89 (see C)
Disk/system and /games come with Macaw OS and can't be changed. /home is yours

Macaw OS runs the same programs on Windows, on PowerPC Macs (Mac OS X and Mac OS 9), on the Raspberry Pi and in a web browser. A program can't reach the computer underneath. It only sees the Macaw disk and the Macaw network (and shares the clipboard).

Your first program

Make one

Open Terminal (it's on the desktop, or in the macaw menu) and type:

new first.lua

This makes /home/first.lua from a template and opens it in Code. Press Ctrl+R (Cmd+R on a Mac) to run it. You get a window with an orange ball that you move with the arrow keys. Change something and press Ctrl+R again, and the window starts over with your change. Ctrl+S saves the file.

Terminal can start other kinds of program too. newcart mygame makes a game cart, newapp myapp.lua makes an app with buttons, and new3d my3d.lua makes a program with a 3D scene in it.

What a program looks like

WINDOW = { w = 240, h = 160, title = "Hello" }

local x = 120

function _init()
  -- once, when the program starts
end

function _update()
  -- 60 times a second: read the keys, move things
  if btn("left") then x = x - 1 end
  if btn("right") then x = x + 1 end
end

function _draw()
  -- draw the window
  cls(colors.navy)
  text("Hello, Macaw!", 8, 8, colors.yellow)
  circfill(x, 80, 8, colors.orange)
end

When the program starts, the file runs once from top to bottom. Anything at the top level, like local x = 120, is set up before _init is called. After that, Macaw OS calls these functions:

FunctionWhen it's called
_init()Once, after the file has run and the window is open
_update()60 times a second, while the program runs
_draw()When the window needs drawing (see below)
_resize(w, h)When someone resizes the window. Its new size is w x h
_close()When the window is closing. Save anything you need to here
_drop(paths, x, y)When files are dragged onto your window, at x, y
_display(w, h, colours)When the screen changes size or number of colours

You only need the ones you use. A program with just _draw works fine.

The window

WINDOW describes the window you want. Every field is optional:

FieldWhat it does
w, hThe size of the inside of the window, in pixels
titleThe words in the title bar (settitle(s) changes them later)
scaleShows every pixel 2, 3 or 4 times as big, if it fits on the screen
realtimetrue draws every frame, which games need (see below)
resizablefalse stops people resizing the window
minw, minhThe smallest size the window can be resized to
fullscreentrue asks to start the window full screen
colors8, 256 or "thousands" asks for the screen in that many colours while your program runs
cursorfalse hides the pointer over the window, for when you draw your own

The top-left pixel of the window is 0, 0. x goes right and y goes down. If someone resizes the window, WINDOW.w and WINDOW.h change to match and _resize is called.

When _draw runs

Most programs only change when someone does something, so Macaw OS doesn't redraw every window every frame. _draw runs while someone is using your window, after they choose a menu item, answer a dialog or drop something on it, and every so often anyway.

  • If _update changes what the window shows (a timer ticked, or a download finished), call redraw() and the window is drawn on the next frame.
  • In a game, things move all the time. Set realtime = true in WINDOW and the window is drawn every frame.
  • Windows nobody can see aren't drawn at all. That includes hidden and rolled-up windows, and windows behind a full-screen one.

When it goes wrong

If your program has a mistake, you hear a squawk and its window shows This program crashed., with what went wrong and the line it happened on. Fix it in Code and press Ctrl+R again.

  • print(...) writes to Terminal, so you can watch values change.
  • Code runs a whole project, too: open its folder (File > Open Folder) and its files are down the left. Run checks that every file compiles, and Problems, under the editor, shows each mistake with its line number and the lines that called it. Click a mistake to go to its line. Run > Profile shows which of your functions take the most time.
  • The Profiler shows how long every open window's _update and _draw take.

A program can't freeze Macaw OS. If it runs for a long time without finishing, because of a loop that never ends or a big file it's loading, it's paused every 30 milliseconds and the rest of the desktop carries on. See busy programs.

Keeping things

Your program can read and write files in /home:

fs.write("/home/hello-score.txt", tostring(score))
local saved = tonumber(fs.read("/home/hello-score.txt") or "") or 0

fs.read returns nil if the file isn't there yet, so the or gives you a value to start with. See Files and the system for the other file calls.

Next

Make a game builds a whole game one step at a time. Or go straight to drawing, input and sound or 3D.

Make a game: Seed Catcher

In Seed Catcher, seeds fall from the sky and you move a macaw along the ground to catch them. Miss three and the game is over. The finished game is about a hundred lines. Each step below leaves you with a program that runs, so try it as you go.

Open Terminal and type new seeds.lua. The new file opens in Code. Delete everything the template put in it, because you'll write the whole program yourself.

1. A window and the sky

WINDOW = { w = 240, h = 160, title = "Seed Catcher", realtime = true }

local GROUND = 148          -- the grass starts here

function _draw()
  cls(colors.sky)
  rectfill(0, GROUND, WINDOW.w, WINDOW.h - GROUND, colors.green)
end

Press Ctrl+R to run it. realtime = true tells Macaw OS to draw the window every frame. A game needs this because things move all the time. cls fills the window with a colour, and rectfill(x, y, w, h, colour) draws a filled rectangle. Here it draws the grass, from GROUND to the bottom of the window.

2. The macaw

You can make a picture from text. Each character is a pixel, and a table says which colour each character stands for. A . is see-through. Put this under the GROUND line, because the macaw's position uses it:

local BIRD = parseimage({
  "...rr...",
  "..rrrr..",
  ".rrkrry.",
  ".rrrryy.",
  "rrrrrr..",
  "bbrrrr..",
  ".bbrr...",
  "..b..b..",
}, { r = colors.red, y = colors.yellow, b = colors.blue, k = colors.night })

local bird = { x = 116, y = GROUND - 16, flip = false }

Draw it in _draw, after the grass:

  blit(BIRD, bird.x, bird.y, 0, 2, bird.flip)

blit(picture, x, y, see-through colour, scale, flip) draws the picture. The macaw is 8x8, drawn at twice the size, so it covers 16x16 pixels. Colour 0 (the dots) isn't drawn at all. For bigger pictures, draw them in Paint and load them with loadimage.

3. Moving

_update runs 60 times a second. btn says whether a key is held down:

function _update()
  if btn("left") then bird.x = bird.x - 2; bird.flip = true end
  if btn("right") then bird.x = bird.x + 2; bird.flip = false end
  bird.x = clamp(bird.x, 0, WINDOW.w - 16)
end

clamp keeps the macaw inside the window. flip turns it to face the way it's moving.

4. Seeds

The seeds are kept in a list. Every so often a new seed starts just above the window at a random place. Each frame, every seed falls a little. Put this under the macaw, above _update:

local seeds = {}
local timer = 0

local function drop_seed()
  add(seeds, { x = 4 + rnd(WINDOW.w - 8), y = -4, speed = 0.6 + rnd(0.6) })
end

In _update:

  timer = timer - 1
  if timer <= 0 then
    drop_seed()
    timer = 40 + rnd(30)            -- the next one in 40 to 70 frames
  end
  for s in all(seeds) do
    s.y = s.y + s.speed
  end

And in _draw, before the macaw:

  for _, s in ipairs(seeds) do circfill(s.x, s.y, 2, colors.brown) end

rnd(n) gives a random number from 0 up to n. add puts something on the end of a list. all goes through a list in a way that lets you take things out of it as you go, which the next step needs.

5. Catching

A seed is caught when it's inside the macaw's 16x16 square. Change the seed loop to this:

  for s in all(seeds) do
    s.y = s.y + s.speed
    if s.y > bird.y and s.y < bird.y + 16 and s.x > bird.x and s.x < bird.x + 16 then
      del(seeds, s)
      score = score + 1
      sfx("coin")
    elseif s.y > GROUND then
      del(seeds, s)
      lives = lives - 1
      sfx("hit")
    end
  end

Put local score, lives = 0, 3 at the top of the file, and show both in _draw:

  text("score " .. score, 4, 4, colors.navy)
  for i = 1, lives do circfill(WINDOW.w - 8 * i, 7, 3, colors.red) end

del takes the seed out of the list. sfx plays one of the built-in sounds: blip, coin, jump, hit, lose, squawk, rawk and chime.

6. Game over, and again

When lives reaches 0, the game stops and waits for Enter. Put everything a new game needs in one function, so that starting again only takes one call:

local function restart()
  bird = { x = 116, y = GROUND - 16, flip = false }
  seeds = {}
  score, lives, timer, over = 0, 3, 0, false
end

restart now gives the variables their values, so they only need declaring. Replace local bird = ..., local seeds = {}, local timer = 0 and local score, lives = 0, 3 with the one line below. Put it straight under the GROUND line, above everything that uses the variables, including restart. _init starts the first game:

local bird, seeds, score, lives, timer, best, over

function _init()
  restart()
end

In the seed loop, after sfx("hit"), end the game when the last life is gone:

      if lives == 0 then
        over = true
        sfx("lose")
      end

At the start of _update, wait for a key while the game is over:

  if over then
    if btnp("enter") or btnp("space") then restart() end
    return
  end

btnp is true in the frame a key goes down, and again now and then as the key repeats while it's held. btn is true every frame the key is down. With btnp, one press starts one game. To show the message at the end of _draw, use centertext, which writes text centred on an x position. Its last number makes the text bigger:

  if over then
    rectfill(40, 56, 160, 40, colors.night)
    centertext("Game over!", 120, 64, colors.yellow, 2)
    centertext("Enter plays again", 120, 84, colors.white)
  end

7. A best score that stays

Files in /home are kept after the program quits. Read the best score when the game starts. Put best = load_best() in _init, before restart(), and put this above _init:

local function load_best()
  return tonumber(fs.read("/home/seedcatcher.txt") or "") or 0
end

Show it under the score in _draw with text("best " .. best, 4, 14, colors.navy). Then save it when it's beaten, inside if lives == 0 then, after sfx("lose"):

        if score > best then
          best = score
          fs.write("/home/seedcatcher.txt", tostring(best))
        end

Finally, make the seeds fall faster as the score goes up by adding + score * 0.03 to their speed in drop_seed.

The whole game

Here is the complete program. It's also in /home/examples/seedcatcher.lua, and you can run it from Terminal with run /home/examples/seedcatcher.lua.

-- Seed Catcher: the game the programming guide's tutorial builds (macaw:docs/tutorial).
-- Seeds fall; the macaw catches them. Miss three and it's over.
WINDOW = { w = 240, h = 160, title = "Seed Catcher", realtime = true }

local BIRD = parseimage({
  "...rr...",
  "..rrrr..",
  ".rrkrry.",
  ".rrrryy.",
  "rrrrrr..",
  "bbrrrr..",
  ".bbrr...",
  "..b..b..",
}, { r = colors.red, y = colors.yellow, b = colors.blue, k = colors.night })

local GROUND = 148          -- the grass starts here
local bird, seeds, score, lives, timer, best, over

local function load_best()
  return tonumber(fs.read("/home/seedcatcher.txt") or "") or 0
end

local function restart()
  bird = { x = 116, y = GROUND - 16, flip = false }
  seeds = {}
  score, lives, timer, over = 0, 3, 0, false
end

function _init()
  best = load_best()
  restart()
end

local function drop_seed()
  -- seeds come faster as the score goes up
  add(seeds, { x = 4 + rnd(WINDOW.w - 8), y = -4, speed = 0.6 + rnd(0.6) + score * 0.03 })
end

function _update()
  if over then
    if btnp("enter") or btnp("space") then restart() end
    return
  end

  -- move
  if btn("left") then bird.x = bird.x - 2; bird.flip = true end
  if btn("right") then bird.x = bird.x + 2; bird.flip = false end
  bird.x = clamp(bird.x, 0, WINDOW.w - 16)

  -- a new seed every second or so
  timer = timer - 1
  if timer <= 0 then
    drop_seed()
    timer = 40 + rnd(30)
  end

  -- fall, get caught, or land
  for s in all(seeds) do
    s.y = s.y + s.speed
    if s.y > bird.y and s.y < bird.y + 16 and s.x > bird.x and s.x < bird.x + 16 then
      del(seeds, s)
      score = score + 1
      sfx("coin")
    elseif s.y > GROUND then
      del(seeds, s)
      lives = lives - 1
      sfx("hit")
      if lives == 0 then
        over = true
        sfx("lose")
        if score > best then
          best = score
          fs.write("/home/seedcatcher.txt", tostring(best))
        end
      end
    end
  end
end

function _draw()
  cls(colors.sky)
  rectfill(0, GROUND, WINDOW.w, WINDOW.h - GROUND, colors.green)
  for _, s in ipairs(seeds) do circfill(s.x, s.y, 2, colors.brown) end
  blit(BIRD, bird.x, bird.y, 0, 2, bird.flip)

  text("score " .. score, 4, 4, colors.navy)
  text("best " .. best, 4, 14, colors.navy)
  for i = 1, lives do circfill(WINDOW.w - 8 * i, 7, 3, colors.red) end

  if over then
    rectfill(40, 56, 160, 40, colors.night)
    centertext("Game over!", 120, 64, colors.yellow, 2)
    centertext("Enter plays again", 120, 84, colors.white)
  end
end

Where next

  • Draw a better macaw and seeds in Paint, and load them with loadimage.
  • Add a seed in another colour that the macaw should avoid.
  • Turn the game into a cart. A cart keeps sprites, a map and music in one folder that you can share as a single file.
  • Write a song for it in Music and play it with playsong (sound).

Drawing

Everything you draw goes into your window. The top-left pixel is 0, 0 and the bottom-right pixel is WINDOW.w - 1, WINDOW.h - 1. Put your drawing calls in _draw.

Shapes

function _draw()
  cls(colors.navy)                              -- fill the window
  rectfill(10, 10, 60, 30, colors.orange)       -- x, y, width, height
  rect(10, 50, 60, 30, colors.white)            -- just the outline
  circfill(120, 40, 20, colors.yellow)          -- centre x, y, radius
  line(0, 100, 239, 100, colors.lime)
  tri(160, 120, 200, 60, 230, 120, colors.pink)
  pset(5, 5, colors.red)                        -- one pixel
end
CallWhat it does
cls(c)Fills the window with colour c
pset(x, y, c)Sets one pixel to colour c
pget(x, y)Returns the colour of a pixel
line(x0, y0, x1, y1, c)Draws a line
rect(x, y, w, h, c)Draws a rectangle's outline
rectfill(x, y, w, h, c)Draws a filled rectangle
box(x, y, w, h, fill, [outline])Draws a filled rectangle with an outline
circ(x, y, r, c)Draws a circle's outline
circfill(x, y, r, c)Draws a filled circle
tri(x0, y0, x1, y1, x2, y2, c)Draws a filled triangle

Text

Each character of the font is 5x8 pixels in a 6x9 cell. CHAR_W and CHAR_H hold the cell's size.

CallWhat it does
text(s, x, y, c, [scale])Writes s with its top left at x, y, and returns the x just after it
textwidth(s, [scale])Returns how wide s would be, in pixels
centertext(s, x, y, c, [scale])Writes s centred on x
shadowtext(s, x, y, c, [shadow], [scale])Writes s with a shadow one pixel down and to the right
wraptext(s, columns)Breaks s into lines of at most columns characters and returns them as a list

Because text returns where it stopped, you can write in several colours along one line:

local x = text("Score: ", 4, 4, colors.white)
text(score, x, 4, colors.yellow)

Colours

You can use 256 colours at once, numbered 0 to 255.

  • 0 to 31 have names, such as colors.black, colors.red and colors.sky. The full list is below. 0 is black, and it's the colour you usually pass to blit as the see-through colour.
  • 32 to 47 are the logo's colours.
  • 48 to 63 are greys, from black to white.
  • 64 to 159 are sixteen hues, each in six bright shades from dark to light.
  • 160 to 255 are the same hues in six muted shades, which give you browns, skin tones and olives.

The 32 names are black, night, slate, steel, mist, white, brown, tan, sand, red, orange, yellow, green, blue, purple, pink, maroon, rust, cream, forest, lime, navy, sky, plum, lavender, teal, mint, charcoal, darkgrey, grey, silver and paper.

CallWhat it does
nearestcolor(r, g, b)Returns the closest of the 256 colours to an RGB colour (each part 0-255)
pal(c)Returns the r, g, b that colour c shows as now
pal(c, r, g, b)Changes what colour c looks like, everywhere on the screen
pal()Puts every colour back to normal
drawpal(c1, c2)Draws colour c1 as c2 from now on. Use it to flash a sprite white, for example
drawpal()Stops swapping colours

Pictures

A picture (an image) is a grid of colours. You can draw it into your window, and you can draw into it.

local ship = loadimage("/home/ship.pxl")    -- made in Paint
local dot = parseimage({ ".9.", "999", ".9." })

function _draw()
  cls(0)
  blit(ship, 50, 40, 0)          -- colour 0 is see-through
  blit(dot, 10, 10, 0, 4)        -- four times as big
end
CallWhat it does
image(w, h)Makes a new picture filled with colour 0
loadimage(path)Loads a picture saved by Paint (.pxl)
saveimage(img, path)Saves a picture as .pxl
parseimage(rows, [map])Makes a picture from text, one character per pixel. map says what colour each character is. Without map, . is 0, and 0-9 and a-v are colours 0-31
decodeimage(png, [maxw], [maxh])Makes a picture from PNG data, shrunk to fit inside maxw x maxh
importpicture(png, [maxw], [maxh])A PNG made elsewhere, for editing: each pixel the nearest of the 256 colours, see-through parts colour 0, made smaller only to fit maxw x maxh (256 x 256 if you don't say). Returns the picture and its own width and height, or nil and why
decodeimage(png, maxw, maxh, nil, false, true)The same for pixel art (a sprite): see-through pixels stay see-through (colour 0), and the others take the nearest colours without dithering, so the picture doesn't shimmer as it moves
loadtexture(path, [size])Loads a photo texture (.tex) for 3D. It's at most 64 pixels across, or size if you give one (up to 1024)
blit(img, x, y, [key], [scale], [flipx], [flipy])Draws a picture. key is a colour to leave out, usually 0
blitpart(img, sx, sy, sw, sh, x, y, [key], [scale], [flipx], [flipy])Draws part of a picture, such as one frame from a sheet

Each picture also has its own calls:

CallWhat it does
img:get(x, y) / img:set(x, y, c)Reads or sets one pixel
img:size()Returns the width and height. img:width() and img:height() return one each
img:clear([c])Fills the picture with one colour
img:copy()Makes a new picture the same as this one
img:getrgb(x, y) / img:setrgb(x, y, r, g, b)Reads or sets a pixel's true colour, which shows when the screen is in thousands of colours

Drawing into a picture

target(img) sends drawing into a picture instead of your window, and target() sends it back to the window. Use it to build something once and draw it many times, such as a background or a minimap:

local bg = image(240, 160)
target(bg)
cls(colors.sky)
for i = 1, 40 do circfill(rnd(240), rnd(100), 2 + rnd(6), colors.white) end
target()

function _draw()
  blit(bg, 0, 0)
end

target returns where you were drawing before, so local was = target(img) ... target(was) goes back to exactly that place. targetsize() returns the size of whatever you're drawing into.

Scrolling and clipping

CallWhat it does
camera(x, y)Moves everything drawn after this by -x, -y. Use it to scroll a big world
camera()Puts the camera back to 0, 0
clip(x, y, w, h)Limits drawing to this rectangle
clip()Lets you draw anywhere again

The screen

The screen starts at 640x360 with 256 colours. People can change it in the Monitors section of System Preferences, to 640x480, 800x600 or 1024x768, and to 8 colours, 256 or thousands.

CallWhat it does
SCREEN_W, SCREEN_HThe screen's current size
display.current()Returns the screen's width, height and colours ("8", "256" or "thousands")
display.sizes()Returns the sizes the screen can be, as { {640, 360}, ... }
display.request(opts, fn)Asks for a different size or number of colours

A game that wants a bigger screen, more or fewer colours, or the whole screen can ask for it: with display.request, fullscreen(true), or fullscreen and colors in WINDOW (asked as it starts). The person sees what your program wants and three buttons:

  • Allow lets it this time.
  • Always Allow lets it now and from then on without asking. People can take that back in the Monitors section of System Preferences.
  • Don't Allow (or Esc, or closing the question) closes your program.

So ask only for what your game needs, and say why in its read-me. The screen changes back when your program quits. Leaving full screen never asks.

display.request({ width = 800, height = 600, colors = "thousands" }, function(ok)
  -- ok is true once the screen is like that; false only when it can't be (a size that
  -- isn't in display.sizes())
  if not ok then print("staying as we are") end
end)

_display(w, h, colours) is called whenever the screen changes. With thousands of colours, photos and 3D show in true colour. With 8 colours, everything is dithered to black, red, green, yellow, blue, magenta, cyan and white.

Input and sound

Keys

function _update()
  if btn("left") then x = x - 1 end           -- held down
  if btnp("space") then sfx("jump") end       -- just pressed, this frame
end
CallWhat it does
btn(key)Returns true while key is held down
btnp(key)Returns true in the frame key goes down, then again every so often while it's held, the way a key repeats when you type
keysp()Returns a list of the names of every key that went down or repeated this frame
textin()Returns the characters typed this frame. Use it for text entry, not for game controls

The key names are left, right, up, down, enter, escape, space, backspace, tab, delete, home, end, pageup, pagedown, shift, ctrl, alt, cmd, f1 to f12, a to z and 0 to 9. Punctuation keys are named by their character (-, =, [, ], ;, ', ,, ., /, `).

Only the window in front gets key presses. Ctrl (Cmd on a Mac) with a letter is kept for menu shortcuts, so use the arrow keys, letters, Space and Enter for game controls.

The mouse

local mx, my, down, pressed, released, wheel = mouse()
if pressed & 1 ~= 0 then print("clicked at", mx, my) end

mouse() returns the pointer's position inside your window, then three button values. These say which buttons are held, which were pressed this frame and which were let go this frame. Each is a sum of 1 (left), 2 (right) and 4 (middle). wheel is how far the scroll wheel turned.

To make your own right-click menu, see Apps.

Sound effects

sfx("coin")

The built-in effects are blip, coin, jump, hit, lose, squawk, rawk (a shorter macaw call) and chime. In a cart, sfx(n) with a number plays the cart's own effects instead, the ones you made in the SFX editor.

Notes and tones

There are four effect voices, numbered 1 to 4. Each voice plays one sound at a time.

play(1, "C4", 200)                         -- voice 1, middle C, 200 ms
play(2, "E4", 200, "triangle", 0.3)        -- a softer wave, quieter
tone(4, 880, 300, "square", 0.4, -2000)    -- 880 Hz, falling 2000 Hz a second
CallWhat it does
play(voice, note, ms, [wave], [volume])Plays a note such as "C4", "F#3" or "Bb5" for ms milliseconds
tone(voice, hz, ms, [wave], [volume], [slide])Plays a frequency in Hz. slide is how many Hz per second the pitch rises by. A negative slide makes it fall
note(name)Returns the frequency of a note. note("A4") is 440
stop()Stops all four voices

The waves are square, pulse, triangle, saw, sine and noise. Volume goes from 0 to 1, and is 0.5 if you leave it out.

Music

You write songs in the Music app, which saves them as .song files. A song you play loops until you stop it:

function _init()
  playsong("/home/music/island.song")
end

function _close()
  stopsong()
end
CallWhat it does
playsong(path or song, [loop])Plays a song. Pass false for loop to play it once
stopsong()Stops the song
loadsong(path)Loads a song so you can change it before you play it
music.volume(v)Sets the music's volume, from 0 to 1
music.note(channel, instrument, n, [volume])Plays one note on the music chip straight away. instrument is 1-16, from the song that's playing
music.release(channel)Releases the note playing on channel
notenumber(name)Returns a note's number. notenumber("C-4") is 49
notename(n)Returns a note's name from its number. notename(49) is "C-4"

The music chip has 16 voices of its own, separate from the four effect voices, so music and sound effects can play at the same time. Each instrument is either a synth, which plays a wave you draw, or a recording of a real instrument. The recorded ones include piano, strings, cello, harp, flute, clarinet, horn, trumpet, marimba and drums. The example songs are in /home/music. Double-clicking one plays it in Jukebox, and the Music app opens it to change it. demo.song (synth) and island.song (recorded) are good songs to start from, and ambient.song is an ambient piece made with the pads below.

For ambient music, the synth has pads and textures that swell in slowly and take seconds to fade: warmpad, glasspad, darkpad, choirpad, swell, drone, air, wind, shimmer, softbell, musicbox and subbass. A note that's still fading keeps ringing when the next one starts, so chords wash into each other. Two settings make a synth sound move. detune adds a second copy of the wave a few cents higher, which makes it wider and richer. drift sweeps the filter down and back up again, slowly, at driftspeed times a second, so a long note breathes.

Programs can make songs too. newrollsong() makes a new song with six tracks. Each track has clips, and each clip holds notes like { t = step, len = steps, n = note, v = volume }, with 16 steps to a bar. The Music app edits them.

Game carts

A cart is a whole game in one folder. It holds the code, a sheet of sprites, a tile map, sound effects and songs. Macaw OS has an editor for each part. When the game is finished, you can pack the cart into a single .cart file (at most 256 KB) that anyone can double-click to play.

Make one

In Terminal:

newcart jumper

This makes /home/carts/jumper with a small platform game in it, and opens its main.lua in Code. Press Ctrl+R to play it. Code's Cart menu opens the cart's editors:

EditorWhat it editsThe file
Sprites256 sprites of 16x16 pixels, and 8 flags for eachgfx.pxl, gfx.flags
MapLayers of tiles, where each tile is a sprite numbermap.map
SFX64 sound effectssfx.sfx
MusicSongsmusic/*.song

cart.info holds the cart's title, its author and a short description:

return {
  title = "Jumper",
  author = "me",
  about = "Jump between the platforms.",
}

Sharing it

In TerminalWhat it does
pack jumperPacks /home/carts/jumper into /home/carts/jumper.cart
unpack jumper.cartUnpacks a cart into a folder in /home/carts, so you can look inside or change it. It won't unpack over a folder that's already there

Double-click a .cart in Files to play it. The games in /games are cart folders too. Right-click one in Files and choose Show Contents to see how it's made.

Sprites

Sprite 0 is the top-left 16x16 square of the sheet. Sprite 1 is the next one along, and sprite 16 is the first sprite in the second row. Colour 0 is see-through.

CallWhat it does
spr(n, x, y, [w], [h], [flipx], [flipy])Draws sprite n. w and h draw a block of sprites, so 2, 2 draws a 32x32 sprite made of four
sspr(sx, sy, sw, sh, x, y, [scale], [flipx], [flipy])Draws any rectangle of the sheet, given in pixels
sprimage(n, [w], [h])Returns a sprite as its own picture, so you can scale it or use it as a 3D texture
fget(n, [flag])Returns sprite n's flags (0-255), or whether one flag (0-7) is set
fset(n, [flag], value)Sets the flags, or one flag

Flags mean whatever you decide. The template's game uses flag 0 to mark solid tiles:

-- is the tile at this pixel solid?
local function solid(x, y)
  return fget(mget(x // 16, y // 16), 0)
end

The map

The map is a grid of tiles, and each tile is a sprite number (0 is empty). A map can have several layers, such as a background, the ground and things in front. You refer to a layer by its number or its name.

CallWhat it does
map([cx, cy], [x, y], [cw, ch], [layer])Draws cw x ch tiles of the map, starting from tile cx, cy, at pixel x, y. With no arguments it draws the whole map at 0, 0
mget(x, y, [layer])Returns the tile at x, y
mset(x, y, n, [layer])Sets the tile at x, y to n
mapsize([layer])Returns how many tiles the map has across and down

The map is usually bigger than the window, so scroll it with camera:

function _draw()
  cls(colors.sky)
  camera(cam_x, 0)        -- everything after this is drawn moved left by cam_x
  map()
  spr(1, player.x, player.y)
  camera()                -- back, for the score
  text(score, 4, 4, colors.white)
end

map only draws the tiles that are inside the window, so a big map doesn't slow it down.

Maps made in Tiled come in with the Map Editor's File > Import Map (or by dropping the .tmx and its picture on it): Tiled's tile n becomes sprite n, cut from the tileset's picture into the sprite sheet. Keep Tiled's Tile Layer Format as CSV. A picture of a whole level comes in with File > Import Map from Picture: it's cut into tiles, and each different one becomes a sprite. Your own code can do the same:

CallWhat it does
importmapimage(path, [tilesize])A picture of a level (a PNG) cut into tiles tilesize across (16 if you don't say; others are made 16 x 16): each different tile becomes a sprite, numbered in the order they're first met, and the same tile again is the same sprite. See-through tiles are 0. Returns the same as importmap
importmap(path)A Tiled map (.tmx, .json) or a CSV of tile numbers. Returns the map (layers as newmap makes them), a 256 x 256 picture of its tiles in their sprites' places (or nil), which sprites they fill (used[n] = true), and notes on what was left out; or nil and why

Sound and music

CallWhat it does
sfx(n, [voice])Plays the cart's sound effect n (0-63)
sfx(-1)Stops all sound effects
music(name, [loop])Plays music/name.song from the cart. A number works as a name too, so music(1) plays music/1.song
music(-1)Stops the music

sfx("coin") with a name still plays the built-in sounds. music.volume() and the other music chip calls work in carts too.

Handy for games

These calls work in carts and in every other program:

CallWhat it does
rnd(n)Returns a random number from 0 up to n. rnd() returns one from 0 to 1, and rnd(list) returns a random item from the list
flr(n), ceil(n)Rounds n down or up to a whole number
mid(a, b, c)Returns the middle value of the three. mid(0, x, 100) keeps x between 0 and 100
clamp(v, lo, hi)Keeps v between lo and hi. It does the same job as mid, with the value first
sgn(n)Returns -1 if n is below 0, otherwise 1
lerp(a, b, t)Returns a value part way from a to b, where t goes from 0 to 1
round(n)Rounds n to the nearest whole number
add(list, v)Puts v on the end of a list
del(list, v)Takes v out of a list
all(list)Goes through a list with for v in all(list). You can safely del items as you go

3D

Macaw OS has a 3D renderer for textured triangles. It has a depth buffer, a sun, up to eight lamps, and fog. On a computer with a graphics card, the card draws it at the screen's full size, sharp and smooth. Otherwise the processor draws it, in the screen's colours. Your program is the same either way.

There are three ways to use it, from the simplest to the most hands-on:

  • Scenes (below). You make things once, such as a camera, a cube, a terrain or a light, then move them about, and render() draws them all. Collisions and clicking on things are built in. Start here.
  • Meshes, further down. You draw each model yourself every frame, with your own camera.
  • The graphics chip. OpenGL-style matrices and draw calls, for full control.

All three draw into the same picture with the same depth buffer, so you can mix them. In 3D space, x goes right, y goes up and z goes forward, away from you. Angles are in degrees.

Scenes

Type new3d world.lua in Terminal to get a scene to start from. Here's a small one:

WINDOW = { w = 240, h = 160, title = "My World", scale = 2 }

local cam = newcamera()
cam:position(0, 1.5, -6)
cam:clscolor(colors.sky)
local sun = newlight("sun")

local ground = newplane(nil, 20)
ground:scale(30, 1, 30)
ground:color(colors.green)

local box = newcube()
box:position(0, 1, 2)
box:color(colors.orange)

function _update()
  if btn("left") then cam:turn(-2, 0, 0) end
  if btn("right") then cam:turn(2, 0, 0) end
  if btn("up") then cam:move(0, 0, 0.1) end
  box:turn(1, 0, 0)
  updateworld()
end

function _draw()
  render()
end

Each frame, move things, then call updateworld() to work out collisions. Then render() draws everything from the camera.

Making things

CallWhat it makes
newcamera()A camera to look through
newlight("sun")Light from far away, like the sun. It shines the way it faces, so turn it with e:rotate to light things from another side
newlight("point", [radius], [strength])A lamp that lights things within radius
newcube([texture], [tiles])A 2x2x2 cube
newsphere([segments], [texture])A ball
newcylinder([segments], [texture], [capped])A cylinder
newcone([segments], [texture])A cone
newplane([texture], [tiles])A flat 2x2 square, facing up
newterrain(cells, height, [texture], [tiles])Hills, 2 units across, which you scale up. height is either a picture, where brighter is higher, or a function (u, v) that returns a height from 0 to 1 for each point. u and v go from 0 to 1 across the terrain
newmesh(verts, tris, [texture])Your own shape (see Meshes, below)
newmodel(path, [textures])A model from an .obj file
newsprite(picture, [height])A flat picture that always faces the camera, for trees and people. It's 1 unit tall unless you give a height
newpivot()An empty thing to group others under

tiles is how many times the texture repeats across each face, or across the whole of a terrain.

What everything can do

CallWhat it does
e:position(x, y, z, [global])Puts it at this place. If it has a parent, the place is measured from the parent unless global is true
e:move(x, y, z)Moves it relative to the way it's facing (z is forward)
e:translate(x, y, z)Moves it along the world's directions
e:rotate(yaw, pitch, roll)Turns it to face this way
e:turn(yaw, pitch, roll)Turns it by this much
e:point(other) or e:point(x, y, z)Turns it to face something
e:scale(s) or e:scale(sx, sy, sz)Sets its size
e:parent(p)Makes it move and turn with p, like a moon going round a planet
e:pos()Returns where it is, as x, y, z
e:forward()Returns the way it's facing
e:up()Returns the way its top is facing
e:dist(other)Returns how far it is from something
e:hide(), e:show()Stops and starts drawing it
e:visible()Returns whether it's drawn. It's false if it or anything it's parented to is hidden
e:texture(picture, [n]), e:color(c)Changes how it looks. For a model with several textures, n says which one to change (the first if you leave it out)
e:fullbright()Stops light shading it, for lamps, the sky and glowing things
e:twosided()Draws both sides of it
e:free()Gets rid of it
terrain:height(x, z)Returns the ground's height at a place

Cameras also have cam:fov(degrees) (80 to start with), cam:clscolor(c) (or false to not clear the picture), cam:fog(near, far, [c]), cam:project(e) for where something is in the window, and cam:pick(x, y, [max]).

The rest of the scene

CallWhat it does
render([camera])Draws everything. It uses the first camera you made unless you give it another
updateworld()Works out collisions for everything that moved
collisions(a, b, [shape], [response])Makes things of type a bump into things of type b (see below)
resetcollisions(e)Forgets where e was. Call it after you move something a long way in one go, so it doesn't collide with everything in between
pick(ox, oy, oz, dx, dy, dz, [max])Returns the nearest pickable thing along a ray from ox, oy, oz in the direction dx, dy, dz, or nil. With max, it ignores anything further away than that
ambient(level)Sets how bright the light is everywhere. It starts at 0.35
clearworld()Throws the whole scene away. The next thing you make starts a new, empty one
world3d()Returns the scene itself. The calls above are short for its methods, so render(cam) is the same as world3d():render(cam)

Bumping into things

Give things a collision type, which can be any number. Then say which types bump into which:

ball:collide(1, 0.5)            -- type 1, a sphere of radius 0.5
wall:collide(2)                 -- type 2
collisions(1, 2, "mesh", "slide")

After updateworld(), a ball that ran into a wall has been pushed back out of it. ball.hits lists what it touched, with the direction the surface faces (nx, ny, nz). The third argument to collisions is the shape to test the wall as. It's "mesh" for its exact shape, "box" or "sphere". The last argument is what happens. With "slide" the ball slides along the wall, and with "stop" it stops.

Clicking on things

box:pickable()                  -- "mesh" (exact) or "sphere" ("box" works too, tested exactly)

local mx, my, _, pressed = mouse()
if pressed & 1 ~= 0 then
  local hit = cam:pick(mx, my)
  if hit then hit.entity:hide() end
end

cam:pick returns a table about what's under the pointer, or nil. It has the thing itself (hit.entity), where it was hit (x, y, z), the direction the surface faces (nx, ny, nz) and how far away it is (dist). pick returns the same table.

The demos in /games show all of this. orbit has things going round other things, flyover has terrain, fog and sprites, and gallery has clicking. marble, Marble Run, is a whole game: a marble rolling round five levels made in Brushwork (see Levels).

Meshes

To draw each model yourself, set up the frame and then draw:

WINDOW = { w = 240, h = 160, title = "Box", realtime = true }

local crate = image(16, 16)
crate:clear(colors.tan)
target(crate)
rect(0, 0, 16, 16, colors.brown)
line(0, 0, 15, 15, colors.brown)
target()

local box = cube3d(1, 1, 1, crate)
local angle = 0

function _update() angle = angle + 1 end

function _draw()
  clear3d(colors.navy)
  camera3d(0, 0, -3)
  light3d(-1, -1, 1)
  box:draw(0, 0, 0, angle, angle / 2, 0)
end
CallWhat it does
clear3d([c])Starts a frame. It clears the depth buffer, and clears the picture to c if you give it
camera3d(x, y, z, [yaw], [pitch], [fov])Sets where the camera is and which way it looks. fov is 90 unless you give it
light3d(dx, dy, dz, [sun], [ambient])Sets the sun's direction and strength, and the light everywhere
pointlight3d(n, x, y, z, radius, [strength])Sets lamp n (1 to 8). A radius of 0 turns it off
fog3d(near, far, c)Adds fog that starts at near and is solid by far. fog3d() turns it off
m:draw([x, y, z], [yaw, pitch, roll], [scale])Draws a mesh
m:drawm(a, b, c, d, e, f, g, h, i, x, y, z)Draws a mesh with your own 3x3 transform. Each corner is multiplied by the rows a b c, d e f and g h i, then moved to x, y, z. Use it to stretch or squash a mesh, or to draw it with a rotation you've worked out yourself
m:texture(n, picture)Changes the mesh's texture n (from 1 to 16)
m:size()Returns how many corners and triangles the mesh has
project3d(x, y, z)Returns where a point lands in the window, as x, y, distance
line3d(x0, y0, z0, x1, y1, z1, [col], [thick])Draws a line in the world, seen through the camera, over the picture. The part behind you is cut off. Use it for outlines and markers
stats3d()Returns how many triangles were drawn this frame

For example, m:drawm(2, 0, 0, 0, 1, 0, 0, 0, 1, x, y, z) draws a mesh twice as wide as it is.

Making meshes:

CallWhat it makes
cube3d(w, h, d, texture, [tiles])A box. texture can be one picture or { sides, top, bottom }
room3d(w, h, d, floor, walls, [ceiling], [tiles])The inside of a box, with the floor at y = 0
loadobj(path, [textures])A model from an .obj file
billboard3d(picture, x, y, z, [height], ["fullbright"])Draws a picture standing at a place, facing the camera
mesh3d(verts, tris, [textures], [texids], [options])Any shape

tiles is how many times the texture repeats across each face. With 0 it repeats once for every unit of size, which is what room3d does unless you say otherwise. cube3d shows the texture once on each face unless you give it tiles.

mesh3d takes the corners as one long list, with five numbers for each, x, y, z, u, v. u and v say which part of the texture goes at that corner, from 0 to 1 across. The triangles are three corner numbers each, counting from 1. The front of a triangle is the side its corners go round anticlockwise. The options are words in a string. "double" draws both sides, and "fullbright" ignores the light.

local tri = mesh3d({ -1, 0, 0, 0, 1,   1, 0, 0, 1, 1,   0, 1.5, 0, 0.5, 0 },
                   { 1, 2, 3 }, { crate }, nil, "double")

Textures

Any picture can be a texture. Textures repeat, and colour 0 is see-through. For photos, Macaw OS comes with a set in /system/textures, which you load with loadtexture:

local rock = loadtexture("/system/textures/rock.tex")

With a graphics card they're drawn in true colour. Without one they're drawn in the nearest of the screen's colours. Photos are kept at most 64 pixels across, which is plenty for a wall where the texture repeats. For something seen big and close, loadtexture(path, 128) keeps more detail, but it takes four times the memory.

The computers Macaw OS was made for had graphics cards with very little memory. An eMac has 32 MB, and a slot-loading iMac has 8 or 16. About and the Profiler both show how much is in use. If your program uses more than it's allowed, Macaw OS tells you once in an alert, and in Terminal each time.

The graphics card

glr is only there when a graphics card is doing the drawing, so check with if glr then.

CallWhat it gives
glr.vram()Roughly how many bytes of the card's memory are in use, how many are allowed (32 MB, or 16 MB on a Rage 128), and whether it's over
glr.info()A table about the card. It has renderer and version (the card's name and OpenGL version), depthbits, maxtexture (the biggest texture it takes), multitexture, cubemap (whether it can do baked reflections), extensions, and how its memory is split up (texturebytes, lightmapbytes and screenbytes)

cubemaps() is a shortcut for glr ~= nil and glr.info().cubemap.

The graphics chip

gpu.* talks to the 3D hardware directly, the way OpenGL 1.x does. You switch features on and off, set up matrices, and send triangles. If you've used old OpenGL, you'll know it already. It draws with the same renderer as scenes and meshes and shares their depth buffer, so you can mix them.

The eye looks down -z with y up, and matrices are column-major. The front of a triangle is the side its corners go round anticlockwise. Each window has its own chip state, so programs can't upset each other.

A spinning pyramid

WINDOW = { w = 240, h = 160, title = "Pyramid", realtime = true }
local t = 0
local SIDES = { colors.red, colors.yellow, colors.green, colors.sky }
local CORNERS = { { -1, -1, 1 }, { 1, -1, 1 }, { 1, -1, -1 }, { -1, -1, -1 } }

function _update() t = t + 1 / 60 end

function _draw()
  gpu.clearcolor(colors.navy)
  gpu.clear()

  gpu.matrixmode("projection")
  gpu.loadidentity()
  gpu.perspective(60, nil, 0.1, 50)    -- field of view, aspect (nil: the window's), near, far
  gpu.matrixmode("modelview")
  gpu.loadidentity()
  gpu.translate(0, 0, -4)
  gpu.rotate(20, 1, 0, 0)
  gpu.rotate(t * 90, 0, 1, 0)

  gpu.enable("depth_test", "cull_face")
  gpu.begin("triangles")
  for i = 1, 4 do
    local a, b = CORNERS[i], CORNERS[i % 4 + 1]
    gpu.color(SIDES[i])
    gpu.vertex(a[1], a[2], a[3])
    gpu.vertex(b[1], b[2], b[3])
    gpu.vertex(0, 1, 0)                -- the top
  end
  gpu.done()
end

Each side is a triangle in its own colour. depth_test makes the near sides hide the far ones, and cull_face skips the sides facing away.

State

CallWhat it does
gpu.enable(cap, ...)Switches on "depth_test", "cull_face", "lighting", "fog" or "texture"
gpu.disable(cap, ...)Switches them off
gpu.isenabled(cap)Returns whether one is on
gpu.depthmask(on)Sets whether drawing writes to the depth buffer
gpu.cullface("back")Sets which side culling hides, "front" or "back"
gpu.frontface("ccw")Sets which way round the corners of a front face go, "ccw" or "cw"
gpu.viewport(x, y, w, h)Draws into part of the window, counting from its top left. gpu.viewport() goes back to the whole window
gpu.clearcolor(c)Sets the colour gpu.clear clears to
gpu.clear(["color depth"])Clears the picture, the depth buffer, or both
gpu.reset()Puts everything back how it started

Matrices

CallWhat it does
gpu.matrixmode(m)Picks which matrix the calls below change, "modelview" or "projection"
gpu.loadidentity()Resets the matrix
gpu.pushmatrix() / gpu.popmatrix()Saves the matrix and gets it back
gpu.translate(x, y, z)Moves
gpu.rotate(degrees, x, y, z)Turns round an axis
gpu.scale(x, [y, z])Grows or shrinks
gpu.perspective(fovy, [aspect], [near], [far])Sets up a perspective projection
gpu.ortho(left, right, bottom, top, [near], [far])Sets up a flat projection
gpu.frustum(left, right, bottom, top, near, far)Sets up a perspective projection by its edges
gpu.lookat(ex, ey, ez, tx, ty, tz, [ux, uy, uz])Looks from the eye at a target. The last three say which way is up, and it's straight up if you leave them out
gpu.loadmatrix(m) / gpu.multmatrix(m)Sets the matrix to your own 16 numbers, or multiplies it by them
gpu.getmatrix(["modelview" or "projection"])Returns a matrix as 16 numbers. Without an argument it returns the current one
gpu.project(x, y, z)Returns where a point lands in the window, as x, y and a depth from 0 (near) to 1 (far). Returns nil if the point is behind the camera

Drawing

Immediate mode sends one corner at a time, between gpu.begin and gpu.done:

CallWhat it does
gpu.begin(mode)Starts drawing. The mode is "triangles", "tristrip", "trifan", "quads", "quadstrip", "polygon", "lines", "linestrip", "lineloop" or "points"
gpu.color(c, [bright])Sets the colour of the next corners
gpu.texcoord(u, v)Sets where on the texture the next corner is
gpu.normal(x, y, z)Sets which way the surface faces, for lighting
gpu.vertex(x, y, [z], [w])Sends a corner
gpu.done()Finishes drawing. It's also gpu["end"](), as in OpenGL

For models with lots of triangles, put them in a buffer once and draw the buffer each frame:

CallWhat it does
gpu.buffer(numbers, [layout])Makes a vertex buffer. buf:set(numbers) replaces what's in it, and buf:count() returns how many corners it holds. layout lists what each corner has, in order. p is the position (3 numbers), t the texture position (2), n the normal (3), c the colour (1), and l light baked in beforehand (1, where 1 is lit as usual)
gpu.indices(list)Makes an index buffer. It counts from 1 and can use at most 65536 corners
gpu.drawarrays(mode, buffer, [first], [count])Draws the corners in order
gpu.drawelements(mode, buffer, indices)Draws the corners the indices pick
local quad = gpu.buffer({
  -1, -1, 0,  0, 1,      -- position, then texture
   1, -1, 0,  1, 1,
   1,  1, 0,  1, 0,
  -1,  1, 0,  0, 0,
}, "pt")
local ix = gpu.indices({ 1, 2, 3, 1, 3, 4 })
-- in _draw:  gpu.bindtexture(img); gpu.drawelements("triangles", quad, ix)

Textures, light and fog

CallWhat it does
gpu.bindtexture(picture)Draws with this texture, or with none if you give nil
gpu.light(n, x, y, z, [w], [strength], [radius])Sets light n (1 to 8). With w at 0 it's a direction the light comes from, like the sun. With w at 1, the default, it's a lamp at that place that fades out by radius. gpu.light(n, false) turns it off
gpu.ambient(a)Sets the light everywhere, from 0 to 1
gpu.shademodel(m)Sets the shading. "flat" shades each face in one colour. "smooth" works the light out at the corners and blends it. "phong" works it out across the face, so highlights land where they should
gpu.material(shine, [sharpness])Sets how shiny surfaces are (0 to 1) and how tight the highlight is (from 2, which is broad, to 64)
gpu.fog(near, far, c)Sets the fog. Switch on "fog" as well
gpu.pointsize(n)Sets how big points are
gpu.stats()Returns what was drawn. That's triangles and corners, then the display lists used, made and missed

Reflecting water

The chip can draw water that reflects like a mirror:

  1. Draw the scene into a picture, from a camera mirrored in the water.
  2. Draw the main scene.
  3. Call gpu.mask(true) and draw the water's surface. Instead of drawing colours, this marks which pixels are water. Then call gpu.mask(false).
  4. Call gpu.water(reflection, options). It mixes the reflection into the marked pixels, with ripples, a tint, and a surface texture drifting over it.
gpu.water(reflection, {
  tint = colors.teal, tintamount = 0.3,
  ripple = 1, time = t,
  surface = loadtexture("/system/textures/water.tex"), surfaceamount = 0.3,
  drops = { { 0.5, 0.5, 1.2 } },          -- where a drip fell (u, v) and how long ago
})
OptionWhat it does
tint, tintamountA colour mixed in, and how much of it (0.2)
near, farHow much it reflects close to you (0.35) and far away (0.85)
rippleHow far the ripples bend the reflection, in pixels (1.5)
timeThe time in seconds, which moves the ripples
flowHow fast the surface texture drifts (1)
surface, surfaceamountA texture for the water itself, and how much it shows (0.3)
dropsWhere drips fell, as { u, v, seconds ago } for each, up to 16. Each one sends out rings
envA baked reflection to use instead of the picture (see below)

The numbers in brackets are what you get if you leave an option out. gpu.clearmask() clears the marked pixels without drawing anything.

Draw the water as a grid of squares rather than one big square, so the graphics card's ripples have corners to move. Draw the mirrored scene without cull_face, because the mirror camera sees floors from underneath. Levels do all of this for you.

Baked reflections

Drawing the scene twice every frame is a lot of work for an older card. Instead, the water can reflect six views that you draw once, from just above its middle:

local faces = {}
local turns = { {90, 0}, {-90, 0}, {0, 90}, {0, -90}, {0, 0}, {180, 0} }  -- +x -x +y -y +z -z
for i, t in ipairs(turns) do
  faces[i] = image(128, 128)
  local was = target(faces[i])
  clear3d(colors.black)
  camera3d(x, y, z, t[1], t[2], 90)        -- square pictures, a quarter turn wide
  drawscene()
  target(was)
end
local env = gpu.envmap(faces, { x = x, y = y, z = z, box = { x0, y0, z0, x1, y1, z1 } })
-- then, each frame, in place of the reflection picture:
gpu.water(nil, { env = env, tint = colors.teal, time = t })

The first time you draw with a cube map (what gpu.envmap makes), it goes onto the graphics card one face per frame, and nothing shows until all six faces are there. env:loaded() tells you whether they are. env:unload() takes it off the card to save memory, and the next time you draw with it, it comes back a face per frame.

box is the room around that place. With it, nearby walls show up in the right place in the water. gpu.envmap returns nil when the graphics card can't do cube maps, and then you draw only the water's surface. newprobe, and a level's water and probes, do all of this for you (see Levels).

Levels

Brushwork is the level editor. It's in the macaw menu, and double-clicking a .lvl file opens it too. You build levels the way the old first-person-shooter editors did, out of brushes. A brush is a solid convex shape like a box, wedge, stair or arch, and brushes can be added together or cut out of each other. Put in lamps and a player start, press Bake (F5) to work out the light, then Play (F6) to walk around.

File > Open Example opens a copy of one of the levels that come with Macaw OS (the Sample, the Atrium, Threefold or the Keep), so you can see how they're made. Your copy goes in /home/maps, and opening the example again never overwrites your changes.

Your own programs can load these levels and draw them quickly. A level is cut into pieces with a BSP tree and portals, so only what the camera can see gets drawn.

The levels that come with it

FileWhat it is
/system/maps/sample.lvlA small room with a few brushes, a good one to start from
/system/maps/atrium.lvlA sunlit hall of pillars and arches around a pool
/system/maps/keep.lvlA fortress of rooms on three floors, about as big as a level in an old shooter
/system/maps/threefold.lvlA castle, an underground base and a temple, joined into one long level

Each has its baked light next to it in a .lit file. Level Player plays any of them: /games/threefold is a cart that only opens Level Player on threefold.lvl, and you can make your own the same way.

Marble Run (/games/marble) is a game of its own made from levels. Its five courses, in /games/marble/levels, float in the sky: each is closed in by a box of faces with the sky texture, so the sky shows all round and lights the course when it's baked. Its rings are crystal entities and its finish is a goal, kinds it describes for itself in /games/marble/entities.lua (see Entities for your game). The game rolls the marble with L.lvl:tracebox.

Walking round a level

WINDOW = { w = 320, h = 180, title = "Walk", realtime = true }

local L = assert(openlevel("/system/maps/sample.lvl"))
local x, y, z, yaw = levelstart(L.lv)       -- the player start's feet, and which way it faces
local HALF, HH = 0.3, 0.8                   -- half the player's width, and half its height

function _update()
  if btn("left") then yaw = yaw - 3 end
  if btn("right") then yaw = yaw + 3 end
  local step = (btn("up") and 0.08 or 0) - (btn("down") and 0.08 or 0)
  if step ~= 0 then
    local dx, dz = math.sin(math.rad(yaw)) * step, math.cos(math.rad(yaw)) * step
    -- slide the player's box along, as far as it gets before it hits something
    local f = L.lvl:tracebox(x, y + HH, z, x + dx, y + HH, z + dz, HALF, HH, HALF)
    x, z = x + dx * f, z + dz * f
  end
end

function _draw()
  clear3d(colors.black)
  camera3d(x, y + 1.5, z, yaw)
  L.lvl:drawbsp()
end

openlevel loads the level (.lvl), builds it, and puts on its baked light from the .lit file next to it. It gives you back a table:

FieldWhat it is
L.lvThe level as a Lua table, with its brushes, entities and settings (see Building levels from code)
L.lvlThe built level, which draws and collides
L.litWhether its baked light was put on (false if there's no .lit, or it was baked for a different version of the level)
L.waterIts water, if it has any (see below)
L.probesIts reflection probes, if it has any (see below)
L.pathThe file it came from

Drawing

CallWhat it does
L.lvl:drawbsp()Draws what the camera can see, through the BSP and portals. This is the fast way. Returns how many leaves and faces it drew
L.lvl:draw()Draws all of it. With a graphics card the card keeps the whole level, so this is quick too
L.lvl:draw{ camera = "gpu" }Draws with the graphics chip's camera, viewport and fog instead of camera3d's
L.lvl:draw{ above = y }Draws only what's above a height (for reflections). L.lvl:draw(y) is short for the same thing

Levels use the same renderer as everything else in 3D, so you can draw meshes, scenes and billboards into them for people, pickups and doors.

Bumping into it

CallWhat it does
L.lvl:tracebox(ax, ay, az, bx, by, bz, hx, hy, hz)Moves a box (half-size hx, hy, hz) with its middle going from a to b. Returns how far it gets (0 to 1), the direction nx, ny, nz of whatever stopped it, and whether anything did
L.lvl:trace(x0, y0, z0, x1, y1, z1)How far along a line it gets before hitting something (0 to 1, where 1 means nothing)
L.lvl:raycast(x, y, z, dx, dy, dz)Where a ray from x, y, z going dx, dy, dz first goes into a brush. It returns t, so the spot is x + t * dx and so on, or nil if it hits nothing. It tries every brush, so it works straight after building a level
L.lvl:boxsolid(x0, y0, z0, x1, y1, z1)Whether a box touches anything solid
L.lvl:boxinside(x, y, z, hx, hy, hz)Whether a box is inside anything

These run in C, so they're quick enough to call many times a frame. Water isn't solid, so you can walk into it.

Water

In Brushwork, Level > Water turns the selected brushes into water. Water isn't solid, and its top is a reflecting surface. L.water is a list of those surfaces, and each one can draw itself with a reflection:

function _draw()
  local cam = { x = x, y = y + 1.5, z = z, yaw = yaw, pitch = 0, fov = 90 }
  for _, w in ipairs(L.water) do
    w:reflect(cam, function(c, above)
      camera3d(c.x, c.y, c.z, c.yaw, c.pitch, c.fov)
      L.lvl:draw{ above = above }
    end)
  end
  clear3d(colors.black)
  camera3d(cam.x, cam.y, cam.z, cam.yaw, cam.pitch, cam.fov)
  L.lvl:drawbsp()
  for _, w in ipairs(L.water) do w:draw(cam, time()) end
end

reflect draws a live reflection. The level is drawn a second time from a camera mirrored under the water, then mixed in with ripples and the water's own drifting surface. The function you give reflect gets the mirrored camera and the water's height.

That second drawing costs time. On a slow computer you can leave it out by not calling reflect (or setting w.reflections = false), and the water becomes a plain sheet.

You can also bake the reflection instead. w:bake(draw, ray) draws six views from just above the middle of the water, one each time you call it, and returns true once all six are done. After that w:draw reflects those views and nothing gets drawn twice. draw is the same function reflect takes, and ray finds the walls around the water so they show up in the right place:

if w.env == nil then
  w:bake(draw, function(...) return L.lvl:raycast(...) end)
end

Baking needs a graphics card with cube maps (cubemaps() tells you). Without one, w.env becomes false and the water stays a plain sheet. Things that move don't show up in a baked reflection.

w:draw(cam, t, how) takes an optional how. Give it "plain" for just the water's surface, or "baked" to use the baked reflection even when there's a live one.

On a PC, Level Player draws live reflections, and drops them for a while if the frame rate falls too low. On PowerPC Macs it never draws them live. It bakes them instead if the graphics card has cube maps (an eMac's Radeon does), and otherwise the water is plain (an iMac G3's Rage 128). In a web browser the water is always plain.

watercamera(c) points the graphics chip the same way as camera3d, for gpu.* drawing in the reflection. It also makes clockwise triangles the front ones.

Shiny surfaces and reflection probes

Any brush can be shiny. In Brushwork, select it and type an amount into its shine field, from 0 (not shiny) to 1 (a mirror). Polished floors look good around 0.2 to 0.4.

A shiny surface reflects the nearest reflection probe. A probe is a point in the level, and the view from there is baked into a cube map. Put probes in with the Probe tool (R). One probe per room is usually enough. Put it near the middle, at about eye height, since that's where the reflections will look most right. A surface uses the closest probe in front of it, and prefers one in the same room.

Bake in Brushwork bakes the probes too. Once the lighting is done, it bakes each probe in the lit level, and they're saved next to the level as a .prb file, with its .lit file. A level that has them opens with its reflections ready, so nothing is baked while it's being played.

In your own programs, openlevel makes the probes ready, with the ones Brushwork baked already in place. bakeprobes bakes any that weren't, like those of a level that was never baked in Brushwork. Call it once a frame until it returns true. Each call draws one of a probe's six views, so it never holds things up:

function _draw()
  bakeprobes(L)
  clear3d(colors.black)
  camera3d(x, y + 1.5, z, yaw)
  L.lvl:drawbsp()
end

Only one probe is on the graphics card at a time, the one nearest the camera, so a level can have many without filling the card's memory. Surfaces that use another probe aren't shiny until you get closer to it. When you do, the old probe is taken off the card and the new one is sent a face per frame, then its reflections fade in. Baked water works the same way. Only the nearest water's reflection is kept on the card.

To keep more on the card, call L.lvl:probelimit(n): then the n probes nearest the camera are on it (from 1 to 64), and surfaces that use any of them shine. Each probe takes about 400 KB of the card's memory, so on an eMac's 32 MB card a few are plenty. L.lvl:probelimit() gives the current limit.

L = openlevel("/home/hall.lvl")
L.lvl:probelimit(3)        -- the three nearest probes reflect at once

If nothing in the level is shiny, bakeprobes does nothing and returns true straight away. Probes need a graphics card with cube maps. Without one, shiny surfaces are drawn as they are. A probe sees the level as it was when it was baked, so things that move aren't in it.

For more control, newprobe(x, y, z) makes a probe of your own. Call p:bake(draw, ray) until it returns true, the same way as w:bake, then p.env is its cube map. L.lvl:setprobes({ env, ... }) tells the level which cube maps to use (up to 64), and L.lvl:setprobes() takes them away. env:pixels() gives a cube map's six faces as bytes, and gpu.envmap(bytes, where) makes it again from them. levelprobedata and applylevelprobes(L, text) do that for a level's probes and its .prb file.

Entities for your game

Besides brushes, a level holds entities: things at a place, each of a kind (its class) with fields. Macaw OS has its own (lamps, area lights, the start and probes) and a few generic kinds any game can use:

ClassWhat it's forIts fields
markerA named place, for a game to findname, angle
pickupSomething to pick upkind, value, respawn
enemySomething that gets in the waykind, health, speed, angle
triggerA box: something happens when the player's in itname, w, h, d, once, target
soundA sound that plays near herefile, volume, radius, loop
signWords to readtext, angle

A game can describe kinds of its own in an entities.lua in its folder. Brushwork finds it for any level in that folder or below it (/home/mygame/levels/one.lvl finds /home/mygame/entities.lua), lists its kinds in the Entity tab with the rest, and gives each field a row in Properties: a number or text to type, yes or no, a choice, a colour. You can add a field of your own to any entity there too, as name = value.

-- /home/mygame/entities.lua
return {
  { name = "coin", label = "Coin", about = "Worth a point.",
    colour = "#ffd700", shape = "ring", size = 0.4, float = 0.6,
    fields = {
      { "value", "number", 1, min = 0 },
      { "kind", "choice", "gold", choices = { "gold", "silver" } },
      { "spins", "bool", true },
    } },
  { name = "door", label = "Door", colour = "#a06030", shape = "zone",
    fields = { { "w", "number", 2 }, { "h", "number", 3 }, { "d", "number", 0.5 },
               { "key", "text", "" } } },
}

shape is how Brushwork draws it: ring, flag, ball, box, diamond, star, figure (person-sized), zone (a box w by h by d), speaker or sign. size is how big that is, and float how far over a floor it goes when you put one down (0 stands on it). A field is { name, type, default }, the type one of number (with min and max if you like), text, bool, choice (with choices), colour or angle. A kind with the same name as a generic one takes its place. The file is only read for its table, never run as part of a program.

In the game, levelentities gives you each one with all its fields, the defaults filled in:

local L = assert(openlevel(APP_DIR .. "/levels/one.lvl"))
local coins = {}
for _, c in ipairs(levelentities(L.lv, "coin")) do
  coins[#coins + 1] = { x = c[1], y = c[2], z = c[3], value = c.value, spins = c.spins }
end
CallWhat it does
entityclasses(path)Returns the kinds a level at path can have: { list = { class, ... }, by = { name = class }, file = its entities.lua }. openlevel puts them in L.classes
entityclass(classes, name)Returns one kind (one nothing describes gets a plain box)
entitydefaults(class, e)Fills in the fields e doesn't have with the kind's defaults
entityvalue(field, v)Returns v made the field's type (or its default), and whether it fitted

Building levels from code

Levels are Lua tables, so programs can make them too. A .lvl file holds one:

return { version = 1,
  brushes = {
    { 0, 0, 0, 8, 1, 8, tex = { "stone", "stone", "stone", "stone", "stone", "stone" } },
  },
  entities = {
    { class = "light", 4, 5, 4, bright = 1.2, radius = 12, colour = "#ffffff", soft = 0.35 },
    { class = "arealight", 4, 6, 4, w = 2, h = 2, facing = "down", bright = 1.5, radius = 12 },
    { class = "start", 2, 1, 2, angle = 0 },
    { class = "probe", 4, 2, 4 },
  },
  settings = { ambient = 0.08, bounce = 1, luxel = 0.5, sky = "cloudy", skylight = 1 },
}
  • A brush is a box, x0, y0, z0, x1, y1, z1, with six textures in the order -x +x -y +y -z +z (west, east, bottom, top, south, north). Or it's a convex shape: { planes = { { nx, ny, nz, d }, ... }, tex = { a name for each plane } }, which is inside where nx*x + ny*y + nz*z <= d (the normals point out).
  • A brush with water = true is a body of water, not a solid: its top is the surface, and you can walk into it.
  • glow = { [face] = { strength, "#rrggbb" } } makes faces glow and light the level when it's baked. A face is a box's side (1 to 6) or a shape's plane. White if no colour.
  • shine = 0.5 makes a brush reflect the nearest probe (0 not at all, 1 a mirror), or face by face with shine = { [face] = 0.5 }.
  • A lamp's soft is how big it is, so how soft its shadows are (0: hard). An area light is a glowing rectangle w by h, facing "down", "up", "+x", "-x", "+z" or "-z".
  • A probe is where shiny things' reflections are seen from.
  • Other kinds of entity are a game's: the generic ones and its own (see Entities for your game). Their fields are numbers, text or true/false, and the level keeps every one.
  • sky names a sky round the level (levelskies() lists them). Faces textured "sky" show it and give off its light, skylight times as strong.
  • Texture names are the built-in ones (LEVEL_TEXTURE_NAMES lists them) or a .pxl picture's path. The baked light is kept next to the level in a .lit file.
CallWhat it does
newlevel()Returns an empty level table
loadlevel(path) / savelevel(lv, path)Read and write .lvl files
buildlevel(lv)Builds a level table into something that draws (L.lvl above)
levelstart(lv)Returns where the player starts, as x, y, z, angle. It's 0, 2, 0, 0 if there's no start
levellights(lv)Returns its lamps and area lights, ready for baking
levelwater(lv)Returns its water surfaces as { { x0 =, z0 =, x1 =, z1 =, y = }, ... }, for newwater
levelprobes(lv)Returns its probes as { { x, y, z }, ... }, for newprobe
levelentities(lv, class)Returns its entities of one class, like "pickup", as { { x, y, z, field = value, ... }, ... }: copies, with their class's defaults for any field the level doesn't give (a level from openlevel)
levellitpath(path)Returns where a level's .lit file goes
levelskies() / levelsky(name)Returns the skies there are, and a sky's six pictures for lvl:setsky
leveltexture(name)Returns the picture for one of the built-in texture names

And on a built level:

CallWhat it does
lvl:bake(lights, [options])Starts working out the light. The options are ambient (0.08), bounce (1, how much light bounces) and softness (0.35, the size of lamps that don't give one)
lvl:bakestep([ms])Bakes for up to ms milliseconds (30 if left out). Returns whether it's done, how far it's got (0 to 1), and what it's doing
lvl:lightdata() / lvl:setlight(data)Gets the baked light to save it, and puts it back. setlight returns false if the light was baked for a different level
lvl:unbake()Back to plain shading
lvl:setsky({ px, nx, py, ny, pz, nz })Puts a sky around the level, from six square pictures. lvl:setsky() takes it away
lvl:faces()Returns every face of the built level, with its corners, texture number and which way it faces
lvl:stats()Returns numbers about it, such as faces, leaves, portals, luxels, baked, drawn (faces drawn last time), shiny and probes

/games/threefold/main.lua shows how small a cart around Level Player can be, and the Atrium and Threefold levels are worth opening in Brushwork to see how they're put together.

Apps

Programs with buttons, text boxes and lists use ui, the toolkit every Macaw OS program gets. To start one, type newapp myapp.lua in Terminal. There are three examples to read in /home/examples: greeter.lua, todo.lua and widgets.lua, which shows every widget there is.

How it works

You don't make widgets once and keep them. Instead, _draw calls them in order each frame, between ui.begin() and ui.finish(). Each widget draws itself and tells you what the person did with it. Your program keeps the values:

WINDOW = { w = 260, h = 180, title = "Settings" }

local name, loud, volume = "", false, 5

function _draw()
  ui.begin()
  ui.heading("Settings")
  name = ui.textbox("name", name, { placeholder = "your name" })
  loud = ui.checkbox("Loud", loud)
  volume = ui.slider("Volume", volume, 0, 10, 1)
  ui.row(2)
  if ui.button("Save") then print("saved", name) end
  if ui.button("Cancel") then close() end
  ui.finish()
end

ui.begin() clears the window to the paper colour. Use ui.begin({ bg = false }) if you don't want that. Widgets stack down the window from the top. Tab moves between them, and Enter or Space presses the one with the focus.

Widgets

CallWhat it does
ui.label(text, [colour])Some text
ui.heading(text)A heading
ui.separator()A line across the window
ui.button(label, [{ w = }])A button. Returns true in the frame it's clicked
ui.checkbox(label, value)A tick box. Returns the new value
ui.radio(label, selected)One of a set of choices. Returns true when it's clicked
ui.slider(label, v, min, max, [step])A slider. Returns the new value
ui.textbox(id, text, [opts])A box to type in. Returns the new text, and whether Enter was pressed. opts can have placeholder, password and w
ui.listbox(id, items, selected, [rows])A list. Returns the number of the selected item, and whether it was double-clicked
ui.dropdown(id, items, selected)A drop-down menu. Returns the number of the selected item
ui.tabs(id, names, current)Tabs along the top. Returns the current tab
ui.progress(fraction, [label])A progress bar, from 0 to 1
ui.swatches(colour, [{ all = true }])Colours to pick from. With all it shows all 256
ui.image(picture, [scale])A picture. Returns true when it's clicked

Text boxes, lists, drop-downs and tabs take an id. This is a name you choose, different for each one, so the widget can remember things between frames, such as where the cursor is or how far the list is scrolled.

A password box ({ password = true }) has a key button. It saves the password in Nestchain, or fills it in from there.

Layout

CallWhat it does
ui.row(n, [weights])Puts the next n widgets side by side. With weights such as { 2, 1 }, the first is twice as wide as the second
ui.space([pixels])Leaves a gap
ui.group(title) ... ui.endgroup()Draws a box with a title around the widgets in between
ui.at(x, y, w)Puts the next widget at exactly this place
ui.disabled = trueGreys out the widgets that follow, until you set it back to false

Menus

Set MENUS and the menu bar shows your menus while your window is in front:

MENUS = {
  { "File", {
    { "New", new_file, "n" },              -- label, what it does, Ctrl+key
    { "Save", save, "s" },
    "-",                                   -- a dividing line
    { "Close", close, "w" },
  } },
  { "View", {
    { "Grid", toggle_grid, checked = show_grid },
    { "Zoom In", zoom_in, "=", enabled = zoom < 4 },
  } },
}

MENUS can also be a function that returns the menus. Then checked and enabled are worked out again each time a menu opens.

Right-click menus

Define CONTEXT_MENU(x, y) to give your window a right-click menu. It's called with the place that was clicked and returns the items:

function CONTEXT_MENU(x, y)
  return { { "Paint here", function() paint(x, y) end }, "-", { "Clear", clear_all } }
end

To open a menu from your own code, call popupmenu(items, [x, y]). Without x and y it opens at the pointer.

Dialogs

Dialogs don't pause your program. Instead they call a function when the person answers.

CallWhat it does
alert(message)Shows a message with an OK button
confirm(question, fn)Asks a question with OK and Cancel buttons, and calls fn() if they click OK
askstring(prompt, default, fn)Asks for some text, then calls fn(text)
openfile(fn, [opts])Shows the Open dialog, then calls fn(path). opts can have dir and ext = { "pxl", "png" }
savefile(fn, [opts])Shows the Save dialog, then calls fn(path). opts can have dir and name
pickcolour(fn, [hex], [title])Shows the colour picker, then calls fn("#rrggbb")
openfile(function(path)
  picture = loadimage(path)
end, { dir = "/home", ext = { "pxl" } })

Drag and drop

CallWhat it does
function _drop(paths, x, y)Called when files are dropped on your window, at x, y: dragged from Files, or from the computer (those are put in /home/Imports first)
pickfiles()Asks the person to pick files from their computer (the website only). They come to your _drop(paths, -1, -1) once they're in. Returns false where it can't
canpickfiles()true where pickfiles works (the website)
startdrag(paths)Starts dragging files out of your window, to Files, the Trash, the desktop or another program
putondesktop(path)Puts an alias of a file, folder, program or game on the desktop, and returns the alias's file in /home/Desktop (or nil and why)

The rest of the desktop

CallWhat it does
open(path, ...)Opens a file the way double-clicking it would. For a program, the extra arguments reach it as ARGS
close()Closes your window (asking first if it has unsaved work)
settitle(s)Changes your window's title
fullscreen(on)Asks to make your window fill the screen, or puts it back. Asking shows the person a question: if they don't allow it, your program closes (see Drawing)
focused()Returns whether your window is in front
setclipboard(s) / getclipboard()Puts text on the clipboard and gets it back. Every program shares it, and so does the computer underneath
getpref(key) / setpref(key, value)Reads and changes system preferences. For example, getpref("highlight") is the highlight colour

Unsaved work

If your program has work that closing it would lose, say so, and Macaw OS asks before it closes, shuts down or restarts: Save, Don't Save or Cancel.

local changed = false

function _unsaved() return changed end

function _save()
  savefile(function(path)
    if fs.write(path, "my work") then changed = false end
  end, { dir = "/home", name = "work.txt" })
end

_save may ask where to save. Your program closes once _unsaved returns false; if the person cancels, or saving fails, it stays open. Without _save, they can only close it or keep it.

Files and the system

The disk

FolderWhat's in it
/homeYour own programs, pictures, songs and carts
/gamesThe games that come with Macaw OS
/systemMacaw OS itself, with its programs, libraries, textures, sounds and this guide
/prefsSettings, saved passwords and installed extensions
/trashThe Trash
/ramA place for scratch files

/system and /games come packed with Macaw OS, so you can't change them. You can read and copy from them, but save your own files in /home. Paths always start with / and use / between folders.

CallWhat it does
fs.read(path)Returns a file's contents as a string, or nil and the reason
fs.write(path, s)Writes a file. It makes the file, or replaces what was there
fs.append(path, s)Adds to the end of a file
fs.list(dir)Returns a list of the names in a folder. Folders come first and end in /
fs.exists(path)Returns whether it's there, and whether it's a folder
fs.info(path)Returns its size, when it was last changed (in seconds since 1970), and whether it's a folder
fs.mkdir(path)Makes a folder
fs.remove(path)Deletes a file or an empty folder for good. It doesn't go to the Trash
fs.rename(a, b)Moves or renames a file or folder

For working with paths there's basename(p) (the last part), dirname(p) (the folder it's in), joinpath(a, b) and extension(p) (such as "lua", in lower case).

Your program can keep its files next to it. APP_PATH is your program's path and APP_DIR is its folder. include("other.lua") runs another Lua file from your folder in your program's globals, so you can split a big program into several files.

To save a table, write it out as Lua and load it back in:

local function save(t)
  local out = { "return {" }
  for k, v in pairs(t) do out[#out + 1] = ("  %s = %q,"):format(k, v) end
  out[#out + 1] = "}"
  fs.write("/home/mygame-save.lua", table.concat(out, "\n"))
end

local function restore()
  local src = fs.read("/home/mygame-save.lua")
  local f = src and load(src, "save", "t", {})
  return f and f() or {}
end

When you give load an empty table as its last argument, the file runs with nothing it can call. So a save file can only hand back its values.

Lua in Macaw OS

Programs are written in Lua 5.4. You get the usual string, table, math, utf8 and coroutine libraries, and os.time, os.date and os.clock. A few things are left out so that a program can't reach the computer Macaw OS runs on:

  • There's no io, package or require. Use fs.* and include instead.
  • load only takes Lua source, not precompiled chunks. It runs the code in your program's own globals unless you give it a different table. There's no string.dump.
  • debug only has traceback and getinfo.

Files stay on the Macaw disk, and the only network a program can use is the Macaw network.

CallWhat it does
time()A clock in seconds, with fractions. Take one reading from another to time something
print(...)Writes to Terminal and the log
markdown(text)Turns Markdown into HTML, and also returns the first heading as a title
split(s, [sep])Cuts a string into a list at each sep. Without sep it cuts at new lines
trim(s)Returns s without the spaces at each end

The system

CallWhat it does
sys.platformWhat Macaw OS is running on. It's "windows", "web", "emac" (any PowerPC Mac on Mac OS X), "mac9" (Mac OS 9), "mac", or "unix" (the Raspberry Pi and other Linux)
ismac()Returns whether Macaw OS is running on a Mac (any of them)
modkey()Returns the name of the key that shortcuts are held with: "Cmd" on a Mac, "Ctrl" elsewhere. Text from strings already says it: a Ctrl+ in it shows as Cmd+ on a Mac
sys.versionWhich version of Macaw OS this is
sys.fps()The current frame rate, in frames a second
sys.display()The screen's width, height and colours. The colours are 8, 256 or "thousands"
sys.volume([v])Returns the volume for all sound, from 0 to 1. Give it v to change it. This changes it for the whole of Macaw OS, not just your program, until someone sets it in System Preferences or Macaw OS starts again
sys.screenshot(path)Saves the whole screen as a PNG file at path. Returns true if it worked
sys.title(s)Sets the title of the window Macaw OS runs in on the computer underneath. It does nothing on Mac OS 9
sys.cursor(on)Shows (true) or hides (false) the computer's own pointer over Macaw OS. It starts hidden, because Macaw OS draws its own. It stays as you leave it after your program quits, so set it back
sys.clipboard()Returns the text on the computer's own clipboard, or nil if there isn't any
sys.setclipboard(s)Puts text on the computer's own clipboard

To change the screen's size or colours, ask with display.request (see Drawing). Changing the screen directly, and making up key presses and clicks, are for Macaw OS's own programs: yours don't have them. For the clipboard, getclipboard() and setclipboard(s) from Apps are usually the better choice. They share one clipboard with every Macaw OS program as well as the computer, and they change characters the Macaw font doesn't have into ones it does.

Busy programs

A program that takes a long time doesn't hold up the rest of Macaw OS, whether it's loading a big level, laying out a long web page, or stuck in a loop that never ends. Your code runs in slices. If it hasn't finished after 30 milliseconds it's paused, and it carries on in the next frame. While it's paused, its window says "Loading..." or "Working...", the pointer spins over it, and everything else keeps running.

You don't need to do anything to get this, and it means a long job in _init is fine. The exception is _draw, which always finishes within its frame, so keep your drawing quick.

Saved passwords

Nestchain is Macaw OS's keychain. Each program has its own, kept apart from every other program's:

CallWhat it does
nestchain.set(service, account, password, [note])Saves a password
nestchain.get(service, account)Returns the password, or nil
nestchain.has(service, account)Returns whether there's a password saved
nestchain.remove(service, account)Forgets the password
nestchain.list([service])Lists what's saved, as { service, account, label, changed } for each. It never includes the passwords

A program can only have the system's own passwords if the person says so. These are the ones Dial-Up and Hotline save, and ones saved from password boxes:

CallWhat it does
nestchain.request(service, account, fn)Asks for one. The person chooses Allow Once, Always Allow or Don't Allow, then fn(password, why) is called. why is "denied" if they said no, or "none" if there's no password
nestchain.choose(fn)Lets the person pick one of their saved passwords for you, then calls fn(password, service, account)
nestchain.keep(password, [{ service =, account = }], [fn])Asks the person what the password is for, then saves it. Your program can read it back later without asking

Passwords are kept encrypted in /prefs. Never print one or save it anywhere else.

System Extensions

An extension is a piece of Lua with no window that loads when Macaw OS starts. You might use one for a clock in the menu bar, an item in the macaw menu, or a check for new mail every minute. To install one, drop it on Extensions (under System Tools in the macaw menu). You turn it on and off there, and the change happens straight away without a restart.

EXTENSION = { name = "Clock", version = "1.0", author = "me",
              about = "The time, in the menu bar." }

local m = ext.menu("12:00", { { "Hello", function() ext.alert("Hi!") end } })
ext.every(1, function() m:settitle(os.date("%H:%M")) end)
CallWhat it does
ext.menu(title, items)Adds a menu to the menu bar, with items written as in 0. The menu has menu:settitle(s), menu:setitems(items) and menu:remove()
ext.apple(label, fn, [key])Adds an item to the macaw menu
ext.startup(fn)Runs fn once the desktop is up
ext.every(seconds, fn)Runs fn every so many seconds. It returns a timer t, and t.stop() stops it
ext.task(fn)Runs fn on its own, a slice each frame. fn hands the time back with ext.sleep(seconds) or ext.yield()
ext.unload(fn)Runs fn when the extension is turned off
ext.data() / ext.save(t)A table that's kept from one start to the next
ext.open(path), ext.launch(path), ext.alert(msg), ext.getpref(k)Work with the desktop
ext.pet()Puts the macaw on the desktop while the extension is on (as Macaw Pet does)

If an extension crashes, runs for 2 seconds without a break, or takes more than 5 seconds to start, only that extension stops. It's turned off and shown as crashed in Extensions, with the reason, and everything it added is removed. Start from /home/examples/extensions/hello.lua when you write your own.

Memory

Every program has its own memory, with real addresses. You can ask for some with malloc, read and write single bytes with peek and poke, and give it back with free. Your window's picture is in there too, so poking the right address changes a pixel.

Each program's memory is its own. A bad address in one program can't touch another one, or anything outside Macaw OS. It just stops that program with an error saying which address was wrong.

The machine

The Corvus has 512 MB of memory. Everything every program has asked for counts against it, along with the memory Macaw OS uses itself. About Macaw OS and the Profiler show how much is in use. When it's all used, malloc returns 0.

Memory you've asked for doesn't take up room on the real computer until you write to it. Until then it reads as zeros. So a program can ask for a big block and use a little of it.

Addresses

AddressesWhat's there
0x00000000 to 0x0000FFFFNothing. Reading or writing here is an error, so a pointer that's 0 (NULL) fails straight away
0x00010000 onwardsYour window's picture, one byte per pixel, row by row. Each byte is a colour number
0x01000000 onwardsThe heap, where malloc gives out memory

Anywhere else, and heap memory that malloc hasn't given out, is an error to touch.

Numbers bigger than a byte are stored with the most significant byte first, as on a PowerPC. So poke4(a, 0x01020304) puts 1 at a and 4 at a + 3.

Reading and writing

CallWhat it does
peek(addr) / poke(addr, n)Reads or writes one byte, 0 to 255. Bigger numbers keep their low 8 bits, so poke(a, -1) writes 255
peek2(addr) / poke2(addr, n)Two bytes, 0 to 65535
peek4(addr) / poke4(addr, n)Four bytes, 0 to 4294967295. Negative numbers wrap round, so poke4(a, -1) reads back as 4294967295
peekf(addr) / pokef(addr, x)A 4-byte floating point number (a C float)
peekd(addr) / poked(addr, x)An 8-byte floating point number (a C double)
peekstr(addr, [max])The bytes from addr up to the first 0, as a string. With max, at most that many
pokestr(addr, s)Writes the string's bytes and then a 0
memset(addr, n, count)Writes the byte n into count bytes
memcpy(to, from, count)Copies count bytes. It works even when the two overlap

Asking for memory

CallWhat it does
malloc(size)Gives you size bytes and returns their address, or 0 if there isn't room. The address is always a multiple of 16
calloc(count, size)The same for count things of size bytes each, set to zero
realloc(addr, size)Makes a block bigger or smaller, keeping what's in it. It may move, so use the address it returns
free(addr)Gives a block back. free(0) does nothing. Freeing an address malloc didn't give you, or freeing a block twice, is an error
memory()How many bytes this program has asked for, how much of the machine is in use, and how big it is
local list = malloc(100 * 4)         -- room for 100 four-byte numbers
for i = 0, 99 do poke4(list + i * 4, i * i) end
print(peek4(list + 10 * 4))          -- 100
free(list)

Drawing through memory

screenmem() returns your window picture's address, its width and its height. The pixel at x, y is at addr + y * width + x.

WINDOW = { w = 160, h = 100, title = "Stripes", realtime = true }

function _draw()
  local addr, w, h = screenmem()
  for y = 0, h - 1 do
    for x = 0, w - 1 do
      poke(addr + y * w + x, (x // 8 + y // 8) % 2 == 0 and colors.navy or colors.sky)
    end
  end
end

It's the same picture the drawing calls draw into, so you can mix the two. A window that's resized gets a new picture, so ask screenmem() again rather than keeping the size.

C

Macaw OS runs programs written in C as well as Lua. It's C89, the C of the late 1980s and 1990s, with its whole standard library, plus a few later additions like // comments, long long and <stdint.h>. A C program gets its own memory with real addresses (see Memory), and its window works the same way a Lua program's does.

Your first C program

In Terminal, type:

new hello.c

That makes /home/hello.c from a template and opens it in Code. Press Ctrl+R to compile and run it. Double-clicking a .c file opens it in Code, and run hello.c in Terminal runs it. There's a whole game in C, Worm, at the end of this page.

#include <macaw.h>

int x = 60, y = 40;

void _update(void) {
  if (btn("left")) x--;
  if (btn("right")) x++;
}

void _draw(void) {
  cls(NAVY);
  circfill(x, y, 8, ORANGE);
}

int main(void) {
  window(160, 100, "Hello from C");
  realtime(1);
  return 0;
}

main runs once when the program starts. If the program defines _init, _update, _draw or _close, Macaw OS calls them the same way it calls a Lua program's. window(w, h, title) and realtime(1) take the place of Lua's WINDOW table.

A program with no window and no _draw is a console program. Whatever it prints shows in a window of its own, like a terminal.

#include <stdio.h>

int main(void) {
  int i;
  for (i = 1; i <= 10; i++) printf("%d squared is %d\n", i, i * i);
  return 0;
}

Programs in more than one file

Give cc every file, and a name for the program with -o:

cc main.c util.c -o game.mx

Each file is compiled on its own, then they're linked into one program. A function or global that one file uses has to be defined in exactly one of them. One marked static belongs to its own file, so two files can each have a static int count without a clash.

/* util.c */
static int calls = 0;
int twice(int n) { calls++; return n * 2; }
int calls_so_far(void) { return calls; }
/* main.c */
#include <stdio.h>
int twice(int n);
int calls_so_far(void);

int main(void) {
  printf("%d %d\n", twice(21), calls_so_far());
  return 0;
}

The .mx file is the compiled program. Double-click it, or type game in Terminal, to run it. You don't need the .c files to run it. With no -o, cc only checks that the files compile and link.

Today a .mx holds the program compiled to Lua. A faster interpreter for C is on the way, and its programs will be .mx files too. A version of Macaw OS that can't run a .mx says so instead of trying.

When something's wrong

A mistake that stops the program compiling is shown before anything runs, with the line it's on:

/home/hello.c:12: y isn't declared

So is one that stops it linking:

/home/main.c:3: twice is used but never defined (in any of the files)

A mistake while it runs, like using a NULL pointer, reading memory that malloc didn't give out or dividing by zero, stops the program with the line it happened on:

/home/hello.c:20: bad address 0x00000004: that's the null page (a NULL pointer?)

It only ever stops that program. A bad pointer can't touch anything else.

The language

All of C89 is there:

  • char, short, int and long, signed and unsigned, float and double, plus long long and _Bool. An int and a long are 32 bits, a long long is 64, and pointers are 32. Whole numbers wrap round on overflow.
  • Pointers and pointer arithmetic, arrays and arrays of arrays, struct, union, enum, typedef and bit-fields.
  • Structs passed to and returned from functions by value, and assigned with =.
  • Functions that take ..., using <stdarg.h>.
  • Pointers to functions, so qsort takes a comparison function.
  • if, while, do, for, switch with fall-through, break, continue and goto.
  • The preprocessor: #include, #define (with arguments, # and ##), #if, #ifdef, #elif, #error, __LINE__, __FILE__, __DATE__ and __TIME__.
  • Initialisers with or without inner braces, like int grid[2][2] = { 1, 2, 3, 4 };, and struct point p = { .x = 3, .y = 4 };.
  • Old-style function definitions, implicit int, wide strings (L"...") and trigraphs.

Numbers bigger than a byte are stored most significant byte first, as on a PowerPC.

A few things work differently from a C compiler on another computer:

  • A case label has to be right inside its switch's braces, not inside a block within them, so Duff's device won't compile.
  • setjmp has to start a statement of its own: setjmp(b);, x = setjmp(b);, if (setjmp(b) == 0) or switch (setjmp(b)). A break, continue or goto can't jump from after it to outside the block it's in. After a longjmp, local variables keep their latest values, as if they were all volatile.
  • Characters are single bytes, and the only locale is "C".

Headers

HeaderWhat's in it
<stdio.h>printf and the rest of its family, scanf's family, and files: fopen, fclose, fgets, fputs, fread, fwrite, fseek, ftell, fflush, remove, rename and the rest
<stdlib.h>malloc, calloc, realloc and free, atoi, atof, strtol, strtoul, strtod, rand and srand (RAND_MAX is 32767), qsort, bsearch, abs, div, exit, atexit, abort and getenv
<string.h>strlen, strcpy, strcat, strcmp and their n versions, strchr, strrchr, strstr, strspn, strcspn, strpbrk, strtok, strerror, memcpy, memmove, memset, memcmp and memchr
<math.h>sin, cos, tan and their inverses, sinh, cosh, tanh, exp, log, log10, pow, sqrt, fabs, floor, ceil, fmod, frexp, ldexp and modf, and M_PI
<ctype.h>isdigit, isalpha, isspace, isprint and the rest, toupper and tolower
<time.h>time, clock, difftime, mktime, localtime, gmtime, asctime, ctime and strftime
<setjmp.h>, <signal.h>setjmp and longjmp; signal and raise
<errno.h>, <assert.h>, <locale.h>, <stdarg.h>errno, assert, setlocale and localeconv, and va_list
<stddef.h>, <limits.h>, <float.h>, <stdbool.h>, <stdint.h>size_t and NULL, INT_MAX, DBL_MAX and so on, bool, and int32_t and its friends
<macaw.h>stdio, stdlib, string and math, plus Macaw OS's own calls (below)
<macaw3d.h>3D: scenes, meshes, textures and the graphics card (below)
<macawgpu.h>The graphics chip's gpu.* calls
<macawlevel.h>Levels: opening, drawing, colliding with, building and baking them
<macawui.h>The toolkit of buttons, sliders and lists, and the dialogs

Every call in Macaw OS's own headers has its own entry in the C reference, which says what it does and what each of its parameters is for: the window and drawing, input, sound and the system, 3D, the graphics chip, levels, and buttons, lists and dialogs.

A file's name is looked up from the program's own folder, unless it starts with /. A file is read when it's opened, and written when it's flushed or closed, or when the program ends. Nobody can type into a program's stdin, so getchar and scanf find nothing there: use textinput instead.

Macaw OS's calls

<macaw.h> names every colour in capitals, so NAVY, ORANGE and WHITE are the same numbers as colors.navy and the rest in Lua. Its calls work the way the Lua ones of the same name do:

KindCalls
The windowwindow, windowscale (each pixel 2 x 2 or bigger), resizable, realtime, windowmin (the smallest it can be made), windowcolors and windowcursor (in main, as WINDOW would), redraw, close, settitle, fullscreen, focused
Drawingcls, pset, pget, line, rect, rectfill, box, circ, circfill, tri, text, textscaled, centertext, shadowtext, textwidth, wraptext and wrapline, clip, noclip, camera
Colourspal, palreset, drawpal (draw one colour as another), drawpalreset, nearestcolor
The screendisplay_width, display_height, display_current, display_sizes and display_size, display_request
Screen memoryscreenmem (the window picture's address), screenwidth, screenheight
Picturesnewpicture, loadpicture (a .pxl or .png), savepicture, parsepicture, decodepicture and decodepicturefile (a PNG, shrunk to fit), importpicture and importpicturefile (a PNG for editing), freepicture, picturewidth, pictureheight, picturesize, pictureget, pictureset, pictureclear, picturecopy, picturegetrgb, picturesetrgb, drawpicture, drawpart, drawpictureex and drawpartex (scaled and flipped), drawinto
Sprites and the mapspr, sprex (a block of sprites, flipped), sspr, sprimage, spritesheet, fget, fset, map, mget, mset, mapwidth, mapheight, maplayers, maplayername, importmap and importmapimage (read with imap_layers, imap_layername, imap_size, imap_get, imap_picture, imap_used, imap_notes, imap_note, and let go with imap_free)
Inputbtn, btnp, keysp and keyspname, mouse (three int * to fill in with the position and buttons), textinput (what's been typed since last time)
Soundsfx, play, tone, note, stop, music, which plays a song from Tracker (music(NULL) stops it), playsong, stopsong, loadsong, playloadedsong, freesong, music_volume, music_note, music_release, notenumber, notename
Timenow, the seconds since Macaw OS started, as a double
Folders and filesfileexists, isfolder, makefolder, fileinfo, and listfolder, which gives the name of a folder's first, second, third ... thing
Textmarkdown (as HTML, with its title)
The clipboardgetclipboard, setclipboard
The desktopopenpath (opens a file or program, as a double-click does), getpref, setpref
The networknet_online, net_dial, net_connect, net_listen, net_accept, net_port, net_send, net_receive, net_readline, net_read, net_status, net_peer, net_close
The systemplatform, ismac, modkey, memory, sys_version, sys_fps, sys_display, sys_volume, sys_screenshot, sys_title, sys_cursor, sys_clipboard, sys_setclipboard
Passwordsnest_set, nest_get, nest_has, nest_remove, nest_list (read with nest_listitem, nest_listlabel, nest_listchanged), nest_request, nest_choose, nest_keep
Handy for gamesrnd, mid, clamp, sgn, lerp, flr (floor, ceil and round are math.h's, and round(-2.5) there is -3)

A picture, a song, an imported map, a connection and a listener are each a number, and 0 means it didn't work. The last number you give drawpicture and drawpart is a colour to leave out, or -1 to draw every pixel. drawinto(p) draws into picture p instead of the window, and drawinto(0) goes back to the window.

A call that gives back text takes a buffer and its size, like notename(n, buf, sizeof buf), and returns the whole text's length, so a buffer that's too small still tells you how big it should be. Most give -1 when there's nothing to give. A list comes in two steps: one call says how many, like wraptext(s, 30) or keysp(), and another gives item i, counting from 0, like wrapline(i, buf, sizeof buf).

Calls that ask the person take a function to call with the answer, as Lua's do: display_request(800, 600, COLORS_THOUSANDS, done) calls done(1) once the screen has changed, and nest_request(service, account, got) calls got(password, why), with the password NULL if they said no. Text your function is given is yours only while it runs, so copy it if you want to keep it. Colours for the screen are 8, 256 or COLORS_THOUSANDS.

A program can define _drop(const char **paths, int n, int x, int y) for files dropped on its window, and _display(int w, int h, int colours) for when the screen changes, as well as _init, _update, _draw, _resize and _close.

The network calls never wait. net_receive takes whatever has arrived so far, and net_readline gives -1 until a whole line is there, so call them from _update. net_status is 0 while connecting, 1 when open (or closed with some still to read), 2 once closed and 3 if it failed. To go online, call net_dial(): Dial-Up opens if it's needed, and net_online() is 1 once the line is up. Lua's spawn, wait_online and sleep wait inside a task; C does the same by checking in _update. listfolder(path, i, name, size) counts from 0, and gives 0 once there's nothing left.

The sprites and the map are the program's own: gfx.pxl, gfx.flags and map.map in its folder, made with Sprites and Map as for a cart. A map layer is given by name, like mget(x, y, "Terrain"), and NULL means the first. map(cx, cy, x, y, 0, 0, NULL) draws a whole layer, and camera(x, y) scrolls it. Where Lua has true or false, such as for flipping, C gives 1 or 0.

How Lua's calls look in C

Every call in this guide is in C too, apart from a few that only make sense in Lua: ext.* (extensions are written in Lua), the table helpers add, del and all, and spawn, wait_online and sleep (above). They follow the same rules:

  • Something Lua gives you as a table you call methods on (a 3D thing, a mesh, a level) is a number in C, and its methods are calls that take that number first. cube:position(x, y, z) is position3d(cube, x, y, z, 0). 0 means there isn't one.
  • Where Lua lets you leave an argument out, C needs every one. Each header says what to give for "the usual" (usually -1, 0 or NULL).
  • A call that gives back several numbers fills in pointers you pass it, like mouse does. You can pass NULL for any you don't want.
  • Lists count from 0 in C, where Lua counts from 1.
  • Where Lua takes a function, C takes a pointer to one of yours.
  • Text comes back the way getclipboard gives it: you pass a buffer and its size, and it returns how long the whole text is.

Here's a program that draws straight into its window's memory:

#include <macaw.h>

void _draw(void) {
  unsigned char *pixels = (unsigned char *)screenmem();
  int w = screenwidth(), h = screenheight(), x, y;
  for (y = 0; y < h; y++)
    for (x = 0; x < w; x++)
      pixels[y * w + x] = (x ^ y) & 31;
}

int main(void) {
  window(128, 128, "Pattern");
  realtime(1);
  return 0;
}

3D

#include <macaw3d.h> for everything on the 3D page. Here's that page's first scene in C:

#include <macaw3d.h>

int cam, box;

void _update(void) {
  if (btn("left")) turn3d(cam, -2, 0, 0);
  if (btn("right")) turn3d(cam, 2, 0, 0);
  if (btn("up")) move3d(cam, 0, 0, 0.1);
  turn3d(box, 1, 0, 0);
  updateworld();
}

void _draw(void) { render(0); }

int main(void) {
  int ground;
  window(240, 160, "My World");
  windowscale(2);
  cam = newcamera();
  position3d(cam, 0, 1.5, -6, 0);
  clscolor3d(cam, SKY);
  newlight("sun", -1, -1);
  ground = newplane(0, 20);
  scale3d(ground, 30, 1, 30);
  color3d(ground, GREEN);
  box = newcube(0, -1);
  position3d(box, 0, 1, 2, 0);
  color3d(box, ORANGE);
  return 0;
}
LuaC
newcamera(), newlight(kind, [radius], [strength]), newcube, newsphere, newcylinder, newcone, newplane, newpivot, newspriteThe same names. Each gives a number for the thing
newterrain(cells, height, ...)newterrain with a height picture, or newterrainfn with your own double height(double u, double v)
newmesh(verts, tris, ...), newmodel(path, ...)The same, with the corners as an array of float (5 each: x, y, z, u, v), the triangles as int (3 each, from 0), and textures as an array of picture numbers
e:position, move, translate, rotate, turn, scale, parent, hide, show, visible, texture, color, fullbright, twosided, freeposition3d(e, ...), move3d(e, ...) and so on
e:point(other), e:point(x, y, z)point3d(e, other), pointat3d(e, x, y, z)
e:pos(), e:forward(), e:up()pos3d(e, &x, &y, &z), forward3d, up3d
e:dist(other), terrain:height(x, z)dist3d(e, other), height3d(terrain, x, z, &h), which is 1 if it's over the terrain
e:collide(type, radius), e.hits, e:pickable(shape)collide3d, hitcount3d(e) and gethit3d(e, i, &hit), pickable3d
cam:fov, cam:clscolor, cam:fog, cam:project, cam:pickfov3d, clscolor3d (-1 to not clear), camfog3d, camproject3d, campick3d
render([cam]), updateworld, collisions, resetcollisions, pick, ambient, clearworldThe same names. render(0) uses the first camera
clear3d, camera3d, light3d, pointlight3d, fog3d, project3d, line3d, stats3dThe same names. fog3d() with nothing is nofog3d(), and lamps count from 0
cube3d, room3d, loadobj, mesh3d, billboard3dThe same names, plus cube3dsides for a box with its own top and bottom
m:draw, m:drawm, m:texture, m:sizedrawmesh(m, ...), drawmeshm, meshtexture, meshsize, and freemesh when you're done with it
loadtexture(path, [size])The same, giving a picture number
glr, glr.vram(), glr.info(), cubemaps()glrpresent(), glrvram(&used, &allowed), glrinfotext(field, buf, size) and glrinfonumber(field), cubemaps()

What a ray, a click or a bump hits comes back in a hit3d: x, y, z, the way the surface faces (nx, ny, nz), dist, and entity, the thing it hit.

The graphics chip

#include <macawgpu.h> for the graphics chip's calls. They're Lua's gpu.* with gpu_ in front, and modes and features are the same words: gpu_enable("depth_test") (one a call), gpu_begin("triangles"). A buffer, an index buffer and a cube map are each a number. Lights are 0 to 7, and indices and gpu_drawarrays's first corner count from 0. Matrices are 16 floats, column by column. gpu_water's options are a gpu_wateropts: start it with gpu_wateropts w = GPU_WATER_DEFAULTS;, then set what you want, with drips in w.drops and how many in w.ndrops.

CallWhat it does
gpu_enable(cap), gpu_disable(cap), gpu_isenabled(cap)Switch a feature on or off, and say whether it's on
gpu_depthmask(on), gpu_cullface(side), gpu_frontface(way)Depth writing, which side culling hides, which way round a front face goes
gpu_viewport(x, y, w, h)Draw into part of the window (w or h 0: the whole window)
gpu_clearcolor(c), gpu_clear(what), gpu_reset()Clear the picture and depth (NULL: both), and put everything back
gpu_matrixmode(m), gpu_loadidentity(), gpu_pushmatrix(), gpu_popmatrix()Pick and reset a matrix, save it and get it back
gpu_translate, gpu_rotate, gpu_scaleMove, turn and grow (gpu_scale takes all three sizes)
gpu_perspective, gpu_ortho, gpu_frustum, gpu_lookatProjections (0 for the usual aspect, near and far), and looking from an eye at a target
gpu_loadmatrix(m), gpu_multmatrix(m), gpu_getmatrix(which, m)Your own 16 floats in, or a matrix out
gpu_project(x, y, z, &sx, &sy, &depth)Where a point lands in the window: 0 if it's behind the camera
gpu_begin(mode) ... gpu_done()A corner at a time, with gpu_vertex, gpu_vertex4, gpu_color, gpu_colorex (with a brightness), gpu_texcoord and gpu_normal
gpu_buffer(floats, count, layout), gpu_bufferset, gpu_buffercount, gpu_freebufferA vertex buffer
gpu_indices(list, count), gpu_freeindicesAn index buffer
gpu_drawarrays(mode, buf, first, count), gpu_drawelements(mode, buf, indices)Draw a buffer in order (count -1: the rest), or by its indices
gpu_bindtexture(picture)Draw with a texture (0: none)
gpu_light(n, x, y, z, w, strength, radius), gpu_lightoff(n)Light n (strength -1: the usual)
gpu_ambient, gpu_shademodel, gpu_material, gpu_fog, gpu_pointsizeLight everywhere, shading, shininess, fog, point size
gpu_stats(&tris, &corners, &used, &made, &missed)What was drawn
gpu_mask(on), gpu_clearmask(), gpu_water(reflection, &opts)Reflecting water (&opts can be NULL)
gpu_envmap(faces, x, y, z, box), gpu_envmapbytes(bytes, n, x, y, z, box)A cube map from six pictures, or from gpu_envpixels's bytes (box can be NULL)
gpu_envloaded, gpu_envunload, gpu_envpixels(env, buf, size, &across), gpu_freeenvmapWhether it's on the card, taking it off, its bytes, letting it go

Levels

#include <macawlevel.h> for Levels. A level is a number: openlevel, loadlevel and newlevel each give one, and 0 means it didn't work (levelerror says why). openlevel builds it and puts on its baked light. After loadlevel, newlevel or a change, buildlevel builds it. Lua's L.lvl:tracebox(...) is leveltracebox(L, ...), and so on. A camera is a levelcam, with x, y, z, yaw, pitch, fov (fov 0 means 90). Where Lua takes a function to draw a view, such as for water's reflection, C takes void draw(const levelcam *c, double above, void *user): point camera3d at c and call leveldrawabove(L, above). A list (of entities, lights or water) is a count, then a call for item i. Here's the page's walk round a level:

#include <macawlevel.h>

int L;
double x, y, z, yaw;

void _update(void) {
  double step = (btn("up") ? 0.08 : 0) - (btn("down") ? 0.08 : 0), dx, dz, f;
  if (btn("left")) yaw -= 3;
  if (btn("right")) yaw += 3;
  dx = sin(yaw * M_PI / 180) * step;
  dz = cos(yaw * M_PI / 180) * step;
  f = leveltracebox(L, x, y + 0.8, z, x + dx, y + 0.8, z + dz, 0.3, 0.8, 0.3, NULL, NULL, NULL, NULL);
  x += dx * f;
  z += dz * f;
}

void _draw(void) {
  clear3d(BLACK);
  camera3d(x, y + 1.5, z, yaw, 0, 0);
  leveldrawbsp(L, NULL);
}

int main(void) {
  L = openlevel("/system/maps/sample.lvl");
  levelstart(L, &x, &y, &z, &yaw);
  window(320, 180, "Walk");
  realtime(1);
  return 0;
}
CallWhat it does
openlevel(path), loadlevel(path), newlevel()A level: opened, built and lit; only read; or empty
buildlevel(L), savelevel(L, path), freelevel(L)Build it (and its water and probes), write its .lvl, let it go
levelerror(buf, size), levelbuilt, levellit, levelpath, levellitpath, levelprobepathWhy it didn't work, and about a level
leveldrawbsp(L, &faces), leveldraw(L), leveldrawabove(L, y), leveldrawgpu(L), leveldrawgpuabove(L, y)Draw it: through the BSP, all of it, only above a height, or with the graphics chip's camera
leveltracebox(L, a, b, half-size, &nx, &ny, &nz, &hit)How far a box gets (0 to 1), and what stopped it
leveltrace, levelraycast (-1: nothing), levelboxsolid, levelboxinsideLines, rays and boxes
watercount(L), newwater(L, x0, z0, x1, z1, y), waterinfoIts water
waterreflect(L, i, &cam, draw, user), waterdraw(L, i, &cam, t, how)A live reflection, then the water (how: NULL, "plain" or "baked")
waterbake, waterbaked, waterreflections(L, i, on), watercamera(&cam)Baked reflections, live ones on (1), off (0) or asking (-1), and the chip's camera
bakeprobes(L), levelprobelimit(L, n)Bake its probes a face a call (1 when done), and how many are on the card (0 asks)
probecount, probeat(L, i), newprobe(x, y, z, size), probepos, probebake(p, draw, user, L), probebaked, probeenvProbes, baked a face a call. probeenv is a <macawgpu.h> cube map
levelsetprobes(L, envs, n), levelprobedata(L, buf, size), applylevelprobes(L, data, n)Which cube maps it reflects, and its .prb bytes
levelstart, levellightcount and levellight, levelwatercount and levelwater, levelprobecount and levelprobeWhat's in it
levelentitycount(L, class), levelentity(L, class, i, &x, &y, &z)Its entities of a class (NULL: all of them), with their class's defaults
levelentitynum, levelentitytext, levelentityhas, levelentityfieldAn entity's field by name, as a number or text, what kind it is, and its names
entityclasses(path), entityclasscount, entityclassname, entityclassinfo, entityclassfieldcount, entityclassfieldThe kinds of entity and their fields
leveladdbox(L, x0, y0, z0, x1, y1, z1, tex), leveladdshape(L, planes, n, tex)Add a box (six texture names, NULL: stone) or a convex shape (4 floats a plane)
levelbrushtexture, levelbrushwater, levelbrushglow(L, b, face, strength, colour), levelbrushshine(L, b, face, shine)A brush's faces, water, glow and shine (face -1: all of it)
levelbrushcount, levelbrushbox, levelremovebrushIts brushes
leveladdentity(L, class, x, y, z), levelentitysetnum, levelentitysettext, levelentitysetbool, levelmoveentity, levelremoveentityEntities and their fields
levelsetting, levelsettingtext, levelsetsetting, levelsetsettingtextambient, bounce, luxel, skylight and sky
levelskies(i, buf, size), levelsky(name, pictures, &r, &g, &b), leveltexture(name), leveltexturename(i, buf, size)Skies and the built-in textures, as pictures
levelbake(L, lights, n, ambient, bounce, softness), levelbakestep(L, ms, &progress, what, size)Bake its light (NULL lights: its own)
levellightdata(L, buf, size), levelsetlight(L, data, n), levelunbake(L)Its light as bytes to keep, putting it back, and plain shading
levelsetsky(L, pictures), levelfacecount, levelface, levelstat(L, name)A sky (NULL: none), its faces, and numbers like "faces" and "baked"

Windows with controls

#include <macawui.h> for the toolkit and the dialogs. Call the widgets from _draw, between ui_begin() and ui_finish(). A value a widget changes, such as a box's tick or a text box's text, lives in your program, and you pass a pointer to it. A widget gives 1 in the frame it's changed or clicked. A list is an array of strings and how many, numbered from 0, with -1 for nothing picked. Dialogs don't wait: they call a function of yours with the answer, and don't call it if the person cancels. Text a dialog gives your function only lasts for that call, so copy it to keep it.

#include <macawui.h>

static char name[32] = "";
static int loud = 0;
static double volume = 5;

static void hello(const char *answer) {
  char msg[64];
  sprintf(msg, "Hello, %s!", answer);
  alert(msg);
}

void _draw(void) {
  ui_begin();
  ui_heading("Settings");
  ui_textboxex("name", name, sizeof name, "your name", 0, 0);
  ui_checkbox("Loud", &loud);
  ui_slider("Volume", &volume, 0, 10, 1);
  ui_row(2, NULL);
  if (ui_button("Greet", 0)) alert(name[0] ? name : "Hello!");
  if (ui_button("Ask", 0)) askstring("Who's there?", "", hello);
  ui_finish();
}

int main(void) {
  window(220, 130, "Settings");
  return 0;
}
CallWhat it does
ui_begin(), ui_finish()Start and end the widgets for this frame
ui_beginex(x, y, w, bg)The same with a margin (-1: 8), a width (0: the window's) and a background (UI_DEFAULT, or UI_KEEP to keep what's drawn)
ui_label(s, colour), ui_heading(s), ui_separator()Text (colour -1: the usual), a heading, a line across
ui_button(label, w)A button (w 0 fits the label)
ui_checkbox(label, &on), ui_radio(label, &choice, value)A tick box, and one of a set: ticked while choice is value, and a click sets it
ui_slider(label, &v, min, max, step)A slider for a double (step 0: any value)
ui_textbox(id, buf, size), ui_textboxex(id, buf, size, placeholder, w, password)A box to type in. It gives 1 when Enter is pressed
ui_listbox(id, items, n, &selected, rows), ui_dropdown(id, items, n, &selected, w), ui_tabs(id, names, n, &current)A list (1 on a double-click), a drop-down menu, tabs
ui_progress(fraction, label), ui_swatches(&colour, all), ui_image(picture, scale)A progress bar, colours to pick from, a picture
ui_row(n, weights), ui_space(pixels), ui_group(title) ... ui_endgroup(), ui_at(x, y, w)Side by side (NULL weights: equal), a gap, a box round some widgets, an exact place
ui_disabled(on)Grey out the widgets after it. It gives what it was before
ui_focus(buf, size), ui_setfocus(id), ui_typing(), ui_rect(id, &x, &y, &w, &h), ui_nexty()The keyboard's widget, and where widgets are
alert(message), confirm(question, fn), askstring(prompt, initial, fn)A message, an OK or Cancel question, a question with typing
openfile(fn, dir, exts, n), savefile(fn, dir, name)The Open and Save dialogs
pickcolour(fn, hex, title)The colour picker. fn gets "#rrggbb", and the same as 0xRRGGBB
ondrop(fn), pickfiles(), canpickfiles(), startdrag(paths, n, label), putondesktop(path, buf, size)Files dropped on the window, picked from the computer (the website only), dragged out, or put on the desktop

A whole game in C

Worm is a small game written in C. It's in /home/examples/worm.c, so open it in Code and press Ctrl+R to play. Steer the worm to the red berries with the arrow keys. Each berry makes it longer, and every fifth makes it faster. It's over when the worm runs into a wall or into itself, and Enter starts another game.

It uses a lot of what's on this page:

  • #define names the garden's size and the file the best score is kept in. Change COLS or ROWS and the window, the walls and the drawing all change with it.
  • Two structs hold the game. A point is one square, and a worm is an array of points with its length and direction. w.body[i] = w.body[i - 1] copies one point over another, and square(w.body[i], GREEN) passes one to a function by value.
  • on_worm is given a pointer to the worm, const worm *wm, and reads it through wm->body.
  • rand puts each berry somewhere new. srand(time(NULL)) makes every game different.
  • fopen, fscanf and fprintf keep the best score in /home/worm.txt, so it's still there next time.
  • sprintf turns the score into text, and textwidth lines text up on the right or in the middle.
  • _update moves the worm one square every few frames. _draw draws the whole garden again each time, from what's in the structs.

Here's all of it:

/* Worm: a whole game in C. Steer the worm to the berries with the arrow keys. Each one
   makes it longer, and every fifth makes it faster. Don't hit the walls or yourself.
   Ctrl+R in Code compiles and runs it. The best score is kept in /home/worm.txt. */
#include <macaw.h>
#include <time.h>

#define CELL 8                    /* each square of the garden, in pixels */
#define COLS 20
#define ROWS 14
#define TOP 12                    /* the score bar's height */
#define MAXLEN (COLS * ROWS)
#define BEST_FILE "/home/worm.txt"

typedef struct {
  int x, y;
} point;

typedef struct {
  point body[MAXLEN];             /* body[0] is the head */
  int length;
  int dx, dy;                     /* the way it's going */
  int nextdx, nextdy;             /* the way the keys last said to go */
} worm;

static worm w;
static point berry;
static int score, best, over, ticks, speed;

/* the best score so far, from its file (0 if there isn't one yet) */
static int load_best(void) {
  FILE *f = fopen(BEST_FILE, "r");
  int n = 0;
  if (f) {
    if (fscanf(f, "%d", &n) != 1) n = 0;
    fclose(f);
  }
  return n;
}

static void save_best(int n) {
  FILE *f = fopen(BEST_FILE, "w");
  if (f) {
    fprintf(f, "%d\n", n);
    fclose(f);
  }
}

/* is p on one of the first n squares of the worm? */
static int on_worm(const worm *wm, point p, int n) {
  int i;
  for (i = 0; i < n; i++)
    if (wm->body[i].x == p.x && wm->body[i].y == p.y) return 1;
  return 0;
}

/* a berry somewhere the worm isn't */
static void place_berry(void) {
  do {
    berry.x = rand() % COLS;
    berry.y = rand() % ROWS;
  } while (on_worm(&w, berry, w.length));
}

static void restart(void) {
  int i;
  w.length = 4;
  for (i = 0; i < w.length; i++) {
    w.body[i].x = 8 - i;
    w.body[i].y = ROWS / 2;
  }
  w.dx = w.nextdx = 1;
  w.dy = w.nextdy = 0;
  score = 0;
  over = 0;
  ticks = 0;
  speed = 8;                      /* frames between moves */
  place_berry();
}

/* turn, but never straight back on itself */
static void steer(int dx, int dy) {
  if (dx != -w.dx || dy != -w.dy) {
    w.nextdx = dx;
    w.nextdy = dy;
  }
}

static void game_over(void) {
  over = 1;
  sfx("lose");
  if (score > best) {
    best = score;
    save_best(best);
  }
}

/* one move of one square */
static void step(void) {
  point head;
  int i, grow;
  w.dx = w.nextdx;
  w.dy = w.nextdy;
  head.x = w.body[0].x + w.dx;
  head.y = w.body[0].y + w.dy;
  grow = head.x == berry.x && head.y == berry.y;

  /* the tail moves out of the way, unless the worm is growing */
  if (head.x < 0 || head.x >= COLS || head.y < 0 || head.y >= ROWS
      || on_worm(&w, head, grow ? w.length : w.length - 1)) {
    game_over();
    return;
  }
  if (grow) w.length++;
  for (i = w.length - 1; i > 0; i--) w.body[i] = w.body[i - 1];
  w.body[0] = head;

  if (grow) {
    score++;
    sfx("coin");
    if (score % 5 == 0 && speed > 3) speed--;
    if (w.length == MAXLEN) game_over();   /* the whole garden is worm */
    else place_berry();
  }
}

void _update(void) {
  if (over) {
    if (btnp("enter") || btnp("space")) restart();
    return;
  }
  if (btnp("left")) steer(-1, 0);
  if (btnp("right")) steer(1, 0);
  if (btnp("up")) steer(0, -1);
  if (btnp("down")) steer(0, 1);
  if (++ticks >= speed) {
    ticks = 0;
    step();
  }
}

static void square(point p, int colour) {
  rectfill(p.x * CELL, TOP + p.y * CELL, CELL - 1, CELL - 1, colour);
}

static void centred(const char *s, int y, int colour) {
  text(s, (COLS * CELL - textwidth(s)) / 2, y, colour);
}

void _draw(void) {
  char line[32];
  int i;
  cls(FOREST);
  rectfill(0, 0, COLS * CELL, TOP, NIGHT);
  sprintf(line, "Score %d", score);
  text(line, 2, 2, WHITE);
  sprintf(line, "Best %d", best);
  text(line, COLS * CELL - textwidth(line) - 2, 2, YELLOW);

  circfill(berry.x * CELL + 3, TOP + berry.y * CELL + 3, 3, RED);
  for (i = w.length - 1; i > 0; i--) square(w.body[i], GREEN);
  square(w.body[0], LIME);

  if (over) {
    rectfill(16, 44, COLS * CELL - 32, 36, NIGHT);
    centred("Game over", 50, WHITE);
    centred("Enter plays again", 64, SILVER);
  }
}

int main(void) {
  srand((unsigned)time(NULL));
  best = load_best();
  restart();
  window(COLS * CELL, TOP + ROWS * CELL, "Worm");
  realtime(1);
  return 0;
}

Some things to try: make the worm come out the other side when it reaches an edge instead of crashing, put a few rocks in the garden, or give it a second berry that makes it shorter.

C reference: the window and drawing

These calls come from #include <macaw.h>. They open your window, draw into it, and work with pictures, sprites and maps. A picture is a number: 0 means there isn't one, and for drawinto it means the window itself. The Drawing chapter explains the Lua calls these are built on, and the C chapter shows how a C program fits together.

The window

window

void window(int w, int h, const char *title)

Says what size your window should be and what its title bar says. Call it in main, and it takes the place of Lua's WINDOW table.

  • w: the width of the inside of the window, in pixels. It's at least 8, and made smaller if it wouldn't fit on the screen.
  • h: the height of the inside of the window, in pixels. It's at least 8, and made smaller if it wouldn't fit.
  • title: the words in the title bar. NULL keeps the program's own name.

realtime

void realtime(int on)

Makes your window draw every frame, which games and animations need. Without it, _draw runs only when something may have changed.

  • on: 1 to draw every frame, 0 to go back to drawing only when needed.

windowscale

void windowscale(int scale)

Shows every pixel of your window bigger, for pixel art. Call it in main.

  • scale: how many screen pixels across each of your pixels is: 2 shows each as 2 x 2. It's kept between 1 and 4, and made smaller if the window wouldn't fit.

resizable

void resizable(int on)

Says whether people can resize your window with its size box. Windows can be resized unless you say otherwise.

  • on: 1 to let people resize it, 0 to stop them.

redraw

void redraw(void)

Asks for your window to be drawn again on the next frame. Call it from _update when something changes what the window shows, such as a timer or a download.

It takes nothing.

close

void close(void)

Closes your window, asking first if it has unsaved work.

It takes nothing.

settitle

void settitle(const char *title)

Changes the words in your window's title bar while the program runs.

  • title: the new title.

windowmin

void windowmin(int w, int h)

Sets the smallest size people can resize your window to. Call it in main, before the window opens.

  • w: the smallest width, in pixels. 0 means the usual 96, and it's never below 16.
  • h: the smallest height, in pixels. 0 means the usual 48, and it's never below 16.

windowcolors

void windowcolors(int colours)

Asks for the screen to show this many colours while your program runs. Call it in main; the person is asked when the window opens, and if they don't allow it, your program closes.

  • colours: 8, 256 or COLORS_THOUSANDS. Any other number, such as 0, leaves the screen as it is.

windowcursor

void windowcursor(int on)

Shows or hides the pointer while it's over your window. Hide it when you draw your own pointer.

  • on: 1 to show the pointer, 0 to hide it.

fullscreen

void fullscreen(int on)

Asks to make your window fill the screen, or puts it back. Asking shows the person a question, and if they don't allow it, your program closes. Leaving full screen never asks.

  • on: 1 to ask for full screen, 0 to go back to a normal window.

focused

int focused(void)

Tells you whether your window is the one in front, for example to pause a game when it isn't.

It takes nothing.

Returns 1 if your window is in front, or 0 if it isn't.

Drawing

cls

void cls(int colour)

Fills the whole window, or the picture you're drawing into, with one colour. It stays inside the clip rectangle, and the camera doesn't move it.

  • colour: the colour to fill it with, from 0 to 255.

pset

void pset(int x, int y, int colour)

Sets one pixel to a colour.

  • x: how far the pixel is from the window's left edge, in pixels.
  • y: how far the pixel is from the window's top, in pixels.
  • colour: the colour to set it to, from 0 to 255.

pget

int pget(int x, int y)

Reads the colour of one pixel of the window, or of the picture you're drawing into.

  • x: how far the pixel is from the window's left edge, in pixels.
  • y: how far the pixel is from the window's top, in pixels.

Returns the pixel's colour, from 0 to 255, or 0 if the pixel is outside the window.

line

void line(int x0, int y0, int x1, int y1, int colour)

Draws a straight line from one point to another.

  • x0: how far the start is from the window's left edge, in pixels.
  • y0: how far the start is from the window's top, in pixels.
  • x1: how far the end is from the window's left edge, in pixels.
  • y1: how far the end is from the window's top, in pixels.
  • colour: the line's colour, from 0 to 255.

rect

void rect(int x, int y, int w, int h, int colour)

Draws the outline of a rectangle, one pixel thick.

  • x: how far its left edge is from the window's left edge, in pixels.
  • y: how far its top edge is from the window's top, in pixels.
  • w: its width in pixels. 0 or less draws nothing.
  • h: its height in pixels. 0 or less draws nothing.
  • colour: the outline's colour, from 0 to 255.

rectfill

void rectfill(int x, int y, int w, int h, int colour)

Fills a rectangle with one colour.

  • x: how far its left edge is from the window's left edge, in pixels.
  • y: how far its top edge is from the window's top, in pixels.
  • w: its width in pixels.
  • h: its height in pixels.
  • colour: the colour to fill it with, from 0 to 255.

circ

void circ(int x, int y, int r, int colour)

Draws the outline of a circle.

  • x: how far the centre is from the window's left edge, in pixels.
  • y: how far the centre is from the window's top, in pixels.
  • r: the radius, in pixels. A negative radius draws nothing.
  • colour: the outline's colour, from 0 to 255.

circfill

void circfill(int x, int y, int r, int colour)

Draws a filled circle.

  • x: how far the centre is from the window's left edge, in pixels.
  • y: how far the centre is from the window's top, in pixels.
  • r: the radius, in pixels.
  • colour: the colour to fill it with, from 0 to 255.

tri

void tri(int x0, int y0, int x1, int y1, int x2, int y2, int colour)

Draws a filled triangle between three corners.

  • x0: how far the first corner is from the window's left edge, in pixels.
  • y0: how far the first corner is from the window's top, in pixels.
  • x1: how far the second corner is from the window's left edge, in pixels.
  • y1: how far the second corner is from the window's top, in pixels.
  • x2: how far the third corner is from the window's left edge, in pixels.
  • y2: how far the third corner is from the window's top, in pixels.
  • colour: the colour to fill it with, from 0 to 255.

text

void text(const char *s, int x, int y, int colour)

Writes text in the built-in font. Each character takes a cell 6 pixels wide and 9 high, and \n starts a new line.

  • s: the text to write.
  • x: how far the text's left edge is from the window's left edge, in pixels.
  • y: how far the text's top is from the window's top, in pixels.
  • colour: the text's colour, from 0 to 255.

textwidth

int textwidth(const char *s)

Measures how wide some text would be, so you can line it up before you write it.

  • s: the text to measure.

Returns its width in pixels: 6 for each character, or the widest line's width if it has more than one.

clip

void clip(int x, int y, int w, int h)

Limits drawing to a rectangle, so nothing is drawn outside it. The camera doesn't move the rectangle.

  • x: how far the rectangle's left edge is from the window's left edge, in pixels.
  • y: how far the rectangle's top edge is from the window's top, in pixels.
  • w: the rectangle's width in pixels.
  • h: the rectangle's height in pixels.

noclip

void noclip(void)

Lets you draw anywhere in the window, or the picture you're drawing into, again after clip.

It takes nothing.

camera

void camera(int x, int y)

Moves everything drawn after it by -x, -y. Use it to scroll a world that's bigger than the window, and camera(0, 0) to put it back.

  • x: how far to the right the view moves, in pixels.
  • y: how far down the view moves, in pixels.

box

void box(int x, int y, int w, int h, int fill, int outline)

Draws a filled rectangle with an outline in another colour.

  • x: how far its left edge is from the window's left edge, in pixels.
  • y: how far its top edge is from the window's top, in pixels.
  • w: its width in pixels.
  • h: its height in pixels.
  • fill: the colour inside, from 0 to 255.
  • outline: the outline's colour, from 0 to 255, or -1 for no outline.

centertext

void centertext(const char *s, int x, int y, int colour)

Writes text centred on a point across, which is handy for titles and buttons.

  • s: the text to write.
  • x: where the middle of the text goes, in pixels from the window's left edge.
  • y: how far the text's top is from the window's top, in pixels.
  • colour: the text's colour, from 0 to 255.

shadowtext

void shadowtext(const char *s, int x, int y, int colour, int shadow)

Writes text with a shadow one pixel down and to the right, so it stands out on a busy background.

  • s: the text to write.
  • x: how far the text's left edge is from the window's left edge, in pixels.
  • y: how far the text's top is from the window's top, in pixels.
  • colour: the text's colour, from 0 to 255.
  • shadow: the shadow's colour, from 0 to 255. 0 is black.

textscaled

void textscaled(const char *s, int x, int y, int colour, int scale)

Writes text with every pixel of the font made bigger.

  • s: the text to write.
  • x: how far the text's left edge is from the window's left edge, in pixels.
  • y: how far the text's top is from the window's top, in pixels.
  • colour: the text's colour, from 0 to 255.
  • scale: how big each font pixel is: 2 makes the text twice as big. Below 1 counts as 1.

wraptext

int wraptext(const char *s, int columns)

Breaks text into lines short enough to fit, breaking at spaces where it can. Read the lines afterwards with wrapline.

  • s: the text to break up. Each \n in it starts a new line.
  • columns: the most characters a line can have. Below 1 counts as 1.

Returns how many lines there are.

wrapline

int wrapline(int i, char *buf, int size)

Gives you one of the lines the last wraptext made.

  • i: which line, counting from 0.
  • buf: where to put the line's text.
  • size: how many bytes buf holds. A line that's too long is cut short to fit.

Returns the whole line's length in characters, or -1 if there's no line i.

Colours

pal

void pal(int colour, int r, int g, int b)

Changes what one colour number looks like, everywhere on the screen, until you put it back with palreset.

  • colour: the colour number to change, from 0 to 255.
  • r: how much red it has, from 0 to 255.
  • g: how much green it has, from 0 to 255.
  • b: how much blue it has, from 0 to 255.

palreset

void palreset(void)

Puts every colour back to how it normally looks, after pal.

It takes nothing.

drawpal

void drawpal(int from, int to)

From now on, anything you draw in one colour is drawn in another instead. Use it to flash a sprite white when it's hit, for example.

  • from: the colour to swap, from 0 to 255.
  • to: the colour to draw instead, from 0 to 255.

drawpalreset

void drawpalreset(void)

Stops swapping colours, so every colour draws as itself again.

It takes nothing.

nearestcolor

int nearestcolor(int r, int g, int b)

Finds which of the 256 colours is closest to a mix of red, green and blue, as they look now.

  • r: how much red, from 0 to 255.
  • g: how much green, from 0 to 255.
  • b: how much blue, from 0 to 255.

Returns the nearest colour number, from 0 to 255.

The window's memory

screenmem

int screenmem(void)

Gives you the address of your window's picture in memory, so you can write pixels into it directly. Each pixel is one byte holding its colour: the pixel at x, y is at the address plus y * screenwidth() + x.

It takes nothing.

Returns the address. Turn it into a pointer with (unsigned char *)screenmem().

screenwidth

int screenwidth(void)

Tells you how wide your window's picture is. Ask again after the window is resized, because it gets a new picture.

It takes nothing.

Returns the width in pixels.

screenheight

int screenheight(void)

Tells you how tall your window's picture is. Ask again after the window is resized.

It takes nothing.

Returns the height in pixels.

The screen

display_width

int display_width(void)

Tells you how wide the whole screen is now.

It takes nothing.

Returns the screen's width in pixels.

display_height

int display_height(void)

Tells you how tall the whole screen is now.

It takes nothing.

Returns the screen's height in pixels.

display_current

void display_current(int *w, int *h, int *colours)

Tells you the screen's size and how many colours it shows, all in one call.

  • w: where to put the width in pixels: pass the address of an int, like &w, or NULL.
  • h: where to put the height in pixels: pass the address of an int, like &h, or NULL.
  • colours: where to put the number of colours (8, 256 or COLORS_THOUSANDS): pass &colours, or NULL.

display_sizes

int display_sizes(void)

Finds out which sizes the screen can be. Read each one afterwards with display_size.

It takes nothing.

Returns how many sizes there are.

display_size

int display_size(int i, int *w, int *h)

Gives you one of the sizes the last display_sizes found. Call display_sizes first.

  • i: which size, counting from 0.
  • w: where to put its width in pixels: pass the address of an int, like &w.
  • h: where to put its height in pixels: pass the address of an int, like &h.

Returns 1 if there's a size i, or 0 if there isn't.

display_request

void display_request(int w, int h, int colours, void (*fn)(int ok))

Asks for the screen to be a different size or show a different number of colours. The person is asked first, and if they don't allow it, your program closes. The screen goes back when your program quits.

  • w: the width you want, in pixels, or 0 to keep it as it is.
  • h: the height you want, in pixels, or 0 to keep it as it is.
  • colours: 8, 256 or COLORS_THOUSANDS, or 0 to keep it as it is.
  • fn: your function to call with the answer: ok is 1 once the screen has changed, 0 if that size isn't one it can be. NULL if you don't need to know.

Pictures

newpicture

int newpicture(int w, int h)

Makes a new, empty picture that you can draw into or draw from. Every pixel starts as colour 0.

  • w: its width in pixels, from 1 to 4096.
  • h: its height in pixels, from 1 to 4096.

Returns the picture's number, or 0 if the size is out of range.

loadpicture

int loadpicture(const char *path)

Loads a picture from a file: a .pxl saved by Paint, or a .png.

  • path: the file's path, from your program's folder unless it starts with /.

Returns the picture's number, or 0 if the file couldn't be read.

freepicture

void freepicture(int p)

Lets go of a picture you've finished with. Don't use its number afterwards: that stops your program with an error.

  • p: the picture's number.

picturewidth

int picturewidth(int p)

Tells you how wide a picture is.

  • p: the picture's number.

Returns its width in pixels.

pictureheight

int pictureheight(int p)

Tells you how tall a picture is.

  • p: the picture's number.

Returns its height in pixels.

drawpicture

void drawpicture(int p, int x, int y, int key)

Draws a whole picture into the window, or into the picture you're drawing into.

  • p: the picture's number.
  • x: how far its left edge goes from the window's left edge, in pixels.
  • y: how far its top edge goes from the window's top, in pixels.
  • key: a colour to leave out so it's see-through, usually 0, or -1 to draw every pixel.

drawpart

void drawpart(int p, int sx, int sy, int sw, int sh, int x, int y, int key)

Draws one rectangle of a picture, such as a single frame from a sheet of them.

  • p: the picture's number.
  • sx: how far the part's left edge is from the picture's left edge, in pixels.
  • sy: how far the part's top edge is from the picture's top, in pixels.
  • sw: the part's width in pixels.
  • sh: the part's height in pixels.
  • x: how far it goes from the window's left edge, in pixels.
  • y: how far it goes from the window's top, in pixels.
  • key: a colour to leave out so it's see-through, usually 0, or -1 to draw every pixel.

drawinto

void drawinto(int p)

Sends all drawing into a picture instead of your window, so you can build something once and draw it many times. It also undoes any clip.

  • p: the picture to draw into, or 0 to go back to drawing into the window.

drawpictureex

void drawpictureex(int p, int x, int y, int key, int scale, int flipx, int flipy)

Draws a whole picture, made bigger or flipped.

  • p: the picture's number.
  • x: how far its left edge goes from the window's left edge, in pixels.
  • y: how far its top edge goes from the window's top, in pixels.
  • key: a colour to leave out so it's see-through, usually 0, or -1 to draw every pixel.
  • scale: how big each pixel is drawn: 2 makes it twice as big. Below 1 counts as 1.
  • flipx: 1 to mirror it left to right, 0 not to.
  • flipy: 1 to turn it upside down, 0 not to.

drawpartex

void drawpartex(int p, int sx, int sy, int sw, int sh, int x, int y, int key, int scale, int flipx, int flipy)

Draws one rectangle of a picture, made bigger or flipped.

  • p: the picture's number.
  • sx: how far the part's left edge is from the picture's left edge, in pixels.
  • sy: how far the part's top edge is from the picture's top, in pixels.
  • sw: the part's width in pixels.
  • sh: the part's height in pixels.
  • x: how far it goes from the window's left edge, in pixels.
  • y: how far it goes from the window's top, in pixels.
  • key: a colour to leave out so it's see-through, usually 0, or -1 to draw every pixel.
  • scale: how big each pixel is drawn: 2 makes it twice as big. Below 1 counts as 1.
  • flipx: 1 to mirror it left to right, 0 not to.
  • flipy: 1 to turn it upside down, 0 not to.

savepicture

int savepicture(int p, const char *path)

Saves a picture as a .pxl file, which Paint can open.

  • p: the picture's number.
  • path: the file to save it as, from your program's folder unless it starts with /.

Returns 1 if it was saved, or 0 if it couldn't be.

parsepicture

int parsepicture(const char **rows, int n, const char *chars, const int *colours)

Makes a picture from rows of text, one character for each pixel. It's a quick way to draw small things in your code.

  • rows: an array of strings, one for each row of pixels, from the top.
  • n: how many rows there are.
  • chars: the characters you use, in a string, like ".#o". NULL means . is colour 0, and 0-9 and a-v are colours 0 to 31.
  • colours: an array giving the colour for each character in chars, in the same order. Characters not in chars are 0.

Returns the picture's number, or 0 if it couldn't be made. It's as wide as the longest row.

decodepicture

int decodepicture(const void *png, int n, int maxw, int maxh, int background, int sprite, int *w, int *h)

Makes a picture from PNG data in memory, such as a file you've read or something downloaded. It's shrunk to fit if it's too big.

  • png: where the PNG's bytes are.
  • n: how many bytes there are.
  • maxw: the widest the picture can be, in pixels, or 0 for any width (up to 4096).
  • maxh: the tallest the picture can be, in pixels, or 0 for any height (up to 4096).
  • background: the colour see-through parts are put on, as 0xRRGGBB, or -1 for white.
  • sprite: 1 for pixel art: no dithering, and see-through parts stay colour 0. 0 for a photo.
  • w: where to put the PNG's own width before shrinking: pass the address of an int, like &w, or NULL.
  • h: where to put the PNG's own height before shrinking: pass the address of an int, like &h, or NULL.

Returns the picture's number, or 0 if the data isn't a PNG it can read.

decodepicturefile

int decodepicturefile(const char *path, int maxw, int maxh, int background, int sprite, int *w, int *h)

The same as decodepicture, but reads the PNG from a file.

  • path: the PNG file's path, from your program's folder unless it starts with /.
  • maxw: the widest the picture can be, in pixels, or 0 for any width (up to 4096).
  • maxh: the tallest the picture can be, in pixels, or 0 for any height (up to 4096).
  • background: the colour see-through parts are put on, as 0xRRGGBB, or -1 for white.
  • sprite: 1 for pixel art: no dithering, and see-through parts stay colour 0. 0 for a photo.
  • w: where to put the PNG's own width before shrinking: pass the address of an int, like &w, or NULL.
  • h: where to put the PNG's own height before shrinking: pass the address of an int, like &h, or NULL.

Returns the picture's number, or 0 if the file couldn't be read as a PNG.

importpicture

int importpicture(const void *png, int n, int maxw, int maxh, int *w, int *h)

Brings in a PNG made elsewhere, ready for editing: each pixel becomes the nearest of the 256 colours, and see-through parts become colour 0. It's made smaller only if it doesn't fit.

  • png: where the PNG's bytes are.
  • n: how many bytes there are.
  • maxw: the widest the picture can be, in pixels, or 0 for 256.
  • maxh: the tallest the picture can be, in pixels, or 0 for 256.
  • w: where to put the PNG's own width: pass the address of an int, like &w, or NULL.
  • h: where to put the PNG's own height: pass the address of an int, like &h, or NULL.

Returns the picture's number, or 0 if the data isn't a PNG it can read.

importpicturefile

int importpicturefile(const char *path, int maxw, int maxh, int *w, int *h)

The same as importpicture, but reads the PNG from a file.

  • path: the PNG file's path, from your program's folder unless it starts with /.
  • maxw: the widest the picture can be, in pixels, or 0 for 256.
  • maxh: the tallest the picture can be, in pixels, or 0 for 256.
  • w: where to put the PNG's own width: pass the address of an int, like &w, or NULL.
  • h: where to put the PNG's own height: pass the address of an int, like &h, or NULL.

Returns the picture's number, or 0 if the file couldn't be read as a PNG.

pictureget

int pictureget(int p, int x, int y)

Reads the colour of one pixel of a picture.

  • p: the picture's number.
  • x: how far the pixel is from the picture's left edge, in pixels.
  • y: how far the pixel is from the picture's top, in pixels.

Returns the pixel's colour, from 0 to 255, or 0 if it's outside the picture.

pictureset

void pictureset(int p, int x, int y, int colour)

Sets one pixel of a picture to a colour. A pixel outside the picture is left alone.

  • p: the picture's number.
  • x: how far the pixel is from the picture's left edge, in pixels.
  • y: how far the pixel is from the picture's top, in pixels.
  • colour: the colour to set it to, from 0 to 255.

picturesize

void picturesize(int p, int *w, int *h)

Tells you a picture's width and height in one call.

  • p: the picture's number.
  • w: where to put the width in pixels: pass the address of an int, like &w, or NULL.
  • h: where to put the height in pixels: pass the address of an int, like &h, or NULL.

pictureclear

void pictureclear(int p, int colour)

Fills a whole picture with one colour.

  • p: the picture's number.
  • colour: the colour to fill it with, from 0 to 255.

picturecopy

int picturecopy(int p)

Makes a new picture that's the same as another one, so you can change the copy and keep the first.

  • p: the number of the picture to copy.

Returns the new picture's number.

picturegetrgb

void picturegetrgb(int p, int x, int y, int *r, int *g, int *b)

Reads a pixel's true colour as red, green and blue. That's what shows when the screen is in thousands of colours.

  • p: the picture's number.
  • x: how far the pixel is from the picture's left edge, in pixels.
  • y: how far the pixel is from the picture's top, in pixels.
  • r: where to put the red, from 0 to 255: pass the address of an int, like &r, or NULL.
  • g: where to put the green, from 0 to 255: pass the address of an int, like &g, or NULL.
  • b: where to put the blue, from 0 to 255: pass the address of an int, like &b, or NULL.

picturesetrgb

void picturesetrgb(int p, int x, int y, int r, int g, int b)

Sets a pixel's true colour, which shows when the screen is in thousands of colours. The pixel's colour number becomes the nearest of the 256.

  • p: the picture's number.
  • x: how far the pixel is from the picture's left edge, in pixels.
  • y: how far the pixel is from the picture's top, in pixels.
  • r: how much red, from 0 to 255.
  • g: how much green, from 0 to 255.
  • b: how much blue, from 0 to 255.

Sprites and the map

spr

void spr(int n, int x, int y)

Draws one 16 x 16 sprite from your program's sprite sheet, gfx.pxl. Colour 0 in it is see-through.

  • n: the sprite's number, from 0 to 255. Sprite 0 is the top-left one, and 16 starts the second row.
  • x: how far its left edge goes from the window's left edge, in pixels.
  • y: how far its top edge goes from the window's top, in pixels.

sprex

void sprex(int n, int x, int y, int w, int h, int flipx, int flipy)

Draws a block of sprites together, flipped if you like. A 2 x 2 block is a 32 x 32 sprite made of four.

  • n: the number of the block's top-left sprite, from 0 to 255.
  • x: how far its left edge goes from the window's left edge, in pixels.
  • y: how far its top edge goes from the window's top, in pixels.
  • w: how many sprites across the block is. Below 1 counts as 1.
  • h: how many sprites down the block is. Below 1 counts as 1.
  • flipx: 1 to mirror it left to right, 0 not to.
  • flipy: 1 to turn it upside down, 0 not to.

sspr

void sspr(int sx, int sy, int sw, int sh, int x, int y, int scale, int flipx, int flipy)

Draws any rectangle of the sprite sheet, given in pixels rather than sprites.

  • sx: how far the rectangle's left edge is from the sheet's left edge, in pixels.
  • sy: how far the rectangle's top edge is from the sheet's top, in pixels.
  • sw: the rectangle's width in pixels.
  • sh: the rectangle's height in pixels.
  • x: how far it goes from the window's left edge, in pixels.
  • y: how far it goes from the window's top, in pixels.
  • scale: how big each pixel is drawn: 2 makes it twice as big. Below 1 counts as 1.
  • flipx: 1 to mirror it left to right, 0 not to.
  • flipy: 1 to turn it upside down, 0 not to.

fget

int fget(int n)

Reads a sprite's flags, from gfx.flags. Flags mean whatever you decide, such as flag 0 for a solid tile.

  • n: the sprite's number, from 0 to 255.

Returns all 8 flags as one number, from 0 to 255: flag f is set if (fget(n) >> f) & 1 is 1.

fset

void fset(int n, int flags)

Sets all 8 of a sprite's flags at once, while your program runs.

  • n: the sprite's number, from 0 to 255.
  • flags: the flags as one number, from 0 to 255: add 1 << f for each flag f you want set.

map

void map(int cx, int cy, int x, int y, int cw, int ch, const char *layer)

Draws tiles from your program's map, map.map, each one a 16 x 16 sprite. Only the tiles inside the window are drawn, and empty tiles (0) aren't drawn at all.

  • cx: which column of the map to start from, counting tiles from 0.
  • cy: which row of the map to start from, counting tiles from 0.
  • x: how far from the window's left edge to draw, in pixels.
  • y: how far from the window's top to draw, in pixels.
  • cw: how many tiles across to draw, or 0 for the layer's whole width.
  • ch: how many tiles down to draw, or 0 for the layer's whole height.
  • layer: the layer's name, like "Terrain", or NULL for the first layer.

mget

int mget(int x, int y, const char *layer)

Reads one tile of the map.

  • x: the tile's column, counting from 0.
  • y: the tile's row, counting from 0.
  • layer: the layer's name, or NULL for the first layer.

Returns the tile's sprite number, or 0 if it's empty, off the map, or there's no such layer.

mset

void mset(int x, int y, int n, const char *layer)

Changes one tile of the map while your program runs. A tile off the map is left alone.

  • x: the tile's column, counting from 0.
  • y: the tile's row, counting from 0.
  • n: the sprite number to put there, from 0 to 255. 0 makes it empty.
  • layer: the layer's name, or NULL for the first layer.

mapwidth

int mapwidth(const char *layer)

Tells you how many tiles across a map layer is.

  • layer: the layer's name, or NULL for the first layer.

Returns its width in tiles, or 0 if there's no such layer.

mapheight

int mapheight(const char *layer)

Tells you how many tiles down a map layer is.

  • layer: the layer's name, or NULL for the first layer.

Returns its height in tiles, or 0 if there's no such layer.

maplayers

int maplayers(void)

Tells you how many layers your map has.

It takes nothing.

Returns how many layers there are.

maplayername

int maplayername(int i, char *buf, int size)

Gives you the name of one of the map's layers, to pass to map or mget.

  • i: which layer, counting from 0.
  • buf: where to put the layer's name.
  • size: how many bytes buf holds. A name that's too long is cut short to fit.

Returns the whole name's length, or 0 if there's no layer i.

Sprites as pictures

sprimage

int sprimage(int n, int w, int h)

Copies a sprite, or a block of them, into a picture of its own. Use it to scale a sprite or use it as a 3D texture.

  • n: the number of the top-left sprite, from 0 to 255.
  • w: how many sprites across to copy, from 1 to 16, or 0 for 1.
  • h: how many sprites down to copy, from 1 to 16, or 0 for 1.

Returns the new picture's number, or 0 if it couldn't be made.

spritesheet

int spritesheet(void)

Gives you your program's whole sprite sheet as a picture, 256 x 256 pixels. Whatever you draw into it shows in spr and map straight away.

It takes nothing.

Returns the sprite sheet's picture number. It's the same number each time.

Maps made elsewhere

importmap

int importmap(const char *path)

Reads a map made in another program: a Tiled map (.tmx or .json) or a CSV of tile numbers. It keeps at most 8 layers.

  • path: the map file's path, from your program's folder unless it starts with /.

Returns a number for the imported map, or 0 if it couldn't be read.

importmapimage

int importmapimage(const char *path, int tilesize)

Reads a picture of a whole level (a PNG) and cuts it into tiles. Each different tile becomes a sprite, numbered 1, 2, 3 in the order they're first met, and see-through tiles are 0.

  • path: the PNG file's path, from your program's folder unless it starts with /.
  • tilesize: how many pixels across each tile is, from 4 to 64, or 0 for 16. Other sizes are made 16 x 16.

Returns a number for the imported map, or 0 if it couldn't be read.

imap_layers

int imap_layers(int m)

Tells you how many layers an imported map has.

  • m: the imported map's number.

Returns how many layers it has.

imap_layername

int imap_layername(int m, int layer, char *buf, int size)

Gives you the name of one of an imported map's layers.

  • m: the imported map's number.
  • layer: which layer, counting from 0.
  • buf: where to put the layer's name.
  • size: how many bytes buf holds. A name that's too long is cut short to fit.

Returns the whole name's length, or -1 if there's no such layer.

imap_size

int imap_size(int m, int layer, int *w, int *h)

Tells you how big one layer of an imported map is, in tiles.

  • m: the imported map's number.
  • layer: which layer, counting from 0.
  • w: where to put its width in tiles: pass the address of an int, like &w, or NULL.
  • h: where to put its height in tiles: pass the address of an int, like &h, or NULL.

Returns 1 if there's such a layer, or 0 if there isn't.

imap_get

int imap_get(int m, int layer, int x, int y)

Reads one tile of an imported map.

  • m: the imported map's number.
  • layer: which layer, counting from 0.
  • x: the tile's column, counting from 0.
  • y: the tile's row, counting from 0.

Returns the tile's sprite number, or 0 if it's empty, off the map, or there's no such layer.

imap_picture

int imap_picture(int m)

Gives you a 256 x 256 picture of the imported map's tiles, each in its sprite's place, laid out like a sprite sheet.

  • m: the imported map's number.

Returns the picture's number, or 0 if the map brought no tiles with it.

imap_used

int imap_used(int m, int sprite)

Tells you whether the imported map's tiles fill a sprite, so you know which places in the sheet they take.

  • m: the imported map's number.
  • sprite: the sprite number to ask about, from 0 to 255.

Returns 1 if the map's tiles fill that sprite, or 0 if they don't.

imap_notes

int imap_notes(int m)

Tells you how many notes the import left, about what was left out or changed. Read each one with imap_note.

  • m: the imported map's number.

Returns how many notes there are.

imap_note

int imap_note(int m, int i, char *buf, int size)

Gives you one of the import's notes, as text you can show the person.

  • m: the imported map's number.
  • i: which note, counting from 0.
  • buf: where to put the note's text.
  • size: how many bytes buf holds. A note that's too long is cut short to fit.

Returns the whole note's length, or -1 if there's no note i.

imap_free

void imap_free(int m)

Lets go of an imported map you've finished with. A picture you got from imap_picture stays until you freepicture it.

  • m: the imported map's number.

C reference: input, sound and the system

These are the calls in #include <macaw.h> for the keyboard and mouse, sound and music, files, the network, the system and saved passwords. They work like the Lua calls of the same names in Input and sound, Networking and Files and the system, and C explains how text, lists and your own functions pass between you and them. Keys are named by text, like "left", "space" or "z". None of the network calls waits: each does what it can straight away, so call it again from _update until it's done.

The keyboard and mouse

btn

int btn(const char *key)

Tells you whether a key is held down right now. Use it for movement and anything else that carries on while the key is held.

  • key: the key's name, like "left", "space", "a" or "f1". A name it doesn't know stops the program with an error.

Returns 1 while the key is held down, or 0. It's always 0 while your window isn't the one in front.

btnp

int btnp(const char *key)

Tells you whether a key was pressed this frame. It's true again every so often while the key is held, the way typing repeats, so use it for menus and jumps.

  • key: the key's name, as for btn.

Returns 1 in the frame the key goes down or repeats, or 0.

mouse

void mouse(int *x, int *y, int *buttons)

Finds out where the pointer is and which mouse buttons are held down.

  • x: where to put the pointer's x in your window, in its own pixels: pass the address of an int, like &x, or NULL.
  • y: where to put the pointer's y in your window, the same way. Both can be outside the window, even negative.
  • buttons: where to put the buttons held: 1 for left, 2 for right and 4 for middle, added together. It's 0 over another window.

textinput

int textinput(char *buf, int size)

Gives you the characters typed this frame, for a text box or a name. Use btn and btnp for game controls instead.

  • buf: where the typed text goes.
  • size: how many bytes buf holds. Text that doesn't fit is cut short.

Returns how many bytes were typed, even if buf was too small for them all. It's 0 in most frames.

keysp

int keysp(void)

Makes a list of every key that went down or repeated this frame. Read the names from it with keyspname.

It takes nothing.

Returns how many keys are in the list.

keyspname

int keyspname(int i, char *buf, int size)

Gives the name of one key in the list keysp made, so you can see what was pressed without testing every key.

  • i: which key in the list, from 0 to one less than keysp() returned.
  • buf: where the key's name goes, like "left" or "q".
  • size: how many bytes buf holds. A name that doesn't fit is cut short.

Returns the name's whole length, or -1 if there's no key i in the list.

Sound

sfx

void sfx(const char *name)

Plays one of Macaw OS's ready-made sound effects. They play on voice 4 and sometimes 3 ("chime" uses all four), and cut off whatever you're playing there.

  • name: the effect: "blip", "coin", "jump", "hit", "lose", "squawk", "rawk", "chime" or "shutter". Any other name stops the program with an error.

play

void play(int voice, const char *note, int ms)

Plays a musical note on one of the four sound-effect voices, as a square wave at half volume.

  • voice: which voice plays it, from 1 to 4. A new sound on a voice stops the one before.
  • note: the note's name, like "C4" (middle C), "F#3" or "Bb5". A name it can't read stops the program with an error.
  • ms: how long it lasts, in milliseconds.

tone

void tone(int voice, double hz, int ms)

Plays a plain beep at any pitch on one of the four sound-effect voices, as a square wave at half volume.

  • voice: which voice plays it, from 1 to 4. A new sound on a voice stops the one before. Other numbers play nothing.
  • hz: the pitch in hertz: 440 is the A above middle C.
  • ms: how long it lasts, in milliseconds.

note

double note(const char *name)

Works out the pitch of a named note, to give to tone.

  • name: the note's name, like "A4", "C#5" or "Eb3", in capitals or small letters.

Returns the note's pitch in hertz (note("A4") is 440), or 0 if it can't read the name.

stop

void stop(void)

Stops whatever the four sound-effect voices are playing. A song on the music chip carries on.

It takes nothing.

music

void music(const char *path)

Plays a song made in Tracker from its start, or stops it. For songs made in the Music app, use playsong.

  • path: the song file's path. A path without / at the start is from your program's folder. NULL stops the music.

Songs and the music chip

playsong

int playsong(const char *path, int loop)

Plays a song file on the music chip, from the Music app or Tracker. The chip has voices of its own, so sound effects can play at the same time.

  • path: the song file's path, like "/home/music/island.song". A path without / at the start is from your program's folder.
  • loop: 1 to let it loop until you stop it, or 0 to play it once.

Returns 1 if the song started, or 0 if it couldn't be read.

stopsong

void stopsong(void)

Stops the song that's playing.

It takes nothing.

loadsong

int loadsong(const char *path)

Reads a song file once, so you can play it many times with playloadedsong without reading the file again.

  • path: the song file's path. A path without / at the start is from your program's folder.

Returns a number for the song, or 0 if it couldn't be read.

playloadedsong

int playloadedsong(int song, int loop)

Plays a song you loaded with loadsong.

  • song: the number loadsong gave you. A number that isn't a song stops the program with an error.
  • loop: 1 to let it loop until you stop it, or 0 to play it once.

Returns 1 if the song started, or 0 if it couldn't.

freesong

void freesong(int song)

Lets go of a song you loaded, once you won't play it again. If it's playing, it carries on.

  • song: the song's number. A number that isn't a song is ignored.

music_volume

void music_volume(double v)

Sets how loud the music chip is, for songs and for music_note. There's one chip, so this changes the music of every program.

  • v: the volume, from 0 (silent) to 1 (full). Numbers outside that are kept to it.

music_note

void music_note(int channel, int instrument, double n, double volume)

Plays one note on the music chip straight away, with an instrument from the last song played. Use it for music that answers what the player does.

  • channel: which of the chip's 16 channels plays it, from 0 to 15. A new note on a channel takes over from the last.
  • instrument: which of the song's instruments plays it, from 0 to 15. If no song has set it up, nothing plays.
  • n: the note's number, as notenumber gives it: 49 is C-4, middle C. Fractions fall between two notes.
  • volume: how loud, from 0 to 1. Any number below 0 means 1.

music_release

void music_release(int channel)

Lets go of the note playing on a channel, so it fades away the way its instrument does.

  • channel: the channel, from 0 to 15.

notenumber

int notenumber(const char *name)

Turns a note's name, written the way Tracker writes it, into its number.

  • name: the note, like "C-4", "F#3" or "A-5": a letter, - or #, then the octave. "---" is no note and "===" is a note-off.

Returns the note's number ("C-4" is 49, and each semitone up is 1 more), 97 for "===", or 0 for "---" or a name it can't read.

notename

int notename(int n, char *buf, int size)

Turns a note's number back into its name, the way Tracker writes it.

  • n: the note's number: 49 is C-4. 0 gives "---" and 97 gives "===".
  • buf: where the name goes, like "C-4".
  • size: how many bytes buf holds. A name that doesn't fit is cut short.

Returns the name's whole length, which is 3 for the notes from 0 to 97.

Time

now

double now(void)

Tells you how long Macaw OS has been running. Take one reading from another to time something.

It takes nothing.

Returns the seconds since Macaw OS started, with fractions down to a millisecond.

Folders and files

fileexists

int fileexists(const char *path)

Checks whether there's a file or folder at a path.

  • path: the path to check. A path without / at the start is from your program's folder.

Returns 1 if there's a file or folder there, or 0.

isfolder

int isfolder(const char *path)

Checks whether a path is a folder.

  • path: the path to check. A path without / at the start is from your program's folder.

Returns 1 if it's a folder, or 0 if it's a file or isn't there.

makefolder

int makefolder(const char *path)

Makes a new folder. It makes one at a time, so the folder it goes in has to be there already.

  • path: the new folder's path. A path without / at the start is from your program's folder.

Returns 1 if it made the folder, or 0 if it couldn't, for example because it's already there.

listfolder

int listfolder(const char *path, int index, char *name, int size)

Gives the name of one thing in a folder. Call it with index 0, 1, 2 and so on until it returns 0, to go through them all.

  • path: the folder. A path without / at the start is from your program's folder.
  • index: which thing, counting from 0. Folders come first, then files, each in order of name.
  • name: where its name goes. A folder's name has no / on the end, so use isfolder to tell.
  • size: how many bytes name holds. A name that doesn't fit is cut short.

Returns 1 if there's a thing at index, or 0 once there's nothing left or the folder isn't there.

fileinfo

int fileinfo(const char *path, double *size, double *modified, int *isfolder)

Finds out how big a file is, when it last changed and whether it's a folder.

  • path: the file or folder. A path without / at the start is from your program's folder.
  • size: where to put its size in bytes: pass the address of a double, like &size, or NULL.
  • modified: where to put when it last changed, in seconds since 1970: the address of a double, or NULL.
  • isfolder: where to put 1 if it's a folder or 0 if not: the address of an int, or NULL.

Returns 1 if it's there, or 0 if it isn't (and then nothing is written).

Markdown

markdown

int markdown(const char *text, char *html, int size, char *title, int tsize)

Turns Markdown into HTML, and gives you its first heading to use as a title.

  • text: the Markdown to turn into HTML.
  • html: where the HTML goes.
  • size: how many bytes html holds. HTML that doesn't fit is cut short.
  • title: where the first heading's text goes (empty if there isn't one), or NULL if you don't need it.
  • tsize: how many bytes title holds, or 0 with NULL.

Returns the whole HTML's length. If it's size or more, html was cut short.

The clipboard

getclipboard

int getclipboard(char *buf, int size)

Gets the text on the clipboard, the one every Macaw OS program shares with the computer underneath.

  • buf: where the clipboard's text goes.
  • size: how many bytes buf holds. Text that doesn't fit is cut short.

Returns the whole text's length, or 0 if the clipboard is empty.

setclipboard

void setclipboard(const char *s)

Puts text on the clipboard, for every Macaw OS program and the computer underneath.

  • s: the text to put there.

The desktop

openpath

int openpath(const char *path, const char **args, int n)

Opens a file or program as double-clicking it would: a program runs, and a document opens in its program.

  • path: what to open. A path without / at the start is from your program's folder.
  • args: an array of text to give a program you open, which it gets as ARGS, or NULL for none.
  • n: how many there are in args, or 0 for none.

Returns 1 if it opened, or 0 if it couldn't.

getpref

int getpref(const char *key, char *buf, int size)

Reads one of the system preferences, the settings in System Preferences, as text.

  • key: the setting's name, like "volume" or "clock_24h".
  • buf: where its value goes: a number like "0.8", "true" or "false", or the setting's own text.
  • size: how many bytes buf holds. A value that doesn't fit is cut short.

Returns the value's whole length, or -1 if there's no setting called key.

setpref

int setpref(const char *key, const char *value)

Changes one of the system preferences. The change is saved, so it stays after Macaw OS starts again.

  • key: the setting's name. Programs can't change the screen's (display_...): ask with display_request instead.
  • value: the new value as text: a number, "true" or "false" (or "1" or "0"), or text. NULL puts it back as it starts.

Returns 1 if it changed, or 0 if there's no such setting or the text doesn't suit it.

The network

net_online

int net_online(void)

Checks whether Macaw OS is dialled in to the Macaw network.

It takes nothing.

Returns 1 while it's online, or 0.

net_dial

void net_dial(void)

Asks Macaw OS to go online: Dial-Up opens and dials, unless it's online already. It doesn't wait, so check net_online in _update to see when the line is up.

It takes nothing.

net_connect

int net_connect(const char *host, int port)

Starts a connection to a computer on the Macaw network. It doesn't wait: check net_status to see when it's open.

  • host: the name to connect to, like "macaw.com", "isp.macaw" for the ISP, or "name.macaw" for someone dialled in.
  • port: the port to connect to on that computer, like 80 for web pages.

Returns a number for the connection, or 0 if Macaw OS isn't online. Then it also opens Dial-Up to dial.

net_send

int net_send(int s, const void *data, int n)

Sends bytes down a connection. Anything you send while it's still connecting goes once it's open.

  • s: the connection's number, from net_connect or net_accept.
  • data: the bytes to send, such as a string or an array.
  • n: how many bytes to send. For a string, that's strlen(data).

Returns how many bytes it took to send, or 0 if the connection has closed.

net_readline

int net_readline(int s, char *buf, int size)

Takes one whole line that has arrived on a connection. Use it for text that comes a line at a time, like a chat or a web server's answer.

  • s: the connection's number.
  • buf: where the line goes, without its line ending (\n or \r\n).
  • size: how many bytes buf holds. The rest of a line that doesn't fit is lost.

Returns the line's whole length, or -1 if no whole line has arrived yet. Once the other end closes, a last line without an ending comes too.

net_read

int net_read(int s, void *buf, int n)

Takes exactly n bytes from a connection, once that many have arrived. Use it when you know how much is coming.

  • s: the connection's number.
  • buf: where the bytes go. It has to hold at least n bytes.
  • n: how many bytes to take.

Returns n, or -1 if fewer than n bytes have arrived so far (and then it takes none).

net_receive

int net_receive(int s, void *buf, int size)

Takes whatever has arrived on a connection so far, up to size bytes.

  • s: the connection's number.
  • buf: where the bytes go. They don't end with a 0, so use the number it returns.
  • size: the most bytes to take: how many buf holds. Any more wait for the next call.

Returns how many bytes it took, which is 0 if nothing has arrived.

net_status

int net_status(int s)

Tells you how a connection is getting on.

  • s: the connection's number.

Returns 0 while it's connecting, 1 when it's open (or closed with some still to read), 2 once it's closed, or 3 if it went wrong.

net_peer

int net_peer(int s, char *buf, int size)

Tells you who is at the other end of a connection.

  • s: the connection's number.
  • buf: where their address goes: the host you connected to, or the address of someone who connected to you.
  • size: how many bytes buf holds. An address that doesn't fit is cut short.

Returns the address's whole length.

net_close

void net_close(int s)

Closes a connection, or stops a listener. Everything closes by itself when your window does.

  • s: the number of the connection or listener. A number that isn't one is ignored.

net_listen

int net_listen(int port)

Starts listening on a port, so other people on the Macaw network can connect to you at yourname.macaw.

  • port: the port to listen on, like 7000. 0 picks a free one from 40000 to 60000, and net_port says which.

Returns a number for the listener, or 0 if it couldn't, because Macaw OS isn't online or the port is in use.

net_accept

int net_accept(int listener)

Takes the next person who has connected to your listener. It doesn't wait, so call it from _update.

  • listener: the number net_listen gave you.

Returns a number for the new connection, or 0 if nobody is waiting.

net_port

int net_port(int listener)

Tells you which port a listener is on, which you need after net_listen(0).

  • listener: the number net_listen gave you.

Returns the port's number.

The system

platform

int platform(char *buf, int size)

Tells you what Macaw OS is running on.

  • buf: where the name goes: "windows", "web", "emac" (a PowerPC Mac), "mac9" (Mac OS 9), "mac" or "unix".
  • size: how many bytes buf holds. A name that doesn't fit is cut short.

Returns the name's whole length.

ismac

int ismac(void)

Checks whether Macaw OS is running on any kind of Mac.

It takes nothing.

Returns 1 on a Mac ("emac", "mac9" or "mac"), or 0.

modkey

int modkey(char *buf, int size)

Gives the name of the key people hold for shortcuts, so your help text can name the right one.

  • buf: where the name goes: "Cmd" on a Mac, "Ctrl" everywhere else.
  • size: how many bytes buf holds. A name that doesn't fit is cut short.

Returns the name's whole length.

memory

void memory(double *mine, double *used, double *total)

Tells you how much memory your program has and how much the machine has.

  • mine: where to put how many bytes your program has asked for: the address of a double, or NULL.
  • used: where to put how many bytes every program together is using: a double's address, or NULL.
  • total: where to put how many bytes the machine has (512 MB): a double's address, or NULL.

sys_version

int sys_version(char *buf, int size)

Tells you which version of Macaw OS this is.

  • buf: where the version goes, as text.
  • size: how many bytes buf holds. Text that doesn't fit is cut short.

Returns the version's whole length.

sys_fps

double sys_fps(void)

Tells you how fast Macaw OS is drawing right now.

It takes nothing.

Returns the frame rate, in frames a second.

sys_display

void sys_display(int *w, int *h, int *colours)

Finds out the size of the whole screen and how many colours it shows.

  • w: where to put the screen's width in pixels: pass the address of an int, like &w, or NULL.
  • h: where to put the screen's height in pixels, the same way.
  • colours: where to put its colours: 8, 256 or COLORS_THOUSANDS (32768).

sys_volume

double sys_volume(double v)

Reads the volume of all sound in Macaw OS, and can change it. A change is for the whole system, until someone sets it in System Preferences or Macaw OS starts again.

  • v: the new volume, from 0 to 1. Any number below 0 leaves it as it is, so sys_volume(-1) only reads it.

Returns the volume now, from 0 to 1.

sys_screenshot

int sys_screenshot(const char *path)

Saves a picture of the whole screen as a PNG file.

  • path: where to save it, like "/home/shot.png". A path without / at the start is from your program's folder.

Returns 1 if it saved the picture, or 0 if it couldn't.

sys_title

void sys_title(const char *s)

Sets the title of the window Macaw OS runs in on the computer underneath. It does nothing on Mac OS 9.

  • s: the new title.

sys_cursor

void sys_cursor(int on)

Shows or hides the computer's own pointer over Macaw OS. It starts hidden, because Macaw OS draws its own, and it stays as you leave it after your program quits.

  • on: 1 to show it, or 0 to hide it.

sys_clipboard

int sys_clipboard(char *buf, int size)

Gets the text on the computer's own clipboard. getclipboard is usually better: it also has what Macaw OS programs copy.

  • buf: where the clipboard's text goes.
  • size: how many bytes buf holds. Text that doesn't fit is cut short.

Returns the text's whole length, or -1 if there's no text on it.

sys_setclipboard

void sys_setclipboard(const char *s)

Puts text on the computer's own clipboard. setclipboard is usually better, because every Macaw OS program can paste it too.

  • s: the text to put there.

Saved passwords (Nestchain)

nest_set

int nest_set(const char *service, const char *account, const char *password, const char *label)

Saves a password in your program's own keychain, which no other program can read. Saving another for the same service and account replaces it.

  • service: what the password is for, like "mygame.macaw".
  • account: whose password it is, like a user name. NULL is the same as "".
  • password: the password to save.
  • label: a note to keep with it, shown in the list, or NULL to keep the note it had.

Returns 1 if it was saved, or 0 if it wasn't.

nest_get

int nest_get(const char *service, const char *account, char *buf, int size)

Reads back a password your program saved with nest_set.

  • service: what the password is for.
  • account: whose password it is. NULL is the same as "".
  • buf: where the password goes. Never print it or save it anywhere else.
  • size: how many bytes buf holds. A password that doesn't fit is cut short.

Returns the password's whole length, or -1 if there isn't one saved.

nest_has

int nest_has(const char *service, const char *account)

Checks whether your program has a password saved, without reading it.

  • service: what the password is for.
  • account: whose password it is. NULL is the same as "".

Returns 1 if there's one saved, or 0.

nest_remove

int nest_remove(const char *service, const char *account)

Forgets a password your program saved.

  • service: what the password is for.
  • account: whose password it is. NULL is the same as "".

Returns 1 if it forgot one, or 0 if there wasn't one.

nest_list

int nest_list(const char *service)

Makes a list of what your program has saved, in order of service and then account. Read it with nest_listitem, nest_listlabel and nest_listchanged. It never holds the passwords.

  • service: only list the ones for this service, or NULL to list them all.

Returns how many are in the list.

nest_listitem

int nest_listitem(int i, char *service, int ssize, char *account, int asize)

Gives the service and account of one entry in the list nest_list made.

  • i: which entry, from 0.
  • service: where its service goes.
  • ssize: how many bytes service holds. Text that doesn't fit is cut short.
  • account: where its account goes.
  • asize: how many bytes account holds. Text that doesn't fit is cut short.

Returns 1 if there's an entry i in the list, or 0.

nest_listlabel

int nest_listlabel(int i, char *buf, int size)

Gives the note kept with one entry in the list nest_list made.

  • i: which entry, from 0.
  • buf: where its note goes. It's empty if it has none.
  • size: how many bytes buf holds. A note that doesn't fit is cut short.

Returns the note's whole length, or -1 if there's no entry i.

nest_listchanged

double nest_listchanged(int i)

Tells you when one entry in the list nest_list made was last saved.

  • i: which entry, from 0.

Returns when it was saved, in seconds since 1970, or 0 if there's no entry i.

nest_request

void nest_request(const char *service, const char *account, void (*fn)(const char *password, const char *why))

Asks the person for one of the system's own passwords, such as Dial-Up's. They choose Allow Once, Always Allow or Don't Allow, then fn gets the answer. If there's no such password, or they've chosen Always Allow before, fn is called straight away.

  • service: what the password is for.
  • account: whose password it is. NULL is the same as "".
  • fn: your function for the answer: password (NULL if you can't have it), and why, "denied" or "none" then. Copy the password to keep it.

nest_choose

void nest_choose(void (*fn)(const char *password, const char *service, const char *account))

Lets the person pick one of their saved passwords for your program. If they cancel, fn isn't called.

  • fn: your function, called with the password they picked and its service and account. Copy them to keep them.

nest_keep

int nest_keep(const char *password, const char *service, const char *account, void (*fn)(const char *service, const char *account))

Offers to save a password the person typed in the system's keychain: a box asks them what it's for. Your program can have it back later with nest_request, without them being asked.

  • password: the password to save.
  • service: what it's for, to fill in the box with, or NULL to let the person say.
  • account: whose it is, to fill in the box with, or NULL to let the person say.
  • fn: your function, called with the service and account once it's saved, or NULL. It isn't called if they cancel.

Returns 1 if the box opened, or 0 if it didn't, for example because password is empty.

Handy maths for games

rnd

double rnd(double n)

Gives a random number, for dice, enemy moves and anything else that should change each time.

  • n: the top of the range. A number that isn't a real one (NaN or infinite) counts as 0.

Returns a random number from 0 up to, but not including, n, with fractions. flr(rnd(6)) + 1 rolls a dice.

mid

double mid(double a, double b, double c)

Gives the middle one of three numbers. With a low and a high limit either side, it keeps a number between them.

  • a: the first number.
  • b: the second number.
  • c: the third number.

Returns whichever of the three is between the other two.

clamp

double clamp(double v, double lo, double hi)

Keeps a number between two limits, like a player's position inside the screen.

  • v: the number to keep in range.
  • lo: the lowest it may be.
  • hi: the highest it may be.

Returns v, or lo if v is below it, or hi if v is above it.

sgn

int sgn(double n)

Tells you whether a number is below 0, for things like which way something faces.

  • n: the number to look at.

Returns -1 if n is below 0, or 1 otherwise. So sgn(0) is 1, not 0.

lerp

double lerp(double a, double b, double t)

Finds the number part of the way from one number to another, for smooth movement and fades.

  • a: where it starts, when t is 0.
  • b: where it ends, when t is 1.
  • t: how far along, from 0 to 1: 0.5 is halfway. Numbers outside that go past a or b.

Returns a + (b - a) * t.

flr

double flr(double n)

Rounds a number down to a whole number, as floor does: flr(2.7) is 2 and flr(-2.5) is -3.

  • n: the number to round. A number that isn't a real one (NaN or infinite) gives 0.

Returns the biggest whole number that isn't more than n, as a double.

C reference: 3D

These calls come from #include <macaw3d.h>. Each thing in a scene (a camera, a light, a cube, a terrain) is a number, and 0 means none. There are two ways to do 3D: make a scene once and let render() draw it every frame, or make meshes and draw them yourself with your own camera. The 3D page explains both, and C shows how Lua's calls become C ones.

Making things

newcamera

int newcamera(void)

Makes a camera to look through. It starts at 0, 0, 0 looking along z, sees 80 degrees across and clears the picture to NIGHT. The first camera you make is the one render(0) uses.

It takes nothing.

Returns the new camera's number.

newlight

int newlight(const char *kind, double radius, double strength)

Makes a light. A sun lights everything from far away and shines the way it faces, so turn it with rotate3d. A lamp lights things near where you put it.

  • kind: "sun" or "point" (a lamp). NULL makes a sun.
  • radius: for a lamp, how far its light reaches, in world units. 0 or less: 8.
  • strength: how bright it is. 0 or less: 0.75 for a sun, 1.2 for a lamp.

Returns the new light's number.

Shapes, terrain and models

newcube

int newcube(int texture, double tiles)

Makes a cube 2 units across, from -1 to 1 each way around its position. Use scale3d to change its size.

  • texture: the picture to cover it with. 0: plain light grey.
  • tiles: how many times the texture repeats across each face. 0 or less: once.

Returns the new cube's number.

newsphere

int newsphere(int segments, int texture)

Makes a ball 2 units across (a radius of 1).

  • segments: how many bands it has from top to bottom, with twice as many round it. 0 or less: 12.
  • texture: the picture to wrap round it. 0: plain light grey.

Returns the new ball's number.

newcylinder

int newcylinder(int segments, int texture, int capped)

Makes a cylinder with a radius of 1, from y = -1 to y = 1.

  • segments: how many flat sides it has round it. 0 or less: 16.
  • texture: the picture to wrap round it. 0: plain light grey.
  • capped: 1 to close the ends with flat discs, 0 to leave it an open tube.

Returns the new cylinder's number.

newcone

int newcone(int segments, int texture)

Makes a cone with its point at y = 1 and a closed, round base of radius 1 at y = -1.

  • segments: how many flat sides it has round it. 0 or less: 16.
  • texture: the picture to wrap round it. 0: plain light grey.

Returns the new cone's number.

newplane

int newplane(int texture, double tiles)

Makes a flat square 2 units across, lying at y = 0 and facing up. Use it for floors. It can only be seen from above unless you use twosided3d.

  • texture: the picture to cover it with. 0: plain light grey.
  • tiles: how many times the texture repeats across it. 0 or less: once.

Returns the new square's number.

newterrain

int newterrain(int cells, int heightpicture, int texture, double tiles)

Makes hills from a picture. The terrain goes from -1 to 1 across x and z, with heights from 0 to 1, so scale it up with scale3d.

  • cells: how many squares it has along each side. 0 or less: 32.
  • heightpicture: a picture stretched over it, where brighter colours are higher. 0: flat.
  • texture: the picture to cover it with. 0: plain light grey.
  • tiles: how many times the texture repeats across the whole terrain. 0 or less: cells / 4.

Returns the new terrain's number.

newterrainfn

int newterrainfn(int cells, double (*height)(double u, double v), int texture, double tiles)

Makes hills like newterrain, but your own function works out how high each point is.

  • cells: how many squares it has along each side. 0 or less: 32.
  • height: your function, called once for each corner as the terrain is made. It gets u (across x) and v (along z), each 0 to 1, and returns a height from 0 to 1. NULL: flat.
  • texture: the picture to cover it with. 0: plain light grey.
  • tiles: how many times the texture repeats across the whole terrain. 0 or less: cells / 4.

Returns the new terrain's number.

newmesh

int newmesh(const float *corners, int ncorners, const int *triangles, int ntriangles, const int *textures, int ntextures, const int *texids)

Makes a thing with a shape of your own, built from triangles.

  • corners: an array with 5 floats for each corner: x, y, z, then u and v, which say where on the texture it goes (0 to 1 across).
  • ncorners: how many corners there are (not how many floats).
  • triangles: an array with 3 corner numbers for each triangle, counting from 0. The front is the side its corners go round anticlockwise.
  • ntriangles: how many triangles there are.
  • textures: an array of picture numbers for its textures, or NULL for plain light grey.
  • ntextures: how many pictures are in textures (16 at most are used). 0: plain light grey.
  • texids: an array with one number for each triangle, saying which texture it uses, counting from 0. NULL: all use the first.

Returns the new thing's number.

newmodel

int newmodel(const char *path, const int *textures, int ntextures)

Makes a thing from a model in an .obj file.

  • path: the .obj file. A path that doesn't start with / is in your program's folder.
  • textures: an array of picture numbers, one for each material in the order they first come in the file. NULL: plain light grey.
  • ntextures: how many pictures are in textures. 0: plain light grey.

Returns the new thing's number, or 0 if the file couldn't be read or has no faces.

newsprite

int newsprite(int picture, double height)

Makes a flat picture that always turns to face the camera, for trees and people. Its bottom middle stands at its position, and its width follows the picture's shape. Colour 0 in the picture is see-through.

  • picture: the picture to show.
  • height: how tall it is, in world units. 0 or less: 1.

Returns the new sprite's number.

newpivot

int newpivot(void)

Makes an empty, invisible thing. Parent other things to it with parent3d so they move and turn together.

It takes nothing.

Returns the new pivot's number.

What every thing can do

position3d

void position3d(int e, double x, double y, double z, int global)

Puts a thing at a place. If it has a parent, the place is measured from the parent unless global is 1.

  • e: the thing's number.
  • x: where it goes across, in world units.
  • y: how high it goes.
  • z: where it goes along the third direction, forward into the scene.
  • global: 1 to give a place in the world even if it has a parent, 0 to measure from its parent.

move3d

void move3d(int e, double x, double y, double z)

Moves a thing along the way it's facing, so you can walk a camera forward whichever way it points.

  • e: the thing's number.
  • x: how far to move to its right, in world units (negative: left).
  • y: how far to move up from its own point of view.
  • z: how far to move forward (negative: backward).

translate3d

void translate3d(int e, double x, double y, double z)

Moves a thing along the world's directions, whichever way it's facing. If it has a parent, these are the parent's directions.

  • e: the thing's number.
  • x: how far to move across, in world units.
  • y: how far to move up (negative: down).
  • z: how far to move forward along z.

rotate3d

void rotate3d(int e, double yaw, double pitch, double roll)

Turns a thing to face a particular way, whichever way it faced before.

  • e: the thing's number.
  • yaw: which way round it faces, in degrees. More turns it to the right.
  • pitch: how far it tips, in degrees. More tips its front down.
  • roll: how far it leans to one side, in degrees.

turn3d

void turn3d(int e, double yaw, double pitch, double roll)

Turns a thing by this much from the way it faces now. Call it every frame to keep something spinning.

  • e: the thing's number.
  • yaw: how far to turn it round, in degrees. Positive turns right.
  • pitch: how far to tip it, in degrees. Positive tips its front down.
  • roll: how far to lean it to one side, in degrees.

point3d

void point3d(int e, int other)

Turns a thing to face another thing, and takes away any lean.

  • e: the number of the thing to turn.
  • other: the number of the thing it should face.

pointat3d

void pointat3d(int e, double x, double y, double z)

Turns a thing to face a place in the world, and takes away any lean.

  • e: the thing's number.
  • x: the place's position across, in world units.
  • y: the place's height.
  • z: the place's position along z.

scale3d

void scale3d(int e, double sx, double sy, double sz)

Sets a thing's size. 1 is the size it was made at, and shapes start 2 units across.

  • e: the thing's number.
  • sx: how much to stretch it across its own x direction (2 is twice as wide).
  • sy: how much to stretch it up its own y direction.
  • sz: how much to stretch it along its own z direction.

parent3d

void parent3d(int e, int parent)

Makes a thing move, turn and grow with another, like a moon going round a planet. It stays where it is in the world when you do it.

  • e: the number of the thing to attach.
  • parent: the number of the thing it moves with. 0: on its own again.

pos3d

void pos3d(int e, double *x, double *y, double *z)

Finds out where a thing is in the world, counting any parents.

  • e: the thing's number.
  • x: where to put its x: pass the address of a double, like &x (or NULL).
  • y: where to put its height: the address of a double, like &y.
  • z: where to put its z: the address of a double, like &z.

forward3d

void forward3d(int e, double *x, double *y, double *z)

Finds out which way a thing is facing in the world, as a direction 1 unit long.

  • e: the thing's number.
  • x: where to put the direction's x: the address of a double, like &x (or NULL).
  • y: where to put the direction's y (up): the address of a double, like &y.
  • z: where to put the direction's z: the address of a double, like &z.

up3d

void up3d(int e, double *x, double *y, double *z)

Finds out which way a thing's top is facing in the world, as a direction 1 unit long.

  • e: the thing's number.
  • x: where to put the direction's x: the address of a double, like &x (or NULL).
  • y: where to put the direction's y (up): the address of a double, like &y.
  • z: where to put the direction's z: the address of a double, like &z.

dist3d

double dist3d(int e, int other)

Works out how far apart two things are in the world.

  • e: the first thing's number.
  • other: the second thing's number.

Returns the distance between them, in world units.

hide3d

void hide3d(int e)

Stops drawing a thing, and anything parented to it. Hidden things can't be bumped into or clicked on.

  • e: the thing's number.

show3d

void show3d(int e)

Starts drawing a thing again after hide3d.

  • e: the thing's number.

visible3d

int visible3d(int e)

Finds out whether a thing is being drawn.

  • e: the thing's number.

Returns 1 if it's drawn, or 0 if it or anything it's parented to is hidden.

texture3d

void texture3d(int e, int picture, int n)

Changes the picture a thing is covered with. It doesn't change a sprite's picture.

  • e: the thing's number.
  • picture: the new picture.
  • n: which of its textures to change, counting from 0. Use 0 unless it's a model with several.

color3d

void color3d(int e, int colour)

Paints a thing all one colour, in place of its texture. On a model with several textures, only the first changes.

  • e: the thing's number.
  • colour: a colour number, such as ORANGE.

fullbright3d

void fullbright3d(int e, int on)

Stops light and shade changing how a thing looks, for lamps, the sky and glowing things.

  • e: the thing's number.
  • on: 1 to draw it at full brightness, 0 to light it as usual again.

twosided3d

void twosided3d(int e, int on)

Draws the back of each face as well as the front, for flat things seen from both sides.

  • e: the thing's number.
  • on: 1 to draw both sides, 0 to draw only the front again.

free3d

void free3d(int e)

Takes a thing out of the scene for good. Anything parented to it goes too.

  • e: the thing's number. Don't use it again afterwards.

height3d

int height3d(int terrain, double x, double z, double *height)

Finds how high the ground of a terrain is at a place, so you can keep things standing on it. It counts the terrain's position and size, but not any turning.

  • terrain: the terrain's number.
  • x: the place's position across, in world units.
  • z: the place's position along z.
  • height: where to put the ground's height: pass the address of a double, like &h.

Returns 1 if the place is over the terrain, or 0 if it isn't (and nothing is written).

collide3d

void collide3d(int e, int type, double radius)

Gives a thing a collision type, so collisions and updateworld can make it bump into things. When it moves, it's tested as a ball.

  • e: the thing's number.
  • type: any number you choose for this kind of thing, such as 1 for the player and 2 for walls.
  • radius: the radius of its ball, in world units. 0 or less: the one it had, or 1.

hitcount3d

int hitcount3d(int e)

Finds out how many things a thing bumped into during the last updateworld().

  • e: the thing's number.

Returns how many hits it has. Get each one with gethit3d.

gethit3d

int gethit3d(int e, int i, hit3d *hit)

Gets one of the things a thing bumped into during the last updateworld(): the thing, where it touched, and the way the surface there faces.

  • e: the thing's number.
  • i: which hit, from 0 to hitcount3d(e) - 1.
  • hit: where to put the hit: pass the address of a hit3d, like &hit. Its dist is 0.

Returns 1 if there was a hit i, or 0 if there wasn't.

pickable3d

void pickable3d(int e, const char *shape)

Lets rays and the mouse hit a thing, so pick and campick3d can find it.

  • e: the thing's number.
  • shape: "mesh" (its exact shape), "sphere" (a ball round it), "box" (tested exactly, like "mesh") or "none" to stop it. NULL: "mesh".

Cameras

fov3d

void fov3d(int camera, double degrees)

Sets how wide a camera's view is. A small angle zooms in, a big one sees more.

  • camera: the camera's number.
  • degrees: the angle the camera sees across the picture's width. It starts at 80, and 10 to 170 work.

clscolor3d

void clscolor3d(int camera, int colour)

Sets the colour the picture is cleared to before a camera draws, such as the sky.

  • camera: the camera's number.
  • colour: a colour number, such as SKY. -1: don't clear, and draw over what's there.

camfog3d

void camfog3d(int camera, double near, double far, int colour)

Adds fog to what a camera sees, so far-off things fade into a colour.

  • camera: the camera's number.
  • near: how far from the camera the fog starts, in world units. Less than 0: no fog.
  • far: how far away the fog becomes solid, in world units.
  • colour: the fog's colour number. -1: the camera's clear colour (or NIGHT if it doesn't clear).

camproject3d

int camproject3d(int camera, double x, double y, double z, double *sx, double *sy, double *dist)

Works out where a place in the world shows up in a camera's picture, for putting labels over things. It uses the size of the last picture the camera drew (320 by 200 before it has drawn one).

  • camera: the camera's number.
  • x: the place's position across, in world units.
  • y: the place's height.
  • z: the place's position along z.
  • sx: where to put how far across the picture it is, in pixels: the address of a double, like &sx.
  • sy: where to put how far down the picture it is, in pixels: the address of a double, like &sy.
  • dist: where to put how far ahead of the camera it is, in world units: the address of a double.

Returns 1 if the place is in front of the camera, or 0 if it's behind (and nothing is written).

campick3d

int campick3d(int camera, double x, double y, double max, hit3d *hit)

Finds the pickable thing under a point in a camera's picture, such as the mouse pointer.

  • camera: the camera's number.
  • x: the point's distance from the picture's left edge, in pixels.
  • y: the point's distance from the picture's top edge, in pixels.
  • max: how far away to look, in world units. 0 or less: no limit.
  • hit: where to put what was hit: pass the address of a hit3d, like &hit (or NULL).

Returns the number of the thing under the point, or 0 if there's nothing there.

The scene

render

void render(int camera)

Draws the whole scene through a camera, into the window (or the picture you're drawing into). Call it in _draw.

  • camera: the camera's number. 0: the first camera you made.

updateworld

void updateworld(void)

Works out collisions for everything with a collision type: things that ran into something are pushed back out, and their hits are noted. Call it each frame after you move things.

It takes nothing.

collisions

void collisions(int a, int b, const char *shape, const char *response)

Makes things of one collision type bump into things of another.

  • a: the type of the things that move and bump, as given to collide3d.
  • b: the type of the things they bump into.
  • shape: how the b things are tested: "mesh" (exactly), "box" or "sphere". NULL: "mesh".
  • response: "slide" to slide along what they hit, or "stop" to stop. NULL: "slide".

resetcollisions

void resetcollisions(int e)

Forgets where a thing was. Call it after you move something a long way in one go, so it doesn't collide with everything in between.

  • e: the thing's number.

pick

int pick(double ox, double oy, double oz, double dx, double dy, double dz, double max, hit3d *hit)

Finds the nearest pickable thing along a ray, such as a line of sight or a shot.

  • ox: where the ray starts across, in world units.
  • oy: the height the ray starts at.
  • oz: where the ray starts along z.
  • dx: the across part of the ray's direction. It can be any length.
  • dy: the up part of the ray's direction.
  • dz: the z part of the ray's direction.
  • max: how far along the ray to look, in world units. 0 or less: no limit.
  • hit: where to put what was hit: pass the address of a hit3d, like &hit (or NULL).

Returns the number of the thing it hit, or 0 if it hit nothing.

ambient

void ambient(double level)

Sets how bright the light is everywhere in the scene, even where no light shines.

  • level: 0 for none, up to 1 for full brightness. It starts at 0.35.

clearworld

void clearworld(void)

Throws the whole scene away. The next thing you make starts a new, empty one, so don't use the old numbers again.

It takes nothing.

Meshes you draw yourself

clear3d

void clear3d(int colour)

Starts a frame of meshes: it clears the depth buffer, and the picture too if you give a colour.

  • colour: the colour number to clear the picture to. -1: clear only the depth buffer.

camera3d

void camera3d(double x, double y, double z, double yaw, double pitch, double fov)

Sets where the camera for meshes is and which way it looks.

  • x: the camera's position across, in world units.
  • y: the camera's height.
  • z: the camera's position along z.
  • yaw: which way round it looks, in degrees. More turns it right.
  • pitch: how far it looks up, in degrees (unlike things, positive is up).
  • fov: the angle it sees across the picture's width, in degrees, kept to 10 to 170. 0 or less: 90.

light3d

void light3d(double dx, double dy, double dz, double sun, double amb)

Sets the sun for meshes: the way its light travels and how strong it is, and the light everywhere.

  • dx: the across part of the way sunlight travels. The direction can be any length.
  • dy: the up part of the way sunlight travels (negative shines down).
  • dz: the z part of the way sunlight travels.
  • sun: how strong the sun is. Less than 0: 0.75.
  • amb: how bright the light is everywhere, from 0 to 1. Less than 0: 0.35.

Lamps, fog and lines

pointlight3d

void pointlight3d(int n, double x, double y, double z, double radius, double strength)

Sets one of the eight lamps for meshes, which lights things near it, fading out at its radius.

  • n: which lamp, from 0 to 7.
  • x: the lamp's position across, in world units.
  • y: the lamp's height.
  • z: the lamp's position along z.
  • radius: how far its light reaches, in world units. 0 turns it off.
  • strength: how bright it is. Less than 0: 1.

fog3d

void fog3d(double near, double far, int colour)

Adds fog to meshes, so far-off things fade into a colour.

  • near: how far from the camera the fog starts, in world units.
  • far: how far away the fog becomes solid, in world units.
  • colour: the fog's colour number.

nofog3d

void nofog3d(void)

Turns the fog off again.

It takes nothing.

project3d

int project3d(double x, double y, double z, double *sx, double *sy, double *dist)

Works out where a place in the world shows up in the picture, seen through camera3d's camera.

  • x: the place's position across, in world units.
  • y: the place's height.
  • z: the place's position along z.
  • sx: where to put how far across the picture it is, in pixels: the address of a double, like &sx.
  • sy: where to put how far down the picture it is, in pixels: the address of a double, like &sy.
  • dist: where to put how far ahead of the camera it is, in world units: the address of a double.

Returns 1 if the place is in front of the camera, or 0 if it's behind (and nothing is written).

line3d

void line3d(double x0, double y0, double z0, double x1, double y1, double z1, int colour, int thick)

Draws a line between two places in the world, seen through camera3d's camera, over the picture. It isn't hidden behind things, and the part behind the camera is cut off. Use it for outlines and markers.

  • x0: where the line starts across, in world units.
  • y0: the height the line starts at.
  • z0: where the line starts along z.
  • x1: where the line ends across.
  • y1: the height the line ends at.
  • z1: where the line ends along z.
  • colour: the line's colour number.
  • thick: 1 for a line two pixels wide, 0 for one pixel.

stats3d

int stats3d(void)

Finds out how much 3D drawing there was this frame, for checking your program's speed.

It takes nothing.

Returns how many triangles were drawn since the last clear3d.

Making meshes

cube3d

int cube3d(double w, double h, double d, int texture, double tiles)

Makes a box mesh, seen from outside, centred on 0, 0, 0.

  • w: how wide it is across x, in world units.
  • h: how tall it is.
  • d: how deep it is along z.
  • texture: the picture on every face. Give a real picture: with 0 nothing is drawn.
  • tiles: how many times the texture repeats across each face. 0: once for every unit. Less than 0: once a face.

Returns the new mesh's number.

cube3dsides

int cube3dsides(double w, double h, double d, int sides, int top, int bottom, double tiles)

Makes a box mesh like cube3d, with different pictures on its sides, top and bottom.

  • w: how wide it is across x, in world units.
  • h: how tall it is.
  • d: how deep it is along z.
  • sides: the picture on its four sides.
  • top: the picture on top. 0: the sides' picture.
  • bottom: the picture underneath. 0: the top's picture.
  • tiles: how many times the textures repeat across each face. 0: once for every unit. Less than 0: once a face.

Returns the new mesh's number.

room3d

int room3d(double w, double h, double d, int floor, int walls, int ceiling, double tiles)

Makes the inside of a box, for standing in. It's centred on 0, 0, 0, so its floor is at y = -h / 2.

  • w: how wide it is across x, in world units.
  • h: how tall it is.
  • d: how deep it is along z.
  • floor: the floor's picture.
  • walls: the walls' picture.
  • ceiling: the ceiling's picture. 0: the walls' picture.
  • tiles: how many times the textures repeat across each face. 0 or less: once for every unit.

Returns the new mesh's number.

loadobj

int loadobj(const char *path, const int *textures, int ntextures)

Makes a mesh from a model in an .obj file.

  • path: the .obj file. A path that doesn't start with / is in your program's folder.
  • textures: an array of picture numbers, one for each material in the order they first come in the file. NULL: plain light grey.
  • ntextures: how many pictures are in textures. 0: plain light grey.

Returns the new mesh's number, or 0 if the file couldn't be read or has no faces.

mesh3d

int mesh3d(const float *corners, int ncorners, const int *triangles, int ntriangles, const int *textures, int ntextures, const int *texids, const char *options)

Makes a mesh of any shape from your own corners and triangles.

  • corners: an array with 5 floats for each corner: x, y, z, then u and v, which say where on the texture it goes (0 to 1 across).
  • ncorners: how many corners there are (not how many floats).
  • triangles: an array with 3 corner numbers for each triangle, counting from 0. The front is the side its corners go round anticlockwise.
  • ntriangles: how many triangles there are.
  • textures: an array of picture numbers for its textures. Give at least one: without any, nothing is drawn.
  • ntextures: how many pictures are in textures (16 at most are used).
  • texids: an array with one number for each triangle, saying which texture it uses, counting from 0. NULL: all use the first.
  • options: words in a string: "double" draws both sides, "fullbright" ignores the light. NULL or "": neither.

Returns the new mesh's number.

Drawing meshes

billboard3d

void billboard3d(int picture, double x, double y, double z, double height, int fullbright)

Draws a picture standing upright at a place, turned to face camera3d's camera, for trees and people. Its width follows the picture's shape, and colour 0 is see-through.

  • picture: the picture to draw.
  • x: where its bottom middle goes across, in world units.
  • y: the height its bottom stands at.
  • z: where its bottom middle goes along z.
  • height: how tall it is, in world units. 0 or less: 1.
  • fullbright: 1 to ignore the light, 0 to light it as usual.

drawmesh

void drawmesh(int mesh, double x, double y, double z, double yaw, double pitch, double roll, double scale)

Draws a mesh at a place, turned and sized as you say. Call it each frame, after clear3d and camera3d.

  • mesh: the mesh's number.
  • x: where it goes across, in world units.
  • y: how high it goes.
  • z: where it goes along z.
  • yaw: how far it's turned round, in degrees. Positive turns it right.
  • pitch: how far it's tipped, in degrees. Positive tips its front down.
  • roll: how far it leans to one side, in degrees.
  • scale: how big it's drawn, the same each way (2 is twice the size). 0 or less: 1.

drawmeshm

void drawmeshm(int mesh, double a, double b, double c, double d, double e, double f, double g, double h, double i, double x, double y, double z)

Draws a mesh with a 3 by 3 transform of your own, to stretch or squash it or turn it in a way you've worked out. Each corner's new x is a·x + b·y + c·z, its y uses d e f and its z g h i, then it's moved to x, y, z.

  • mesh: the mesh's number.
  • a: the first row's first number: how much a corner's x adds to its new x.
  • b: the first row's second number: how much a corner's y adds to its new x.
  • c: the first row's third number: how much a corner's z adds to its new x.
  • d: the second row's first number: how much a corner's x adds to its new y.
  • e: the second row's second number: how much a corner's y adds to its new y.
  • f: the second row's third number: how much a corner's z adds to its new y.
  • g: the third row's first number: how much a corner's x adds to its new z.
  • h: the third row's second number: how much a corner's y adds to its new z.
  • i: the third row's third number: how much a corner's z adds to its new z.
  • x: where it goes across, in world units.
  • y: how high it goes.
  • z: where it goes along z.

meshtexture

void meshtexture(int mesh, int n, int picture)

Changes one of a mesh's textures.

  • mesh: the mesh's number.
  • n: which texture, from 0 to 15.
  • picture: the new picture.

meshsize

void meshsize(int mesh, int *corners, int *triangles)

Finds out how many corners and triangles a mesh has.

  • mesh: the mesh's number.
  • corners: where to put how many corners it has: pass the address of an int, like &n (or NULL).
  • triangles: where to put how many triangles it has: the address of an int (or NULL).

freemesh

void freemesh(int mesh)

Lets go of a mesh when you've finished with it, so its memory can be used again.

  • mesh: the mesh's number. Don't use it again afterwards.

Textures

loadtexture

int loadtexture(const char *path, int size)

Loads a photo texture from a .tex file, such as one in /system/textures. Bigger photos are shrunk as they load, keeping their shape.

  • path: the .tex file. A path that doesn't start with / is in your program's folder.
  • size: the most pixels across (or down) to keep, from 8 to 1024. 0 or less: 64.

Returns the new picture's number, or 0 if the file couldn't be read or isn't a .tex.

The graphics card

glrpresent

int glrpresent(void)

Finds out whether a graphics card is doing the drawing. The other calls here only tell you anything when one is.

It takes nothing.

Returns 1 if a graphics card is drawing, or 0 if the processor is.

cubemaps

int cubemaps(void)

Finds out whether the graphics card can draw baked reflections (cube maps).

It takes nothing.

Returns 1 if it can, or 0 if it can't or there's no graphics card.

glrvram

int glrvram(int *used, int *allowed)

Finds out roughly how much of the graphics card's memory your program is using.

  • used: where to put how many bytes are in use: pass the address of an int, like &used (or NULL).
  • allowed: where to put how many bytes are allowed: the address of an int, like &allowed (or NULL).

Returns 1 if it's using more than it's allowed, or 0 if not. With no graphics card it writes 0s and returns 0.

glrinfotext

int glrinfotext(const char *field, char *buf, int size)

Gets one fact about the graphics card as text, such as its name.

  • field: which fact: "renderer" (the card's name), "version" (its OpenGL version) or "extensions".
  • buf: where to put the text. It's cut short to fit, and is empty with no graphics card.
  • size: how many bytes buf holds.

Returns how long the whole text is, so you can tell if buf was too small.

glrinfonumber

double glrinfonumber(const char *field)

Gets one fact about the graphics card as a number.

  • field: which fact: "depthbits", "maxtexture" (the biggest texture it takes), "multitexture" or "cubemap" (yes or no), or how its memory is split: "texturebytes", "lightmapbytes" or "screenbytes".

Returns the number, 1 or 0 for yes-or-no facts, and 0 for an unknown field or with no graphics card.

C reference: the graphics chip

#include <macawgpu.h> to talk to the 3D hardware from C. Call these from your program's _draw function: they draw into the window (or into the picture drawinto picked), and they work the way old OpenGL 1.x does. They're Lua's gpu.* calls with gpu_ in front, so The graphics chip has the ideas and examples, and C says how C programs work.

State

gpu_enable

void gpu_enable(const char *cap)

Switches a feature of the chip on. It stays on until you switch it off or call gpu_reset.

  • cap: the feature, one a call: "depth_test", "cull_face", "lighting", "fog" or "texture".

gpu_disable

void gpu_disable(const char *cap)

Switches a feature of the chip off.

  • cap: the feature, one a call: "depth_test", "cull_face", "lighting", "fog" or "texture".

gpu_isenabled

int gpu_isenabled(const char *cap)

Tells you whether a feature is switched on.

  • cap: the feature: "depth_test", "cull_face", "lighting", "fog" or "texture".

Returns 1 if it's on, 0 if it's off.

gpu_depthmask

void gpu_depthmask(int on)

Sets whether drawing writes to the depth buffer, the hidden picture of how far away each pixel is. Turn it off while you draw see-through things.

  • on: 1 to write depths (how it starts), 0 to leave the depth buffer alone.

gpu_cullface

void gpu_cullface(const char *side)

Picks which side of each triangle "cull_face" skips. It only matters while "cull_face" is on.

  • side: "back" (how it starts) to skip triangles facing away, or "front" to skip those facing you.

gpu_frontface

void gpu_frontface(const char *way)

Says which way round a triangle's corners go, on the screen, when you're looking at its front.

  • way: "ccw" for anticlockwise (how it starts), or "cw" for clockwise.

gpu_viewport

void gpu_viewport(int x, int y, int w, int h)

Makes drawing go into one part of the window, like a smaller window inside it.

  • x: the part's left edge, in pixels from the window's left.
  • y: the part's top edge, in pixels from the window's top.
  • w: its width in pixels. 0 goes back to the whole window.
  • h: its height in pixels. 0 goes back to the whole window.

gpu_clearcolor

void gpu_clearcolor(int colour)

Sets the colour gpu_clear fills the picture with.

  • colour: a colour number from 0 to 255, like NAVY.

gpu_clear

void gpu_clear(const char *what)

Fills the picture with the clear colour, empties the depth buffer, or both, inside the viewport. Do it at the start of each frame. It also starts gpu_stats's counts again.

  • what: "color" for the picture, "depth" for the depth buffer, or NULL (or "color depth") for both.

gpu_reset

void gpu_reset(void)

Puts all of the chip's settings back how they started: features, matrices, lights, fog, the texture and the viewport.

It takes nothing.

Matrices

A matrix is a grid of 16 numbers that moves, turns, grows or projects every corner you draw. There are two: "modelview" places things in front of the camera, and "projection" turns 3D into the flat picture. The calls below change whichever one gpu_matrixmode picked.

gpu_matrixmode

void gpu_matrixmode(const char *m)

Picks which matrix the matrix calls after it change.

  • m: "modelview" (how it starts) or "projection".

gpu_loadidentity

void gpu_loadidentity(void)

Resets the current matrix so it changes nothing. You usually do this before setting up a camera or a projection.

It takes nothing.

gpu_pushmatrix

void gpu_pushmatrix(void)

Saves a copy of the current matrix, so you can change it and get the saved one back with gpu_popmatrix. Each matrix can have 31 saved at once.

It takes nothing.

gpu_popmatrix

void gpu_popmatrix(void)

Gets back the matrix you last saved with gpu_pushmatrix. It's an error if nothing was saved.

It takes nothing.

gpu_translate

void gpu_translate(double x, double y, double z)

Moves everything you draw after it.

  • x: how far to move along x, to the right.
  • y: how far to move along y, upwards.
  • z: how far to move along z, towards you. The eye looks down -z.

gpu_rotate

void gpu_rotate(double degrees, double x, double y, double z)

Turns everything you draw after it round an axis, anticlockwise when you look along the axis towards the middle.

  • degrees: how far to turn, in degrees.
  • x: the axis's x. 1, 0, 0 turns round the x axis.
  • y: the axis's y. 0, 1, 0 turns round the y axis.
  • z: the axis's z. 0, 0, 1 turns round the z axis. All three 0 does nothing.

gpu_scale

void gpu_scale(double x, double y, double z)

Grows or shrinks everything you draw after it.

  • x: how much wider: 1 leaves it, 2 doubles it, 0.5 halves it.
  • y: how much taller, in the same way.
  • z: how much deeper, in the same way.

gpu_perspective

void gpu_perspective(double fovy, double aspect, double znear, double zfar)

Sets up a perspective projection, where far things look smaller. Call it on the projection matrix, after gpu_loadidentity.

  • fovy: how much the camera sees from top to bottom, in degrees. 60 is usual.
  • aspect: the picture's width divided by its height. 0 uses the window's (or the viewport's).
  • znear: the nearest distance it draws, more than 0. 0 means 0.1.
  • zfar: the furthest distance it draws. 0 means 100.

gpu_ortho

void gpu_ortho(double left, double right, double bottom, double top, double znear, double zfar)

Sets up a flat projection, where things stay the same size however far away they are. It's handy for 2D drawing and maps.

  • left: the x at the picture's left edge.
  • right: the x at the picture's right edge.
  • bottom: the y at the picture's bottom edge.
  • top: the y at the picture's top edge.
  • znear: the nearest distance it draws. Lua's usual is -1.
  • zfar: the furthest distance it draws. Lua's usual is 1.

gpu_frustum

void gpu_frustum(double left, double right, double bottom, double top, double znear, double zfar)

Sets up a perspective projection by where its edges are. gpu_perspective is easier to think about, and this lets you make a lopsided view.

  • left: the x of the left edge, at the near distance.
  • right: the x of the right edge, at the near distance.
  • bottom: the y of the bottom edge, at the near distance.
  • top: the y of the top edge, at the near distance.
  • znear: the nearest distance it draws, more than 0.
  • zfar: the furthest distance it draws.

gpu_lookat

void gpu_lookat(double ex, double ey, double ez, double tx, double ty, double tz, double ux, double uy, double uz)

Points the camera from an eye at a target. Call it on the modelview matrix, before you place things.

  • ex: the eye's x.
  • ey: the eye's y.
  • ez: the eye's z.
  • tx: the x of the place it looks at.
  • ty: the y of the place it looks at.
  • tz: the z of the place it looks at.
  • ux: the x of which way is up. Give 0, 0, 0 for all three for straight up.
  • uy: the y of which way is up.
  • uz: the z of which way is up.

gpu_loadmatrix

void gpu_loadmatrix(const float *m)

Replaces the current matrix with 16 numbers of your own.

  • m: an array of 16 floats, column by column, so m[12], m[13] and m[14] are the move.

gpu_multmatrix

void gpu_multmatrix(const float *m)

Multiplies the current matrix by 16 numbers of your own, as gpu_translate and the others do with theirs.

  • m: an array of 16 floats, column by column, so m[12], m[13] and m[14] are the move.

gpu_getmatrix

void gpu_getmatrix(const char *which, float *m)

Copies a matrix out, so you can keep it or work with it.

  • which: "modelview", "projection", or NULL for the one gpu_matrixmode picked.
  • m: an array of 16 floats it fills in, column by column.

gpu_project

int gpu_project(double x, double y, double z, double *sx, double *sy, double *depth)

Works out where a point in your 3D world lands in the window, with the matrices as they are now. Use it to put a label over a 3D thing.

  • x: the point's x.
  • y: the point's y.
  • z: the point's z.
  • sx: pass the address of a double, like &sx, for pixels from the window's left. NULL skips it.
  • sy: pass the address of a double for pixels from the window's top. NULL skips it.
  • depth: pass the address of a double for how far away it is, 0 near to 1 far. NULL skips it.

Returns 1, or 0 if the point is behind the camera (and then nothing is filled in).

Drawing a corner at a time

gpu_begin

void gpu_begin(const char *mode)

Starts drawing shapes a corner at a time. Send the corners with gpu_vertex, then call gpu_done.

  • mode: what the corners make: "triangles", "tristrip", "trifan", "quads", "quadstrip", "polygon", "lines", "linestrip", "lineloop" or "points".

gpu_color

void gpu_color(int colour)

Sets the colour of the corners you send after it, for drawing without a texture.

  • colour: a colour number from 0 to 255, like RED.

gpu_colorex

void gpu_colorex(int colour, double bright)

Sets the colour of the next corners, and how bright they are.

  • colour: a colour number from 0 to 255, like RED.
  • bright: 1 as it is, less for darker (0 is black), up to 1.3 for brighter.

gpu_texcoord

void gpu_texcoord(double u, double v)

Sets which place on the texture the next corner shows.

  • u: across the picture, 0 at its left edge and 1 at its right.
  • v: down the picture, 0 at its top edge and 1 at its bottom.

gpu_normal

void gpu_normal(double x, double y, double z)

Sets which way the surface faces at the next corners, so lighting knows how much light falls on it.

  • x: the direction's x.
  • y: the direction's y.
  • z: the direction's z. It needn't be 1 long. It starts as 0, 0, 1.

gpu_vertex

void gpu_vertex(double x, double y, double z)

Sends a corner (a vertex), with the colour, texture place and normal set last.

  • x: the corner's x.
  • y: the corner's y.
  • z: the corner's z.

gpu_vertex4

void gpu_vertex4(double x, double y, double z, double w)

Sends a corner with a fourth number, w, as OpenGL's glVertex4 does.

  • x: the corner's x.
  • y: the corner's y.
  • z: the corner's z.
  • w: 1 is the same as gpu_vertex. The place is x, y and z divided by w.

gpu_done

void gpu_done(void)

Finishes the shapes gpu_begin started and draws them.

It takes nothing.

gpu_end

void gpu_end(void)

The same as gpu_done, named as in OpenGL.

It takes nothing.

Buffers

A buffer keeps a model's corners, so you send them once and draw them each frame. Buffers and index buffers are numbers.

gpu_buffer

int gpu_buffer(const float *numbers, int count, const char *layout)

Makes a vertex buffer: a list of corners kept ready to draw.

  • numbers: an array of floats, corner after corner, each with the numbers its layout lists, in that order.
  • count: how many floats there are in all, a whole number of corners.
  • layout: what each corner has: p position (3), t texture place (2), n normal (3), c colour (1), l light baked in (1, where 1 is lit as usual). It needs a p. NULL means "p".

Returns the buffer's number. It's an error if count isn't a whole number of corners.

gpu_bufferset

void gpu_bufferset(int buf, const float *numbers, int count)

Replaces what's in a buffer, keeping its layout. The number of corners can change.

  • buf: the buffer, from gpu_buffer.
  • numbers: an array of floats, as for gpu_buffer.
  • count: how many floats there are in all, a whole number of corners.

gpu_buffercount

int gpu_buffercount(int buf)

Tells you how many corners a buffer holds.

  • buf: the buffer, from gpu_buffer.

Returns the number of corners.

gpu_freebuffer

void gpu_freebuffer(int buf)

Lets go of a buffer you've finished with. Its number doesn't work after this.

  • buf: the buffer, from gpu_buffer. 0, or one already let go, is ignored.

gpu_indices

int gpu_indices(const int *list, int count)

Makes an index buffer: a list of which corners of a vertex buffer to draw, so a corner shared by several triangles is only kept once.

  • list: an array of int corner numbers, counting from 0, up to 65535.
  • count: how many numbers are in list.

Returns the index buffer's number. A number out of range is an error.

gpu_freeindices

void gpu_freeindices(int indices)

Lets go of an index buffer you've finished with.

  • indices: the index buffer, from gpu_indices. 0, or one already let go, is ignored.

gpu_drawarrays

void gpu_drawarrays(const char *mode, int buf, int first, int count)

Draws a buffer's corners in order, as if you'd sent them between gpu_begin and gpu_done.

  • mode: what the corners make, as for gpu_begin, like "triangles".
  • buf: the buffer, from gpu_buffer.
  • first: the first corner to draw, counting from 0.
  • count: how many corners to draw. -1 draws all the rest.

gpu_drawelements

void gpu_drawelements(const char *mode, int buf, int indices)

Draws the corners of a buffer that an index buffer picks, in the index buffer's order.

  • mode: what the corners make, as for gpu_begin, like "triangles".
  • buf: the buffer, from gpu_buffer.
  • indices: the index buffer, from gpu_indices. A corner the buffer hasn't got is an error.

Textures, light and fog

gpu_bindtexture

void gpu_bindtexture(int picture)

Draws the next shapes with a picture on them, a texture, placed by gpu_texcoord or a buffer's t. "texture" is switched on to start with.

  • picture: a picture number from newpicture or loadpicture. 0 draws with no texture.

gpu_light

void gpu_light(int n, double x, double y, double z, double w, double strength, double radius)

Sets up one of the eight lights and switches it on. It's placed through the modelview matrix as it is now, so set your camera first. Switch on "lighting" too.

  • n: which light, from 0 to 7. Light 0 starts on, as a sun over your left shoulder.
  • x: the x of the light's place, or of the direction it comes from.
  • y: the y of its place or direction.
  • z: the z of its place or direction.
  • w: 0 for a direction the light comes from, like the sun; 1 for a lamp at x, y, z.
  • strength: how bright it is. -1 is the usual: 0.75 for a direction, 1 for a lamp.
  • radius: how far a lamp's light reaches, fading out on the way. 0 means it doesn't fade.

gpu_lightoff

void gpu_lightoff(int n)

Switches one light off.

  • n: which light, from 0 to 7.

gpu_ambient

void gpu_ambient(double a)

Sets the light that falls everywhere, even where no light reaches, so shadows aren't black.

  • a: how much, from 0 (none) to 1 (fully lit). It starts at 0.35.

gpu_shademodel

void gpu_shademodel(const char *m)

Sets how lighting is worked out across each triangle.

  • m: "flat" for one shade a face, "smooth" (how it starts) for blending between corners, "phong" for working it out across the face, so highlights land where they should.

gpu_material

void gpu_material(double shine, double sharpness)

Sets how shiny the surfaces you draw next are.

  • shine: how shiny, from 0 (not at all, how it starts) to 1 (very).
  • sharpness: how tight the highlight is, from 2 (broad) to 64 (a pin-point). 0 means 16.

gpu_fog

void gpu_fog(double znear, double zfar, int colour)

Sets the fog, which fades things into a colour the further away they are. Switch on "fog" as well.

  • znear: how far in front of the eye the fog starts. It starts at 10.
  • zfar: how far away things are lost in the fog completely. It starts at 50.
  • colour: the fog's colour number, from 0 to 255. -1 keeps the colour it had.

gpu_pointsize

void gpu_pointsize(double n)

Sets how big the dots are when you draw with "points".

  • n: the size in pixels. It starts at 1.

gpu_stats

int gpu_stats(int *tris, int *corners, int *used, int *made, int *missed)

Tells you how much was drawn, to help you find out what's slow.

  • tris: pass the address of an int for the triangles drawn since the last gpu_clear. NULL skips it.
  • corners: pass the address of an int for the corners sent since the last gpu_clear. NULL skips it.
  • used: pass the address of an int for how many times a saved drawing (display list) was drawn again. NULL skips it.
  • made: pass the address of an int for how many display lists were made. NULL skips it.
  • missed: pass the address of an int for drawings worked out afresh instead. NULL skips it.

Returns the number of triangles drawn since the last gpu_clear.

Reflecting water

To draw water that reflects: draw the scene into a picture from a camera mirrored in the water, draw the main scene, call gpu_mask(1), draw the water's surface, call gpu_mask(0), then call gpu_water.

gpu_mask

void gpu_mask(int on)

While it's on, the triangles you draw don't show: they mark which pixels are water, for gpu_water.

  • on: 1 to start marking, 0 to go back to drawing.

gpu_clearmask

void gpu_clearmask(void)

Clears the marked water pixels without drawing anything.

It takes nothing.

gpu_waterdefaults

void gpu_waterdefaults(gpu_wateropts *o)

Fills in every one of gpu_water's options with its usual value, so you can change only the ones you want. gpu_wateropts w = GPU_WATER_DEFAULTS; does the same.

  • o: pass the address of a gpu_wateropts, like &w. Every field is filled in.

gpu_water

void gpu_water(int reflection, const gpu_wateropts *o)

Mixes a reflection into the marked water pixels, with ripples, a tint and a drifting surface, then clears the marks.

  • reflection: the picture drawn from the mirrored camera. 0 for none, when you give a cube map in env.
  • o: the address of your gpu_wateropts, or NULL for every option's usual value. A number below 0 (or tint at -1) means the usual, in brackets:
  • tintamount: how much of the tint is mixed in (0.2).
  • near, far: how much it reflects close to you (0.35) and far away (0.85).
  • ripple: how far ripples bend the reflection, in pixels (1.5).
  • time: the time in seconds, which moves the ripples (0).
  • flow: how fast the surface texture drifts (1).
  • surfaceamount: how much the surface texture shows (0.3).
  • drops: where drips fell, each { u, v, seconds ago } on the water's texture places.
  • tint: the colour mixed in (BLUE).
  • surface: a picture for the water's own surface (0: none).
  • env: a cube map from gpu_envmap to reflect instead of the picture (0: none).
  • ndrops: how many of drops are used, from 0 to 16.

Baked reflections

A cube map is six views from one place, drawn once, that water can reflect instead of a picture drawn again every frame. Cube maps are numbers, like buffers.

gpu_envmap

int gpu_envmap(const int *faces, double x, double y, double z, const double *box)

Makes a cube map from six square pictures. It goes onto the graphics card a face a frame the first time you draw with it.

  • faces: an array of six picture numbers, the views looking along +x, -x, +y, -y, +z and -z, in that order.
  • x: the x of the place the views were drawn from.
  • y: the y of that place.
  • z: the z of that place.
  • box: an array of six doubles, { x0, y0, z0, x1, y1, z1 }: the room's lowest and highest corners. NULL for none.

Returns the cube map's number, or 0 if the graphics card can't do cube maps.

gpu_envmapbytes

int gpu_envmapbytes(const void *bytes, int n, double x, double y, double z, const double *box)

Makes a cube map again from the bytes gpu_envpixels gave you, such as ones you saved in a file.

  • bytes: the bytes from gpu_envpixels.
  • n: how many bytes there are.
  • x: the x of the place the views were drawn from.
  • y: the y of that place.
  • z: the z of that place.
  • box: an array of six doubles, { x0, y0, z0, x1, y1, z1 }, as for gpu_envmap. NULL for none.

Returns the cube map's number, or 0 if the bytes aren't six square faces or the card can't do cube maps.

gpu_envloaded

int gpu_envloaded(int env)

Tells you whether all six faces of a cube map are on the graphics card yet. Nothing shows until they are.

  • env: the cube map, from gpu_envmap.

Returns 1 if they're all there, 0 if not.

gpu_envunload

void gpu_envunload(int env)

Takes a cube map off the graphics card to save its memory. The next time you draw with it, it goes back a face a frame.

  • env: the cube map, from gpu_envmap.

gpu_envpixels

int gpu_envpixels(int env, void *buf, int size, int *across)

Copies a cube map's six faces out as bytes, so you can save them and make it again with gpu_envmapbytes. Call it with buf NULL first to find out how big a buffer you need.

  • env: the cube map, from gpu_envmap.
  • buf: a buffer for the bytes: blue, green, red for each texel (texture pixel), face by face, top row first. NULL copies nothing.
  • size: how many bytes buf holds. It copies no more than that.
  • across: pass the address of an int for how many texels across each face is. NULL skips it.

Returns how many bytes there are in all, or 0 if there are none.

gpu_freeenvmap

void gpu_freeenvmap(int env)

Lets go of a cube map you've finished with.

  • env: the cube map, from gpu_envmap. 0, or one already let go, is ignored.

C reference: levels

These calls come from #include <macawlevel.h>. They let a C program open, draw, walk round and even build the levels you make in Brushwork, the level editor. A level is a number: openlevel, loadlevel and newlevel each give you one, and 0 means it didn't work. They work the same way as Lua's level calls, which Levels explains in more detail, and C tells you about C on Macaw OS.

A few things to know

  • A level has two halves. Its table is what's in the .lvl file: its brushes, entities and settings. Its built level is that table made into something that draws and that you can bump into. openlevel gives you both; loadlevel and newlevel give you only the table until you call buildlevel.
  • A brush is a solid convex shape, like a box or a wedge, that the level is made of. An entity is a thing at a place in the level, such as a lamp, the player start or a pickup.
  • Everything counts from 0: the first brush, the first water, the first face.
  • A path that doesn't start with / is taken from your program's folder.
  • Calls that give text copy it into a buffer you pass, cut to fit with a 0 on the end, and return the length of the whole text, so you can tell when your buffer was too small.
  • Asking a level that isn't built yet to draw or collide is an error, and your program stops with a message. So is using a brush, entity, water or probe that isn't there, except in the calls whose entries say they return 0 for one that isn't there.

The structs

levelcam is a camera, for water and reflection probes:

  • x, y, z: where the camera is, in the level's units.
  • yaw: which way it turns, in degrees (0 looks along +z, 90 along +x).
  • pitch: how far it looks up, in degrees (negative looks down).
  • fov: how wide it sees, in degrees (0 or less means 90).

levelviewfn is the type of a function you write for water and probes to call. They call it when they need the view from a camera drawn: a mirrored camera under the water for a reflection, or one of the six views round a probe. Your function sets camera3d to the camera and draws the level above the height it's given (with leveldrawabove(level, above)), plus anything else that should show. It returns nothing. Where a call takes one, you can pass NULL, and then it draws just the level. Its arguments are:

  • c: the camera to draw from, a levelcam. It's only there during the call, so don't keep the pointer.
  • above: the height of the water, so you can leave out what's under it; for a probe it's -1e30, which means draw everything.
  • user: whatever pointer you gave the call that takes your function, passed back unchanged.

levellightinfo is a lamp or an area light, as levellight gives them and levelbake takes them. An area light is a glowing rectangle that lights one way.

  • x, y, z: where it is (for an area light, its middle).
  • bright: how bright it is (a lamp is 1.2 and an area light 1.5 if the level doesn't say).
  • radius: how far its light reaches (12 if the level doesn't say).
  • r, g, b: its colour, each from 0 to 1.
  • soft: a lamp's size, so how soft its shadows are (0 is hard; -1 means use the bake's softness).
  • area: 1 for an area light, 0 for a lamp.
  • w, h: an area light's size across.
  • facing: which way an area light faces: LIGHT_DOWN (0), LIGHT_UP (1), LIGHT_PX (+x, 2), LIGHT_NX (-x, 3), LIGHT_PZ (+z, 4) or LIGHT_NZ (-z, 5).

Opening, saving and building

openlevel

int openlevel(const char *path)

Reads a .lvl file, builds it, and puts on its baked light from the .lit file next to it (and its baked probes from the .prb file, if the light went on). This is the usual way to start: the level is ready to draw and bump into straight away.

  • path: the level's file name, like "/system/maps/sample.lvl".

Returns the level's number, or 0 if it couldn't be opened (levelerror says why).

loadlevel

int loadlevel(const char *path)

Reads a .lvl file into a level table without building it. Use it when you want to look at or change a level before building it, or don't need to draw it at all.

  • path: the level's file name.

Returns the level's number, or 0 if it couldn't be read (levelerror says why).

newlevel

int newlevel(void)

Makes an empty level, with no brushes or entities, for building from code. Its settings start as an ambient of 0.08, a bounce of 1 and a luxel of 0.5.

It takes nothing.

Returns the new level's number.

savelevel

int savelevel(int level, const char *path)

Writes a level's table to a .lvl file, which Brushwork can open. It doesn't save the baked light: levellightdata gives you that to keep yourself. Brush corners are written to 4 significant figures and entity numbers to 6, so keep your sizes simple.

  • level: the level to save.
  • path: the file to write, usually ending in .lvl.

Returns 1 if it was saved, or 0 if it couldn't be (levelerror says why).

buildlevel

int buildlevel(int level)

Builds a level's table into a level that draws and collides. Call it after loadlevel or newlevel, and again whenever you've changed the brushes. It makes the level's water and probes afresh from its table, and the new build has no baked light yet.

  • level: the level to build.

Returns 1 if it was built, or 0 if it couldn't be (levelerror says why).

freelevel

void freelevel(int level)

Lets go of a level and everything built for it. After this the number means nothing, so don't use it again.

  • level: the level to free (one that isn't a level is ignored).

levelerror

int levelerror(char *buf, int size)

Gives the message from the last call that didn't work, such as a file that wasn't there.

  • buf: where the message goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the whole message.

levelbuilt

int levelbuilt(int level)

Tells you whether a level has been built, so whether it can draw and collide yet.

  • level: the level to ask about.

Returns 1 if it's built, or 0 if not.

levellit

int levellit(int level)

Tells you whether a level has baked light on it, from its .lit file, levelsetlight or a finished bake.

  • level: the level to ask about.

Returns 1 if it's lit, or 0 if it has plain shading.

levelpath

int levelpath(int level, char *buf, int size)

Gives the file a level was opened or loaded from.

  • level: the level to ask about.
  • buf: where the file name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the file name, or 0 for a level from newlevel.

levellitpath

int levellitpath(const char *path, char *buf, int size)

Gives the file a level's baked light is kept in: the same name with .lit in place of .lvl.

  • path: the level's file name.
  • buf: where the .lit file's name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the .lit file's name.

levelprobepath

int levelprobepath(const char *path, char *buf, int size)

Gives the file a level's baked reflection probes are kept in: the same name with .prb in place of .lvl.

  • path: the level's file name.
  • buf: where the .prb file's name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the .prb file's name.

Drawing

These draw a built level with camera3d's camera, unless they say otherwise.

leveldrawbsp

int leveldrawbsp(int level, int *faces)

Draws only the parts of the level the camera can see, working them out through the level's BSP tree and portals (the way it's cut into pieces). This is the fast way, and the one to use each frame.

  • level: the level to draw.
  • faces: the address of an int to get how many faces were drawn, like &n, or NULL.

Returns how many leaves (pieces of the level) were drawn.

leveldraw

void leveldraw(int level)

Draws all of the level. With a graphics card this is quick too, since the card keeps the whole level.

  • level: the level to draw.

leveldrawabove

void leveldrawabove(int level, double y)

Draws only the part of the level above a height. Use it in a levelviewfn, to leave out what's under the water.

  • level: the level to draw.
  • y: the height, in the level's units; only what's above it is drawn.

leveldrawgpu

void leveldrawgpu(int level)

Draws all of the level with the graphics chip's camera, viewport and fog (from <macawgpu.h>) instead of camera3d's.

  • level: the level to draw.

leveldrawgpuabove

void leveldrawgpuabove(int level, double y)

Draws the part of the level above a height, with the graphics chip's camera.

  • level: the level to draw.
  • y: the height, in the level's units; only what's above it is drawn.

Bumping into it

These work on a built level. Water isn't solid, so they go straight through it.

leveltracebox

double leveltracebox(int level, double ax, double ay, double az, double bx, double by, double bz, double hx, double hy, double hz, double *nx, double *ny, double *nz, int *hit)

Moves a box from one place towards another and tells you how far it gets before it hits something. Use it to move a player or a ball: it stops just short of the wall.

  • level: the level to move through.
  • ax: x of the box's middle where it starts.
  • ay: y of the box's middle where it starts.
  • az: z of the box's middle where it starts.
  • bx: x of where the box's middle is going.
  • by: y of where the box's middle is going.
  • bz: z of where the box's middle is going.
  • hx: half the box's width along x (less than 0 counts as 0).
  • hy: half the box's height.
  • hz: half the box's depth along z.
  • nx: the address of a double for x of the direction the thing it hit faces, or NULL.
  • ny: the address of a double for y of that direction, or NULL.
  • nz: the address of a double for z of that direction, or NULL.
  • hit: the address of an int to get 1 if it hit something and 0 if not, or NULL.

Returns how far it got, from 0 (not at all) to 1 (all the way).

leveltrace

double leveltrace(int level, double x0, double y0, double z0, double x1, double y1, double z1)

Follows a line from one point to another and tells you how far it gets before it hits something. Use it to see whether one place can see another.

  • level: the level to look through.
  • x0: x of where the line starts.
  • y0: y of where the line starts.
  • z0: z of where the line starts.
  • x1: x of where the line ends.
  • y1: y of where the line ends.
  • z1: z of where the line ends.

Returns how far along it got, from 0 to 1, where 1 means it hit nothing.

levelraycast

double levelraycast(int level, double x, double y, double z, double dx, double dy, double dz)

Sends a ray from a point in a direction and finds where it first goes into a brush. It tries every brush, so it works straight after building. A ray that starts inside a brush doesn't count that one.

  • level: the level to look through.
  • x: x of where the ray starts.
  • y: y of where the ray starts.
  • z: z of where the ray starts.
  • dx: how far the ray goes along x each step.
  • dy: how far the ray goes along y each step.
  • dz: how far the ray goes along z each step.

Returns t, so the spot it hits is x + t * dx, y + t * dy, z + t * dz, or -1 if it hits nothing. If the direction is one unit long, t is the distance.

levelboxsolid

int levelboxsolid(int level, double x0, double y0, double z0, double x1, double y1, double z1)

Tells you whether a box touches anything solid. The corners can be given in either order.

  • level: the level to look in.
  • x0: x of one corner of the box.
  • y0: y of that corner.
  • z0: z of that corner.
  • x1: x of the opposite corner.
  • y1: y of the opposite corner.
  • z1: z of the opposite corner.

Returns 1 if the box touches something solid, or 0 if it's in open space.

levelboxinside

int levelboxinside(int level, double x, double y, double z, double hx, double hy, double hz)

Tells you whether a box is inside a brush, by more than just touching it. Use it to check a player hasn't ended up stuck in a wall.

  • level: the level to look in.
  • x: x of the box's middle.
  • y: y of the box's middle.
  • z: z of the box's middle.
  • hx: half the box's width along x.
  • hy: half the box's height.
  • hz: half the box's depth along z.

Returns 1 if the box is inside something, or 0 if not.

Water

In Brushwork you can make brushes into water. Water isn't solid, and its top is a surface that reflects. A built level has a list of water surfaces, which you draw after the level. Each needs its reflection drawn first, with waterreflect, or baked once with waterbake.

watercount

int watercount(int level)

Tells you how many water surfaces a level has to draw: those built from its water brushes, and any you've added with newwater.

  • level: the level to ask about.

Returns how many water surfaces there are (they count from 0).

newwater

int newwater(int level, double x0, double z0, double x1, double z1, double y)

Adds a water surface of your own: a flat rectangle at a height. buildlevel makes the list again from the level's table, so add yours after building.

  • level: the level to add it to.
  • x0: x of one corner.
  • z0: z of that corner.
  • x1: x of the opposite corner.
  • z1: z of the opposite corner.
  • y: the water's height.

Returns the new water's number, or -1 if one of the numbers wasn't a proper number.

waterinfo

void waterinfo(int level, int i, double *x0, double *z0, double *x1, double *z1, double *y)

Gives where a water surface is.

  • level: the level it's in.
  • i: which water, from 0.
  • x0: the address of a double for its smallest x, or NULL.
  • z0: the address of a double for its smallest z, or NULL.
  • x1: the address of a double for its largest x, or NULL.
  • z1: the address of a double for its largest z, or NULL.
  • y: the address of a double for its height, or NULL.

waterreflect

void waterreflect(int level, int i, const levelcam *cam, levelviewfn draw, void *user)

Draws a water's live reflection: the level is drawn again from a camera mirrored under the water, into the water's own picture. Call it before you clear the screen and draw the scene, then waterdraw after. It does nothing if the water's reflections are off.

  • level: the level the water's in.
  • i: which water, from 0.
  • cam: the camera you're looking from, a levelcam (see The structs).
  • draw: your function that draws the mirrored view, or NULL to draw just the level.
  • user: any pointer you like, passed to draw as its user; NULL is fine.

waterdraw

void waterdraw(int level, int i, const levelcam *cam, double t, const char *how)

Draws a water surface, with ripples and its reflection mixed in. Call it after you've drawn the level, with the same camera.

  • level: the level the water's in.
  • i: which water, from 0.
  • cam: the camera you're looking from, a levelcam.
  • t: the time in seconds, which moves the ripples and drips (time() will do).
  • how: NULL for the live reflection if there is one, "plain" for just the surface, or "baked" for the baked one.

waterbake

int waterbake(int level, int i, levelviewfn draw, void *user)

Bakes a water's reflection once, so it doesn't have to be drawn every frame. Each call draws one of six views from just above the middle of the water; keep calling it until it returns 1. Things that move won't show in a baked reflection.

  • level: the level the water's in.
  • i: which water, from 0.
  • draw: your function that draws each view, or NULL to draw just the level.
  • user: any pointer you like, passed to draw as its user; NULL is fine.

Returns 1 once it's done (or once it's clear it can't be baked), or 0 while there are views left.

waterbaked

int waterbaked(int level, int i)

Tells you whether a water's reflection has been baked.

  • level: the level the water's in.
  • i: which water, from 0.

Returns 1 if it's baked, 0 if not yet, or -1 if it can't be (the graphics card has no cube maps).

waterreflections

int waterreflections(int level, int i, int on)

Turns a water's reflection on or off, or asks whether it's on. With it off, the water is a plain sheet, which is quicker on a slow computer.

  • level: the level the water's in.
  • i: which water, from 0.
  • on: 1 to turn reflections on, 0 to turn them off, or -1 just to ask.

Returns 1 if reflections are on now, or 0 if they're off.

watercamera

void watercamera(const levelcam *cam)

Points the graphics chip's camera the same way as camera3d, so gpu_ drawing in a reflection lines up with the level. It also makes clockwise triangles the front ones.

  • cam: the camera to match, a levelcam.

Reflection probes

A shiny surface reflects the nearest reflection probe: a point in the level whose view all round is baked into a cube map (six square pictures, one each way). Probes need a graphics card with cube maps; without one, shiny surfaces are drawn as they are. A probe is a number of its own, not a level.

bakeprobes

int bakeprobes(int level)

Bakes any of a level's own probes that aren't baked yet, a little at a time. Call it once a frame until it returns 1; each call draws one of a probe's six views, so it never holds things up. If nothing in the level is shiny, there's nothing to do.

  • level: the level whose probes to bake.

Returns 1 once all are done (or there's nothing to bake), or 0 while there's more to do.

levelprobelimit

int levelprobelimit(int level, int n)

Sets how many probes may be on the graphics card at once, the ones nearest the camera, or asks. Each takes about 400 KB of the card's memory.

  • level: a built level.
  • n: how many, from 1 to 64 (more counts as 64), or 0 to ask.

Returns the limit now.

probecount

int probecount(int level)

Tells you how many probes a built level has.

  • level: the level to ask about.

Returns how many probes there are (0 before it's built).

probeat

int probeat(int level, int i)

Gives one of a level's probes as a probe number, for the calls below.

  • level: the level it's in.
  • i: which probe, from 0.

Returns the probe's number (the same one each time you ask for that probe).

newprobe

int newprobe(double x, double y, double z, int size)

Makes a probe of your own at a place. Bake it with probebake, then give its cube map to a level with levelsetprobes.

  • x: x of where it is.
  • y: y of where it is (eye height is a good choice).
  • z: z of where it is.
  • size: how many pixels across each of its six pictures is, from 8 to 256 (0 or less: 128).

Returns the probe's number, or 0 if a place wasn't a proper number.

probepos

void probepos(int probe, double *x, double *y, double *z)

Gives where a probe is.

  • probe: the probe's number.
  • x: the address of a double for its x, or NULL.
  • y: the address of a double for its y, or NULL.
  • z: the address of a double for its z, or NULL.

probebake

int probebake(int probe, levelviewfn draw, void *user, int level)

Bakes a probe, drawing one of its six views each call. Keep calling it until it returns 1.

  • probe: the probe's number.
  • draw: your function that draws each view, or NULL to draw just level.
  • user: any pointer you like, passed to draw as its user; NULL is fine.
  • level: a built level to find the walls round the probe in (and to draw if draw is NULL), or 0 for none.

Returns 1 once it's done (or it can't be baked), or 0 while there are views left.

probebaked

int probebaked(int probe)

Tells you whether a probe has been baked.

  • probe: the probe's number.

Returns 1 if it's baked, 0 if not yet, or -1 if it can't be (the graphics card has no cube maps).

probeenv

int probeenv(int probe)

Gives a baked probe's cube map. It's the same kind of number <macawgpu.h>'s gpu_envmap gives, so gpu_envpixels and gpu_envmapbytes can keep it as bytes and make it again.

  • probe: the probe's number.

Returns the cube map's number, or 0 if the probe isn't baked yet.

levelsetprobes

void levelsetprobes(int level, const int *envs, int n)

Tells a built level which cube maps its shiny surfaces reflect. Each shiny face uses the nearest one in front of it, and prefers one in the same room.

  • level: the level.
  • envs: an array of cube map numbers (from probeenv); 0s in it are skipped. NULL takes them all away.
  • n: how many numbers are in envs, up to 64 (0 takes them all away).

levelprobedata

int levelprobedata(int level, void *buf, int size)

Gives a level's baked probes as the bytes of a .prb file, for you to save. Call it with NULL first to find out how big a buffer you need.

  • level: the level.
  • buf: where the bytes go, or NULL to only ask how many there are.
  • size: how many bytes buf holds; no more than that are written.

Returns how many bytes there are in all, or 0 if none of its probes is baked.

applylevelprobes

int applylevelprobes(int level, const void *data, int count)

Gives a built level's probes their cube maps from a .prb file's bytes, so they don't need baking again.

  • level: a built level.
  • data: the bytes, as levelprobedata gave them or as read from the .prb file.
  • count: how many bytes are at data.

Returns 1 if every probe got its cube map, or 0 if any didn't.

What's in a level

These read the level's table, so they work before it's built too.

levelstart

void levelstart(int level, double *x, double *y, double *z, double *angle)

Gives where the player starts: the player start's feet, and which way it faces. A level with no start gives 0, 2, 0 and an angle of 0.

  • level: the level.
  • x: the address of a double for x, or NULL.
  • y: the address of a double for y (where the feet are), or NULL.
  • z: the address of a double for z, or NULL.
  • angle: the address of a double for which way it faces, in degrees, or NULL.

levellightcount

int levellightcount(int level)

Tells you how many lamps and area lights a level has.

  • level: the level.

Returns how many lights there are.

levellight

int levellight(int level, int i, levellightinfo *light)

Gives one of a level's lamps or area lights, with the defaults filled in for what the level doesn't say.

  • level: the level.
  • i: which light, from 0.
  • light: a levellightinfo to fill in (see The structs), or NULL just to check it's there.

Returns 1 if there's an i'th light, or 0 if not.

levelwatercount

int levelwatercount(int level)

Tells you how many water brushes a level's table has.

  • level: the level.

Returns how many water surfaces the table has.

levelwater

int levelwater(int level, int i, double *x0, double *z0, double *x1, double *z1, double *y)

Gives where one of the table's water surfaces is: the top of a water brush (a shaped one gives the box round it).

  • level: the level.
  • i: which water, from 0.
  • x0: the address of a double for its smallest x, or NULL.
  • z0: the address of a double for its smallest z, or NULL.
  • x1: the address of a double for its largest x, or NULL.
  • z1: the address of a double for its largest z, or NULL.
  • y: the address of a double for its height (the brush's top), or NULL.

Returns 1 if there's an i'th water, or 0 if not.

levelprobecount

int levelprobecount(int level)

Tells you how many probe entities a level's table has.

  • level: the level.

Returns how many probes the table has.

levelprobe

int levelprobe(int level, int i, double *x, double *y, double *z)

Gives where one of the table's probes is.

  • level: the level.
  • i: which probe, from 0.
  • x: the address of a double for its x, or NULL.
  • y: the address of a double for its y, or NULL.
  • z: the address of a double for its z, or NULL.

Returns 1 if there's an i'th probe, or 0 if not.

Entities

Each entity has a class, its kind, such as "pickup" or "start", and fields with values. These calls read a level's entities of one class, with the class's defaults filled in for fields the level doesn't give. Give the class as NULL for every entity, in the level's order. A field reads as a number or as text, whichever it is.

levelentitycount

int levelentitycount(int level, const char *class_)

Tells you how many entities of a class a level has.

  • level: the level.
  • class_: the class, like "pickup", or NULL for every entity.

Returns how many there are.

levelentity

int levelentity(int level, const char *class_, int i, double *x, double *y, double *z)

Gives where an entity is.

  • level: the level.
  • class_: the class, or NULL for every entity.
  • i: which one of them, from 0.
  • x: the address of a double for its x, or NULL.
  • y: the address of a double for its y, or NULL.
  • z: the address of a double for its z, or NULL.

Returns 1 if there's an i'th one, or 0 if not.

levelentityhas

int levelentityhas(int level, const char *class_, int i, const char *field)

Tells you whether an entity has a field, and what kind of value it holds.

  • level: the level.
  • class_: the class, or NULL for every entity.
  • i: which one of them, from 0.
  • field: the field's name, like "value".

Returns 0 if there's no such field, 1 for a number, 2 for text, or 3 for true or false.

levelentitynum

double levelentitynum(int level, const char *class_, int i, const char *field)

Gives an entity's field as a number. Text that's a number reads as that number, true as 1 and false as 0.

  • level: the level.
  • class_: the class, or NULL for every entity.
  • i: which one of them, from 0.
  • field: the field's name.

Returns the field's value, or 0 if there's no such field (or it isn't a number).

levelentitytext

int levelentitytext(int level, const char *class_, int i, const char *field, char *buf, int size)

Gives an entity's field as text. Numbers come out as a level file writes them, and true or false as "true" or "false".

  • level: the level.
  • class_: the class, or NULL for every entity.
  • i: which one of them, from 0.
  • field: the field's name.
  • buf: where the text goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the text, or 0 if there's no such field.

levelentityfield

int levelentityfield(int level, const char *class_, int i, int k, char *buf, int size)

Gives the name of one of an entity's fields, so you can go through them all. They come in alphabetical order, and "class" is one of them.

  • level: the level.
  • class_: the class, or NULL for every entity.
  • i: which one of them, from 0.
  • k: which field, from 0.
  • buf: where the field's name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the name, or 0 once there are no more fields.

Kinds of entity

These tell you about the classes a level can have: Macaw OS's own (light, arealight, start, probe), the generic ones (marker, pickup, enemy, trigger, sound, sign) and a game's own, from an entities.lua in the level's folder or a folder above it. Where a call takes classes, you can give it a level's number for the level's own classes, or a number from entityclasses.

entityclasses

int entityclasses(const char *path)

Finds the classes a level at a place can have, reading the game's entities.lua if there is one. The level doesn't need to exist yet.

  • path: where the level is (or would be), like "/home/mygame/levels/one.lvl".

Returns a number for that set of classes, or 0 if they couldn't be found.

entityclasscount

int entityclasscount(int classes)

Tells you how many classes there are in a set.

  • classes: a set of classes from entityclasses, or a level's number.

Returns how many classes there are.

entityclassname

int entityclassname(int classes, int i, char *buf, int size)

Gives the name of one class in a set: Macaw OS's own first, then the game's, then the generic ones.

  • classes: a set of classes from entityclasses, or a level's number.
  • i: which class, from 0.
  • buf: where the name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the name, or 0 once there are no more.

entityclassinfo

int entityclassinfo(int classes, const char *name, const char *what, char *buf, int size)

Gives one thing about a class, as text. A class nobody describes comes back as a plain grey box marked "unknown".

  • classes: a set of classes from entityclasses, or a level's number.
  • name: the class's name, like "pickup".
  • what: "label", "about", "colour", "shape", "size" or "float"; or "system", "generic", "game" or "unknown", which give "true" if it's that kind.
  • buf: where the text goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the text, or 0 if there's nothing (so 0 for a kind it isn't).

entityclassfieldcount

int entityclassfieldcount(int classes, const char *name)

Tells you how many fields a class describes.

  • classes: a set of classes from entityclasses, or a level's number.
  • name: the class's name.

Returns how many fields it has (0 for a class nobody describes).

entityclassfield

int entityclassfield(int classes, const char *name, int k, char *fname, int fsize, char *type, int tsize, char *def, int dsize)

Gives one of a class's fields: its name, its type and its default, each as text.

  • classes: a set of classes from entityclasses, or a level's number.
  • name: the class's name.
  • k: which field, from 0.
  • fname: where the field's name goes, a char array.
  • fsize: how many bytes fname holds.
  • type: where its type goes: "number", "text", "bool", "choice", "colour" or "angle".
  • tsize: how many bytes type holds.
  • def: where its default goes, as text (true or false as "true" or "false").
  • dsize: how many bytes def holds.

Returns 1 if there's a k'th field, or 0 if not.

Building from code: brushes

These change a level's table. Call buildlevel afterwards to see the changes. A box's six faces, in order, are -x, +x, -y, +y, -z and +z (west, east, bottom, top, south, north), and a texture is a built-in name like "brick" or a .pxl picture's path.

levelbrushcount

int levelbrushcount(int level)

Tells you how many brushes a level has.

  • level: the level.

Returns how many brushes there are.

leveladdbox

int leveladdbox(int level, double x0, double y0, double z0, double x1, double y1, double z1, const char **tex)

Adds a box-shaped brush, from one corner to the opposite one. The corners can be given in either order.

  • level: the level to add it to.
  • x0: x of one corner.
  • y0: y of that corner.
  • z0: z of that corner.
  • x1: x of the opposite corner.
  • y1: y of the opposite corner.
  • z1: z of the opposite corner.
  • tex: an array of six texture names, one a face in the order above; NULL, or a NULL name, means "stone".

Returns the new brush's number, or -1 if a corner wasn't a proper number.

leveladdshape

int leveladdshape(int level, const float *planes, int n, const char **tex)

Adds a convex brush of any shape, such as a wedge or a ramp, made of flat sides (planes). The brush is the space inside all of them.

  • level: the level to add it to.
  • planes: four floats for each plane, nx ny nz d; inside is where nx*x + ny*y + nz*z <= d, so the normal points out.
  • n: how many planes, from 4 to 320.
  • tex: an array of n texture names, one a plane; NULL, or a NULL name, means "stone".

Returns the new brush's number, or -1 if it couldn't be added (too few planes, or a bad one).

levelremovebrush

void levelremovebrush(int level, int b)

Takes a brush out of the level. The brushes after it move down one number.

  • level: the level.
  • b: which brush, from 0.

levelbrushbox

int levelbrushbox(int level, int b, double *x0, double *y0, double *z0, double *x1, double *y1, double *z1)

Gives a brush's corners: a box's own, or the box round a shaped brush.

  • level: the level.
  • b: which brush, from 0.
  • x0: the address of a double for the smallest x, or NULL.
  • y0: the address of a double for the smallest y, or NULL.
  • z0: the address of a double for the smallest z, or NULL.
  • x1: the address of a double for the largest x, or NULL.
  • y1: the address of a double for the largest y, or NULL.
  • z1: the address of a double for the largest z, or NULL.

Returns 1 for a box, 2 for a shaped brush, or 0 if there's no such brush.

levelbrushtexture

void levelbrushtexture(int level, int b, int face, const char *name)

Changes the texture on one face of a brush.

  • level: the level.
  • b: which brush, from 0.
  • face: which face, from 0: a box's side in the order above, or a shape's plane.
  • name: the texture's name; NULL means "stone".

levelbrushwater

void levelbrushwater(int level, int b, int on)

Makes a brush water or solid again. Water isn't solid, and its top is a reflecting surface.

  • level: the level.
  • b: which brush, from 0.
  • on: 1 to make it water, or 0 to make it solid.

levelbrushglow

void levelbrushglow(int level, int b, int face, double strength, const char *colour)

Makes a face of a brush glow. A glowing face lights the level when its light is baked.

  • level: the level.
  • b: which brush, from 0.
  • face: which face, from 0.
  • strength: how strongly it glows; 0 or less stops it glowing.
  • colour: its colour as text, like "#ff8800"; NULL means white.

levelbrushshine

void levelbrushshine(int level, int b, int face, double shine)

Makes a brush, or one face of it, shiny, so it reflects the nearest probe.

  • level: the level.
  • b: which brush, from 0.
  • face: which face, from 0, or -1 for the whole brush (which clears the faces' own shine).
  • shine: how shiny, from 0 (not at all) to 1 (a mirror).

Building from code: entities and settings

leveladdentity

int leveladdentity(int level, const char *class_, double x, double y, double z)

Adds an entity of a class at a place. Give it fields with the calls below.

  • level: the level.
  • class_: its class, like "pickup" or "light".
  • x: x of where it is.
  • y: y of where it is.
  • z: z of where it is.

Returns the entity's number, in the level's order (as levelentity counts with a NULL class), or -1 if the class was empty or a place wasn't a proper number.

levelremoveentity

void levelremoveentity(int level, int e)

Takes an entity out of the level. The entities after it move down one number.

  • level: the level.
  • e: which entity, from 0, in the level's order.

levelmoveentity

void levelmoveentity(int level, int e, double x, double y, double z)

Moves an entity to a new place.

  • level: the level.
  • e: which entity, from 0, in the level's order.
  • x: x of the new place.
  • y: y of the new place.
  • z: z of the new place.

levelentitysetnum

void levelentitysetnum(int level, int e, const char *field, double v)

Sets one of an entity's fields to a number.

  • level: the level.
  • e: which entity, from 0, in the level's order.
  • field: the field's name, like "bright".
  • v: the number.

levelentitysettext

void levelentitysettext(int level, int e, const char *field, const char *text)

Sets one of an entity's fields to text, or takes the field away.

  • level: the level.
  • e: which entity, from 0, in the level's order.
  • field: the field's name, like "colour".
  • text: the text, or NULL to take the field away.

levelentitysetbool

void levelentitysetbool(int level, int e, const char *field, int v)

Sets one of an entity's fields to true or false.

  • level: the level.
  • e: which entity, from 0, in the level's order.
  • field: the field's name, like "once".
  • v: 1 (or anything not 0) for true, 0 for false.

levelsetting

double levelsetting(int level, const char *name)

Gives one of a level's number settings: "ambient" (the light everywhere), "bounce" (how much light bounces), "luxel" (the size of a patch of baked light) or "skylight" (how strong the sky's light is).

  • level: the level.
  • name: the setting's name.

Returns the setting's value, or 0 if the level doesn't have it.

levelsettingtext

int levelsettingtext(int level, const char *name, char *buf, int size)

Gives one of a level's settings as text, such as "sky", the name of the sky round it.

  • level: the level.
  • name: the setting's name.
  • buf: where the text goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the text, or 0 if the level doesn't have that setting.

levelsetsetting

void levelsetsetting(int level, const char *name, double v)

Sets one of a level's number settings. savelevel keeps "ambient", "bounce", "luxel" and "skylight".

  • level: the level.
  • name: the setting's name.
  • v: its new value (something that isn't a proper number takes the setting away).

levelsetsettingtext

void levelsetsettingtext(int level, const char *name, const char *text)

Sets one of a level's settings to text, such as "sky".

  • level: the level.
  • name: the setting's name.
  • text: its new value, or NULL to take the setting away.

Skies and textures

levelskies

int levelskies(int i, char *buf, int size)

Gives the name of one of the skies there are, in alphabetical order, so you can list them.

  • i: which sky, from 0.
  • buf: where the name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the name, or 0 once there are no more.

levelsky

int levelsky(const char *name, int *pictures, double *r, double *g, double *b)

Gives a sky's six pictures, for levelsetsky, and its average colour.

  • name: the sky's name, like "cloudy".
  • pictures: an array of six ints for its pictures' numbers (px nx py ny pz nz), or NULL.
  • r: the address of a double for the red in its colour, 0 to 1, or NULL.
  • g: the address of a double for the green, 0 to 1, or NULL.
  • b: the address of a double for the blue, 0 to 1, or NULL.

Returns 1 if there's a sky of that name, or 0 if not.

leveltexture

int leveltexture(const char *name)

Gives the picture for a texture name, to draw with yourself.

  • name: a built-in texture name, or a .pxl picture's path; NULL means "stone".

Returns the picture's number. A name it doesn't know gives the stone picture.

leveltexturename

int leveltexturename(int i, char *buf, int size)

Gives the name of one of the built-in textures, so you can list them.

  • i: which texture, from 0.
  • buf: where the name goes, a char array.
  • size: how many bytes buf holds.

Returns the length of the name, or 0 once there are no more.

Baking light and the built level

Baking light works out how the level's lamps, glowing faces and sky light every surface, bounces and shadows included, and keeps the result. It takes a while, so it's done a step at a time. These calls need a built level.

levelbake

int levelbake(int level, const levellightinfo *lights, int n, double ambient, double bounce, double softness)

Starts baking a level's light. Then call levelbakestep until it's done.

  • level: the level to bake.
  • lights: an array of levellightinfo (see The structs), or NULL for the level's own lamps and area lights.
  • n: how many lights are in lights.
  • ambient: the light everywhere, even in shadow; less than 0 for the level's setting (or 0.08).
  • bounce: how much light bounces off surfaces; less than 0 for the level's setting (or 1).
  • softness: the size of lamps that don't give one, so how soft their shadows are; less than 0 for 0.35.

Returns 1 if baking has started, or 0 if it couldn't (levelerror says why, such as a level too big to light).

levelbakestep

int levelbakestep(int level, double ms, double *progress, char *what, int size)

Bakes for a little while. Call it once a frame until it returns 1; then the level is lit.

  • level: the level being baked.
  • ms: how long to bake for, in milliseconds (0 or less means 30).
  • progress: the address of a double for how far it's got, from 0 to 1, or NULL.
  • what: where text saying what it's doing goes (like "bouncing light"), or NULL.
  • size: how many bytes what holds.

Returns 1 once the baking is done, or 0 while there's more to do.

levellightdata

int levellightdata(int level, void *buf, int size)

Gives a level's baked light as bytes, to save in its .lit file. Call it with NULL first to find out how big a buffer you need.

  • level: the level.
  • buf: where the bytes go, or NULL to only ask how many there are.
  • size: how many bytes buf holds; no more than that are written.

Returns how many bytes there are in all, or 0 if the level isn't baked.

levelsetlight

int levelsetlight(int level, const void *data, int n)

Puts baked light back on a level, from bytes levellightdata gave or a .lit file holds.

  • level: the level.
  • data: the bytes.
  • n: how many bytes are at data.

Returns 1 if the light went on, or 0 if it was baked for a different level.

levelunbake

void levelunbake(int level)

Takes a level's baked light off, back to plain shading.

  • level: the level.

levelsetsky

void levelsetsky(int level, const int *pictures)

Puts a sky round a level, from six square pictures, or takes it away. Faces with the "sky" texture show it. buildlevel already puts on the sky the level's "sky" setting names.

  • level: the level.
  • pictures: an array of six picture numbers (px nx py ny pz nz), like levelsky gives, or NULL for no sky.

levelfacecount

int levelfacecount(int level)

Tells you how many faces the built level has. Building cuts brushes into faces, so this isn't the same as six times the brushes.

  • level: the level.

Returns how many faces there are.

levelface

int levelface(int level, int i, float *xyz, int max, int *tex, double *nx, double *ny, double *nz)

Gives one face of the built level: its corners, its texture and which way it faces. The corners go anticlockwise, seen from the front.

  • level: the level.
  • i: which face, from 0.
  • xyz: an array of floats for the corners, three (x, y, z) for each, or NULL.
  • max: how many corners xyz has room for (so it holds 3 * max floats).
  • tex: the address of an int for its texture's number, from 0, or NULL.
  • nx: the address of a double for x of the way it faces, or NULL.
  • ny: the address of a double for y of the way it faces, or NULL.
  • nz: the address of a double for z of the way it faces, or NULL.

Returns how many corners the face has (even if more than max), or 0 if there's no face i.

levelstat

double levelstat(int level, const char *name)

Gives a number about the built level, such as "faces", "leaves", "portals", "luxels" (patches of baked light), "baked" (1 if it's lit), "drawn" (faces drawn last time), "shiny" (shiny faces) or "probes" (cube maps it's been given).

  • level: the level.
  • name: the name of the number you want.

Returns that number, or 0 for a name there isn't.

C reference: buttons, lists and dialogs

#include <macawui.h> for the toolkit of buttons, sliders, text boxes and lists, and for the dialogs. The widgets are immediate mode: you don't make them once and keep them, but call them every frame from your _draw function, between ui_begin and ui_finish. Each one draws itself and returns 1 in the frame it's clicked or changed, and the values it changes live in your program. Apps explains the toolkit, and C says how C programs work.

The frame and layout

ui_begin

void ui_begin(void)

Starts this frame's widgets. It clears the window to the paper colour, and widgets then stack down from the top left, 8 pixels in.

It takes nothing.

ui_beginex

void ui_beginex(int x, int y, int w, int bg)

Starts this frame's widgets, like ui_begin, but you choose where they go and what's behind them.

  • x: the left margin in pixels. -1 means 8.
  • y: the top margin in pixels. -1 means 8.
  • w: how wide the widgets are, in pixels. 0 is the window's width less the margins.
  • bg: a colour number to clear the window to, UI_DEFAULT for the paper colour, or UI_KEEP to keep what's drawn.

ui_finish

void ui_finish(void)

Ends this frame's widgets. It draws an open drop-down's list on top of everything, and moves the keyboard's focus when Tab was pressed.

It takes nothing.

ui_row

void ui_row(int n, const double *weights)

Puts the next few widgets side by side on one line, sharing its width.

  • n: how many widgets go on the line, up to 64.
  • weights: an array of n doubles for their widths, like { 2, 1 } to make the first twice as wide. NULL makes them all as wide.

ui_space

void ui_space(int pixels)

Leaves a gap before the next widget.

  • pixels: how tall the gap is, in pixels. 0 means 8.

ui_group

void ui_group(const char *title)

Starts a box with a title round the widgets that follow, until ui_endgroup.

  • title: the text at the top of the box. NULL for no title.

ui_endgroup

void ui_endgroup(void)

Ends the box ui_group started, and draws it round the widgets inside.

It takes nothing.

ui_at

void ui_at(int x, int y, int w)

Puts the next widget at exactly this place, instead of under the last one.

  • x: its left edge, in pixels from the window's left.
  • y: its top edge, in pixels from the window's top.
  • w: its width in pixels. 0 gives it the width it would usually have.

ui_disabled

int ui_disabled(int on)

Greys out the widgets after it, and they stop answering the mouse and keys. It stays that way, into the next frames too, until you switch it off.

  • on: 1 to grey them out, 0 to go back to normal.

Returns what it was before: 1 if widgets were greyed out, 0 if not.

ui_nexty

int ui_nexty(void)

Tells you where the next widget would go, so you can draw something of your own under a form.

It takes nothing.

Returns the next widget's top, in pixels from the window's top, or -1 outside ui_begin and ui_finish.

Widgets

ui_label

void ui_label(const char *s, int colour)

Shows some text, wrapped onto more lines if it's too long for the width.

  • s: the text.
  • colour: a colour number for it. -1 for the usual colour.

ui_heading

void ui_heading(const char *s)

Shows a heading, with a line under it.

  • s: the heading's text.

ui_separator

void ui_separator(void)

Draws a line across, to divide one part of a form from the next.

It takes nothing.

ui_button

int ui_button(const char *label, int w)

Shows a button. Enter or Space presses it too, while it has the keyboard's focus.

  • label: the text on the button.
  • w: its width in pixels. 0 fits the label (or fills its share of a ui_row).

Returns 1 in the frame it's clicked, 0 otherwise.

ui_checkbox

int ui_checkbox(const char *label, int *on)

Shows a tick box. A click ticks it or takes the tick away.

  • label: the text beside the box.
  • on: the address of an int of yours: 1 ticked, 0 not. A click changes it.

Returns 1 in the frame it's changed, 0 otherwise.

ui_radio

int ui_radio(const char *label, int *choice, int value)

Shows one choice of a set, where only one can be picked. Give every choice of the set the same choice.

  • label: the text beside it.
  • choice: the address of an int of yours, which the set shares. A click sets it to value.
  • value: this choice's number. It shows as picked while *choice is value.

Returns 1 in the frame it's clicked, 0 otherwise.

ui_slider

int ui_slider(const char *label, double *v, double min, double max, double step)

Shows a slider for picking a number between two others. The arrow keys move it too.

  • label: the text to its left. NULL or "" for none.
  • v: the address of a double of yours with the value. Dragging changes it.
  • min: the value at the left end.
  • max: the value at the right end.
  • step: the slider moves in steps of this size from min. 0 lets it take any value.

Returns 1 in the frame *v changes, 0 otherwise.

ui_textbox

int ui_textbox(const char *id, char *buf, int size)

Shows a box to type text in. Ctrl+C, Ctrl+X and Ctrl+V copy, cut and paste.

  • id: a name you choose, different for each box, so it remembers where its cursor is.
  • buf: your buffer with the text, which typing changes.
  • size: how many bytes buf holds, with its 0 at the end. Typing that won't fit isn't taken.

Returns 1 in the frame Enter is pressed in it, 0 otherwise.

ui_textboxex

int ui_textboxex(const char *id, char *buf, int size, const char *placeholder, int w, int password)

Shows a box to type text in, like ui_textbox, with a few more choices.

  • id: a name you choose, different for each box.
  • buf: your buffer with the text, which typing changes.
  • size: how many bytes buf holds, with its 0 at the end. Typing that won't fit isn't taken.
  • placeholder: grey text shown while the box is empty, like "your name". NULL for none.
  • w: its width in pixels. 0 for the full width.
  • password: 0 for plain text, UI_PASSWORD for stars and a key button for Nestchain, UI_PASSWORD_NOKEY for stars only.

Returns 1 in the frame Enter is pressed in it, 0 otherwise.

ui_listbox

int ui_listbox(const char *id, const char **items, int n, int *selected, int rows)

Shows a list to pick from. It scrolls with the mouse wheel, and the up and down keys move through it.

  • id: a name you choose, different for each list, so it remembers how far it's scrolled.
  • items: an array of n strings, the items from the top. A NULL one shows as empty.
  • n: how many items there are.
  • selected: the address of an int of yours: the picked item, counting from 0, or -1 for none.
  • rows: how many rows show at once. 0 means 5.

Returns 1 in the frame an item is double-clicked, or Enter is pressed on it, 0 otherwise.

ui_dropdown

int ui_dropdown(const char *id, const char **items, int n, int *selected, int w)

Shows a drop-down menu: a box with the picked item, which opens a list when it's clicked.

  • id: a name you choose, different for each one.
  • items: an array of n strings, the choices. A NULL one shows as empty.
  • n: how many items there are.
  • selected: the address of an int of yours: the picked item, counting from 0, or -1 for none.
  • w: its width in pixels. 0 for the full width.

Returns 1 in the frame another item is picked, 0 otherwise.

ui_tabs

int ui_tabs(const char *id, const char **names, int n, int *current)

Shows a row of tabs. You draw the widgets for the tab that's showing after it.

  • id: a name you choose, different for each set of tabs.
  • names: an array of n strings, the tabs' names from the left.
  • n: how many tabs there are.
  • current: the address of an int of yours: the tab showing, counting from 0. A click changes it.

Returns 1 in the frame another tab is clicked, 0 otherwise.

ui_progress

void ui_progress(double fraction, const char *label)

Shows a progress bar, for how far through something you are.

  • fraction: how full the bar is, from 0 (empty) to 1 (full).
  • label: text in the middle of the bar, like "50%". NULL for none.

ui_swatches

int ui_swatches(int *colour, int all)

Shows squares of colour to pick one from.

  • colour: the address of an int of yours: the picked colour number. A click changes it.
  • all: 0 for the 32 named colours, 1 for all 256.

Returns 1 in the frame another colour is picked, 0 otherwise.

ui_image

int ui_image(int picture, int scale)

Shows a picture among the widgets.

  • picture: a picture number from newpicture or loadpicture.
  • scale: how many times bigger to draw it, from 1 to 16. 0 means 1.

Returns 1 in the frame it's clicked, 0 otherwise.

The keyboard's focus, and where widgets are

ui_focus

int ui_focus(char *buf, int size)

Tells you which widget has the keyboard's focus, so your own key handling can leave it alone.

  • buf: a buffer for the widget's id, such as a text box's id. It gets "" when none has it.
  • size: how many bytes buf holds.

Returns the id's length, or 0 if no widget has the focus.

ui_setfocus

void ui_setfocus(const char *id)

Gives the keyboard's focus to a widget, such as a text box you want the person to type in first.

  • id: the widget's id. NULL takes the focus away from every widget.

ui_typing

int ui_typing(void)

Tells you whether a text box is taking the keys. While it is, Ctrl+C, X, V and A are the text box's, not your menus'.

It takes nothing.

Returns 1 if a text box has the focus, 0 if not.

ui_rect

int ui_rect(const char *id, int *x, int *y, int *w, int *h)

Tells you where a widget was last drawn, in the window.

  • id: the widget's id, as you gave it to a text box, list, drop-down or tabs.
  • x: pass the address of an int for its left edge, in pixels. NULL skips it.
  • y: pass the address of an int for its top edge, in pixels. NULL skips it.
  • w: pass the address of an int for its width, in pixels. NULL skips it.
  • h: pass the address of an int for its height, in pixels. NULL skips it.

Returns 1, or 0 if no widget with that id has been drawn.

Dialogs

Dialogs don't pause your program. Each calls a function of yours when the person answers, and doesn't call it if they cancel. Text it's given lasts only for that call, so copy it to keep it.

alert

void alert(const char *message)

Shows a message with an OK button.

  • message: the text to show.

confirm

void confirm(const char *question, void (*fn)(void))

Asks a question with OK and Cancel buttons.

  • question: the text of the question.
  • fn: your function, called with nothing if they click OK. NULL only shows the question.

askstring

void askstring(const char *prompt, const char *initial, void (*fn)(const char *text))

Asks the person to type some text.

  • prompt: the question above the box.
  • initial: the text in the box to start with. NULL for an empty box.
  • fn: your function, called with the text they typed when they click OK.

openfile

void openfile(void (*fn)(const char *path), const char *dir, const char **exts, int n)

Shows the Open dialog, for the person to pick a file.

  • fn: your function, called with the whole path of the file they picked.
  • dir: the folder it starts in, from your program's folder unless it starts with /. NULL for /home.
  • exts: an array of n file endings it can open, without the dot, like { "pxl", "png" }. NULL for any file.
  • n: how many endings are in exts. 0 for any file.

savefile

void savefile(void (*fn)(const char *path), const char *dir, const char *name)

Shows the Save dialog, for the person to choose a name and a folder. It asks first if the file is already there.

  • fn: your function, called with the whole path to save to.
  • dir: the folder it starts in, from your program's folder unless it starts with /. NULL for /home.
  • name: the file name it suggests. NULL for "untitled".

pickcolour

void pickcolour(void (*fn)(const char *hex, int rgb), const char *hex, const char *title)

Shows the colour picker, for picking any colour.

  • fn: your function, called with the colour as "#rrggbb" text and as the number 0xRRGGBB.
  • hex: the colour it starts on, like "#ff8800". NULL for white.
  • title: the picker window's title. NULL for "Pick a Colour".

Drag and drop

ondrop

void ondrop(void (*fn)(const char **paths, int n, int x, int y))

Sets a function to call when files are dropped on your window, from Files or the computer. It takes the place of a _drop function.

  • fn: your function. It gets an array of n whole paths, and where they were dropped in the window, in pixels (-1, -1 for files from pickfiles). NULL stops it.

canpickfiles

int canpickfiles(void)

Tells you whether pickfiles works here. It only works on the website.

It takes nothing.

Returns 1 if it works, 0 if not.

pickfiles

int pickfiles(void)

Asks the person to pick files from their computer. Once they're copied in, they come to your ondrop function (or _drop), at -1, -1.

It takes nothing.

Returns 1 if it asked, or 0 where it can't (anywhere but the website).

startdrag

void startdrag(const char **paths, int n, const char *label)

Starts dragging files out of your window, to Files, the Trash, the desktop or another program. Call it while the mouse button is down: they're dropped where it's let go.

  • paths: an array of n paths, each from your program's folder unless it starts with /.
  • n: how many paths there are.
  • label: the text shown by the pointer while dragging. NULL for the first file's name.

putondesktop

int putondesktop(const char *path, char *buf, int size)

Puts an alias of a file, folder, program or game on the desktop.

  • path: what to make an alias of, from your program's folder unless it starts with /.
  • buf: a buffer for the alias's own path, in /home/Desktop, or for why it didn't work.
  • size: how many bytes buf holds.

Returns the length of the alias's path, or -1 if it didn't work.

Networking

Macaw OS is on the Macaw network, a small internet of its own where everyone dials in to a Macaw ISP. Programs can connect to anyone dialled in to the same ISP, to the sites registered with it, and to the ISP's own services. They can't reach the internet outside. The network is closed, so nobody can use a Macaw OS program to get at the outside world, or get at Macaw OS from it.

Everything goes over the dial-up line, at the line's speed. A 56k line brings in about 5 KB a second.

Tasks

Network code has to wait. It waits to dial, for the other end to answer, and for data to arrive. A program can't stop and wait without freezing its window, so network code runs in a task. A task is a function that runs a little each frame alongside your program, and it can wait as long as it needs to.

local status = "connecting..."

local function show(s)
  status = s
  redraw()                         -- the window only draws again when asked
end

spawn(function()
  if not wait_online() then show("not online"); return end    -- dials if it has to
  local s, err = connect("macaw.com", 80)
  if not s then show(err); return end
  s:send("GET / HTTP/1.0\r\nHost: macaw.com\r\n\r\n")
  show(s:readline() or "no answer")    -- "HTTP/1.0 200 OK"
  s:close()
end, function(err) show("went wrong: " .. err) end)

function _draw()
  cls(colors.paper)
  text(status, 4, 4, colors.night)
end

The window isn't realtime, so it only draws again when you call redraw(). That's why show calls it each time the status changes.

CallWhat it does
spawn(fn, [on_error])Runs fn as a task. If it crashes, on_error(message) is called
wait_online()Dials if Macaw OS isn't online, and waits. Returns false if the person cancels
online()Returns whether Macaw OS is online now
sleep(seconds)Waits, in a task

Connecting

CallWhat it does
connect(host, port, [seconds])Connects, and waits until the connection is open (for 15 seconds at most). Returns a socket, or nil and the reason
tcp(host, port)Starts connecting without waiting. Check s:status() to see when it's open

Hosts are names on the Macaw network. They can be macaw.com and the other sites people register, isp.macaw for the ISP itself, or name.macaw for someone called name who's dialled in.

These are a socket's calls:

CallWaits?What it does
s:send(data)noSends data
s:readline()yesReturns a line without its line ending, or nil once the other end has gone
s:read(n)yesReturns exactly n bytes
s:readall([progress])yesReturns everything until the other end closes. progress(bytes) is called as data comes in
s:pollline()noReturns a whole line if one has arrived, or nil
s:receive()noReturns whatever has arrived
s:status()noReturns "connecting", "open", "closed" or "error", and a message
s:close()noCloses the connection

The calls that wait only work in a task.

Serving

Other people can connect to you at yourname.macaw. This program answers everyone who connects on port 7000, and counts them:

local visitors = 0

spawn(function()
  if not wait_online() then return end
  local l = assert(listen(7000))
  while true do
    local c = l:accept()               -- doesn't wait, and is nil if nobody's there
    if c then
      c:send("Hello from Macaw OS\r\n")
      c:close()
      visitors = visitors + 1
      redraw()
    end
    sleep(0.1)
  end
end)

function _draw()
  cls(colors.paper)
  text(visitors .. " visitors", 4, 4, colors.night)
end
CallWhat it does
listen(port)Listens on a port. Returns a listener, or nil and the reason
l:accept()Returns the next person who has connected, as a socket and where they're from. Returns nil if nobody has
l:port()Returns the port
l:close()Stops listening

When your window closes, its sockets and tasks close with it.

Programs to learn from

Macaw OS's own network programs are in /system/apps, and they're worth reading:

  • Browser (browser.lua) shows web pages over HTTP, written in HTML or Markdown.
  • FTP (ftp.lua) copies files to and from FTP servers.
  • Hotline (hotline.lua) does chat, news and files.
  • Server (server.lua) serves web pages, FTP and a Hotline server from your /home.

The simplest way to put something on the network is a website. You can write pages in Markdown in /home/www and run Server. Or you can register a name on the Macaw OS website and edit your pages there.

The Server app

Server shares web pages, files over FTP and a Hotline chat room from your computer. Everyone on the Macaw network can reach them while you're dialled in. Its settings are in its window, and it remembers them. Stop the server before you change them.

SettingWhat it does
NameWhat the server calls itself to visitors
Web pages, FTP files, HotlineTurns each one on or off and sets its port. They start as 8080, 2121 and 5500
FolderWhere each one's files come from. It has to be a folder inside /home, so nothing else on the disk can be shared by mistake
List folders that have no index pageWhen someone visits a folder without an index.html or index.md, shows them what's in it. Untick it and they get "not found" instead
Ask for a name and passwordLets only someone who signs in with the name and password you give use FTP. The password is saved in Nestchain, never in a plain file
Let anyone upload / Let them uploadWhether people can put files in the FTP folder, make folders and delete files. With sign-in on, only the person who signed in can
WelcomeThe message Hotline shows people when they join
Admin and passwordA Hotline account for you. Log in with it in Hotline and you're the admin. Your name shows in red, and you can right-click someone to disconnect them, or disconnect and ban them until the server stops. Leave the login empty for no admin
Let guests in, and its passwordWhether people can join Hotline without the admin's login. Give a password and guests need it too. Leave it empty and anyone can join
Guests can post news / Guests can downloadWhat guests may do. The admin can always do both

With sign-in off, anyone can use FTP with any name and password (most FTP programs send anonymous). They can only read files unless you let anyone upload.

Nothing on the Hotline server works until someone has logged in. Both Hotline passwords are saved in Nestchain.

Your address on the network is name.macaw, where name is the name you dial in with. Other people visit your pages at http://name.macaw:8080/, and connect to your FTP at name.macaw on port 2121.

The FTP app

FTP copies files between your computer and an FTP server. Type the server and port on the first row. If the server asks for a name and password, type them on the second row. For servers that don't, leave the name as anonymous. Your files are on the left and the server's are on the right. Select a file and use the arrows in the middle to copy it across.