# painterly
The painted look of **Painted Valley** (blendi/painted-valley on Patch, MIT; ported to Zero as `paintedValley`),
lifted out of the Valley so any world can stand it over its own land: the sky and clouds and the hour's light, the
frame (paint finish, ink line, bloom and the painter's curve), the ground paint on the engine **Terrain**, painted
water, grass and flowers that grow wherever the host says, trees from a list the host supplies, and shade thrown by
hills, roofs and crowns. Nothing in the package knows a particular place: what the land is, where north is, what
grows where and what its water looks like come from the host's mount config.
The look is NOT the engine's lighting: every painterly material shades itself from one shared block of uniforms and
a few shared maps that `core` pushes into every registered material. A host's own materials join by declaring the
same block (below).
## Use
```luau
local Painterly = require("painterly.painterly")
local p = Painterly.mount({
terrain = "Ground", -- the entity (ref, id or name) carrying the Terrain
field = { origin = { 0, 0 }, extent = 4096, texel = 2 }, -- the square the shared maps cover (see "The field")
seaLevel = 0,
axis = { 0, 1 }, -- the way the place faces: strokes, wind, cloud layout
sun = { latitude = 38.7, declination = 17, north = { 0, -1 }, noon = 13 },
hour = 16.2, drift = 0, -- hour 0..24; drift = hours of day per hour played
wind = { speed = 4.5 }, quality = "high",
sky = { cloudAxis = { 0.3, 0.95 }, liveClouds = false, haze = 1.55, -- haze: the air's thickness x the Valley's
backdrop = { axis = { 0, -1 }, mask = { dir = { 0, -1 }, half = 78, feather = 30 } } }, -- or backdrop = false
paint = { level = 3, distances = { fullFrom = 12, fullTo = 260, farFrom = 90000, farTo = 100000, farKeep = 1 } },
masks = { growth = { meadow = 1 }, dry = { earth = 0.4 }, wet = { shore = 0.5 }, flowers = { meadow = 1 } },
ground = { layers = { cliff = "cliff", shore = "shore", paved = "paved", earth = "earth" },
farLand = { level = 62, hills = 44, reach = 48000, -- painted land past the Terrain's edges
sea = { { x, z, radius }, ... } } }, -- ...and its far bodies of water
water = { shallow = { .2, .33, .27 }, deep = { .014, .075, .115 }, deepAt = 7, swell = 1, glitter = 1, wash = 0.7,
mirror = 0.22, body = { .035, .2, .34 }, shallowBody = { .16, .5, .46 }, bodyMix = 0.55,
aprons = { { x0, z0, x1, z1 }, ... } }, -- sheets of open water past the Terrain's edge
meadow = { stones = { { x, z }, ... } }, -- groups of stones; none by default
trees = { cards = 1, list = nil }, -- or hand the list later: p.trees.set(list)
light = { engine = true, sceneLights = false }, -- write the engine's sun + ambient to the hour's light
})
function update(dt) p.update(dt, { walkers = { { x =, y =, z =, vx =, vz =, onGround = } } }) end -- every frame
function editorUpdate(dt) p.update(dt) end -- and in edit
function onDestroy() p.destroy() end
```
`mount` returns at once and builds over the next frames (bakes and sky paintings yield); `p.ready()` says when it
stands, `p.error` what stopped it. One mount a peer: a second takes the first down. Any part can be left out with
`sky = false`, `ground = false`, `water = false`, `meadow = false`, `trees = false`.
Mount from a component on a plain local entity, on every peer (see `metropolis/verrane/VerraneWorld.component` in the
world this package was made in). Scene needs no lights, sky or post-process entities.
### The handle
| call | |
|---|---|
| `p.ready()`, `p.error`, `p.stale()`, `p.rebuild()`, `p.destroy()` | lifecycle (`stale` = the Terrain was rebuilt under the look; the host calls `rebuild` when it suits: it holds frames) |
| `p.update(dt, opts?)` | every frame; `opts = { camera = {x,y,z}?, forward?, playing?, walkers = { {x,y,z,vx,vz,onGround} }? }` (first walker treads the grass and throws the walker's shadow; the camera is the active camera unless given) |
| `p.setHour(h, soft?)`, `p.hour()`, `p.setDrift(d)` | the day: 0..24 wraps. `soft` for small steps (clouds relight a strip a frame). Night is the moon's light, stars and moon on the dome |
| `p.setWind(angle?, speed?)`, `p.setPaint(level)`, `p.setExposure(x)` | wind towards `angle` (radians round Y), the brush (0 off, 3 full), an exposure multiplier |
| `p.material(shader, opts)`, `p.register(handle)`, `p.unregister(handle)` | a host material that takes the shared light and maps (see "Your own materials") |
| `p.bindSky(materialKey)` | keeps `uZenith, uMid, uHorizon, uGlow, uCloudFace, tClouds` live on a material (mirrors) |
| `p.groundAt(x, z)`, `p.terrain()`, `p.heightfield()` | the host's ground as the mount found it |
| `p.trees.set(list)`, `p.trees.kinds` | the trees: `{ x, z, kind, scale, turn }[]`, replacing what stood. Kinds: 0 great tree, 1 broad, 2 tall, 3 round, 7 bush, 8 wide bush (4 to 6 are 1 to 3's far forms: the part swaps them by distance itself) |
| `p.occluders` | what throws shade (see "Shade") |
| `p.tags.add(owner, list)`, `p.tags.remove(owner)`, `p.tags.budget()` | ink / "already painted" tags for the frame: `{ entity, tag }` or `{ entity, shader, properties }`. A tag under 0.23 draws the ink line; 0.4 marks a thing as painted already. **8 distinct tags in all** (the frame draws one pass per tag); instanced draws cannot be tagged |
| `p.groundMaterial()`, `p.water.material()` | the session materials the mount put on the Terrain and its water child |
| `p.lookFrom({x,y,z} \| nil)` | stand the grass round a place other than the active camera (offscreen captures, cutscene cameras): grass tiles are culled by where they were last put |
`Painterly.current()` answers the standing mount to any other system on the peer.
## What stands where (the package's parts)
| folder | what | lifted from |
|---|---|---|
| `painterly.module` | `mount`: the driver | `paintedValley.core.Valley` (the Valley's land, player, keys and HUD note left out) |
| `core/` | `core.module` (shared uniforms + maps, `configure`, `bake`, `material`), `fieldFromTerrain.computeShader` (NEW: the field's maps from a Terrain), `shade.module` + `occluders` / `shadeCast` compute (NEW: shade), `valleyCommon` / `valleyShade` / `valleyPaint` shader modules, the `*_properties.yaml` blocks | `paintedValley.core` (no `world.module`, `valleyLand`, `cityPlan`, `bakeGround`) |
| `frame/` | the paint pass (Kuwahara brush + ink), `finish.shader` (bloom, vignette, exposure, curve, `wash`/`flash`), tag shaders | `paintedValley.frame` whole; brush distances are settings now |
| `sky/` | dome, hour model, clouds, far country | `paintedValley.sky` whole; axis from the host, far country masked by azimuth or off, 24 h |
| `ground/` | `terrainGround.shader` + `ground.module`: the Valley's ground paint as a Terrain material | `paintedValley.meadow.ground` (meadow branch) + NEW rock, sand, earth, paving, water bed |
| `water/` | `sheet.shader` + `waterPart.module`: painted water on the Terrain's water mesh and on sea aprons | `paintedValley.village.tarn` |
| `meadow/` | grass rings, flowers, fluff, stones, trodden state, brushwork | `paintedValley.meadow` (ground mesh left out) |
| `trees/` | tree kinds, leaf / core / wood shaders, the host's list in cells | `paintedValley.village.trees` (planting and CPU shade cast left out) |
| `character/` | `cel.shader`, `inkTag.shader`: the figure's two-tone paint and per-fragment ink numbers; `Footing.component` (`painterly.character.Footing`): keeps a walking body on the land where it is steeper than its controller walks | `paintedValley.wanderer` (shaders); new (Footing) |
Inside the package every reference is package-relative (`require("~.core.core")`, `asset.resolve("~.meadow.blades",
"shader")`, `#include "~.core.valleyShade"`), with literal names only (a computed `asset.resolve` on a gameplay path
is refused by the engine). GPU resources are named `ptl_*`.
## The field
`core` keeps ONE square of maps over the host's land; every shader finds a place on them by
`extentUv(xz) = (xz - uExtentMin) * uExtentInv`:
| map | format | holds |
|---|---|---|
| `tHeight` | rgba16f | r + g = ground height in metres (two half floats), b, a = slope over 48 m |
| `tMap` | rgba8 | dry, growth, wet, flowers |
| `tShade` | rgba16f | r canopy shade on the ground, g ABSOLUTE top altitude, b solid shade on the ground, a canopy flag |
| `tNoiseHi`, `tStrokes` | | the Valley's noise and brushwork |
`core.bake` runs `fieldFromTerrain` over the Terrain's heightfield (its texels and its surface-layer weights): heights
are read with the terrain's own cell split, so grass stands on the drawn ground when the field's texels are the
terrain's (same origin lattice, same metres per texel: a 4096 m field at 2 m over a terrain at 2 m). `masks` says how
much each terrain layer gives each channel; the Valley's broad dry and wet patches and flower drifts are laid over
that. Grass grows where growth > 0 and nowhere else: a city writes growth 0 under its streets by giving them a
terrain layer that is not in `masks.growth` (or by re-baking with its own masks). Re-bake after the terrain changed:
`p.rebuild()`.
Cost: 2048² field = `tHeight` 32 MiB + `tMap` 16 MiB + `tShade` 32 MiB + occluder map 32 MiB; bake about 2 s first
time, 0.03 s after.
## Your own materials
A shader joins the look by copying `core/shared_properties.yaml` verbatim into its `properties.yaml` (plus
`shade_properties.yaml` / `paint_properties.yaml` / `map_properties.yaml` for the maps it reads; 9 textures a material
at most), including `painterly.core.valleyCommon` (and `valleyShade`, `valleyPaint`), calling `valleyBegin(input.time,
input.view_position)` first, and being made with `p.material(shader, { key, render, properties })` (or
`p.register(handle)`), which pushes the shared values now and on every change of hour or wind. In a `fragment()`:
`cloudAt(xz)` is the sun reaching the ground there (clouds, trees, hills, buildings, the walker), `sunlightAt(world)`
the sun reaching a point ABOVE the ground (walls, roofs, cars, figures: it walks `tShade.g` towards the sun),
`applyFog(c, world)` the hour's haze. The shared names and types are the Valley's and must not change
(`uSunDir uSunColor uSkyColor uBounceColor uFogColor uFogSunColor uFogDensity uWind uExtentMin uExtentInv uHeightRes
uHeroEye uFloor uFloorInv uCloudShade uWalker`). At night `uSunDir` / `uSunColor` are the moon's.
`cityLightAt(world)` and `CITY_LEVEL` (now 0: altitudes are absolute) remain for shaders written against the Valley.
## Shade
`p.occluders` (the `core/shade.module`) holds, for every field texel, the absolute altitude of the top of whatever
stands there. The ground comes from the field; a host lays roofs; the trees part lays every crown.
```luau
local occ = p.occluders
occ.clear("roofs") -- "roofs" | "canopy" | nil (both)
occ.box(x, z, halfX, halfZ, yaw, topAltitude) -- a rectangle footprint turned yaw radians round Y
occ.boxes({ { x, z, hx, hz, yaw, top }, ... })
occ.polygon({ { x, z }, ... }, topAltitude) -- any simple outline
occ.disc(x, z, radius, topAltitude, canopy) -- canopy = true: dappled shade
occ.commit() -- upload, rebuild the map, cast
```
`top` is the roof's own altitude in world metres. The cast (a walk towards the sun for every texel) runs when the
sun has moved a quarter of a degree, a strip of the field a frame; a commit casts at once. The ground, the grass
and the water read the result in one texel; things above the ground call `sunlightAt(world)`.
Limits: the map is at the field's texel (2 m here): a shadow's edge is soft by a metre or two and a gap under 2 m
between roofs closes; one top per texel (no bridges or arcades: what is under a roof is in its shade).
A 6,000-building city is one `boxes` call and one commit (rasterised on the CPU, about 0.1 to 0.3 s).
## The frame
`frame.start()` (called by the mount) adds the render feature `~.frame.framePass` (paint pass at `afterLighting`)
and the post effect `ptl_finish`, and sets the engine's display transform to a linear curve at exposure 1: the
finish writes the picture's own values. `paint.distances`: `fullFrom..fullTo` metres where the brush is two pixels
(one pixel nearer and farther), `farFrom..farTo` where the far land is taken as painted already (`farKeep` under 0.6
stops the brush there; the Valley's 520..700 m / 0.4 is the default, a city with a skyline puts it out of reach).
`frame.setWash(wash, flash)` grades the picture towards grey / lays a pale flash (a game's hit feedback).
<!-- archlook: the line, built things, windows (begin) -->
## The line
Everything that is BUILT is drawn as well as painted: a line round its silhouette, along its creases, between its
parts. The line is made in the frame from the scene's own buffers, so it costs no second draw and needs no tag; an
entity's model and one copy of an instanced draw get the same line. Three passes after the paint finish, at
`afterLighting`: `frame/ink.computeShader` (where a line goes and how heavy, into `ptl_frame_ink`),
`frame/line.computeShader` (a pen's soft edge, and the colour: the darker of the two sides the line parts, deepened
and a little warm, never black), and a blend over the scene colour. They need the deferred path (the material
channel); on another path there is simply no line.
What makes a line:
| from | a line where | governed by |
|---|---|---|
| depth | a surface stands in front of another (silhouette, eave, balcony, a figure before a wall), or against the sky | the NEARER surface's ink weight |
| normals | a crease: a corner, a reveal, a moulding | the lighter of the two weights |
| the ink code | two ids meet, or two key colours differ (trim on a wall, a proud stone, a painted band) | the lighter of the two weights (a drawn surface meeting an undrawn one keeps its own) |
A surface gets a line only if it PUBLISHES an ink code. `#include "painterly.surface.ink"` and, once in
`fragment()`: `inkPublish(key, weight, id, N)` (the head of `surface/ink.shaderModule` says what each is;
`inkId(seed, part)` makes an id). It is a store into the engine's material channel (`zero_publish_shaded_surface`),
not a light: it costs nothing and does not change the surface's colour. A surface that publishes nothing (the
meadow, trees, water, the ground) has weight 0: no line on it, none where it stands in front of something; a drawn
surface in front of it, or meeting it, still gets its line (the foot of a wall on the grass). `painterly.surface.paint`
and `painterly.surface.window` publish for you. (An engine-lit PBR material with metallic above 0.06 reads as a
weight too: give painted things painted materials.)
Weight (0..1) is the one number a material chooses (`uInk.x` on `painterly.surface.paint`; each kind of surface has
its own default). It sets how wide the line is and how far off it is still drawn:
- creases and boundaries are gone at `detailFar x weight` metres (fading from 40 % of that): a wall (0.8) keeps its
corners to ~175 m, ironwork (0.27) to ~60 m, modelled roof tiles (0.2) to ~45 m;
- silhouettes between two surfaces are gone at `skylineFar x weight^2`; against the sky an outline is drawn to
`skylineFar` whatever the weight;
- the step in depth a silhouette needs grows with distance (`gapMin + gapPerM x metres`): a 15 cm window reveal is
drawn across the street, not across the square.
So a far skyline is outlines and big shapes, and tile ribs or a grid of windows never close up into a dark mass.
Width also falls with distance (`width` pixels at 1080 lines close by, `farWidth` of it far off), an outline is a
third heavier than an inner line, and both wander with a number that belongs to the place in the world (not to the
screen or the clock): thick and thin as a hand makes it, without boil, and still when the camera moves. Light lines
break here and there.
Controls, on the mount's handle: `p.frame.setInk({ on = 0|1, width = 2, farWidth = 0.5, detailFar = 220,
skylineFar = 1800, gapMin = 0.03, gapPerM = 0.004, mix = 0.9 })` (any subset; nil = the defaults shown).
The older tag line (`p.tags.add`: a second draw of tagged entities, eight groups at most) still works for figures
whose shader does not publish. A shader that publishes needs no tag; do not do both.
### Looking at the line
Debug views that run only in a capture that names them (no viewport and no plain capture ever shows one):
`capture { pass = "ptlInk" }` the line alone (green where a surface publishes), `"ptlInkCode"` weight in red and id in
green/blue, `"ptlKey"` the key colours, `"ptlNormal"` the normals creases are read from.
## Built things (`painterly.surface`)
One paint for everything built: houses, landmarks, props, street furniture, the walls of a room.
```lua
local shader = asset.resolve("painterly.surface.paint", "shader")
local m = p.material(shader, { key = "myHouse.wall", properties = { uTint = { 0.8, 0.62, 0.42, 1 }, uSurface = 0 } })
model.material = m -- an entity's Model, or the `material` of a renderer.mesh.drawInstanced
```
Made through `p.material` (or registered with `p.register`) it has the hour's light, the shade map and the
brushwork picture. A material nobody registered is lit by a fixed afternoon and has no brush: register it.
What it lays (the head of `surface/arch.shaderModule` has the detail):
- the local colour: `uTint` (linear), or one of a building's colours from the instance's lanes (`uSlot`);
- paint in the field: long sweeps of a broad brush along the wall and runs down it (the package's brushwork picture,
read in the plane of the face), soft patches of another mix of the colour, a wash by height (a dirty foot with a
ragged top, a bleached upper wall, rain streaks under the eave), moved by the building's seed and age;
- the kind of surface, indicated and never tiled (`uSurface`): 0 plaster, 1 stone trim, 2 joinery, 3 tiled roof
plane (courses painted, closing up with distance), 4 iron, 5 foliage, 6 glow, 7 cloth (uv stripes), 8 tile panel
(uv), 9 modelled roof piece, 10 plain side wall, 11 clear glass (alpha), 12 ashlar (a few proud stones, a joint here
and there), 13 brick (courses in patches), 14 timber (boards), 15 paving;
- the light of `surface/light.shaderModule`: sun or cool coloured shade with a ragged turn (`builtSun`,
`builtTones`), the shade thrown by hills, houses and trees (the map of tops), cloud shadows, the street's warm
bounce, lamp pools from the engine's point and spot lights near the surface (`builtLamps`: two clean steps, weak by
day), `uGlow` for what gives light at dusk, the shared haze;
- distance: from `uGroup.x` to `uGroup.y` metres the brush calms and trim / joinery gather towards the wall's colour,
so a far front is two or three planes;
- its ink code: weight by kind (or `uInk.x`), an id from the building's seed and the slot (`uInk.y` = a part number:
two materials with different numbers part with a line), the flat local colour as the key.
Properties (after the shared block and `tShade`; copy `surface/arch_properties.yaml` verbatim): `uSlot`, `uTint`,
`uSurface`, `uGlow`, `uGroup`, `uInk` (x weight or -1, y part number), `uPaint` (x brush, y wash, z age 0..1,
w lamp pools), `uRise` (for a copy without lanes: x = the y of its foot, under -99999 = the ground under it;
y = its height), `tStrokes`.
Instance lanes (optional; `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, or an entity's `ShaderData`). The
same four numbers on every copy of one building:
| lane | x | y | z | w |
|---|---|---|---|---|
| 0 | wall | wall_b | trim | joinery |
| 1 | accent | roof | iron | the building's seed 0..1 |
| 2 | y of its foot | y of its eave | y of the first-floor line | flags: 1 + 2 x pattern = a tiled front |
| 3 | free for the copy (a window pane: width m, height m, lamp seed, 1 = shop) | | | |
Colours are packed sRGB bytes, `r * 65536 + g * 256 + b`. Lane 0.x = 0 means "no lanes": the material's own `uTint`.
`cityGen.shaders.kitPaint` / `kitWindow` are these two shaders under cityGen's names.
A shader of your own that wants the same light without the paint includes `painterly.surface.light` (and
`painterly.surface.ink` for the line); it declares the shared block and `tShade` and calls `valleyBegin` first.
Cluster LOD: the surface has no vertex stage and is opaque, so meshes stay on the cluster path.
## Windows (`painterly.surface.window`)
A pane with a FakeInteriors room behind it (`room_volume`, `room_normals`, `room_emission`; lane 3 = width, height,
seed, shop). By day the pane is glass first: it throws back the sky (upper floors seen from the street) or the
street across (panes at eye level), more where the sun lies on it and with distance; near and in the shade the room
shows, daylit. At dusk lamps come on window by window by seed, shops first; at night lit rooms are warm (amber,
cream, now and then a cold screen) and brighter than the finish's bloom threshold, so their light spills round
the opening; unlit panes are dark glass. Lamp pools on the street itself come from real lights: put a point light
where a lamp or a lit shopfront is and every `painterly.surface` wall near it takes the pool.
<!-- archlook (end) -->
## The day
`sun = { latitude, declination, north = { x, z }, noon }` gives the sun's arc; the colours are chosen by the sun's
elevation from seven keys (`sky.KEYS`: night -18°, blue hour -8°, dusk -3.5°, sunset 2°, golden 11°, 27°, 50°), so
dawn mirrors dusk. Under -4.5° the key light is the moon (opposite the sun). `sky.lightAt(hour)` answers everything
the hour decides (`night` 0..1 is what a host's lamps should follow). Lamp light itself is NOT in the package: the
seam is the shared block (a lamp-lit material adds its own light when `sky.night > 0`) and `tShade`'s spare use.
## Use in another world
1. Install or copy `painterly.package` into the world's source root (its identity is `painterly`).
2. Stand a `Terrain` (any landscape; with none the field is level ground at `level` and everything grows) and one
plain entity with a component of yours that calls `Painterly.mount{...}` and `p.update(dt)` every frame, in
`update` and `editorUpdate`.
3. Say where things are in the mount config: `field` over your land, `axis`, `sun.north`, `masks` by your terrain's
layer names, `ground.layers` for rock / sand / paving / earth, `water` and its `aprons`, `sky.backdrop` (false, or
masked to where land lies beyond yours).
4. Hand it trees (`p.trees.set`), roofs (`p.occluders`), ink tags (`p.tags`), and make your materials with
`p.material`.
World settings the look assumes: `[render] antialiasing = "taa"`, `deferred = true` (the Valley's).
## Past the Terrain's edge
A Terrain draws nothing past its rect. `ground.farLand = { level, hills, reach, sea }` lays a skirt of painted land
round it (`ground/farLand.shader`): each edge leaves at the Terrain's own height and eases to rolling ground about
`level`, rising to hills the farther out, to `reach` metres. `sea = { { x, z, radius }, ... }` are the host's far
bodies of water (discs in world metres, their coasts wandered by noise: a bay, a sound, an estuary's mouth): the
skirt goes under `seaLevel` inside them and comes down to a pale shore at their edge. Where the Terrain's edge is
under `seaLevel` the skirt stays under water too. The water part lays sheets of sea at `seaLevel` under the whole
far land by itself (cells that grow with distance), so the host lays no aprons for it. Below the horizon the sky
itself is haze (land-tinted on the far country's side).
## A body to walk it
The land is the Terrain's own collider: a PlayerPrototype with the engine's avatar, CharacterController and
Locomotion walks it as it stands (measured in Verrane: walk 2.5 m/s, run 7 m/s, feet 0.01 m above the field ground,
36 degree slopes run up at full speed). Two things the host does:
- put `painterly.character.Footing` on the body. The CharacterController lets go of ground steeper than its
`maxSlopeAngle` (45) and the body then falls THROUGH the land (it adds the slide to the frame's fall, the feet go
under the surface and its ground ray starts below the land). Footing runs after the controller and lifts the local
player's feet back onto `p.groundAt`: the body slides down the face and stands where the ground lets it.
- hand the mount the walker every frame in play: `p.update(dt, { walkers = { { x, y, z, vx, vz, onGround } } })`
(the grass is trodden and the walker's shadow thrown from it).
A third-person camera (`@builtin::controller.third_person_follow`: cameraDistance 4.2, shoulderOffset {0.45, 1.55,
0}, cameraRadius 0.25, aimPitch in RADIANS) pulls in against the land by itself (4.2 m to 1.8 m with the back to a
45 degree face).
## Known limits
- The far land carries no trees or grass (paint only), and the far country's strip starts at -2.6 degrees: from
high in the air a band of haze shows between the far land's end and the far hills.
- Grass tiles and the trodden square follow ONE eye per peer (the active camera, or `p.lookFrom`).
- Trees: one draw per (cell, kind, part); far cells swap to the far forms at `trees.FAR_AT` (620 m). No collision
(the host adds colliders from the same list; `p.trees.kinds[k].crown` is a crown radius).
- The older TAG line (`p.tags`) draws 8 tag groups at most and cannot reach instanced draws; the drawn line of
surfaces that publish an ink code has neither limit ("The line").
- The clouds are painted once per hour set (a strip a frame while the hour drifts) and do not move across the sky.