# Recipe: a third-person 3D game

Goal: a hero the player turns and walks, the camera behind it, on a floor with things to
walk round, under a sky with shadows. Two ways: start from the finished template, or
build the small sample below.

## From the template

```sh
frost new mygame --template embers   # a whole third-person game: hero, wardens, embers
frost check mygame/game.toml
frost test mygame                    # its 2,653-step recording holds
```

Read `mygame/game.toml`, `arena.toml` and `main.luau`, then change it.

## From nothing

The third-person sample. Make an empty folder and
write the three files below side by side in it (the comment at the top of each says the
sample's own path; the names are what matter: `game.toml`, `yard.toml`, `main.luau`). The
fourth file, `shots/walk.png`, is made by `frost test --write` from the run, below.

```toml
# example: third-person/game.toml
# A hero to walk round a yard with the camera behind it: the third-person recipe's game.
# A and D turn, W and S walk, Space jumps.
#
#   frost dev game.toml
#   frost run --headless --steps 140 --shot walk.png game.toml
space = "3d"
scene = "yard.toml"
scripts = ["main.luau"]
seed = 1
shots = [{ name = "walk", step = 140 }]
replay = { steps = 240, checksum = "da9834c571080c23", engine = "0.0.1 r280" }
# The run's checksum on the way there, written by `frost test --write`: a test that
# fails says between which two of these steps the game first went another way.
checkpoints = []

[window]
size = [640, 360]
background = 0x1b2030

# 3D physics on Jolt: the hero is a Mover, the floor and the crates are colliders.
[physics]

[input]
actions = ["turn", "walk", "jump"]
recording = [
    { steps = 30 },
    { steps = 80, walk = 1 },
    { steps = 15, turn = -1, walk = 1 },
    { steps = 1, walk = 1, jump = 1 },
    { steps = 114, walk = 1 },
]

[input.keys]
turn = { negative = "A", positive = "D" }
walk = { negative = "S", positive = "W" }
jump = "Space"
```

```toml
# example: third-person/yard.toml
# The camera is the engine's: Follow keeps it behind the hero and in front of walls.
[camera]
Transform = {}
Camera = { fov = 60, near = 0.1, far = 120 }
Follow = { of = "hero", back = 6, up = 2.5 }

# The afternoon sun, with shadows, and a haze that melts the far edge into the sky.
[sky]
Sky = { time = 15.5, shadows = true, reach = 30, haze = 20, haze_far = 60 }

[floor]
Transform = { y = -0.5, sx = 200, sy = 1, sz = 200 }
Mesh = { file = "box", tint = 0x6f8a55 }
Collider = { w = 1, h = 1, d = 1 }

[crate_a]
Transform = { x = 2, y = 0.5, z = 6 }
Mesh = { file = "box", tint = 0xb07a45 }
Collider = { w = 1, h = 1, d = 1 }

[crate_b]
Transform = { x = -3, y = 1, z = 9, sx = 2, sy = 2, sz = 2 }
Mesh = { file = "box", tint = 0x9a6a3c }
Collider = { w = 1, h = 1, d = 1 }

[pillar]
Transform = { x = 4, y = 2, z = 14, sx = 1, sy = 4, sz = 1 }
Mesh = { file = "cylinder", tint = 0xd8d2c4 }
Collider = { shape = "cylinder", w = 1, h = 1 }

# The hero is a capsule the physics walks (Mover); what is drawn is a child of it.
[hero]
Transform = { y = 0.8 }
Collider = { shape = "capsule", w = 0.6, h = 1.6 }
Mover = { step = 0.3 }

[hero_look]
Parent = { of = "hero" }
Transform = { sx = 0.6, sy = 0.8, sz = 0.6 }
Mesh = { file = "capsule", tint = 0xf2364b }
```

```lua
-- example: third-person/main.luau
-- Turn with A and D, walk with W and S, jump with Space. Gravity and the jump are the
-- script's; walking into things, stairs and slopes are the Mover's. No camera code:
-- the camera's Follow (yard.toml) keeps it behind the hero.
local WALK, TURN, JUMP, GRAVITY = 4, 150, 5, 14

state.yaw = state.yaw or 0

function step(dt)
    local hero = find("hero")
    state.yaw = (state.yaw - input.get(0, "turn") * TURN * dt) % 360

    local vy = 0
    if not get(hero, "Mover", "grounded") then
        vy = math.max(get(hero, "Mover", "vy") - GRAVITY * dt, -20)
    elseif input.held(0, "jump") then
        vy = JUMP
    end
    local yaw = math.rad(state.yaw)
    local walk = input.get(0, "walk") * WALK
    set(hero, "Mover", "vx", math.sin(yaw) * walk)
    set(hero, "Mover", "vz", math.cos(yaw) * walk)
    set(hero, "Mover", "vy", vy)

    -- Face the way it walks: a model's front is +z, and the Follow camera turns with it.
    local qx, qy, qz, qw = quat.turn(state.yaw, 0, 0)
    place(hero, get(hero, "Transform", "x"), get(hero, "Transform", "y"), get(hero, "Transform", "z"), qx, qy, qz, qw)
end
```

What matters:

- `space = "3d"` and a `[physics]` table: 3D physics on Jolt, metres, y up.
- The hero is a `Collider` capsule with a `Mover`: the script says the velocity it
  wants (`vx`, `vy`, `vz`), the engine walks it into walls, up `step` ledges and slopes,
  and says `grounded`. Gravity and the jump are the script's.
- What is drawn is a child (`Parent = { of = "hero" }`): a scale on the collider's own
  thing would scale the collider too.
- `Follow = { of = "hero" }` on the camera is the whole camera: behind, above, eased,
  kept in front of walls. Write no camera code.
- `place(e, x, y, z, qx, qy, qz, qw)` turns the hero to face its yaw; a model's front is +z.
- `Sky = { time, shadows = true }` is the sun, the sky and the ambient light at once.

Fetch more with `frost reference 3d`, `frost reference physics`, `frost reference input`.

## Checks

```sh
frost check game.toml                       # checked 3 files: no problems
frost run --headless --steps 140 --shot walk.png game.toml   # look at walk.png
frost test --write game.toml                # writes replay's checksum, takes shots/walk.png
frost test game.toml                        # ok: 240 steps to run checksum ..., 1 shot the same
frost test --restore game.toml              # state survives being put back
```

Order matters the first time: until `frost test --write` has taken the shot, plain `frost
test` fails with `1 of 1 shot changed or new`, even when the checksum holds. `--write`
also writes `checkpoints`, the run's checksum at every 256th step: a 240-step run has none,
so `checkpoints = []` is right. `--shot walk.png` is the picture after the last step;
`--shot 140=walk.png` (as the core writes it) takes the one after step 140 of a longer run.

Look at the shot before accepting: the hero in the middle, the camera behind it, and each
thing's shadow on the floor, away from the sun. (From this angle the hero's own shadow
falls behind it, out of view.) The sample's kept picture:

![The third-person sample at step 140](../../files/examples/third-person/shots/walk.png)

### After a change

A change you meant moves the run: look at a new shot first, then accept both the run and
the picture.

```sh
frost run --headless --steps 140 --shot walk.png game.toml   # look at it
frost test --write game.toml                # the new checksum (a kept shot is compared, not replaced)
frost check --shots --write-shots game.toml # keep the new picture, once you have looked
frost test game.toml                        # ok again
```

Over MCP, the same checks are `game_check`, `game_seek {step: 140}` then `frame_capture`,
and `world_get {entity: "hero", component: "Mover"}` to read `grounded`.

## Next: a ground with hills

The hills sample is the same yard on a height field. The
floor box becomes a `Ground`, which a small TOML file and a grey PNG describe:

```toml
# example: hills/art/hill.ground.toml
# The yard's ground: hill.png's samples, 128 metres across x and z, black at `low` and
# white at `high` metres above the Ground thing's own Transform y.
heights = "hill.png"
size = [128, 128]
low = 0
high = 6
```

The ground's middle is where its thing's `Transform` puts it, and its heights are
measured from that `Transform`'s `y`: a black sample is `low` above it, a white one `high`,
a grey one in between. With `Transform = {}` and `low = 0`, the flat black middle is at
`y = 0`, where the hero stands; the same ground under `Transform = { y = 1 }` is a metre
higher everywhere (measured with `ground.at`). The picture is
square, its side even, 4 to 1024 samples, row 0 at -z. This one is made by a script with
Python's standard library:

```
# example: hills/art/make.py
#!/usr/bin/env python3
"""Writes hill.png, the yard's height field: 128 by 128 grey samples, flat (black) within
18 metres of the middle and rising to hills (up to white) beyond. Python's standard library
only. Run it again after changing a number: python3 make.py"""
import math
import struct
import zlib
from pathlib import Path

SIDE = 128     # samples a side: even, 4 to 1024
METRES = 128.0  # the ground's size, as hill.ground.toml says


def height(x, z):
    """0 to 1: 0 is the file's `low`, 1 its `high`."""
    rise = max(0.0, min(1.0, (math.hypot(x, z) - 18) / 14))
    rise = rise * rise * (3 - 2 * rise)
    return rise * (0.6 + 0.4 * math.sin(x * 0.15) * math.cos(z * 0.12))


rows = []
for row in range(SIDE):  # row 0 is at -z
    z = (row / (SIDE - 1) - 0.5) * METRES
    line = bytearray([0])  # PNG's filter byte: none
    for column in range(SIDE):
        x = (column / (SIDE - 1) - 0.5) * METRES
        line.append(round(max(0.0, min(1.0, height(x, z))) * 255))
    rows.append(bytes(line))


def chunk(kind, data):
    return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))


png = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", SIDE, SIDE, 8, 0, 0, 0, 0))
       + chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + chunk(b"IEND", b""))
(Path(__file__).parent / "hill.png").write_bytes(png)
```

In the sample's `yard.toml`, the floor is:

```toml
[floor]
Transform = {}
Ground = { file = "art/hill.ground.toml", color = 0x6f8a55 }
Collider = { shape = "ground" }
```

`Collider = { shape = "ground" }` makes the physics walk on the same heights, so the
Mover climbs the hills. `ground.at(x, z)` (a script) and the protocol's `ground.at {x, z}`
say the height there: in the sample, 0 at the middle and 5.85 at `x = 50`. Then the
checks above, including "After a change".

## More

- Touch controls on a phone: `[input] fingers` (`frost reference input`), as Embers does.
- Look: [3D rendering](../../guides/3d-rendering.md) for lights, AO, bloom, MSAA.
