Rebuilding Procedural Playground by hand
Stage 6 of 11: all the posts
  1. Before you start
  2. 1A new project
  3. 2Leela's model and texture
  4. 3The ground, the sun and the dusk
  5. 4Second-order dynamics
  6. 5The camera
  7. 6The picture
  8. 7Leela's scene
  9. 8Standing and walking on physics
  10. 9Her bones
  11. 10The player's keys
  12. 11Going further
  13. Last: full screen
  14. How this was checked

Stage 6 of 11

The picture: pixels, an outline and a tube

By the end

  • The game's picture: big PS1 pixels, dithered colours and an old TV tube over it all.
  • A camera that moves only by whole pixels, so still things never shimmer.
  • The outline set up as the repo has it, and the reason it draws nothing under this camera.

Three autoloads turn the plain picture into the game's. An autoload is a node Godot makes at the start and keeps above every scene, so it can work on whatever scene is running, and any script can reach it by name.

AutoloadWhat it does
OutlineIs set up to draw a thin dark line round everything in the group outline. Under this camera it draws nothing, in the repo too: see "The outline" below.
PsxTurns the picture into big pixels with PS1-style colours, caps the game at 30 frames a second, and tells the camera how big a pixel is.
CrtLays an old TV tube over everything: scanlines, glow, rounded corners.

All of it came from Wagee, so you bring the files in and read what they do.

Bring them in

  1. Copy these seven files from the repo's look/ folder into yours: outline.gd, outline.gdshader, psx.gd, psx_screen.gdshader, psx_wobble.gdshader, crt.gd and crt.gdshader.
  2. Open Project → Project Settings, tab Globals, sub-tab Autoload.
  3. Press Select Script/Scene and choose res://look/outline.gd. A row appears, named Outline, with Enable ticked under Global Variable.
  4. Do the same for psx.gd (it's named Psx) and crt.gd (Crt).
  5. The rows must read Outline, Psx, Crt from the top. The two arrows at the right end of a row move it up and down.
Clip · 1:02 · no sound Steps 2 to 5. The three scripts are chosen one after another with Select Script/Scene. Added in this order, they need no moving.

The names matter: the scripts look for each other as /root/Psx and /root/Crt. The order matters too: Outline swaps each mesh for a copy of itself with extra data in it, and that has to happen before Psx swaps materials.

Put the box in the outline's group

A group is only a name that nodes can share, so that a script can ask for "everything called this".

  1. In main.tscn select StandIn and open the Groups dock (a tab beside the Inspector and Signals).
  2. Press + (its tooltip is Add a new group.). In Create New Group, type outline as the name, leave the Global switch off, and press Create.
  3. outline is now in the list, under Scene Groups, with its checkbox ticked: that tick is what puts StandIn in the group. A small badge by StandIn in the Scene dock says it's in one.
Clip · 0:23 · no sound The three steps. (Global only decides whether the editor lists a group in every scene. To the running game a group is just its name.)

Checkpoint

Run it.

  • The picture is in chunky pixels, each 2 screen pixels across in a 720-row window (3 in a 1080-row one).
  • The fog's fade is a fine pattern of dots, not smooth.
  • There are scanlines, a little glow, and dark rounded corners.
  • The box has no outline. That's expected: "The outline" below says why, and how to see one.

Click the game so it has the keyboard, then: F2 switches the pixels off and on, and F4 the tube. (F5 is the outline's. These keys only work in a game run from the editor.)

  • No pixels or tube, and errors about files not found: one of the seven files isn't in look/.
  • Pixels but no tube, or the other way round: that script isn't in the Autoload list.

The pixels: psx.gd and psx_screen.gdshader

Psx is a CanvasLayer, a 2D layer over the 3D picture. It holds one rectangle the size of the screen, and the rectangle's shader redraws the picture that's under it:

look/psx.gd lines 32–43
func _ready() -> void:
	layer = -1  # over the 3D, under any HUD (layer 1 and up) and the CRT (crt.gd)
	var material := ShaderMaterial.new()
	material.shader = SCREEN
	material.set_shader_parameter("strength", strength)
	_screen.material = material
	_screen.mouse_filter = Control.MOUSE_FILTER_IGNORE
	_screen.set_anchors_preset(Control.PRESET_FULL_RECT)
	add_child(_screen)
	get_viewport().size_changed.connect(_fit)
	await get_tree().process_frame  # the level builds itself in its _ready
	_set_on(true)

It waits a frame before switching on, because the level's pieces build themselves in their own _ready.

How big is a pixel? A whole number of screen pixels, worked out from the window's height:

look/psx.gd lines 118–121
func _fit() -> void:
	var size := Vector2(get_window().size)
	pixel = maxf(1.0, roundf(lerpf(1.0, size.y / ROWS, strength)))
	(_screen.material as ShaderMaterial).set_shader_parameter("pixel", pixel)

At full strength there'd be 256 rows down the window, like a PS1 game. The project's strength is 0.6, which gives blocks of 2 screen pixels in a 720-row window and 3 in a 1080-row one: about 360 rows either way.

The shader runs once for every pixel of the screen:

look/psx_screen.gdshader lines 17–28
void fragment() {
	vec2 cell = floor((FRAGCOORD.xy + shift) / pixel);
	// Each pixel takes its colour from the screen pixel in its middle, at that pixel's centre. (With
	// an even `pixel`, as at 720p, the middle falls between two of them, and edges flickered as the
	// view moved.)
	vec3 c = textureLod(screen, (cell * pixel + floor(pixel * 0.5) + 0.5) * SCREEN_PIXEL_SIZE, 0.0).rgb;
	float levels = exp2(mix(8.0, 5.0, strength)) - 1.0;  // (5 bits a colour at full strength, 8 at none)
	ivec2 d = ivec2(mod(cell, 4.0));
	c += DITHER[d.y * 4 + d.x] / 255.0 * (31.0 / levels);
	c = round(clamp(c, 0.0, 1.0) * levels) / levels;
	COLOR = vec4(c, 1.0);
}
  • cell is which big pixel this screen pixel belongs to. (shift is the camera's, below.)
  • c is the colour of the one screen pixel in the middle of that cell. Every screen pixel in the cell gets it, so the cell is one flat block.
  • levels is how many shades each of red, green and blue may have. The PS1's 15-bit colour had 32. At this strength it's about 73.
  • DITHER is the dots in the fog. With so few shades, a smooth fade would break into bands. So before rounding to a shade, each pixel is nudged up or down a little by a fixed 4 × 4 pattern. Neighbours round different ways, and the eye mixes them back into a fade.

Psx also sets the pace. When it switches on, it caps the game at 30 frames a second (Engine.max_fps = FPS if on else 0) and takes over any playing AnimationPlayer, to step it 15 times a second. Nothing here plays an AnimationPlayer (stage 9 switches Leela's off), and code that moves things itself, like the camera, still runs every frame.

The wobble that never runs. psx_wobble.gdshader is the PS1's other habit: a model's corners snap to a grid, so it jitters as it moves. Psx puts that shader on everything in the groups psx_character and psx_prop. But the shader only snaps under a perspective camera, and this one has none:

look/psx_wobble.gdshader lines 26–29
	vec3 view = (MODELVIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
	if (PROJECTION_MATRIX[3][3] < 0.5) {  // the camera's view, not the sun's (orthographic) shadow pass
		view = round(view * grid) / grid;
	}

PROJECTION_MATRIX[3][3] is 0 for a perspective view and 1 for an orthographic one. The test is there to leave the sun's shadow pass alone (the sun's view is orthographic), and here it leaves the camera's alone too. So in this project those groups give a model the shader's flat, shine-free shading and no jitter. It's the same in the repo.

The camera again: moving by whole pixels

Now that the picture is made of big pixels, there's a problem you can see for yourself.

Try it

Run the game, press Remote, click Camera and untick Snap. Now move StandIn 4 m, as in stage 5, and watch the edges of the floor's tiles while the camera glides. They crawl: pixels along every edge flicker between the two greys. Tick Snap and do it again: the tiles hold still and the whole picture slides.

Here's why. Each big pixel shows the world at one point, the middle of its cell. When the camera moves by part of a big pixel, all those points slide a little way across the world. A tile's edge that fell between two of them now falls on one, and that pixel changes colour. It happens all over the picture, on things that aren't moving at all.

The cure is t3ssel8r's:

  1. Work out how many metres one picture pixel covers. Call it a texel.
  2. Only ever put the camera a whole number of texels along its own right and up. Now the points land on the same spots of the world every frame, and a thing standing still keeps exactly its pixels.
  3. That alone would make the view move in jerks of one big pixel. So take what was rounded off, which is less than one big pixel, and slide the finished picture by it. Screen pixels are smaller than picture pixels, so the view glides again.

That's the rest of _place():

camera/iso_camera.gd lines 93–105
	var psx := get_node_or_null("/root/Psx")
	var pixel: float = psx.pixel if psx and psx.on else 1.0  # screen pixels to one of the picture's
	var rows := float(get_window().size.y)
	var shift := Vector2.ZERO
	if snap and rows > 0.0:
		var texel := _shown / rows * pixel  # m of the world to one of the picture's pixels
		var dx := where.dot(b.x) - roundf(where.dot(b.x) / texel) * texel
		var dy := where.dot(b.y) - roundf(where.dot(b.y) / texel) * texel
		where -= b.x * dx + b.y * dy
		shift = Vector2(dx, -dy) / texel * pixel  # (in screen pixels, y down)
	global_position = where
	if psx:
		psx.set_shift(shift)
  • texel: in a 720-row window at this zoom, 3.5 / 720 × 2, just under a centimetre.
  • where.dot(b.x) is how far along its own right the camera is. roundf(... / texel) * texel is the nearest whole texel to that, and dx is what's left over. dy is the same along its up.
  • where -= ... takes the leftovers off: the camera is on the grid.
  • shift is the leftovers in screen pixels (y turned over, because the screen's y runs down). It goes to Psx.set_shift(), which hands it to the shader. That's the + shift in the shader's first line.

The outline: outline.gd and outline.gdshader

First, the plain fact: with this camera you won't see an outline. The scripts do all their work, and one test in the shader then throws the result away. It's the same in the repo. It's still worth setting up, because a later script asks for the Outline autoload by name, and worth understanding. At the end there's a way to watch it work.

The outline is an old trick called an inverted hull: draw the model a second time, a little bigger, in one dark colour, and inside out, so that only its far side is drawn. The bigger copy shows round the edges of the real one.

"A little bigger" means pushing every corner of the mesh outwards, along its normal (the direction the surface faces there). That goes wrong at a hard edge. At a box's corner three faces meet, and the mesh has three corners there, one for each face, each with its own normal. Pushed out, they fly apart and the outline has gaps.

So outline.gd gives every corner a second normal: the average of all the normals at that spot. It keeps it in a spare slot of the mesh called CUSTOM0:

look/outline.gd lines 76–87
		var sums := {}
		for i in verts.size():
			var key := verts[i].snapped(Vector3.ONE * 0.0001)
			sums[key] = sums.get(key, Vector3.ZERO) + normals[i]
		var custom := PackedFloat32Array()
		custom.resize(verts.size() * 4)
		for i in verts.size():
			var n: Vector3 = (sums[verts[i].snapped(Vector3.ONE * 0.0001)] as Vector3).normalized()
			custom[i * 4] = n.x
			custom[i * 4 + 1] = n.y
			custom[i * 4 + 2] = n.z
		arrays[Mesh.ARRAY_CUSTOM0] = custom

Why this is code

The editor has no button for "average this mesh's normals and keep them in a spare slot". And it has to be done to every mesh in the group, including a BoxMesh (which is turned into an ordinary mesh first, because a built-in shape has no spare slots) and anything made while the game runs. That's a loop over a group, so it's a script: refresh(), above it in the file.

The shader does the pushing. It's set as each mesh's Material Overlay, a second material drawn over the mesh's own:

look/outline.gdshader lines 13–29
void vertex() {
	if (PROJECTION_MATRIX[3][3] > 0.5) {  // the sun's (orthographic) shadow pass: outlines cast no shadow
		POSITION = vec4(2.0, 2.0, 2.0, 1.0);
	} else {
		vec3 view = (MODELVIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
		if (wobble) {
			view = round(view * grid) / grid;
		}
		vec4 clip = PROJECTION_MATRIX * vec4(view, 1.0);
		vec3 n = (MODELVIEW_MATRIX * vec4(CUSTOM0.xyz, 0.0)).xyz;
		vec2 dir = (PROJECTION_MATRIX * vec4(n, 0.0)).xy * VIEWPORT_SIZE;  // in screen pixels
		if (length(dir) > 1e-6) {
			clip.xy += normalize(dir) * width * 2.0 / VIEWPORT_SIZE * clip.w;
		}
		POSITION = clip;
	}
}
  • dir is the smoothed normal as a direction on the screen, and the corner is pushed along it by width screen pixels. So the line is the same thickness however far the camera's zoomed. outline.gd sets width to one PSX pixel.
  • The first if is why nothing shows. It's there so that outlines cast no shadow: it asks whether the view is orthographic, as the sun's shadow pass is, and if so throws the hull off screen. In Wagee, whose camera has perspective, that picks out the sun's pass. Here the camera's own view is orthographic too, so the hull is thrown away there as well. It's the wobble's test the other way up.

That's been seen, not only read. On the owner's PC one paused frame of the repo's game was pictured with the outline switched on and off. Through the game's camera not one pixel differs. Through a camera with perspective, 11,732 do.

Try it: watch them work

Give the camera perspective for a moment.

  1. Run the game, press Remote and click Camera.
  2. Type proj into Filter Properties and set Projection to Perspective. The view jumps a long way back: the floor to the horizon, and the box a speck.
  3. Change the filter to fov and set FOV to 6.7.

A lens that narrow, from 30 m back, frames almost the same view. But the camera's pass is no longer orthographic, so the box gets a thin dark line along its edges: the outline. (That was done in the editor the clips were recorded in, and the line showed.) From stage 7 on Leela gets one too, and the wobble's snap runs on her: each corner moves in steps of 2.5 cm, between two and three pixels of the picture at this zoom, so look for a faint jitter as she walks. (That half is read from the shader, not watched.) Stop the game to put it all back.

Making either of them work under the real camera means telling the camera's pass from the sun's some other way. That changes the look, so it's the owner's call.

The tube: crt.gd and crt.gdshader

Crt is another CanvasLayer, on layer 9, over everything. Its shader draws the screen again as an old TV would show it: dark gaps between scanlines, red, green and blue stripes, a soft glow, colour fringes, grain, and corners that darken and round off.

It asks Psx for the size of a pixel, so its scanlines sit on the picture's rows:

look/crt.gd lines 47–53
func _fit() -> void:
	var height := float(get_window().size.y)
	var pixel := maxf(1.0, roundf(height / ROWS))
	var psx := get_node_or_null("/root/Psx")
	if psx and psx.on:
		pixel = psx.pixel * ceilf(3.0 / psx.pixel)
	(_screen.material as ShaderMaterial).set_shader_parameter("rows", height / pixel)

Why it's like this

Two changes were made to Wagee's tube, and both are worth keeping.

  • strength is 0.5 (crt.gd). At Wagee's full strength the owner couldn't see properly.
  • The tube is flat and steady. Wagee's bulged, shrank the picture a touch and jittered each line sideways. All three move the picture's pixels about, which undid the camera's careful snapping: the floor wobbled as the camera moved. So they're switched off:
look/crt.gdshader lines 14–15, 24
uniform float curvature = 0.0;       // how much the tube bulges (Wagee: 0.11; above 0 the pixels wobble)
uniform float underscan = 1.0;       // below 1 shrinks the picture so a HUD clears the corners (Wagee: 0.975; the pixels wobble)
// ...
uniform float wobble = 0.0;          // each line's sideways jitter, in screen widths (Wagee: 0.0006; the edges shimmer)

Checkpoint: before stage 7

  • Project Settings → Globals → Autoload lists Outline, Psx and Crt, in that order.
  • StandIn is in the group outline.
  • The game is stopped, so nothing you changed in the Remote tree is left: Snap is on, and the camera has no perspective.
  • Run it once more: fat pixels, a dotted fade into the fog, scanlines and rounded corners, and no outline.