Source — Snippets & scripts

</> CODE.

Standalone bits I'm fond of. Pick a language to filter. Swap in your own scripts — each block is one card.

Language —
reproject.py Python

TerraSketch — WGS84 bbox → Lambert-93 metres, via one cached pyproj transformer.

from pyproj import Transformer

# One reusable, thread-safe transformer (EPSG:4326 -> EPSG:2154).
# always_xy=True -> pass (lon, lat), get (easting, northing) in metres.
_wgs84_to_l93 = Transformer.from_crs("EPSG:4326", "EPSG:2154", always_xy=True)

def bbox_to_lambert93(south, west, north, east):
    min_x, min_y = _wgs84_to_l93.transform(west, south)
    max_x, max_y = _wgs84_to_l93.transform(east, north)
    return min_x, min_y, max_x, max_y   # projected metres, SW -> NE

# Local Unity space = offset from the SW corner; y stays free for elevation.
def to_local(easting, northing, origin):
    return easting - origin.easting, northing - origin.northing
poisson.py Python

TerraSketch — Bridson Poisson-disk sampling: even, natural scatter with a guaranteed minimum spacing (condensed).

import math

def poisson_disk(width, height, radius, rng, k):
    """Bridson (2007): grid-accelerated O(n), seeded for reproducibility."""
    cell = radius / math.sqrt(2)            # at most one sample per grid cell
    grid = BackgroundGrid(width, height, cell)
    first = (rng.uniform(0, width), rng.uniform(0, height))
    samples, active = [first], [first]

    while active:
        base = rng.choice(active)
        for _ in range(k):                  # k tries before a point is retired
            angle = rng.uniform(0, 2 * math.pi)
            dist  = rng.uniform(radius, 2 * radius)
            p = (base[0] + math.cos(angle) * dist,
                 base[1] + math.sin(angle) * dist)
            if grid.in_bounds(p) and not grid.too_close(p, radius):
                samples.append(p); active.append(p); grid.insert(p)
                break
        else:
            active.remove(base)             # no room left near this point
    return samples
road_mask.py Python

TerraSketch — smooth OSM roads (Chaikin) and stamp them as an anti-aliased distance field.

import numpy as np

# Round OSM polylines with Chaikin corner-cutting (endpoints kept).
def chaikin(points, iterations, cut=0.25):
    for _ in range(iterations):
        out = [points[0]]
        for a, b in zip(points, points[1:]):
            out.append(lerp(a, b, cut))
            out.append(lerp(a, b, 1 - cut))
        out.append(points[-1])
        points = out
    return points

# Stamp a segment as an anti-aliased distance field: smoothstep falloff
# past the core half-width, max-combined so overlapping roads stay clean.
def edge_coverage(dist, half_width, edge):
    t = np.clip((half_width + edge - dist) / edge, 0.0, 1.0)
    return t * t * (3.0 - 2.0 * t)          # smoothstep
perlin_field.py Python

2D value-noise field, vectorised with NumPy.

import numpy as np

def fade(t):
    return t * t * t * (t * (t * 6 - 15) + 10)

def value_noise(w, h, scale=8, seed=0):
    rng = np.random.default_rng(seed)
    g = rng.random((scale + 1, scale + 1))
    ys, xs = np.mgrid[0:h, 0:w] / np.array([[h], [w]]) * scale
    x0, y0 = xs.astype(int), ys.astype(int)
    tx, ty = fade(xs - x0), fade(ys - y0)
    a = g[y0, x0]     * (1 - tx) + g[y0, x0 + 1]     * tx
    b = g[y0 + 1, x0] * (1 - tx) + g[y0 + 1, x0 + 1] * tx
    return a * (1 - ty) + b * ty
vec3.hpp C++

Tiny header-only 3-vector for toy renderers.

#pragma once
#include <cmath>

struct Vec3 {
    float x{}, y{}, z{};
    Vec3 operator+(const Vec3& o) const { return {x+o.x, y+o.y, z+o.z}; }
    Vec3 operator*(float s)       const { return {x*s, y*s, z*s}; }
    float dot(const Vec3& o)      const { return x*o.x + y*o.y + z*o.z; }
    float length()                const { return std::sqrt(dot(*this)); }
    Vec3 normalized()             const { return *this * (1.0f / length()); }
};
arena.c C

Bump-allocator arena — fast, no per-alloc free.

#include <stddef.h>
#include <stdint.h>

typedef struct { uint8_t *base; size_t cap, used; } Arena;

void *arena_alloc(Arena *a, size_t size, size_t align) {
    size_t p = (a->used + (align - 1)) & ~(align - 1);
    if (p + size > a->cap) return NULL;   /* out of space */
    a->used = p + size;
    return a->base + p;
}

void arena_reset(Arena *a) { a->used = 0; }
EventBus.cs C#

Minimal typed pub/sub for tools & gameplay.

using System;
using System.Collections.Generic;

public static class EventBus
{
    static readonly Dictionary<Type, Delegate> _map = new();

    public static void On<T>(Action<T> fn) =>
        _map[typeof(T)] = (_map.TryGetValue(typeof(T), out var d)
            ? (Action<T>)d : null) + fn;

    public static void Emit<T>(T evt)
    {
        if (_map.TryGetValue(typeof(T), out var d))
            ((Action<T>)d)?.Invoke(evt);
    }
}
fresnel.frag GLSL

Schlick fresnel rim term for a surface shader.

#version 330 core
in  vec3 vNormal;
in  vec3 vViewDir;
out vec4 fragColor;

uniform vec3 baseColor;

void main() {
    vec3  N = normalize(vNormal);
    vec3  V = normalize(vViewDir);
    float f = pow(1.0 - max(dot(N, V), 0.0), 5.0);  // Schlick
    vec3  col = mix(baseColor, vec3(1.0), f);
    fragColor = vec4(col, 1.0);
}
raf-loop.js JS

Fixed-timestep loop with interpolation alpha.

export function loop(update, render, step = 1000 / 60) {
  let last = performance.now(), acc = 0;
  function frame(now) {
    acc += now - last; last = now;
    while (acc >= step) { update(step / 1000); acc -= step; }
    render(acc / step);            // alpha for interpolation
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}