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
+51
View File
@@ -0,0 +1,51 @@
## The placement preview: a translucent copy of the piece where fire would put it, sea
## green when the server would accept it and rust red when it wouldn't. It asks the same
## Building.target() and Building.check() the server runs, so the ghost and the server
## agree on the client's predicted state.
class_name BuildGhost
extends Node3D
const VALID_COLOUR: Color = Color(0.46, 0.80, 0.70, 0.38)
const INVALID_COLOUR: Color = Color(0.86, 0.32, 0.22, 0.38)
## Whether the last update showed a placement the server would accept.
var valid: bool = false
var result: Building.Result = Building.Result.BAD_REQUEST
var target: Building.Target = null
var _mesh: MeshInstance3D = MeshInstance3D.new()
var _surface: StandardMaterial3D = StandardMaterial3D.new()
var _shown_key: String = ""
func _init() -> void:
_surface.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
_surface.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
_surface.cull_mode = BaseMaterial3D.CULL_DISABLED
_surface.no_depth_test = false
_mesh.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_mesh.material_override = _surface
add_child(_mesh)
## Recomputes the ghost for `player` building `kind` in `material`. Hides it for an
## unknown kind.
func update(sim: Simulation, player: SimEntity, kind: int, material: int) -> void:
target = Building.target(player, kind)
if target == null:
visible = false
valid = false
result = Building.Result.BAD_REQUEST
return
result = Building.check(sim, player, target, material)
valid = result == Building.Result.OK
visible = player.health > 0
var key: String = "%d %s %d" % [target.kind, target.slot, target.facing]
if key != _shown_key:
_shown_key = key
_mesh.mesh = PieceMesher.box_mesh(Building.boxes_for_target(target, sim.ground), Color.WHITE)
_surface.albedo_color = VALID_COLOUR if valid else INVALID_COLOUR
func colour() -> Color:
return _surface.albedo_color
+1
View File
@@ -0,0 +1 @@
uid://bx55hrsf4dmym
+150
View File
@@ -0,0 +1,150 @@
## Builds meshes for structure pieces from their collision boxes, so what players see is
## what blocks them. Faces are split into planks, stone courses or iron panels, each
## with its own slight tint, in the weathered palette from docs/ORIGINALITY.md. This is
## a blockout look; the v0.6 art pass replaces it.
class_name PieceMesher
extends RefCounted
## Base colour per material code, in sRGB.
const COLOURS: Array[Color] = [Color(0.62, 0.50, 0.36), Color(0.60, 0.59, 0.55), Color(0.50, 0.34, 0.26)]
## Size of a plank, course or panel, in metres, per material code.
const STRIP: Array[float] = [0.5, 0.5, 1.0]
## Gap between strips, shown as a darker seam.
const SEAM: float = 0.03
const SEAM_DARKEN: float = 0.45
## A mesh for a piece of `material` made of `boxes`, with strips tinted from `salt`.
static func build(boxes: Array[AABB], material: int, salt: int) -> ArrayMesh:
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
var base: Color = COLOURS[clampi(material, 0, COLOURS.size() - 1)]
var strip: float = STRIP[clampi(material, 0, STRIP.size() - 1)]
var index: int = 0
for box: AABB in boxes:
# Seam colour behind the strips.
_box(tool, box.grow(-SEAM * 0.5), base.darkened(SEAM_DARKEN))
# Wood runs vertically; stone and iron in horizontal bands.
var axis: int = 1 if material != Materials.DRIFTWOOD else (0 if box.size.x >= box.size.z else 2)
if box.size[axis] < strip * 1.5 and axis != 1:
axis = 2 if axis == 0 else 0
var count: int = maxi(1, roundi(box.size[axis] / strip))
var step: float = box.size[axis] / count
for part: int in count:
var piece: AABB = box
piece.position[axis] = box.position[axis] + part * step + SEAM * 0.5
piece.size[axis] = step - SEAM
_box(tool, piece, _tint(base, salt * 131 + index * 17 + part))
index += 1
tool.generate_normals()
var mesh: ArrayMesh = tool.commit()
var surface: StandardMaterial3D = StandardMaterial3D.new()
surface.vertex_color_use_as_albedo = true
surface.vertex_color_is_srgb = true
surface.roughness = 0.95 if material != Materials.SALVAGE_IRON else 0.7
surface.metallic = 0.0 if material != Materials.SALVAGE_IRON else 0.25
mesh.surface_set_material(0, surface)
return mesh
## A ramp drawn as a sloped plank deck on a solid wedge, rather than its stair-step
## collision boxes. The slope runs from the cell's low edge at `base` to its far edge
## one cell up, so the deck passes through the nose of every step.
static func build_ramp(slot: Vector4i, facing: int, material: int, salt: int) -> ArrayMesh:
var g: float = Tuning.GRID_CELL_METRES
var base: Color = COLOURS[clampi(material, 0, COLOURS.size() - 1)]
var origin: Vector3 = Vector3(slot.x * g, slot.y * Tuning.BUILD_LEVEL_METRES, slot.z * g)
var direction: Vector2i = StructureSet.FACING_DIRECTIONS[facing]
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
tool.set_smooth_group(-1)
var planks: int = 8
for plank: int in planks:
var u0: float = (plank + 0.04) / planks
var u1: float = (plank + 0.96) / planks
var colour: Color = _tint(base, salt * 131 + plank)
var corners: Array[Vector3] = []
for corner: Vector2 in [Vector2(u0, 0.0), Vector2(u1, 0.0), Vector2(u1, 1.0), Vector2(u0, 1.0)]:
corners.append(origin + _ramp_point(direction, corner.x, corner.y, g) + Vector3(0.0, 0.02, 0.0))
_quad(tool, corners, colour, Vector3.UP)
# Sides and back of the wedge, in the seam colour.
var dark: Color = base.darkened(0.35)
for side: float in [0.0, 1.0]:
var low: Vector3 = origin + _ramp_point(direction, 0.0, side, g)
var high: Vector3 = origin + _ramp_point(direction, 1.0, side, g)
var foot: Vector3 = Vector3(high.x, origin.y, high.z)
tool.set_color(dark)
for point: Vector3 in [low, high, foot, low, foot, high]:
tool.add_vertex(point)
var back: Array[Vector3] = [
origin + _ramp_point(direction, 1.0, 0.0, g), origin + _ramp_point(direction, 1.0, 1.0, g),
]
var back_low: Array[Vector3] = [Vector3(back[0].x, origin.y, back[0].z), Vector3(back[1].x, origin.y, back[1].z)]
tool.set_color(dark)
for point: Vector3 in [back[0], back[1], back_low[1], back[0], back_low[1], back_low[0], back[0], back_low[1], back[1], back[0], back_low[0], back_low[1]]:
tool.add_vertex(point)
tool.generate_normals()
var mesh: ArrayMesh = tool.commit()
var surface: StandardMaterial3D = StandardMaterial3D.new()
surface.vertex_color_use_as_albedo = true
surface.vertex_color_is_srgb = true
surface.roughness = 0.95
surface.cull_mode = BaseMaterial3D.CULL_DISABLED
mesh.surface_set_material(0, surface)
return mesh
## A point on a ramp's deck: `along` 0..1 up the slope, `across` 0..1 side to side.
static func _ramp_point(direction: Vector2i, along: float, across: float, g: float) -> Vector3:
var height: float = along * g
if direction.x > 0:
return Vector3(along * g, height, across * g)
if direction.x < 0:
return Vector3((1.0 - along) * g, height, across * g)
if direction.y > 0:
return Vector3(across * g, height, along * g)
return Vector3(across * g, height, (1.0 - along) * g)
## Adds a quad with both windings, so it shows from either side.
static func _quad(tool: SurfaceTool, corners: Array[Vector3], colour: Color, _up: Vector3) -> void:
tool.set_color(colour)
for index: int in [0, 1, 2, 0, 2, 3, 0, 2, 1, 0, 3, 2]:
tool.add_vertex(corners[index])
## A plain box mesh, every face flat.
static func box_mesh(boxes: Array[AABB], colour: Color) -> ArrayMesh:
var tool: SurfaceTool = SurfaceTool.new()
tool.begin(Mesh.PRIMITIVE_TRIANGLES)
for box: AABB in boxes:
_box(tool, box, colour)
tool.generate_normals()
return tool.commit()
static func _tint(base: Color, key: int) -> Color:
var h: int = hash(key * 2654435761)
var shift: float = (float(h & 0xff) / 255.0 - 0.5) * 0.14
var warm: float = (float((h >> 8) & 0xff) / 255.0 - 0.5) * 0.06
return Color(clampf(base.r + shift + warm, 0.0, 1.0), clampf(base.g + shift, 0.0, 1.0), clampf(base.b + shift - warm, 0.0, 1.0))
static func _box(tool: SurfaceTool, box: AABB, colour: Color) -> void:
var a: Vector3 = box.position
var b: Vector3 = box.end
var corners: Array[Vector3] = [
Vector3(a.x, a.y, a.z), Vector3(b.x, a.y, a.z), Vector3(b.x, a.y, b.z), Vector3(a.x, a.y, b.z),
Vector3(a.x, b.y, a.z), Vector3(b.x, b.y, a.z), Vector3(b.x, b.y, b.z), Vector3(a.x, b.y, b.z),
]
# Each face as four corner indices, wound clockwise seen from outside (Godot's front).
var faces: Array[PackedInt32Array] = [
PackedInt32Array([4, 5, 6, 7]), PackedInt32Array([3, 2, 1, 0]),
PackedInt32Array([0, 1, 5, 4]), PackedInt32Array([2, 3, 7, 6]),
PackedInt32Array([3, 0, 4, 7]), PackedInt32Array([1, 2, 6, 5]),
]
tool.set_smooth_group(-1)
tool.set_color(colour)
for face: PackedInt32Array in faces:
for corner: int in [0, 1, 2, 0, 2, 3]:
tool.add_vertex(corners[face[corner]])
+1
View File
@@ -0,0 +1 @@
uid://c3ndxshlqtytj
+42
View File
@@ -0,0 +1,42 @@
## Draws every built piece. `sync()` adds a mesh for each piece the simulation has that
## isn't drawn yet and drops meshes for pieces that are gone. Collision never comes from
## here; the simulation's SimGround holds the pieces' boxes.
class_name StructureView
extends Node3D
var _structures: StructureSet
## Piece ID -> MeshInstance3D.
var _drawn: Dictionary = {}
func setup(structures: StructureSet) -> void:
_structures = structures
sync()
func sync() -> void:
if _structures == null:
return
for piece_id: int in _drawn.keys():
if _structures.find(piece_id) == null:
_drawn[piece_id].queue_free()
_drawn.erase(piece_id)
for piece: StructureSet.Piece in _structures.pieces.values():
if _drawn.has(piece.id):
continue
var instance: MeshInstance3D = MeshInstance3D.new()
instance.name = "piece_%d" % piece.id
if piece.kind == StructureSet.RAMP:
instance.mesh = PieceMesher.build_ramp(piece.slot, piece.facing, piece.material, piece.id)
else:
instance.mesh = PieceMesher.build(piece.boxes, piece.material, piece.id)
add_child(instance)
_drawn[piece.id] = instance
func drawn_count() -> int:
return _drawn.size()
func _process(_delta: float) -> void:
sync()
@@ -0,0 +1 @@
uid://cekgr5ql1etfr
+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