B2: Grid building and placement preview

Server-authoritative grid building with wall, floor, ramp, roof and
breakwater pieces in driftwood, stone and salvage iron, plus a client
placement ghost.

- StructureSet: pieces in grid slots (floor, two wall edges, cell
  volume), their collision boxes in SimGround, and touching-neighbour
  links kept up to date for B3. Ramps are stairs of 0.4 m steps; walls
  over lower ground get a skirt down to the terrain; roofs are a low
  stepped pyramid. Pieces are part of the state hash.
- Building: target() snaps look and position to a slot, and check()
  validates any slot as if a hostile client chose it: state, range,
  occupancy, trapping a player, cost and support. Fire in build mode
  places at most 10 pieces a second; players in a low step are lifted.
- Levels are half a cell (2 m) apart, so ground pieces sit within a
  metre of the builder's feet instead of being half buried.
- Client: StructureView draws pieces from their boxes in plank, course
  or panel strips; ramps draw as a sloped deck. BuildGhost shows sea
  green or rust red from the same target() and check().
- Tests: 15 sim tests (targeting, every rejection, overlap, support,
  stairs climbable, skirts, determinism, 24 builders at 10 pieces a
  second within the tick budget) and 5 client tests (ghost states,
  ghost agrees with the server, view sync, mesh orientation).
- Capture scenarios build_fort and build_fort_side.

Closes #16

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 14:23:29 -05:00
co-authored by Claude Opus 5.5
parent b847ba9695
commit f35ebf7171
21 changed files with 1327 additions and 0 deletions
+193
View File
@@ -0,0 +1,193 @@
## Server-authoritative placement. In build mode (BUTTON_BUILD held) a command's
## `selection` is the piece kind and `material` the material code, and fire places.
## The server works out the slot from its own copy of the player's position and look,
## with target(), the same function the client's ghost uses. check() then validates the
## slot as if a hostile client had chosen it.
##
## Targeting: the look direction is snapped to a quarter turn. Walls and breakwaters go
## on the edge of the builder's own cell in that direction. Floors, ramps and roofs go
## in the next cell that way, or in the builder's own cell when looking well down. Ramps
## rise away from the builder. The level is the one nearest the feet, plus a whole cell
## (two levels) when looking well up.
class_name Building
extends RefCounted
enum Result {
OK,
## Dead, swimming, aboard the barge or falling.
NOT_ALLOWED,
## Unknown piece kind or material.
BAD_REQUEST,
OUT_OF_WORLD,
OUT_OF_RANGE,
OCCUPIED,
## Would trap a player inside it.
BLOCKED_BY_PLAYER,
UNAFFORDABLE,
## Touches neither the terrain nor another piece.
UNSUPPORTED,
}
## Where a piece would go.
class Target:
extends RefCounted
var kind: int = 0
var slot: Vector4i = Vector4i.ZERO
var facing: int = 0
static func is_allowed(player: SimEntity) -> bool:
return player.health > 0 and player.drop_state == Drop.NONE and not player.swimming
## Quarter-turn facing (0 +z, 1 +x, 2 -z, 3 -x) nearest the player's yaw.
static func facing_of(player: SimEntity) -> int:
return posmod(roundi(float(player.yaw) / PlayerCommand.YAW_STEPS * 4.0), 4)
## The slot a piece of `kind` would go in from the player's current pose, or null for
## an unknown kind.
static func target(player: SimEntity, kind: int) -> Target:
if kind < 0 or kind >= StructureSet.KINDS.size():
return null
var g: float = StructureSet.cell_size()
var facing: int = facing_of(player)
var direction: Vector2i = StructureSet.FACING_DIRECTIONS[facing]
var pitch_degrees: float = float(player.pitch) / PlayerCommand.PITCH_MAX * 90.0
var feet: Vector3 = player.position
var cell: Vector2i = Vector2i(floori(feet.x / g), floori(feet.z / g))
var level: int = roundi(feet.y / Tuning.BUILD_LEVEL_METRES)
if pitch_degrees > Tuning.BUILD_LOOK_UP_DEGREES:
level += roundi(g / Tuning.BUILD_LEVEL_METRES)
var result: Target = Target.new()
result.kind = kind
result.facing = facing
if StructureSet.is_wall_kind(kind):
match facing:
0:
result.slot = Vector4i(cell.x, level, cell.y + 1, StructureSet.SLOT_WALL_Z)
1:
result.slot = Vector4i(cell.x + 1, level, cell.y, StructureSet.SLOT_WALL_X)
2:
result.slot = Vector4i(cell.x, level, cell.y, StructureSet.SLOT_WALL_Z)
_:
result.slot = Vector4i(cell.x, level, cell.y, StructureSet.SLOT_WALL_X)
# A wall's facing only records which side the builder stood on.
return result
var looking_down: bool = pitch_degrees < -Tuning.BUILD_LOOK_DOWN_DEGREES
if not looking_down:
cell += direction
result.slot = Vector4i(cell.x, level, cell.y, StructureSet.slot_type_of(kind))
return result
## The boxes the piece would have, skirt included, as placed in `ground`.
static func boxes_for_target(at: Target, ground: SimGround) -> Array[AABB]:
var boxes: Array[AABB] = StructureSet.boxes_for(at.kind, at.slot, at.facing)
if StructureSet.is_wall_kind(at.kind):
var skirt: AABB = StructureSet.skirt_for(at.kind, boxes[0], ground)
if skirt.size != Vector3.ZERO:
boxes.append(skirt)
return boxes
## Whether `player` may place a piece of `at.kind` in `material` at `at`. Checks
## everything, as if a hostile client had picked the slot.
static func check(sim: Simulation, player: SimEntity, at: Target, material: int) -> Result:
if not is_allowed(player):
return Result.NOT_ALLOWED
if at == null or at.kind < 0 or at.kind >= StructureSet.KINDS.size() or not Materials.is_valid(material):
return Result.BAD_REQUEST
if at.facing < 0 or at.facing > 3 or at.slot.w != _expected_slot_type(at):
return Result.BAD_REQUEST
var boxes: Array[AABB] = boxes_for_target(at, sim.ground)
if not _inside_world(at, boxes[0]):
return Result.OUT_OF_WORLD
var centre: Vector3 = boxes[0].get_center()
if at.kind == StructureSet.RAMP:
var whole: AABB = boxes[0]
for box: AABB in boxes:
whole = whole.merge(box)
centre = whole.get_center()
if Harvest.eye(player).distance_to(centre) > Tuning.BUILD_RANGE:
return Result.OUT_OF_RANGE
if sim.structures.occupied(at.slot):
return Result.OCCUPIED
if _traps_a_player(sim, boxes):
return Result.BLOCKED_BY_PLAYER
if player.materials[material] < StructureSet.cost_of(at.kind):
return Result.UNAFFORDABLE
if not StructureSet.touches_terrain(boxes, sim.ground) and sim.structures.touching(boxes, sim.ground).is_empty():
return Result.UNSUPPORTED
return Result.OK
## Validates and places. Returns the result; on OK the piece is in `sim.structures`, its
## cost is spent, players standing in a low step of it are lifted onto it, and a
## "piece_placed" event is recorded.
static func place(sim: Simulation, player: SimEntity, at: Target, material: int) -> Result:
var result: Result = check(sim, player, at, material)
if result != Result.OK:
return result
Materials.spend(player, material, StructureSet.cost_of(at.kind))
var piece: StructureSet.Piece = sim.structures.add(at.kind, material, at.slot, at.facing, player.id, sim.tick, sim.ground)
_lift_players(sim, piece.boxes)
sim.events.append({"type": "piece_placed", "player": player.id, "piece": piece.id, "kind": at.kind, "material": material})
return result
## A tick of build mode: fire places at the target if the cooldown allows.
static func act(sim: Simulation, player: SimEntity, command: PlayerCommand) -> void:
if player.action_cooldown > 0 or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return
var at: Target = target(player, command.selection)
if place(sim, player, at, command.material) == Result.OK:
player.action_cooldown = Tuning.BUILD_INTERVAL_TICKS
static func _expected_slot_type(at: Target) -> int:
if StructureSet.is_wall_kind(at.kind):
return at.slot.w if at.slot.w == StructureSet.SLOT_WALL_X or at.slot.w == StructureSet.SLOT_WALL_Z else -1
return StructureSet.slot_type_of(at.kind)
static func _inside_world(at: Target, box: AABB) -> bool:
if at.slot.y < Tuning.BUILD_MIN_LEVEL or at.slot.y > Tuning.BUILD_MAX_LEVEL:
return false
var size: float = Tuning.WORLD_SIZE_METRES
var slack: float = Tuning.BREAKWATER_THICKNESS
return box.position.x >= -slack and box.position.z >= -slack and box.end.x <= size + slack and box.end.z <= size + slack
## True if any player's body overlaps the boxes by more than a step.
static func _traps_a_player(sim: Simulation, boxes: Array[AABB]) -> bool:
for entity: SimEntity in sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER or entity.health <= 0:
continue
var feet: Vector3 = entity.position
var height: float = Movement.body_height(entity)
for box: AABB in boxes:
if not _body_overlaps(box, feet, height):
continue
if box.end.y - feet.y > Tuning.STEP_HEIGHT:
return true
return false
static func _lift_players(sim: Simulation, boxes: Array[AABB]) -> void:
for entity: SimEntity in sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER:
continue
var feet: Vector3 = entity.position
var height: float = Movement.body_height(entity)
for box: AABB in boxes:
if _body_overlaps(box, feet, height) and box.end.y > entity.position.y:
entity.position.y = box.end.y
static func _body_overlaps(box: AABB, feet: Vector3, height: float) -> bool:
var r: float = Tuning.PLAYER_RADIUS
if box.end.y <= feet.y or box.position.y >= feet.y + height:
return false
return feet.x > box.position.x - r and feet.x < box.end.x + r and feet.z > box.position.z - r and feet.z < box.end.z + r
+1
View File
@@ -0,0 +1 @@
uid://br7ubbpapogdb
+6
View File
@@ -28,6 +28,8 @@ var props: PropSet = PropSet.new()
var sea_level: float = Tuning.SEA_LEVEL_START
## Damage per second to a player underwater with no breath left. Set by the tide phase.
var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"]
## Every built piece. Their boxes are part of `ground`.
var structures: StructureSet = StructureSet.new()
## The sky barge, from start_drop() on. Null in matches and tests that start on foot.
var drop: Drop = null
@@ -147,7 +149,10 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
player.action_cooldown -= 1
if command == null or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return
if not Building.is_allowed(player):
return
if command.is_pressed(PlayerCommand.BUTTON_BUILD):
Building.act(self, player, command)
return
if command.selection == BOATHOOK_SLOT:
Harvest.swing(player, ground, props, events)
@@ -202,6 +207,7 @@ func state_hash() -> String:
buffer.put_32(drown_dps)
buffer.put_64(props.count())
buffer.put_data(props.health.to_byte_array())
structures.write_state(buffer)
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
+278
View File
@@ -0,0 +1,278 @@
## Every built piece in a match: walls, floors, ramps, roofs and breakwaters, snapped to
## a grid of Tuning.GRID_CELL_METRES cells. Each piece fills one slot, and each slot holds
## at most one piece. Pieces are axis-aligned boxes in the SimGround, so movement,
## cameras and line of sight treat them like any other solid.
##
## Slots are Vector4i(x, level, z, type), where a piece's base is `level` times
## Tuning.BUILD_LEVEL_METRES (half a cell) above the starting sea:
## - FLOOR: the bottom face of cell (x, level, z).
## - WALL_X: the face at x = x * GRID between cells x - 1 and x, in row z.
## - WALL_Z: the face at z = z * GRID between cells z - 1 and z, in column x.
## - VOLUME: the inside of cell (x, level, z), for a ramp or a roof.
## Walls and breakwaters share wall slots, so a breakwater can't overlap a wall. A
## piece is a whole cell tall, so a slot also counts as taken when the same slot one
## level above or below holds a piece.
##
## Piece IDs count up from 1 and are never reused. Neighbours are pieces whose boxes
## touch, kept up to date as pieces come and go, for structural integrity.
class_name StructureSet
extends RefCounted
## Piece kind codes index this list. Each name is a key of Tuning.BUILD_PIECES.
const KINDS: Array[String] = ["wall", "floor", "ramp", "roof", "breakwater"]
const WALL: int = 0
const FLOOR: int = 1
const RAMP: int = 2
const ROOF: int = 3
const BREAKWATER: int = 4
const SLOT_FLOOR: int = 0
const SLOT_WALL_X: int = 1
const SLOT_WALL_Z: int = 2
const SLOT_VOLUME: int = 3
## Facings: the way a ramp rises, matching yaw (0 is +z, a quarter turn is +x).
const FACING_DIRECTIONS: Array[Vector2i] = [Vector2i(0, 1), Vector2i(1, 0), Vector2i(0, -1), Vector2i(-1, 0)]
## Boxes closer than this count as touching.
const TOUCH: float = 0.05
## Roof tiers: inset from the cell edge and height of each stacked slab, in metres.
const ROOF_TIERS: Array[Vector2] = [Vector2(0.0, 0.3), Vector2(0.7, 0.3), Vector2(1.4, 0.3)]
## A placed piece.
class Piece:
extends RefCounted
var id: int = 0
var kind: int = 0
var material: int = 0
var slot: Vector4i = Vector4i.ZERO
var facing: int = 0
var owner: int = 0
var health: int = 0
var max_health: int = 0
var placed_tick: int = 0
var boxes: Array[AABB] = []
var solid_ids: PackedInt32Array = PackedInt32Array()
## Touches the terrain.
var grounded: bool = false
## Piece ID -> Piece, in ascending ID order.
var pieces: Dictionary = {}
## Piece ID -> PackedInt32Array of touching piece IDs, ascending.
var neighbours: Dictionary = {}
## Removed piece IDs, in the order they went, for views to catch up on.
var removed: PackedInt32Array = PackedInt32Array()
var _next_id: int = 1
var _by_slot: Dictionary = {}
## SimGround solid ID -> piece ID.
var _by_solid: Dictionary = {}
static func cell_size() -> float:
return Tuning.GRID_CELL_METRES
static func slot_type_of(kind: int) -> int:
match kind:
FLOOR:
return SLOT_FLOOR
RAMP, ROOF:
return SLOT_VOLUME
return -1
static func is_wall_kind(kind: int) -> bool:
return kind == WALL or kind == BREAKWATER
static func cost_of(kind: int) -> int:
return Tuning.BUILD_PIECES[KINDS[kind]]["cost"]
static func max_health_of(material: int) -> int:
return Tuning.MATERIALS[Materials.NAMES[material]]["health"]
func count() -> int:
return pieces.size()
func find(piece_id: int) -> Piece:
return pieces.get(piece_id)
## The piece in a slot, or 0.
func at_slot(slot: Vector4i) -> int:
return _by_slot.get(slot, 0)
## True if the slot, or the same slot a level above or below, holds a piece.
func occupied(slot: Vector4i) -> bool:
for dy: int in [-1, 0, 1]:
if _by_slot.has(Vector4i(slot.x, slot.y + dy, slot.z, slot.w)):
return true
return false
## The piece whose box is ground solid `solid_id`, or 0.
func piece_of_solid(solid_id: int) -> int:
return _by_solid.get(solid_id, 0)
func next_id() -> int:
return _next_id
## The collision boxes a piece of `kind` in `slot` would have, before any skirt.
static func boxes_for(kind: int, slot: Vector4i, facing: int) -> Array[AABB]:
var g: float = cell_size()
var base: float = slot.y * Tuning.BUILD_LEVEL_METRES
var boxes: Array[AABB] = []
match kind:
WALL, BREAKWATER:
var t: float = Tuning.BREAKWATER_THICKNESS if kind == BREAKWATER else Tuning.WALL_THICKNESS
if slot.w == SLOT_WALL_X:
boxes.append(AABB(Vector3(slot.x * g - t * 0.5, base, slot.z * g - t * 0.5), Vector3(t, g, g + t)))
else:
boxes.append(AABB(Vector3(slot.x * g - t * 0.5, base, slot.z * g - t * 0.5), Vector3(g + t, g, t)))
FLOOR:
boxes.append(AABB(Vector3(slot.x * g, base, slot.z * g), Vector3(g, Tuning.FLOOR_THICKNESS, g)))
RAMP:
var steps: int = Tuning.RAMP_STEPS
var depth: float = g / steps
var direction: Vector2i = FACING_DIRECTIONS[facing]
for step: int in steps:
var rise: float = (step + 1) * depth
# Distance along the facing of this step's near edge, from the cell's low side.
var along: float = step * depth
var x0: float = slot.x * g
var z0: float = slot.z * g
var box: AABB
if direction.x != 0:
var start: float = x0 + along if direction.x > 0 else x0 + g - along - depth
box = AABB(Vector3(start, base, z0), Vector3(depth, rise, g))
else:
var start_z: float = z0 + along if direction.y > 0 else z0 + g - along - depth
box = AABB(Vector3(x0, base, start_z), Vector3(g, rise, depth))
boxes.append(box)
ROOF:
var y: float = base
for tier: Vector2 in ROOF_TIERS:
boxes.append(AABB(Vector3(slot.x * g + tier.x, y, slot.z * g + tier.x), Vector3(g - tier.x * 2.0, tier.y, g - tier.x * 2.0)))
y += tier.y
return boxes
## A wall or breakwater standing over lower terrain gets a skirt down to the terrain,
## no deeper than one cell, so ground-level walls leave no gap underneath. Returns the
## skirt box, or an empty AABB when none is needed.
static func skirt_for(kind: int, wall_box: AABB, ground: SimGround) -> AABB:
if not is_wall_kind(kind):
return AABB()
var lowest: float = INF
for fx: float in [0.0, 0.25, 0.5, 0.75, 1.0]:
for fz: float in [0.0, 0.5, 1.0]:
var x: float = lerpf(wall_box.position.x, wall_box.end.x, fx if wall_box.size.x > wall_box.size.z else fz)
var z: float = lerpf(wall_box.position.z, wall_box.end.z, fz if wall_box.size.x > wall_box.size.z else fx)
lowest = minf(lowest, ground.terrain_height(x, z))
var gap: float = wall_box.position.y - lowest
if gap <= 0.0 or gap > cell_size():
return AABB()
var bottom: float = lowest - 0.1
return AABB(Vector3(wall_box.position.x, bottom, wall_box.position.z),
Vector3(wall_box.size.x, wall_box.position.y - bottom, wall_box.size.z))
## True if any of `boxes` reaches down to the terrain.
static func touches_terrain(boxes: Array[AABB], ground: SimGround) -> bool:
for box: AABB in boxes:
for fx: float in [0.0, 0.25, 0.5, 0.75, 1.0]:
for fz: float in [0.0, 0.25, 0.5, 0.75, 1.0]:
var x: float = lerpf(box.position.x, box.end.x, fx)
var z: float = lerpf(box.position.z, box.end.z, fz)
if ground.terrain_height(x, z) >= box.position.y - TOUCH:
return true
return false
## IDs of pieces whose boxes touch any of `boxes`, ascending, without repeats.
func touching(boxes: Array[AABB], ground: SimGround) -> PackedInt32Array:
var found: Dictionary = {}
for box: AABB in boxes:
var grown: AABB = box.grow(TOUCH)
for solid_id: int in ground.solids_near(grown.position.x, grown.position.z, grown.end.x, grown.end.z):
var other: int = piece_of_solid(solid_id)
if other != 0 and not found.has(other) and grown.intersects(ground.solids[solid_id]):
found[other] = true
var ids: PackedInt32Array = PackedInt32Array(found.keys())
ids.sort()
return ids
## Adds a piece, its solids and its neighbour links. The caller has validated it.
func add(kind: int, material: int, slot: Vector4i, facing: int, owner: int, tick: int, ground: SimGround) -> Piece:
var piece: Piece = Piece.new()
piece.id = _next_id
_next_id += 1
piece.kind = kind
piece.material = material
piece.slot = slot
piece.facing = facing
piece.owner = owner
piece.placed_tick = tick
piece.max_health = max_health_of(material)
piece.health = piece.max_health
piece.boxes = boxes_for(kind, slot, facing)
if is_wall_kind(kind):
var skirt: AABB = skirt_for(kind, piece.boxes[0], ground)
if skirt.size != Vector3.ZERO:
piece.boxes.append(skirt)
piece.grounded = touches_terrain(piece.boxes, ground)
var links: PackedInt32Array = touching(piece.boxes, ground)
for box: AABB in piece.boxes:
var solid_id: int = ground.add_solid(box)
piece.solid_ids.append(solid_id)
_by_solid[solid_id] = piece.id
pieces[piece.id] = piece
_by_slot[slot] = piece.id
neighbours[piece.id] = links
for other: int in links:
var theirs: PackedInt32Array = neighbours[other]
theirs.append(piece.id)
neighbours[other] = theirs
return piece
## Removes a piece, its solids and its neighbour links. Returns false if unknown.
func remove(piece_id: int, ground: SimGround) -> bool:
var piece: Piece = pieces.get(piece_id)
if piece == null:
return false
for solid_id: int in piece.solid_ids:
ground.remove_solid(solid_id)
_by_solid.erase(solid_id)
for other: int in neighbours[piece_id]:
var theirs: PackedInt32Array = neighbours[other]
theirs.remove_at(theirs.find(piece_id))
neighbours[other] = theirs
neighbours.erase(piece_id)
_by_slot.erase(piece.slot)
pieces.erase(piece_id)
removed.append(piece_id)
return true
## Appends every piece to a hash buffer in ID order.
func write_state(buffer: StreamPeerBuffer) -> void:
buffer.put_64(_next_id)
buffer.put_64(pieces.size())
for piece: Piece in pieces.values():
buffer.put_64(piece.id)
buffer.put_u8(piece.kind)
buffer.put_u8(piece.material)
buffer.put_u8(piece.facing)
for value: int in [piece.slot.x, piece.slot.y, piece.slot.z, piece.slot.w]:
buffer.put_32(value)
buffer.put_64(piece.owner)
buffer.put_32(piece.health)
buffer.put_64(piece.placed_tick)
+1
View File
@@ -0,0 +1 @@
uid://co6d50yd1osd1
+20
View File
@@ -201,6 +201,26 @@ const MATERIALS: Dictionary = {
"stone": {"health": 300, "build_seconds": 5.0},
"salvage_iron": {"health": 500, "build_seconds": 9.0},
}
## Pieces are GRID_CELL_METRES on a side and tall, and snap across to the grid. Up and
## down they snap to levels BUILD_LEVEL_METRES apart, half a cell, so a piece built on
## the ground is never more than a metre above or below the builder's feet. Level 0 is
## the starting sea level; levels run from BUILD_MIN_LEVEL to BUILD_MAX_LEVEL.
const BUILD_LEVEL_METRES: float = 2.0
const BUILD_MIN_LEVEL: int = -8
const BUILD_MAX_LEVEL: int = 63
## A piece's centre must be within this distance of the builder's eye.
const BUILD_RANGE: float = 9.5
## Ticks between placements while fire is held: 10 pieces a second.
const BUILD_INTERVAL_TICKS: int = 3
## Looking further up than this, in degrees, targets the level above.
const BUILD_LOOK_UP_DEGREES: float = 35.0
## Looking further down than this puts floors, ramps and roofs in the builder's own cell.
const BUILD_LOOK_DOWN_DEGREES: float = 40.0
const WALL_THICKNESS: float = 0.3
const BREAKWATER_THICKNESS: float = 0.6
const FLOOR_THICKNESS: float = 0.2
## Ramps are stairs of this many steps, so each riser can be stepped up.
const RAMP_STEPS: int = 10
const BREAKWATER_MAX_HEAD: float = 6.0
const BREAKWATER_WEAR_PER_METRE: float = 2.0
const BREACH_FLOW_METRES_PER_SECOND: float = 1.5