SOURCE / PINNED RELEASE
Made of little things.
Drift City
- Release
- 098731aa0f0f…
- Author-recorded commit
- 2822ea0a4f5b…
- License
- LICENSE
- Author’s source reference
- nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855
Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.
## napplet soyLI workspace
Read [docs/napplet-space.md](docs/napplet-space.md) first for this project's CLI commands, installed skills, preview cleanup and host capabilities. Read [docs/napplet-visual-design.md](docs/napplet-visual-design.md) before styling the creation and its UI. This project and its adapted skills are already installed; do not re-scaffold or reinstall them. Use soyli dev and its printed URL for hosted preview, and stop your preview session after testing. Use the upstream guidance below with those tooling mappings.
# Drift City
Drift a car around a mid-size low-poly map full of traffic, signs and street
furniture to smash through. The camera is a chase cam behind and above the car at three
distances (C), or a first-person view from the driver's seat (V, or the camera
button). Inside (`src/game/cockpit.ts`) there's a low-poly cabin with live speed
and rev dials, a wide interior mirror and two door mirrors (their glass set flat in
the housings) that really show what's behind, and a driver whose hands turn the
wheel (a full turn at full lock, hand over hand), change gear and pull the
handbrake, and whose feet work the clutch, brake and gas. The car changes gear by
itself. Look around with Q / E, F to look down at the pedals, by dragging with
the mouse, or with a gamepad's right stick, from the driver's seat or from outside the car:
there it swings the chase camera right round the car, all the way if you keep going (so
you can see it from any side), and dragging up or down lowers it to near the ground or
raises it to look down from overhead. Let go and the view swings back the short way.
### Modes
The start screen asks for a mode, then a map (Pause → Menu goes back to it):
- **Free drive:** roam the map, drift for points and smash things.
- **Race:** plan a route, then race three rivals along it. The planner
(`src/route-editor.ts`) shows the map's roads with the race line from a start flag
(S) to a finish flag (F). Drag a flag to move it, or grab the line anywhere to pull
out a waypoint; when you let go it snaps onto the nearest road and the line re-routes
along the roads (the shortest way between waypoints, `src/game/race.ts`). Drag the
map to pan, scroll or pinch (or use + / −) to zoom; double-click or long-press a
waypoint to remove it. Tick **Circuit** to bring the route back round to the start,
and pick 1, 2, 3 or 5 laps. The route must be at least 400 m. Each map remembers
its last route.
The **distance slider** along the bottom makes a route for you, from 0.5 to 8 km:
right for longer, left for shorter. It searches the roads from the start flag for a
route that long (a circuit back to the start, with Circuit ticked) that never uses
the same road twice, favouring turns (once it has run straight for a block or so, so
it makes corners with straights between rather than a staircase; straighter only if
that's what it takes to reach the length), and pins it with as few
waypoints as it takes. The flags and waypoints can still be dragged afterwards, and
moving the start flag then sliding again makes a new route from there. Where no
route that long exists (the Country map has few roads), it makes the nearest length
it can.
The race starts on a two-by-two grid behind a chequered gantry, with a 3-2-1
countdown. At every junction where the route turns, each road out of it that isn't
the route is closed by a barrier of red chevron boards pointing the way the route
goes (solid, and kept clear of traffic for the race), with a chevron sign on the
outside of the turn where no road carries on. A trail of see-through blue chevrons (`src/game/race-trail.ts`) runs along the route on the road ahead of you, drifting forward and fading into the distance. Yellow checkpoint arches stand about every 350 m, the route is drawn on
the minimap, and the HUD shows your position, the lap (or distance to go) and the
clock. Your progress only counts along the route, so leaving it doesn't gain
anything; off it, a note says so, and R puts you back on it where you left. The
rivals (Kestrel, Vandal and Nomad, `src/game/rivals.ts`) drive cars just like yours,
with the same physics, so they slide, scrape walls and get knocked
about the same way, leaving skid marks and tyre smoke. An AI works their pedals,
wheel and handbrake every frame: it reads the bends ahead, brakes just in time to be
at each one's limit, takes a racing line (keeping right, cutting to the inside of
bends), and drifts through the turns the way drifters (and self-driving drift
research cars) do: a handbrake flick swings the nose in, then the wheel holds the
slip angle while the throttle sets how hard it can turn (more gas holds more angle;
lifting tightens the line). The angle it holds is worked out from the bend ahead,
so it unwinds smoothly as the road straightens and the tyres grip again. Through
sweeping bends the keener drifters come in faster than grip would allow (up to a
quarter faster) and let the slide carry them round; tight corners and bends with
traffic in them they still take at grip speed. It swings
round on the handbrake where the route doubles back, moves across to get past
slower or oncoming traffic, shoves aside anything stopped in its way, and backs off
and tries again if it gets wedged. It drives smoothly, as a person would: in and
out of a drift the angle it steers for builds up and unwinds gradually (in at about
125 degrees a second, out at about 70) rather than jumping there, its hands and feet
move only so fast (lock to lock in about a third of a second, quicker on grip and
quickest in an emergency), it eases off the throttle out of a slide rather than
lifting all at once, and it only drops a drift once the road has been straight for a
moment, and doesn't take one straight back up. Anything that can be knocked over (bins, cones,
signs, benches, fences, small trees) it ignores and drives straight through; it only
swerves or drops a drift for what would stop it. Each has its own pace and taste for
drifting.
They bump into you, each other and the traffic. The results show everyone's time,
with Race again, Change route and Menu.
Three maps, picked after the mode:
- **City:** the city fills the northern three quarters of the map, laid out in
`src/game/city-plan.ts` and built in `src/game/world.ts`. Four districts, each
with its own look:
- **Downtown**, in the middle and reaching north to z = 480: glass and stone
towers, offices, shops, a fountain plaza, parks and parking lots on a grid of
four-lane streets (two lanes each way, a double yellow line down the middle).
- **Old Town**, the band of three rows of blocks north of Downtown: narrow
terraced houses shoulder to shoulder round each block in bright plaster,
mostly two storeys (now and then three), steep tiled roofs with their gables to
the street (some crow-stepped), shops on the ground floor, gardens in the
middle, and a church with a clock tower and spire.
- **Industrial**, to the east and along the south edge: long blocks (every other
cross street left out) of fenced yards with sawtooth-roofed sheds and loading
docks, brick factories with striped smokestacks, tank farms, container stacks
and water towers. The yards' chain-link fences go flat if you drive at them,
a 3 m panel at a time. Each panel touches only along its own line (a hand's width
either side of the wire), so you can drive right up alongside one without hitting it;
the farm fences are the same.
- **Suburbs**, to the west: gently curving two-lane streets, every one bowed a
little, with crossings on every other grid line north to south (long blocks,
half the crossings of a full grid). Each street runs right into the middle of
the grid crossings it meets, so the asphalt joins up, and where two meet the
pavements join round in a curve. Houses stand close along them on smaller front
lawns (each garage on the same side, so they pack in): painted siding, pitched or hipped roofs, a garage and drive, picket
fences and a mailbox at the kerb. A quarter of the houses are bigger (wider and
deeper), a quarter have an extra storey (up to three), and about one in ten out in
the suburbs has a swimming pool behind it: blue water in a stone surround, with two
loungers, and nothing planted in it. Each back garden has five to seven trees in two staggered
rows, bushes along its back and down its sides, and two or three raised flower
beds near the house, each laid only where there's room; about half the gardens are
fenced, a 1.5 m board fence (plain timber or painted white) down each side from the
house and along the back, which goes flat a panel at a time if you drive at it. The
biggest stretches of open lawn between the houses (none over a house's lot; up to
eight) are parks like the city's, level with the lawns, their paths in from the
sidewalks along the lanes.
A **river** comes down out of the mountains on the south edge, across the
countryside along a level valley floor (a gravel towpath along each bank, and the
ring road over it on two stone bridges with solid parapets), under the south side
and up through Downtown and Old Town, then out past the north side of the highway
in a wide bend and away east to the sea. In the city it runs
between stone walls below the street, with a railing along each bank (solid, so
cars can't go in), a narrow riverside walk, and then a **riverside road** along
each bank, one lane each way, the whole way from the south boulevard to the north
one. The east-west streets that reach the river stop at its riverside road in a T,
their asphalt cut along the road's line (so at an angle where the river runs on the
slant), and never past it into the water. The north-south streets don't come up to it:
each stops at its last crossing before the river, and the stretch it leaves goes to
the blocks beside it as more buildings and parks. Anything left going nowhere is
taken out too, so there are no dead ends. The blocks' pavements are cut exactly along
the riverside roads' curving edges (and any other road crossing them), with a kerb
following the curve, rather than laid in squares with a stepped edge. The riverside
roads' asphalt runs 0.4 m past their lanes on both sides, so on tight bends no sliver
of walk or pavement is left in the road; the walk is cut to the road's edge with its
kerb along that edge, and the river's railing stops wherever the road runs over it.
(Checked by sampling both roads and their junctions every metre: all asphalt.)
Every other east-west street (and the
two boulevards) crosses on a stone bridge from one riverside road to the other (a
slab with an arch underneath, solid parapets that end just past the river's railing
so the turn onto the riverside road stays clear, lamps at their ends): eight bridges. The riverside walk and
its railing run unbroken except where a bridge crosses. Nothing solid stands on the
riverside roads or the bridges: hydrants, bins, benches, lamps, cones and fences are
kept off every street and out of the river, and off the parks' paths.
Junctions with the riverside roads are marked the way US guides lay them out
(MUTCD 3B, NACTO): a zebra crossing square across every street or bridge coming in,
just short of the road it meets; a solid white stop line across its incoming lanes
1.2 m before the crossing; and its centre and lane lines ending at the stop line.
The riverside roads get the same where they come up to a bridge or a boulevard, and
a zebra either side of each street's mouth; their dashed middle line stops short of
the crossings. No crossing is laid over another: one that would be is moved along,
or left out where the leg already has one. No street anywhere ends in nothing: any left with nowhere to go is taken
out, and the airfield and farm roads loop back to the ring road.
Where only two streets meet at a corner, one turning into the other, the corner is
a curve (22 m radius) instead of a square crossing.
**Parks** fill whatever open pavement the buildings leave in Downtown and Old Town
(park blocks, Old Town's courtyards, ground the river, its roads or the highway
kept the buildings off), leaving the plazas, parking lots and churchyard as they
are, a strip of pavement round each building, and the feet of the highway's ramps
(nothing grows through a deck less than 3.5 m up; the roadside grass tufts out in the
country keep off them too): grass shaped to the space, its
edge rounded off, narrow gravel paths winding in from the street, each laid where
nothing stands in its way or hangs over it (no path runs under a highway deck, a ramp
or a building), to a fountain or a flower bed in the middle. Every path's outer end
runs on over the edge of the grass and onto the pavement, so it always joins the
sidewalk; where a gate has no clear way in, the next spot along the edge is tried,
up to three paths a park. Parks that
touch share one fountain, in the biggest; the rest get flower beds. Trees, bushes
round the edge, flowers along the paths, a bench every 18 m or so right at a
path's edge and facing it, two more facing the fountain, and a trash can at each
entrance.
A **raised highway** 9 m up loops round the whole city (outside the straight
boulevard that rings it) with wide 260 m-radius corners, and a crosstown run goes
straight through Downtown over the street at z = 160, forking at each end into two
long quarter-circle curves onto the loop: no sharp turns anywhere. Two lanes each
way, concrete barriers (open where one deck runs into another), tall lights, and
pillars that stand clear of the streets below (in pairs either side of a street
the deck runs over). Opposing lanes never cross. Where the crosstown meets the
loop, each end is a full semi-directional T interchange, the layout used where one
highway ends at another: every way from one onto the other, with left turns
leaving on the right and crossing on bridges instead of across traffic. The right
turns are the quarter-circle curves, one way and two lanes each, lined up with the
right-hand lanes of the roads they join (east end: crosstown going east onto the
loop going north, the loop going north onto the crosstown going west). The left
turns are one-lane connectors: a flyover off the crosstown's right-hand lane, up to
16 m, round over the curves and the loop and down outside it into the loop's far
lanes from their right (east end: onto the loop going south); and from the loop's
far side, off its outer lane, out beyond the loop and along it, then dipping to
3.2 m to pass under the loop where the curve has already merged into it (4.6 m of
headroom under the deck above), back up over the boulevard (4.6 m clear above it)
and round in a long S-bend into the crosstown's lanes from their right (east end: from the loop going south onto the crosstown going west). The
west end is the same turned half round. Up to three decks stack there, and a car
stays on the one it's driving on. Wherever one road passes under another there's at
least 4.6 m of headroom (the lower one dips; no highway goes any higher), and no
pillar stands on a road under it.
Barriers are left out where there's more road beyond them at the same height (where
a ramp or curve splits from the highway or joins it), so where two decks part the
barriers start together in a clean V. The gore in the V, from where the two decks'
edges part up to the barriers, is paved with white chevrons, and the two barriers are
joined across its end by a solid concrete nose, so there's no gap to see or fall
through (24 of them, at every ramp and interchange split and merge). Hitting one (or any wall) at an angle, the
car glances off: the speed into it is taken away, the speed along it kept (less
some scraping), and the nose swings round to follow it.
On and off ramps, one lane and one way, each leaving or joining from the outer lane
on the right. On the loop's north side, an exit and an entry for traffic going
west, and on its south side the same for traffic going east: each eases out
alongside, comes down a smooth slope (gentle at top and bottom, under 10% at the
steepest) and curves in to meet a boulevard crossing square on. Traffic going the
other way (east on the north side, west on the south), whose right is the outside
of the loop, has its own exit on that side: it eases out 25 m beyond the loop,
comes down alongside it and turns back in, passing under the loop near the
ground, to a boulevard crossing. On the crosstown in Downtown, a diamond: an exit
and an entry for each direction on its own side (east: entry from the west, exit
to the east; west: exit to the west, entry from the east), down to the streets at
Downtown's edges. White arrows on every one-way deck point the way to go, one
down the middle of a ramp, one in each lane of a curve. Each barrier ends in a
clean square end, and where a ramp comes down onto a street its edges and
markings stop short of the street, so nothing stands in the road.
Low down, a ramp is walled in so nothing drives under it, the wall closed off with
an end face where it gives way to open pillars.
The south quarter is countryside: farms, forests, the river, a twisting touge
road and an old airfield, round a ring road joined to the city by two roads that
pass under the highway. It rolls gently; the city, airfield and the river's valley
are level.
The City map is wider than the Country one (it reaches 300 m further east and 390 m
further north; the city itself hasn't moved) for the **coast** in the north-east
corner: a sandy beach shelving down into the sea, which runs off to the horizon,
with a barrier just offshore so cars stay out of the water. Mountains close in the
rest of the map. On the coast stands the **port**: a 330 m quay with a yellow and
black kerb along its edge, bollards and fenders, a container ship moored alongside
(dark hull, white cabins and bridge aft, a funnel, its deck stacked with
containers), and a red ship-to-shore gantry crane on rails over it, its boom
reaching out across the ship and a container hanging from its trolley. Behind the
quay is a paved yard of container stacks up to four high in blocks with lanes
between them, light masts and the port office. A road loops round it off the east
boulevard: out along the street at z = 560 under the highway, round a hairpin at the
yard's far end, along the back of it, round another and back in along z = 640.
- **Country:** countryside only, rolling gently. A big wandering loop, two
snaking roads across the middle and three hairpin roads out towards the
mountains, through forests past log cabins, barns and wind turbines.
- **Test:** a small City for trying things out, about 800 by 680 m inside the
mountains (the City is about 2100 by 2190), built by the same code from its own layout
(`useLayout('test')` in `src/game/city-plan.ts`; it loads in about a second). A
5 by 4 grid: the Suburbs down the west column (a curving lane across on every grid
line, so four blocks of houses), Old Town in the next (three blocks of terraces and
the church), the river down the middle column, and east of it the Industrial
district (south) and Downtown (north), two by two, with traffic lights at Downtown's
middle crossing. One bridge, on the middle street; the streets either side of the
river's column are left out, so the cross streets run on to the riverside roads. The
one park is the biggest open stretch the blocks leave (a strip along the river in
Downtown). Round it all a small highway loop, with one exit and one entry off its
north side down to the boulevard crossings at x = 120 and -120, and a curvy country
road out from the south boulevard under the highway, round the south and over the
river on a stone bridge of its own, and back. No coast, port, airfield or farms,
scenery thinned to its size, and 30 traffic cars. On small screens the map picker
shows the three maps in a row, names only.
Roads are generated to stay clean: branches leave other roads square, and each is
re-tried until it doesn't run alongside another (`World.roadProblems()` lists any
spot where roads overlap or cross the runway; it should be empty).
### Accounts and leaderboards
The top of the start screen shows who's playing (`src/online.ts`). Signed in to the
host with Nostr, that's your profile's name (read through the optional `identity`
domain; the game never signs anything). Signed out, you're a guest under a name you
type (**Change name**). Each account keeps its own records, its car designs and the
design on its car, in the napplet's storage under its key.
**Leaderboards** has two shared boards on the host's soyLI backend (the optional `cvm`
domain): **Longest drift** (the longest single slide, timed from when the tail breaks
loose until it has been straight for a third of a second; a slide that ends in a crash
doesn't count) and **Races won** (finishing first). Each player's best is kept. A new
longest drift pops up on the HUD. The boards are casual (the game reports the scores),
and update every couple of seconds while open. Without the backend they say so, and
your own records are still kept.
### Paint shop
**Paint shop** on the start screen takes the car into a studio (`src/game/garage.ts`)
to paint it (`src/paint-shop.ts`):
- **Brush** and **Eraser:** any colour (twelve swatches or a picker), a size from 8 mm
to 80 cm across, opacity and hardness. Strokes follow the bodywork round its edges,
and carry on across door shut lines, handles and vents. The brush paints over shapes;
the eraser rubs out brush paint only, never a shape, so paint over a shape and rub it
out and the shape's there again. (Paint added after rubbing out stays.)
- **Shapes:** circle, square, triangle, diamond, star, heart, ring and arrow. Click the
car to put one on and drag it about; set its width, length, turn, colour and opacity.
Shapes stand upright on the sides, nose and tail and point forward on the bonnet, roof
and boot. A shape is projected onto the car from in front of where it's put, so it
wraps over the body's corners. Click one where it shows to pick it up again (where it's been rubbed out
or painted over, a click puts a new shape on top instead); Delete removes it.
- **Base colour**, **Clear all**, **Undo** / **Redo** (Ctrl+Z / Ctrl+Y), and views from
the left, right, front, back and top. Left-drag paints; right-drag, the **Turn** tool
or two fingers turn the car round; the wheel or a pinch zooms. B, E and S pick the
brush, eraser and shapes, and [ and ] change the brush size.
- **Mirror** (M): while it's on, every stroke and shape goes on both sides of the car,
mirrored down its middle. A mirrored shape is one shape drawn twice, so moving,
resizing or recolouring it (from either side) changes both. Turning Mirror on or off
with a shape picked up mirrors that shape or stops mirroring it.
- **Picker** (I): click the car to pick up the colour the part really is there (the
paint, a shape or a stroke over the base colour; or the glass, trim or tyre's own
colour), not how it looks in the light. The colour goes to the brush or the shapes,
whichever was in use, and that tool comes back.
- The glass, wheels, lights and black trim can't be painted. Only the paint-coloured
bodywork takes paint.
- **Designs** are saved by name. They're editable later, because a design is saved as
its strokes and shapes, not as a picture (`src/paint-designs.ts`: points in
millimetres, packed and deflated, so a design is a few kilobytes). The panel's
**Saved designs** tab (beside **Paint**) lists them, each with a picture of the car in it
(painted on and photographed in the studio when the tab opens): **Use on car** to switch
the car into it, **Open** to paint it, **Copy** and **Delete**, with **New design**,
**Plain paint** (the design off the car) and a meter of how much of the game's 512 KB
of storage is used. Switching away from a design with unsaved changes asks whether to
save them first. **Use on car** puts the design on your car for driving and racing.
The racing stripe goes, and picking a plain colour on the start screen goes back to
plain paint. Without storage you can still paint, and the design stays on the car
until the game is closed.
The paint is drawn on the GPU into one 2048² texture laid over the car's paint
(`src/game/car-paint.ts`). It holds five straight-on views of the body (its sides, top,
nose and tail), and each face shows the view it faces most. A second, half-size map
holds where on the body each texel lands. That lets a brush dab colour everything
inside a small ball, and a shape stencil every face turned towards it near where it
was put, across the edges between views. Faces hidden in their view (inside the
cabin) show none of it.
### Traffic
About 150 vehicles drive around the City map and 60 around Country
(`src/game/traffic.ts`). The **Traffic** checkbox on the first menu screen turns them
off (or back on) for free driving and racing alike; the cars parked in the lots stay
either way. The models are Pursuit PIT's low-poly cars and rigs (MIT,
ported in `src/game/vehicles.ts`) at real sizes: three-box sedans with painted
pillars and side windows, sports cars, pickups, lifted trucks, box trucks, and
articulated semis, tankers and log trucks whose trailers swing round behind them
(rigs keep to the open roads that don't end in town). They follow the road graph in
their lane at the posted limits, slow for bends, keep their distance, brake with lit
brake lights, and go round anything stopped when the other lane is clear (in town
by changing lanes, out of town by overtaking when nothing's coming). At junctions
they turn left, right or carry on, cutting a curve through the corner in their own
lane: in town they move over in good time, to the outer lane to turn right and the
inner lane to turn left. They take turns: one driver crosses at a time while the
others wait at the line.
At startup the map is built a step at a time (`World.create`): the city, the terrain,
the roads, the forests and so on, with the page free to draw and answer its host
between the steps, since all in one go it takes a few seconds. (Switching maps from the
menu still builds in one go, behind the menu.)
What a drifting car leaves depends on what each back wheel is on (`src/game/fx.ts`):
on tarmac and paving, white tyre smoke and black rubber; on dirt, a brown dust cloud
that hangs low and dark brown ruts, a little wider than rubber; on the beach's sand, a
sand-coloured cloud and darker tan ruts; on grass, only a little dust, but a spray of
mud specks and clumps of turf flung back off the wheels (falling, bouncing once and
lying still before they go) and the turf torn into dark brown tracks with tufts of
grass left in them. Rivals leave the same. The smoke and dust are drawn after the
marks (and the contact shadows and race trail), so they hide what's on the road under
them instead of the marks showing through. They're lit like the scene, by some of the
sun's (or moon's) light and the sky's, and tone mapped the same: white in the afternoon,
tinted at sunset, a dim blue-grey at night.
What the cars drive on is exactly what's drawn: once the map is built, every upward
ground surface (terrain, roads, pavements, grass, decks, ramps) goes into a bounding
volume hierarchy ([three-mesh-bvh](https://github.com/gkjohnson/three-mesh-bvh)), and the
height under a car (or traffic, rivals, gates, debris) is a ray cast straight down onto
it from just above the car: the first surface it meets, so a car on a deck stays on the
deck and one under it stays on the street. The kind of surface it hits (asphalt, paving,
grass, dirt) tells the tyres whether they're on tarmac.
The city's streets are one surface too ([Clipper2](https://github.com/Countertype/clipper2-js)
and three's earcut): the outlines of every grid street, crossing, corner curve, riverside
road, bridge and suburb lane are merged a 100 m tile at a time and triangulated, so where
roads meet at any angle there's one clean piece of asphalt with no overlaps or gaps. In
the suburbs the pavements are merged the same way (the roads taken out), their corners
rounded where lanes meet. Each tile's triangles are checked against its area, and a tile
earcut gets wrong is done again in quarters.
The highway is part of the same road graph, up in the air: every road carries its
height, roads only meet where they end on one another at the same height (so a
street crossing under the highway isn't a junction with it), and traffic, rivals,
race gates and the car all ask for the surface at their own height
(`World.height(x, z, y)`): the deck for anything on or just climbing onto it, the
ground for anything underneath. Drivers only see and follow traffic on their own
level. On the highway they do 97 km/h and nobody stops at the merges. One-way roads
(the ramps and the curves) are one way for everyone: traffic only goes down them the
right way, on its own lanes (one down the middle of a ramp, two either side of the
middle of a curve), and race routes are only planned along them that way. Where a
ramp overlaps the highway it's leaving, the surface under a car is the one nearest
its height, and each deck's height comes from its nearest piece, so the slopes are
smooth all the way down with no steps to catch air off. Barriers, railings and walls are solid only at
their own height (`rail` colliders with a bottom and a top), so the street under
the highway is open.
The crossings of the City's two main streets have traffic lights
(`src/game/signals.ts`), a mast on each corner with a head over each lane coming in
and another across the junction. They all run one pattern in step: green for 7 seconds one way,
then amber for 2 seconds before it turns red, while the other way waits on red and
then gets its own 7 seconds of green. Drivers stop for red, and for amber when
they can; turning left, they wait at the line for a gap in the oncoming traffic.
Hit one and it gets shoved and spun; harder hits tear off doors, bumpers and
bonnets, and a big enough hit wrecks it, charred and smoking. Loose cars bump
into each other and pile up. Recovered cars rejoin the road, and wrecks are
cleared away out of sight.
About half the bays in the parking lots (Downtown's and the Industrial yards') have a car parked in them (sedans, sports
cars and pickups, nose in), leaving the middle of each lot clear for drifting. They
sit still until something hits them: a bump knocks one out of its bay, a hard hit
wrecks it, and a wreck is replaced by a fresh car back in its bay out of sight.
### Signs and things to run over
Speed limit signs along the country roads and at the city limits, curve warnings
before sharp bends, stop signs where side roads join, a DRIFT CITY sign at each
road into town and arrows to the airfield (`src/game/signs.ts`). All of them knock
flat, as do lamp posts, trees and bushes. Hydrants (which then gush water),
mailboxes, fences, benches, trash cans, cones, cardboard boxes, plastic barriers
and hay bales go flying and tumble. Every smash scores points, and wrecking
traffic scores more.
The driving started as Mini Samurai's toy car (`src/game/car.ts`), scaled up to
a full-size car (distances and speeds × 2.2), and has since been refined:
- W/S are the pedals, A/D steer. Steering eases off with speed, so fast corners
are wide and stable rather than twitchy. At low speed it turns like a real car:
no tighter than full lock allows (a 5.4 m radius), so it can't spin on the spot,
and a handbrake turn needs some speed to swing round.
- The handbrake (Space/Shift) breaks the back tyres loose; so does a hard brake
into a turn, or flooring it on full lock at low speed (donuts).
- Once sliding, the back stays loose: steer into the turn and stay on the
throttle to hold the angle, counter-steer or lift off to straighten up. A slide
keeps most of its momentum, at a little less top speed.
- Off the pedals the car rolls out gently. Glancing a wall scrapes along it;
only a square hit bounces back.
## Sound credits
All recordings are CC0 (public domain) and bundled through `napplet.assets.json`:
- Engine: [Sport Car Engine With Revving And Backfire](https://audiojungle.net/item/sport-car-engine-with-revving-and-backfire/9517480)
by debsound (AudioJungle, Regular License). The recording is mostly revving, so
`src/game/engine-voice.ts` takes the short idle stretches between the revs, cuts them
into single exhaust pulses (each stretch at its own firing rate, all stretched to one),
averages each stretch's pulses into one clean pulse (the recording's hiss cancels out;
each cylinder always fires its own, so nothing sounds grainy), low-passes what the
revs would push up into the treble
and fires them at the engine's real firing rate, as a V8 (four firings a revolution),
so it keeps that car's deep sound from 900 to 7800 rpm (pitched a touch deeper than
the recording, about a semitone and a half) instead of a sped-up loop's
whine. Loudness follows revs and load like a real car (much quieter on the overrun),
with a faint intake roar and a rev limiter. Gear changes ease the throttle while the revs fall
to the new gear; the engine never cuts out. Muffled through the cabin in first person,
a little quieter from outside. The rivals have the same engine, each heard from where
it is: quieter and duller further off, panned to its side, with its own revs.
- Backfires: [Chev350 Raw](https://freesound.org/people/lonemonk/sounds/123717/) by
lonemonk (Freesound, CC BY 4.0), a Chevrolet 350 V8 hot rod recorded while chasing a
backfire. Eight of its backfires are lifted out without the idling engine under them
(`backfires` asset: the engine heard just before each subtracted from its spectrum,
then harmonic/percussive separation keeps only the bang, each ending once its crack
has died away). They're timed the way real ones are, measured on three recordings (a
sports car blipping its throttle, a Mercedes-AMG V8 and the Chevrolet 350 V8): a fair
share of lift-offs give no pop; the rest one or two, now and then up to five or six;
the first straight away (20-90 ms after lifting) or a little later (150-450 ms); never
closer than 70 ms apart, typically 100-250 ms, the gaps lengthening through a burst;
each louder or quieter than the last; and getting back on the gas ends them. An
upshift on the throttle pops now and then, once, and coasting at high revs crackles
only occasionally (`PopTimer` in `src/game/sound.ts`). Each is pitched up only as far as it needs to sit just under the
engine's own note at those revs (60% of the firing rate, at most 2.2 times its
recorded pitch), a touch higher or lower each time: through the cabin from inside,
with a short slap of echo off the buildings outside, and from the rivals too, from
where they are. Until they've loaded, synthesized bangs stand in.
- Volume: sliders on the start menu and the pause screen (kept in step, and saved) for
the master volume and, under it, music, engines (yours and the rivals') and effects
(tyres, crashes, backfires, clicks): each its own bus into the master, the slider's
value squared so it feels even to the ear. The host's sound setting still mutes it all.
- Menu music: `menusound.wav`, provided by the creator, encoded to 96 kbps MP3
(`menu-music` asset). It's 55 beats at 67.4 BPM, so it loops at exactly 49.0 s and
comes round again on the beat. The original's final chord is cut off dead a tenth of a
second after it starts, then half a second of silence: here, nothing of it removed,
that chord rings out instead (its own tones, carried on from where it was cut and
fading away to nothing by the loop point), so the loop runs on without a jolt. It loops while the menus are up (the
start menu, the race planner, the results), fading in, and fades out while driving or
paused. It starts as the game loads wherever the browser and host let a page play
sound unprompted; where they don't, the moment anything is clicked, tapped or pressed.
- Tyres: two long squeals from [Chrysler LHS tire squeal 04](https://freesound.org/people/audible-edge/sounds/71739/)
and the wheelspin of a [Nissan Maxima burnout](https://freesound.org/people/audible-edge/sounds/71740/),
both by audible-edge, made into seamless loops. Layered by how the tyres slip: a
low scrub at the edge of grip, the full squeal (pitch rising with the slide) and
wheelspin in power slides, with quick attack and slower release so it never
chatters at the limit. [Tires on Gravel Road 1](https://freesound.org/people/OBXJohn/sounds/251661/)
by OBXJohn off the road.
- Impacts: [Collision](https://freesound.org/people/qubodup/sounds/332058/) and
[Fast Collision](https://freesound.org/people/qubodup/sounds/332056/) by qubodup,
[Rest Stop Metal Pole](https://freesound.org/people/yfjesse/sounds/734237/) by
yfjesse (lamp posts), [Wood Crack 1](https://freesound.org/people/utsuru/sounds/183453/)
by utsuru (trees) and [bushhit.wav](https://freesound.org/people/j1987/sounds/106113/)
by j1987 (bushes). New props reuse these: signs and mailboxes the pole, fences
and benches the wood crack, boxes and hay the bush hit.
Tyre roar is filtered noise (there is no wind noise); landings and the interface clicks are
synthesized.
## Brief
- **Job:** free-roam drifting with a drift score.
- **Must-have flows:** drive anywhere on the map; handbrake drifts with smoke,
skid marks and squeal; traffic to weave through or wreck; drift points with
a multiplier that bank when you straighten up and are lost if you crash; reset to the nearest road; keyboard,
gamepad and touch controls.
- **Optional flows:** best drift, paint, camera distance and the traffic setting saved through the
optional `storage` domain, along with each account's records and car designs; the player's
name from the optional `identity` domain (a guest name without it); the shared
leaderboards through the optional `cvm` domain (soyLI's backend); sound, units and screen
shake from the optional `config` domain. Without them the game plays with the defaults.
- **Requires:** nothing. No Nostr reads or publishes.
- **Form factor:** any size from a 200×160 embed (score, speed and road only)
to full screen; touch pedals appear on coarse pointers or after the first touch.
On a machine that can't keep above about 22 frames a second, it draws at a lower
resolution (down to half) until frames are quick again. To keep it light: each
traffic vehicle is merged into one mesh (a rig into two), so the traffic draws in
far fewer calls; and in first person the two door mirrors take turns redrawing,
each at half the frame rate, while the interior mirror redraws every frame.
- **The map** is generated from a fixed seed (`src/game/world.ts`), so it is the
same for everyone.
## Visual direction
- **Character:** a golden-hour postcard town. Warm cream and terracotta walls,
blue-grey towers downtown, bright faceted grass, long soft sun shadows, a
warm haze on the horizon. Low-poly and flat-shaded throughout, so the white
tyre smoke and black skid marks pop against it.
- **Main surface:** one baked, chunked mesh per material for the whole map,
vertex colours plus a façade atlas; one sun light with shadows that follow the
car. The small things (props, trees, bushes, rocks, roadside tufts) are in smaller
chunks of their own, left undrawn beyond a distance set by the graphics setting; the
camera draws no further than the fog's far end (1.9 km), past which everything is
lost in the haze anyway.
- **Graphics setting** (start menu and pause screen, saved): Auto, Low, Medium or High
(`src/game/game.ts`, `TIER`). Low draws straight to the screen at no more than one
pixel per CSS pixel, with three's plain PCF shadows on a 1024 map, the small things
out to 380 m, and the cockpit mirrors refreshed at half rate; Medium adds the soft
shadows (`src/game/shadows.ts`) on a 2048 map, 1.25 pixels per CSS pixel, the small
things to 650 m and post-processing; High 1.75 pixels, 950 m and ambient occlusion
too. Auto starts on Medium and, while driving, steps down a tier when frames come
slower than about 42 a second, or up one after nine seconds quicker than about 75 a
second (never back to a tier it had to leave); on Low, if it's still slow, it draws
at lower resolution, down to half. The readout shows the tier Auto is on. Each new
map's shaders are compiled in the background as it loads, where the browser can.
- **Post-processing** (Medium and High, `src/game/post.ts`): the scene into a
multisampled HDR target; on High, ambient occlusion from the depth alone (twelve
samples a pixel at half resolution, softened; only what's within reach counts, so
creases and corners darken without halos round outlines); bloom on whatever's
brighter than white; the same filmic tone mapping; and a light grade (a touch more
contrast and colour, warmer highlights, cooler shadows, the darks left alone). None
of it touches the sky: every pass reads the depth and leaves the pixels at the far
plane, where the sky is drawn, exactly as they were.
- **Night lights** (`src/game/night.ts`): as the sun sinks below about 3 degrees the
lights come on, full once it's as far under. A third of the windows light up, most
warm, some cool, each its own brightness (the façade shader); street lamps' and the
highway's lenses glow, and every one of them lights what's under it, shadows and all
(`src/game/lamp-bake.ts`): their light is baked, on the GPU, into a top-down map at
0.5 m a texel (the City's 748 lamps in a 16-bit map with an 8-bit height map beside
it, about 27 MB; the Test map's 85 far less). First the map's top surfaces' heights
from straight above; then for each lamp a 256 px depth picture from its head looking
down, and a disc added to the map: at each point the light a three.js spot light
there would give (the same brightness, cone, fall-off and colour as the real lamp
lights below), wherever the depth picture has nothing nearer the lamp (five taps,
for a soft edge), so posts, trees, benches, signs, buildings and the highway's pillars
all cast shadows. It's done a few lamps a frame, nearest the car first, from the first
time the lights come on on each map (a second or two on a graphics card; the game
never waits). The ground, the small things, the water and the buildings read it (a
wall the ground just in front of it, fading up the wall; nothing under a deck or a
canopy, where the baked surface is well above), and so do the cars, the rivals and
the traffic, as they pass under the lamps; by day it isn't read at all. A lamp
knocked over has its light taken out again (the same disc, subtracted). The lamps
nearest the car (within 120 m; two on Medium, four on High, none on Low) shine real
light as well, for the cars' shadows: each a spot with a 512 map, moved to the
nearest lamps a few times a second, those lamps' baked light taken out meanwhile (so
nothing's lit twice), all of them on all night, a spare one dark, so three's shaders
aren't rebuilt as the car comes and goes. Cars' headlights brighten and their tail
lights glow, the traffic's too; and the player's and the rivals' headlights light the
road ahead, a beam from each lamp (spots without shadows; the rivals' come with them
at the start of a race, their shaders compiled in the background).
- **Cars:** their paint, glass and chrome reflect a soft studio environment (three's
RoomEnvironment), fading with the daylight; the map's materials and the sky don't use
it.
- **Water** (river, shallows and sea, `waterMaterial` in `src/game/world.ts`): small
waves run over it in its shading, so the sun glints off it and the light plays across
it, and at glancing angles it takes on the haze's colour.
- **Sky and time of day:** the creator's Godot sky shader (`sky's/SourceCode/shader/main.gdshader`)
ported to three.js (`src/game/sky.ts`): day, sunset and night colours by the sun's
height, two cloud layers drifting so slowly they can barely be seen to move (a
fiftieth of the Godot material's wind), stars, a sun disc and a moon opposite it. Its noise
textures are the Godot NoiseTexture2D resources beside it, made ahead of time with
FastNoiseLite (the library Godot uses) by `tools/make-sky-textures.mjs`. The scene
that wired textures to the shader wasn't among the files, so the clouds are clouds_01
and clouds_02, the stars clouds_04, the night mottling clouds_03; clouds_05 to 07 are
unused. A Time slider (start menu and pause screen, saved) moves the sun through the
day: sunlight, sky light and haze take the shader's colours, twilight glows after
sunset, and the moon lights the night. A day and night cycle will drive it later.
- **Shadows:** soft sun shadows (`src/game/shadows.ts`, percentage-closer soft
shadows): like real sunlight from a disc, a shadow is sharp where its caster meets
the ground and softens the further away the caster is, so a car's is crisp at the
tyres and a tower's soft at its far end. They fade out at the edge of the shadow
map instead of stopping at a line. Contact shadows (`src/game/contact.ts`) darken
the road right under every car and rig (one instanced draw for all of them) and
under the player's car, fading as it jumps; buildings have a soft dark skirt
where they meet the pavement.
- **Buildings:** each one is generated from its own seed as one of several types.
In town: brick walk-ups with arched windows, cornices, ledges, fire escapes and
water tanks; shop rows under striped awnings; blocks of flats with balconies;
small glass-fronted offices; and houses with hipped or gabled roofs and chimneys.
Downtown, on shopfront podiums with entrance canopies: glass towers with metal
crowns, helipads or masts; stepped towers of dark glass; stone towers with corner
piers, setbacks and a spire; and slabs with fins down every bay. The walls sample
eight window styles from one atlas (classic, arched, twin, ribbon, curtain wall,
spandrel, shopfront, balcony); the shader keeps the glass its own colour and gives
every window its own shade, with the odd one lit or its blinds down. Every window
is whole: a wall takes as many bays across, and storeys up, as fit nearest to its
style's size, stretched a little to fit exactly (too narrow for one and it's plain
wall), with plain wall under cornices and crowns. Every building has an entrance in
its ground storey, on the side to the street: shop doors (one to each shop along a
row), front doors with fanlights on the walk-ups and flats, glass doors on the
offices, a revolving door under each tower's canopy, panelled front doors on the
houses, a roller door on the factories and an arched oak door in the church tower.
The doors are cells of the same atlas, in place of one bay's windows (`Soup.wall` in
`src/game/geo.ts`).
Every building is recorded as it's built (`BuildingLog` in `src/game/geo.ts`,
`World.layout`): its kind, the box round it, its roof and trim, and each wall's ends,
material (brick, stone, plaster, concrete, glass, siding, metal or wood), window bays
and storeys, façade style and doors, exactly as laid out, for the buildings' finer
detail on the higher graphics settings to line up with.
- **Walls on the higher settings** (`src/game/facades.ts`, `src/game/wall-surfaces.ts`): Low
draws the walls as above. Medium draws the window atlas at twice the resolution (every
window where it was, with fine frames and a glint along the glass), hangs curtains in
some home windows and lowers blinds part way in others (offices and sheds get blinds
only, shops neither), and gives the plain wall between the windows its material at its
real size, its relief catching the sun: brick in running bond with mortar, ashlar with
chamfered joints, rough render, precast concrete panels with tie holes, clapboard
siding, corrugated metal, timber planks, and brushed metal on the glass towers. The
eight surface textures are made in code (256 px, tiling). High adds a room behind every
window, an interior-mapped box a bay wide, a storey high and most of a bay deep that
shifts as you pass, with its own wall colour, floorboards, ceiling and a band of
furniture, under the glass's reflection (more of it on offices and shops, and further
off); at night the windows with their lights on glow with their rooms. On High half the
windows are dressed (homes' three in ten with curtains and two in ten with blinds,
offices' and sheds' half with blinds), except the towers', which are plain glass.
- **3D detail on the higher settings** (`src/game/building-detail.ts`): near the camera
(within about 130 m on Medium, 260 m on High, the finest pieces half that; never on
Low), built from the building log: window sills, lintels, glazing bars, keystones,
shutters, ribbon-window ledges, mullion fins up the glass towers, shop fascias and
risers, and balconies with railings on the flats; door frames and surrounds, steps,
canopies over the front doors of blocks of flats and walk-ups, the roller doors'
housings and the church's steps; storey ledges and corner pilasters on the older
buildings, brackets under the cornices, and gutters and downpipes along the eaves of
pitched roofs. Each window's pieces are placed by the same layout the façade atlas draws
it with, so they sit on the painted ones; a tower's mullions and bands are whole lines,
not a piece per window; where a wall stands just in front of another (a factory's office
on its hall), the one behind gets none. Every piece is a box without its back face,
instanced: per 80 m chunk of the map and 24 m band of height (each by its own distance,
so a tower's top floors drop out), a draw each for the fine pieces, the other small ones
and the big ones (balconies, canopies: the only ones casting shadows). Chunks are built a
few milliseconds a frame, nearest the camera first (the whole City, about 230,000 pieces,
takes some 150 ms). Near the ground in town it adds about a sixth to a half again to the
triangles drawn on Medium, and a few dozen draws.
- **Other models:** tiered pines and clumped broadleaf trees (now and then a birch),
lamp posts with arms over the road, farmhouses with porches, barns with braced
doors, hayloft and cupola, log cabins with porches, and the player's car with
over-fenders, a splitter and diffuser, shut lines, plates and five-spoke rims.
- **Ground:** each kind of ground is tagged (grass, asphalt, paving, dirt), and the
ground shader lays detail over it from a small tileable noise texture, by world
position: grass gets lusher, paler and dry patches and a grain of blades; asphalt
an aggregate, worn and patched areas and cracks; pavements are cast concrete, with
fine faint joints every 2 m, a cement grain, stains and the odd hairline crack;
dirt, fields and gravel shoulders a coarse grain.
The finest detail fades with distance so it doesn't shimmer. The streets have
manhole covers and kerbside drains, and grass tufts and wildflowers line the
country roads.
- **Interface:** slanted navy "sticker" slabs with heavy italic numerals, like
decals on a rally car: coral for the multiplier, sun yellow for a live drift,
mint for drift angle and new bests. Pop-ups for banked and lost drifts.
- **Theme policy:** app-owned. The host theme never recolours the scene or HUD.
- **Cover frame:** a mid-drift shot at a downtown crossing, smoke and skid marks
behind the car.
Napplets are sandboxed iframe apps. The shell/runtime injects `window.napplet`
before app code runs; the app uses `@napplet/sdk` to call available NAP domains
such as outbox, identity, storage, resource, and notify.
## Start
```bash
soyli setup
soyli dev
```
Build and verify the production artifact:
```bash
pnpm verify
```
`soyli build` uses the pinned Vite plugin to produce one inlined `index.html`.
`soyli publish` signs the standalone NIP-5D manifest; its `x` is the HTML SHA-256.
Do not use the plugin's optional legacy manifest for publication. Read
`docs/napplet-manifest.md` for editable capabilities, discovery metadata and icons.
## Conformance Testing
Verify the napplet conforms to the NAP protocol before publishing. Two variants,
mirroring `vitest` vs `vitest --ui`:
```bash
pnpm test:conformance # headless: build + check; non-zero exit on failure (CI)
pnpm test:conformance:ui # live web runtime; re-runs on every source change
```
It loads the build into a real `sandbox="allow-scripts"` iframe and drives the
protocol with a reference shell. Boot, forbidden-global, and degradation checks
run for a local directory; manifest, wire, and lifecycle checks report `SKIP`
unless the invocation supplies the evidence they require.
Exacting requirements for a passing build:
- Build to a **single self-contained `index.html`** (`@napplet/vite-plugin`
`artifactMode: 'single-file'` in `vite.config.ts`). NIP-5D loads a napplet via
`iframe.srcdoc` with
`sandbox="allow-scripts"` and no `allow-same-origin` (an opaque origin) — there
is no served origin from which to fetch an external `<script src>`, so the JS
must be inlined into the one file. External-asset builds do not boot.
- Do not import `@napplet/shim` from app code. The runtime injects
`window.napplet`; conformance verifies boot and emitted envelopes through the
reference runtime.
- Emit only well-formed envelopes via `@napplet/sdk`. Declare only hard NAP
requirements in `vite.config.ts`; guard optional domains with
`window.napplet?.domain` checks and a graceful fallback.
- Do not reference `window.nostr` or use direct `fetch`/`WebSocket`/`localStorage`.
The executable `index.html` does **not** carry its own manifest hash. Before
execution, the runtime verifies the signed manifest and the HTML SHA-256 against
its `x` tag. Earlier manifests remain readable through the legacy validator.
This generic starter declares no hard domains. Each demo action is optional and
disabled when its injected domain is absent. Add `requires` only after replacing
the demo with a core task that genuinely cannot run without that domain.
## Included
- Vanilla Vite + TypeScript napplet app.
- Typed `@napplet/sdk` helpers over the runtime-injected `window.napplet`
namespace.
- Build-time `@napplet/vite-plugin` wiring for the single-file artifact and
optional local manifest generation.
- Default app-chrome text selection disabled in `src/styles.css`, with
opt-in controls for copyable or editable regions.
- Context documents for NIP-5D, shell boundaries, package surfaces, and authoring
patterns.
- Guidance for handling missing NAP interfaces or numbered wire formats without
submitting unnecessary protocol PRs.
- A responsive capability demo with a replaceable local palette and opt-in host
theming. Choose the creation's own scene/content and UI direction using
`docs/napplet-visual-design.md`; the demo is not a required visual style.
- Installed soyLI-adapted agent skills; tooling guidance in docs/napplet-space.md.
## Authoring Context
Read these before changing protocol-facing behavior:
- `docs/nip-5d.md`
- `docs/boundaries.md`
- `docs/design-patterns.md`
- `docs/package-surfaces.md`
- `docs/new-nap-proposals.md`
- `docs/authoring-checklist.md`
The living NIP-5D source is referenced from `docs/nip-5d.md`; this template does
not treat its local notes as normative protocol text.
For agent-driven work, use the installed `napplet-make` skill. Read
`docs/napplet-space.md` first; `soyli skills update` refreshes managed guidance
while preserving your edits. Living NIP-5D and NAP documents remain protocol truth.
## Text Selection
The starter disables accidental text selection by default. To change the whole
napplet, set `--napplet-text-selection: text` in `src/styles.css`. To opt in one
region, add `data-napplet-select="text"` or `data-napplet-select="all"`.
## Package Scripts
```bash
pnpm dev # local Vite dev server
pnpm type-check # TypeScript strict-mode check
pnpm build # Vite production build
pnpm preview # preview dist/
pnpm test:guidance # stale-guidance and optional-domain regression checks
pnpm verify # guidance test + type-check + build
pnpm test:conformance # headless NAP conformance (build + check, CI exit code)
pnpm test:conformance:ui # live conformance web runtime, re-runs on change
```
