DevLog #8 – Under the hull: terrain that dredges itself, geodesic sails and wrecks that stay down

This devlog is about the naval layer we added to Byzen this month: a port, a longboat, a brig and a frigate, and everything around them. It’s written for people who like to know how things are built. There are formulas, constants taken straight from the code, a few short excerpts, and the bugs that cost us the most time. Byzen runs on Unity 6.3 with URP; the asset tools are Python driving Blender headless.

The port on the Montevideo 1807 skirmish map
The port on the Montevideo 1807 skirmish map, with the two warships it just launched.

1. From two million triangles to a game mesh

Each source model came as a single FBX of about 2,000,000 triangles with 8K textures. The pipeline is one Python script per model, run inside Blender in background mode:

  1. Normalise. Clear the parent empty with CLEAR_KEEP_TRANSFORM and apply transforms. The FBX hangs from a rotated “world” node; skip this and the measured beam comes out wrong. Scale so the longest side is 1.
  2. Decimate to a triangle budget: 8,000 for the longboat, 24,000 for the brig, 20,000 for the frigate. The port gets 24,000 for the warehouse and 16,000 for the piers. Before collapsing we weld vertices (remove_doubles at length × 2·10⁻⁵), because rigging ships with unwelded verts and open boundaries stall the collapse.
  3. New UVs. smart_project at 60° with island margin 0.004, then pack_islands.
  4. Bake the colour from the original surface onto a 2K texture (1K for the longboat). Cycles on CPU, DIFFUSE colour pass only, selected-to-active, cage extrusion = length × 0.004, max ray = extrusion × 4.

Two things broke. First, Blender’s Decimate modifier would not take the brig below about 350,000 triangles, so the script now falls back to pymeshlab’s quadric edge collapse in a subprocess:

ms.meshing_decimation_quadric_edge_collapse( targetfacenum=budget, qualitythr=0.5, preserveboundary=True, optimalplacement=False)

Decimating Blender’s half-collapsed result left the brig blotchy. Running pymeshlab on the original high-poly mesh fixed it, along with a longer bake ray (× 12). Second, this Blender build ships an OCIO 2.5 config that its OCIO 2.4 library can’t load, so colour management runs in fallback mode. Textures come in undecoded, which means the bake is already sRGB. Encoding it again washed everything out. The bake is now saved raw into a Non-Color image.

Waterline from geometry

Every ship’s origin is its waterline, so the floating code only has to keep one point at the surface. We find it from the mesh: take a slice at midships (±6% of the length), walk up from the keel in 2 cm steps measuring the half-beam, and call the gunwale the first height above maximum beam where the beam falls below half. Above that there are only masts and yards.

water = keel + draft * (gunwale - keel) # draft = 0.40 (0.42 longboat)

The frigate’s sails hang low enough to defeat the beam test, so its hull height is set by hand (1.7 normalised units). The results: the longboat draws 0.34 m with 0.46 m freeboard, the brig 0.54 / 0.80, the frigate 0.68 / 1.02.

2. A port that shapes its own shore

The port model also arrives as one mesh with its parts lying side by side. The script splits loose parts, takes the tallest as the warehouse, joins the rest as the piers, lengthens the pile and quay bottoms by 0.15 normalised units (about 2.2 m) so they reach a dredged bed, and puts the origin at the centre of a 10 × 10 m plot at stone-deck height. The warehouse is lowered 0.37 m so it sits on the ground the game will level. The script also writes a JSON with the pier strip and the quay-head rectangle in game axes.

We got the arrangement wrong twice. First we ran the piers out into the river ramps-first. Then we flipped them, which pointed the quay stairs at open water. The right answer was the order the parts came in: warehouse on shore, three piers parallel to it on the water, stone heads at one end, joined to land.

Placement rule

With h = half the plot (5 m), L = pier strip (10 m) and f = the port’s forward axis:

  • The centre and both back corners are dry: terrain ≥ water + 0.3 m. The front corners may be wet; the terrain will be filled.
  • centre + f·(h + L/2) is not dry, so the piers really sit on water.
  • The mooring point centre + f·(h + L + 3) is harbour water: on the naval NavMesh area, at least 1.8 m deep, and at least 1.2 m deep at six points on a 3.5 m circle around it. That last test is what rejects creeks and marshes, where a frigate would run aground.
  • Orientation: try 24 headings and keep the valid one closest to where the player is dragging.

The bug of the month lived here. After the redesign, the port could not be placed anywhere on Montevideo, a map that is mostly bay. A probe that counted which rule failed pointed at the NavMesh sample: NavMesh.SamplePosition with a 3.5 m radius, called from the mooring point at shore height. The naval area is baked on the riverbed, about 3.6 m lower. The fix is one line: sample from the bottom.

p.y = TerrainGenerator.SampleHeight(p); // the naval NavMesh lives on the riverbed
if (!NavMesh.SamplePosition(p, out _, TipSearch, ShipFloat.NavalAreaMask)) return false;

Seating it: level, dredge, raise

Placing the port runs four heightmap operations, all on a rectangle rotated with the building:

  1. Level the plot to water + 1.0 − 0.3, the stone deck minus 30 cm, so the pier planks show. Side skirt uses the building’s normal blend; towards the water the skirt is only 0.5 m, which reads as a quay wall.
  2. Dredge the pier strip, from h + 0.5 to h + L + 3, down to water − 2.2. It only lowers, never raises, and has a 4 m skirt to the sides and seaward but none landward, so it can’t eat the plot.
  3. Raise the quay-head rectangle up to plot level, with a 0.6 m skirt. It only raises. This is what joins the stone heads to the shore.
  4. Clear grass (terrain detail layers) over the plot and the raised ground.

Lower and raise share one routine with a direction flag. Every pass converts each heightmap cell into the building’s local axes with an inverse yaw, measures its distance to the rectangle, and applies a smoothstep weight inside the skirt:

float lx = dx * cos - dz * sin, lz = dx * sin + dz * cos;
float ox = max(0, localMin.x - lx, lx - localMax.x);
float oz = max(0, localMin.y - lz, lz - localMax.y);
float t = 1 - sqrt(ox*ox + oz*oz) / blend; // inside: weight 1
float w = t * t * (3 - 2 * t);
if (raise ? h >= target : h <= target) continue;
h = lerp(h, target, w);

Afterwards the area is queued for an async NavMesh rebake, and resources and props inside it are re-grounded.

Quay heads joined to land, dredged water under the piers
Raised ground under the quay heads, dredged water under the piers. Only the child named “Galpon” (the warehouse) carries a NavMesh obstacle; quays and piers are walkable.

3. Hulls are capsules, not circles

NavMeshAgent avoidance is circular. A 10.5 m frigate with a 2.6 m agent radius lets another ship drive straight into its bow. Each hull is now a capsule along the keel, with half-length and half-beam measured on the models: 1.8 × 0.67 m (longboat), 3.7 × 0.92 (brig), 5.2 × 1.45 (frigate). Once per frame the first ship to update runs every pair:

segA = centre &plusmn; fwd * (halfLength - halfBeam)
(pa, pb) = closest points between segA and segB
penetration = beamA + beamB + 0.15 - |pa - pb|
push = min(penetration * 0.5, 0.25 m) // per frame, no jolts
A.agent.Move( dir * push * massB / (massA + massB))
B.agent.Move(-dir * push * massA / (massA + massB)) // mass = halfLength * halfBeam

Agent.Move respects the NavMesh, so a push can never shove a hull onto land. With n² pairs and a handful of ships the cost doesn’t register. In a test with the frigate dropped 2.5 m deep into the brig, they were clear in under two seconds.

The frigate with its selection ring above the water
The selection ring now sits 0.35 m above the waterline. At 6 cm the water’s depth write was hiding it behind every wave crest.

4. Sails weighted by geodesic distance

Byzen has a wind field that publishes shader globals (_WindDirection, _WindStrength, _WindPhase) for vegetation. We wanted the sails to read the same wind. The hard part is telling the vertex shader how much each sail vertex can move: zero where the canvas is tied to a yard, a mast or a rope, and the most in the middle.

The offline tool (sail_mask.py, numpy + Pillow, no Blender) works on the game mesh:

  1. Find sail faces by colour. Sample the baked texture at the three corners and the centroid of each triangle. It’s canvas if at least 3 of the 4 samples have luminance > 0.50 and saturation < 0.30. Wood is darker and warmer.
  2. Find edges. An edge with exactly one sail face, or a sail face and a non-sail face, is a boundary.
  3. Geodesic distance. Run a multi-source Dijkstra from all boundary vertices across sail edges, weighted by edge length in metres.
  4. Normalise per panel. Find connected components, divide by each panel’s max distance, and shape the curve with w(2 − w), which rises fast and flattens in the middle. Panels whose max distance is under 0.12 m are stray white trim and get 0.

Per-face sail weight on the frigate and the brig
The weight per face, frigate left and brig right: blue at the edge of each panel, orange at its centre.

Two problems with where the weight could live:

  • Vertex colours are out. Unity’s OBJ importer drops them. The weight goes into the alpha of the ship’s base texture, stored as 1 − w so the rest of the ship stays at alpha 1. The material is opaque and wasn’t using alpha. The tool rasterises each triangle into the atlas with barycentric interpolation of the vertex weights, then dilates 3 texels into the gutter so bilinear sampling at UV seams doesn’t pick up zeros. The UVs are thousands of small islands, which is exactly why the distance has to be computed on the surface and not in texture space.
  • The frigate’s sails had nothing to bend. Decimation left them as a few large triangles with almost no interior vertices. Sail faces are now split 1-to-4 until the mean sail edge drops under 0.25 m (at most two levels), with a midpoint cache keyed on vertex pairs so panels stay watertight. The frigate went from 20,000 to about 22,700 triangles; the brig’s sails were already fine.

In the shader we added one function to our lit shader (Byzen/WetLit), called from all four passes so shadows and depth move with the canvas. The mask is read with a LOD-0 fetch in the vertex stage, behind a uniform branch on _SailBillow > 0, so foliage materials pay nothing:

float m = 1.0 - SAMPLE_TEXTURE2D_LOD(_BaseMap, sampler_BaseMap, uv, 0).a;
float s = saturate(_WindStrength);
float phase = dot(posWS.xz, float2(0.73, 1.31)) + posWS.y * 0.9;
float fill = _SailBillow * (0.35 + 0.65 * s) * (0.92 + 0.08 * sin(t * 0.7 + phase * 0.2));
float flap = _SailFlutter * (0.3 + s) * sin(t * (2.6 + 3.0 * s) + phase * 2.2);
posWS += windDir * (fill * m + flap * m * 0.6);
posWS += windSide * (flap * m * 0.35);

Maximum billow is 0.9 m on the frigate and 0.7 m on the brig. Flutter is 12% of billow. In dead calm the canvas holds 35% of its belly and barely moves.

Same frame of the frigate, sails flat and filled
Same frame, billow forced to 0 on the left. A pixel diff shows changes only on the canvas: masts, yards and rigging stay put.

5. Broadsides

Ships used to fire one ball from a point at the bow. Now the brig and the frigate have gun ports, measured on the meshes: the half-beam at gun-deck height (0.62 m above the waterline on the frigate, 0.5 m on the brig), sampled every half metre along the keel. That gives seven ports a side on the frigate, from z = −3.0 to +1.8 m, and five on the brig.

Attacking is a two-part change in the unit’s attack state:

  • Aim with the side. Instead of facing the target, the ship turns to the perpendicular that’s closer to its current heading. It only fires when the broadside is within 30° of the target.
  • Fire gun by gun. The side is sign(dot(target − pos, right)). The first gun is the port nearest the target, then the next ones alternate towards bow and stern, 70–160 ms apart. Each gun gets the full cannon treatment from our pooled muzzle system: flash core and three tongues, 18 sparks, a pooled point light, the report, and smoke whose drag and rise come from the same wind field.

Damage did not change. One real projectile leaves from the nearest port. The others are pooled visual-only cannonballs (Projectile.SpawnVisual: no target and no hit, just flight and a water splash), scattered ±3 m around the target.

Brig and frigate firing broadsides at the shore
Both ships firing on the shore. Smoke per gun is 30% of a field cannon’s.

The smoke went through two cuts. At full field-cannon density (28 puffs per gun, lifetimes of 8–15 s), twelve guns built a bank that hid both ships, so we went to 60% per gun, then 30% after playtesting. The low blast that rolls sideways off each muzzle is scaled the same way.

Warships also bombard the coast on their own. An idle unit normally only picks targets inside its faction’s territory, and a leash drops the target if it leaves. Warships skip both checks when the target is within cannon range (13 m frigate, 11 m brig), so they shell anything on the shore. They don’t chase inland, because a target out of range goes back through the normal rules.

6. A seated crew that fights

Boarding a ship deactivates the unit’s GameObject, the same pattern as garrisoning. For the longboat we wanted the troops visible, without un-deactivating the unit and fighting its agent and AI. So the crew component takes only the unit’s Visual child, its rigged model, and reparents it to one of six seats on the longboat’s thwarts. The seats are three rows of two, 8 cm above the waterline, measured on the mesh. The visual goes back under the unit on landing, and is destroyed with it if the unit dies aboard or the boat sinks.

The model’s Animator stays alive under the boat, and the crew component drives it directly:

  • Base layer: Sit_Listen, a clip we already had from the night camp scenes.
  • Upper layer: our human controller already had an upper-body layer (avatar mask: everything under DEF-spine.001) for attacks on horseback. We added Attack_Fire, Attack_Thrust and Attack_Bow to it, reusing the base-layer clips so per-character overrides still apply. A one-off editor patch added them to the existing controller. To attack, the crew component sets that layer’s weight to 1 and plays the state, then drops the weight back after 0.9 s. The legs stay seated the whole time.
  • Seat height. The sit clip carries its own pelvis height, so on the first frame we force an Animator.Update(0), measure the pelvis bone, and shift the model so the hips sit 12 cm above the thwart.
  • Facing. Everyone faces the bow. Towards a target they twist at 240°/s, clamped to ±40°.

Each seated soldier scans the entity grid every 0.4 s for the nearest hostile in reach: weapon range for rifles and bows, 2.6 m for lances and bayonets. It fires on its own unit’s attack rate through the normal damage path (CombatService.MakeShot with the seated unit as attacker), with the impact 0.08 s, 0.35 s or 0.45 s after the gesture for musket, thrust and bow. The inactive unit’s transform is copied from the seat every frame, so muzzle position, range checks and the shot’s origin are all correct. The longboat itself no longer attacks: no crew, no fire.

Six soldiers seated in the longboat facing the bow
Six seats, six soldiers: three Guaraní lancers and three riflemen, facing forward on the thwarts.

7. Damage you can read, ruins and wrecks

Buildings and ships now show their health. A small component polls hp / maxHp every 0.25 s:

  • Stage 1 (< 70%): smoke from our chimney-smoke emitter.
  • Stage 2 (< 40%): one fire.
  • Stage 3 (< 15%): three fires.
  • Charring: a MaterialPropertyBlock lerps _BaseColor from white towards (0.42, 0.37, 0.33) with damage. On ships it goes only 45% of the way, because the dark wood went black.
  • Debris: buildings drop four pieces from roof height each time they cross a threshold for the first time.

Fire spots come from the model’s bounds, seeded by instance ID so they don’t jump between runs. On buildings they sit at 60–85% of the height inside the middle of the footprint; on ships they run along the deck. Fire scale is clamp(maxExtent × 0.18, 0.6, 2.4), or × 0.14 on ships. Buildings under construction are skipped, because there health climbs from zero and isn’t damage.

The fires are a new subclass of our fire system’s base class, without logs or fuel: shelter = 0.35, so heavy rain can win, and only the first fire per structure gets a light. One gotcha: a fire source re-ignites itself by default (its per-frame step drives intensity back up on dry ground), so a structure fire is created with Extinguish(), which latches it off until Ignite(). Our fire system has no pooling yet, and its ADR warns past about 20 fires, so structure fires are capped at 30 live; past that, new stages are smoke only.

Collapse and sink

On death, the entity’s Visual child is detached before the entity is destroyed, and a wreck component animates it. Fires and smoke are children of the visual, so they come along.

Building collapse, 2.4 s, with e = smoothstep(u):

shake = random_xz * 0.12 * (1 - u)
sink = height * (1 - 0.32) * 0.35 * e
tilt = lerp(0, 5..11 deg, e) around a random horizontal axis
scaleY = lerp(1, 0.32, e); scaleXZ = 1 + 0.06 * e

Fourteen debris pieces fall from roof height with a short bounce, and a dust burst goes up. The ruin keeps a smoulder plume for 25 s, while the remaining fires die off one by one over 4–12 s.

A rancho from full health to a smouldering ruin
A rancho from full health to a ruin. Its texture is dark to begin with; the charring shows better on whitewashed walls.

Ship sinking, 7 s. The resting depth is bottom = min(SampleHeightMin(pos, radius) + 0.4, water − 0.3), using the lowest terrain under the hull so it doesn’t hang off a slope.

list = clamp01(u / 0.3) // heel over first
down = u * u // then go, accelerating
y = lerp(startY, bottom, down)
pos += fwd * 0.6 * down
rot = start * Euler(pitch * down, 0, roll * lerp(0.45 * list, 1, down))
// pitch in &plusmn;14 deg, roll in &plusmn;18..32 deg

Every 0.25–0.5 s while the hull is crossing the surface, a splash spawns at a random point along it. Each fire is destroyed the moment its world Y drops below the water. The wreck then stays on the bottom. In shallow water the mastheads stay above the surface, the way a grounded ship would look.

A brig from full health to a wreck on the riverbed
From full health to the riverbed.

How long ruins and wrecks last comes from a graphics setting that existed but had no effect until now. Off removes them once the animation ends, temporary keeps them 120 s, and permanent leaves them forever. When they go, they sink 1.2 × their height over 5 s and are destroyed. They’re plain GameObjects, not entities: no obstacles, no selection, no gameplay.

8. Smaller fixes

  • Markers on water. Move and attack markers used terrain height, so orders to ships put the marker on the riverbed. They now use max(terrain, waterLevel + waveHeight + 0.15).
  • Portraits. The three ships have painted HUD portraits, made from Cycles renders of the models with a waterline holdout, then run through a painterly filter (mode filter, ink outline, sepia grade) to match the rest of the HUD.
  • A workflow lesson. Several play-mode tests broke with a domain reload in the middle of the match. We were triggering compiles with a script-only recompile, which doesn’t import changed files, and Unity picked them up when play mode started. Refresh the AssetDatabase, not just the scripts.

HUD portraits: longboat, brig, frigate and port
Longboat, brig, frigate and port.

What’s next

Only the longboat has seats; the brig and frigate still carry their troops hidden, because their decks need seat or standing points of their own. The enemy AI keeps guard ships but doesn’t plan landings yet. The fire system still needs the pooling its ADR asks for. And the port isn’t in the map editor’s palette. If you try the Montevideo skirmish, build a port, send the frigate along the coast, and tell us what broke.