> devlog · rendering

Drawing a dungeon in a terminal

How every room in the game is built from a seed, folded into a lit picture, flooded, and walked into in 3D. No game engine, no GPU, no shaders: Python, a 32-color palette and a grid of character cells.

PTG devlog11-minute tech demo15 min read

The tech demo, 11½ minutes, calm on purpose. Everything in it is the game's own code drawing, or the game itself being played. Watch it on YouTube.

Most games that look like this are made in an engine: a scene graph, a renderer, shaders, a GPU. This one is a Textual app. It lays itself out on a grid of character cells and runs in a terminal, a browser tab or a phone. There is no 3D model of the dungeon anywhere on disk, and no painted backgrounds. Every room you see was generated a moment before you walked in.

The video walks through the whole pipeline, one stage at a time. This page is the same walk, slower, with the numbers from the code.

00The game

It's a roguelite. You explore a floor room by room, you click an action or type what you want to try, and a twenty-sided die decides, against your character's stats. The engine keeps the facts, and a narrator tells you what happened.

The video's first 75 seconds, here on the page: the game, then a room taken apart.

A drowned congregant drops into a flooded street
Lych Lane, on the Drowned. Through a door in 3D, and a congregant drops in.
The d20 card: trip the congregant, a 15, IT WORKS
"Trip the congregant." The die is thrown: a 15, and it works.
A new item's card: the Silvered Blade, its model turning
Something new. Every item has its own picture and its own 3D model.
The pack, its items on a shelf, the equipped doll beside them
The pack. What you carry, what you wear, and what each does.

01Every room

The room this page takes apart is the Chandlery, on the Drowned, the eighth floor. Nobody drew it. The game drew it, from a seed, in Python.

It's one of seventy-six kinds of room, across ten floors. The same code draws every one of them, from that floor's own look (bricks and candles, earth and torches, marble under the stars, a cave of glowing mold) and the things that floor allows. Each room is drawn fresh from its seed, with its own layout, decor and contents, so no two ever come out the same.

Ten rooms from ten floors in a grid
Ten rooms, ten floors, one renderer: the Sunken Crypt, the Goblin Warren, the Overgrown Ruins, Norfel, the Underbloom (twice), the Hush, the Stitchery, the Drowned and the Underdrawing.

02A room, as the engine sees it

Each room is a plan: a 25 × 9 interior inside a wall, written as characters. # is wall, + a door, ~ water, O a pillar. Decor is painted by small rules: water as two or three random ellipses, pillars in rows, bones scattered. Features stand against the walls, the fixture in the middle, and the two cells inside every doorway are kept clear so you can always get in and out.

The Chandlery's plan written in characters
The Chandlery's plan. Shelves along the back and front walls, the shrine † in the middle, a rack of candles ı and a wax trough ∪ against the walls.

This plan is the truth about the room. The narrator (a language model, when one is switched on) is only ever told where things are. It never places them, because language models are bad at keeping space consistent. Every picture, every 3D frame and every map is drawn from these characters.

in the code · layout.py build, _paint, KEEP_CLEAR

03Folding the plan into a picture

The picture is drawn in one-point perspective from the doorway you came in by. Every cell of the plan gets two coordinates: a, how far across (negative is left), and z, how far away. One formula does almost all the work: a cell z deep is drawn smaller by

s(z) = d / (z + d)    x = center + a · k · s    y = floor(s) − v · (floor(s) − ceiling(s))

d is how far the camera stands behind the doorway (0.7 of the room's depth), k sets how wide the room looks, and the horizon sits 30% of the way down the frame. At the doorway s is 1 and the floor meets the bottom of the frame. At infinite depth s is 0 and everything converges on the horizon. Walls are the same points lifted a fraction v of the way to the ceiling.

The plan's grid in perspective, with depth rows labeled by their s and the formulas on the side walls
The sums on the grid: rows at depths 1 to 8 with their s, a line at one fixed a, the horizon, and a point lifted halfway up a wall.
The room's surfaces textured but evenly lit
Textures, from hashed value noise: the same room draws the same way every time, and nothing is stored.
The finished Chandlery
Lit, then furnished, far to near, each thing sized against how tall a person would be at that depth.

The picture isn't projected from geometry the way a 3D renderer does it. It goes the other way: every pixel asks where it lands. For each pixel the code works out which surface it's on (back wall, side wall, floor, ceiling), the (a, z, v) point there, which brick or flagstone that is, and how far into it. That surface pass is about nine tenths of a picture's work and depends only on the room's size, its lights and which door you came in by, so it's kept: a room you come back to only redraws what stands in it.

in the code · room_picture.py View, Lens, _geometry, _paint, _layer

04A floor is a walk on a grid

A floor starts as a handful of rooms on a square grid. They grow one at a time from a seeded random walk: pick a room, pick a direction, step. The only bias is that 60% of the time the walk steps from one of the last three rooms, so the floor stretches out into wings instead of clumping.

while len(coords) < size:
    source = rng.choice(coords[-3:]) if rng.random() < 0.6 else rng.choice(coords)
    dx, dy = DELTA[rng.choice(DIRECTIONS)]
    cell = (source[0] + dx, source[1] + dy)
    if cell in index: continue
    ...   # a new room, joined to its source

That gives a tree, and trees mean backtracking, so two extra doors make loops. A breadth-first search numbers every room by its distance from the entrance. The farthest dead end gets the boss, and the door into it locks. Everything comes from named random streams, so the same seed always builds the same floor, and adding a feature to one room never shifts a die roll anywhere else.

The Drowned's floor as a graph, colored by distance
The Drowned, seed 23. Gold lines are the loops; red is the farthest dead end.
The same floor with each room's plan drawn in
Each room filled with its plan, walls shared with its neighbors.

in the code · world.py _layout, _add_loops, _bfs, _build_floor

05Light, and light that isn't fire

A room has a list of lights: the lantern you carry, candles and wall sconces, a burning shrine, anything that glows. A pixel's light is the room's ambient, plus your lantern falling off with depth, plus every light in reach with a squared falloff:

level = ambient + lantern·(1 − 0.9·z)^1.6 + Σ power·(1 − dist/radius)²

Then the level picks a color off a ramp, eight shades of a palette color from black to highlight. Warm light switches to the fire ramp, and the cold light of something growing switches to the floor's glow ramp. Where one shade meets the next, a 4 × 4 Bayer matrix nudges the threshold pixel by pixel, so the bands interleave instead of stepping: ordered dithering, as 1990s games did it, for the same reason.

The Underbloom's glowcap grove, lit teal
The Underbloom. Only the shrine's candles burn. The caps and mold give a cold, teal light.
A close-up of ordered dithering
The Bayer cross-hatch, close up, where two shades meet.

Flicker costs almost nothing. As the surfaces are painted, every pixel a flame reaches is noted with what it was painted from. A flicker beat is just those pixels shaded again a little brighter or dimmer, keeping only the ones whose color changes. The loop is made once per room and sent to the browser once, which plays it on its own.

in the code · room_picture.py Picture.light, shade, _pick, flicker, _patched

06Water

In a room's plan, water is only a ~ in some cells. Each floor pixel blends the four cells around it and is water above a threshold, so square cells come out as round pools. Ripples are rows of the water picked by a hash, a few of them a step brighter. They bunch up toward the horizon on their own, the way they do on real water.

Reflections are done a column at a time. The code finds the waterline (where a wall or a thing meets the water) and mirrors what's above it into the water below, in the water's own colors, but only every other row. The rows between stay plain water, and that's what makes it look broken up by the surface rather than pasted on.

The parish nave with reflections off
Reflections off.
The parish nave with reflections
Reflections on: the pillars and the congregant in the water.
The reflected pixels highlighted in gold
The pixels the reflection pass changed, in gold: a column at a time, every other row.

in the code · room_picture.py _wet, _water, _reflections

07Lighting flat sprites

The monsters and props are hand-drawn pixel art, lit from the top left. To light one from a real candle it needs a shape, so the code invents one: the silhouette is inflated into a Poisson pillow (solve ∇²h = −4 inside it with a few dozen sweeps of over-relaxation, then take √h), round where it's broad and a tube where it's thin. The slope gives every pixel a normal.

Then, to keep it pixel art: a pixel that faces the flame more than it faced the artist's light moves one step up its own color's ramp, one that faces it less moves one step down. Never a new hue. Outline that faces the flame takes the flame's color, as a rim. Each fire in the room is scored by its power over its distance, and the best one lights the sprite.

A sprite as drawn, its pillow, its normals, and relit
The Precentor: as drawn, the pillow, its normals, and lit by the flame.
The Tallyman at his desk, half as drawn and half relit
The Tallyman at his desk. Left of the line, as drawn; right, lit by the candle nearest him.

in the code · relight.py pillow, facing, step, relit

08Cast shadows (a spike)

An experiment, not in the game yet: each thing throws its own silhouette away from the light that matters most where it stands. Nothing is painted over it. The light there drops a step, and the room's own ramps and dithering draw the shadow. It reads on flagstones and vanishes into noisier floors, and the relit sprites did far more for the picture.

The sexton's house without cast shadows
As the game draws it.
The same room with the spike's shadows highlighted
With the spike's shadows, the changed pixels in gold.

09One room, every screen

The same Picture class draws the room at whatever size it's handed: wide across the top in the wide grid, tall in the upright one, a strip on a phone. It doesn't crop a master image. Its lens recomposes the room for the shape.

The Chandlery drawn for four screens
Four screens, four drawings, each fresh at its own size.
WhereHow it reaches the screenPixels in a cell
Browser, desktop app, phonean image on the page's art layer, over xterm.js4 × 8, square
Kitty, Ghosttyan image through the Kitty graphics protocol4 × 8, square
Any other terminalhalf-block characters, two colors a cell1 × 2

In a plain terminal a cell can only hold a character, so the picture falls back to the upper half block ▀, its foreground the top pixel and its background the bottom one. Everywhere else there are no half-height pixels: sixteen times the pixels, all square, and every color still snapped to the 32-color palette.

The same patch in half blocks and at the page's resolution
The shrine, close up: a plain terminal's half blocks, and the page's square pixels.

10Upscaling our own art

The walls are drawn at the page's full resolution, but the sprites were made 24 to 48 pixels across. Blown up four times in blocks, they looked pasted on. So fixtures and about 34 props are now drawn in code at the page's pixels (boxes, cylinders, bowls and flames, shaded by the room's own light), and monsters go through Scale2x or Scale3x, which fills a corner from its neighbors' colors instead of copying it. Bosses keep their pixels.

The sunk street with sprites blown up in blocks
Blocks.
The same street with props drawn in code and the toad smoothed
Drawn in code, smoothed.
The toad up close, in blocks and smoothed
The toad: blocks, then Scale2x and Scale3x.

11Into 3D

Walk through a door and the camera doesn't cut: it walks you across the room in true perspective, a first-person raycaster drawn from the same plans. The floor's room plans are stitched into one map, and each frame casts one ray per column: step to whichever grid line is nearer until the ray hits a wall (DDA), all 640 columns at once in numpy. A wall's height on screen is one over its distance. Floors and ceilings go a row at a time, things stand up as sprites clipped by a depth buffer, and a bookshelf lies flat along its wall.

The first frame is the picture. The walk starts from the 2D picture's own camera, worked out backward from its lens, with the world squeezed along its depth by the same amount the picture squeezes a deep room. So when the walk begins, nothing jumps.

The 2D picture
The 2D picture.
The raycaster's first frame
The raycaster's first frame, from the picture's own camera.
A 3D frame with the floor map and its rays
A ray a column: 40 of the 640 rays on the floor map.

in the code · projector.py Floor, _cast, draw, picture_camera, Path, look_round

12What it costs

3,761lines: the room picture
2,218lines: the raycaster
1,207lines: things drawn in code
76kinds of room, 10 floors
32colors, every pixel
~0.3 sa picture, at the page's size

The stack is Python, Pillow, numpy for the 3D, and Textual for everything on screen.

Loose ends

The Underbloom doesn't walk in 3D yet. Its cave walls and mycelium floor have no 3D painter, so its door walks fall back to bricks. Shadows are a spike. To ship, they'd be a layer of their own over the kept surfaces, redrawn when something moves.

The dungeon is listening.

Get notified