Files
tidewall/src/sim/prop_set.gd
T
claudeandClaude Opus 5.5 6b21e9d4f1 N5: Replicate building, world damage, tide and loot
Built pieces, props' health, opened chests and the tide's schedule now reach
clients as WORLD messages on the reliable channel, and each player is told
what they carry as OWN messages.

- NetWorld: the WORLD and OWN wire formats, and world_hash(), a digest of
  everything replicated this way.
- WorldSender: one message after each tick in which something changed, the
  same for everyone, and the whole state for someone joining or a new match.
  StructureSet and PropSet keep the change lists it reads.
- ClientWorld: applies them to the client's world, so pieces and broken props
  are solid for prediction. A piece's health follows from its building and
  damage, so building costs nothing on the wire.
- Placing ahead of the server: a provisional piece goes up with the command
  and is replaced by the server's, or taken back once a snapshot shows the
  server had its chance. Snapshots carry the newest WORLD number for that.
- Protocol version 3.

A test plays a whole scripted match on a real island with a ClientGame
attached and compares the two worlds' hashes throughout.

Closes #36

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:27:58 -05:00

277 lines
11 KiB
GDScript

## The island's scattered props: pines, scrub, boulders, wrecks and crates. Like the
## island and its points of interest, both ends build the same set from the seed alone,
## so props are never sent over the network. Only damage to them is match state.
##
## Placement walks a jittered grid of CELL-metre squares. Every square draws the same
## number of random values whatever it ends up holding, so a change in one square's
## outcome never shifts the next. A kind's chance in a square comes from its density in
## the square's elevation band (Tuning.PROP_DENSITY), scaled by a grove noise for pines
## and scrub, so forests have thickets and clearings.
##
## Each prop is one axis-aligned collision box in SimGround. Destroying a prop removes
## its box, so players can walk where it stood. Props are stored in packed arrays,
## because there are thousands of them.
class_name PropSet
extends RefCounted
## Side of the placement squares, in metres. At most one prop per square.
const CELL: float = 4.0
## Random values drawn per square: pick, jitter x, jitter z, size, height, length, turn.
const DRAWS: int = 7
## Kind codes, in the order kinds are tried within a square.
const KINDS: Array[String] = ["pine", "scrub", "boulder", "wreck", "crate"]
## Band names, indexed by Island.Band.
const BAND_NAMES: Array[String] = ["sea", "beach", "marsh", "forest", "highland", "summit"]
## Grove noise scale, in metres, and how strongly it thins or thickens growth.
const GROVE_METRES: float = 70.0
const GROVE_STRENGTH: float = 1.6
## Lowest ground props stand on, in metres above the starting sea. Wrecks lie lower.
const MIN_HEIGHT: float = 0.4
const WRECK_MIN_HEIGHT: float = 0.1
## Most ground rise across a footprint each kind accepts, in metres.
const TILT_LIMITS: Dictionary = {"pine": 1.6, "boulder": 2.0, "wreck": 1.2, "scrub": 0.6, "crate": 0.6}
## Boxes sink this far into the ground at their lowest corner, so none float on slopes.
const SINK: float = 0.25
## Per prop, indexed by prop ID (0 .. count() - 1).
var kinds: PackedByteArray = PackedByteArray()
## Where the prop meets the ground, at its footprint centre.
var positions: PackedVector3Array = PackedVector3Array()
## Visual yaw in radians. Collision is the box in `boxes` whatever the yaw.
var yaws: PackedFloat32Array = PackedFloat32Array()
var boxes: Array[AABB] = []
var health: PackedInt32Array = PackedInt32Array()
## The SimGround solid ID of each prop's box, or -1 when it isn't in a ground.
var solid_ids: PackedInt32Array = PackedInt32Array()
## Prop IDs in the order they were destroyed, for views to catch up on.
var destroyed: PackedInt32Array = PackedInt32Array()
## Props damaged since whoever sends them to clients last cleared this. A set: the
## values mean nothing. Not match state.
var changed: Dictionary = {}
var _ground: SimGround
## SimGround solid ID -> prop ID, for props whose box is in `_ground`.
var _by_solid: Dictionary = {}
## Places props for `island`, clear of `placed` points of interest.
static func generate(island: Island, placed: PoiSet) -> PropSet:
var props: PropSet = PropSet.new()
props._place(island, placed)
return props
func count() -> int:
return kinds.size()
func kind_name(prop: int) -> String:
return KINDS[kinds[prop]]
func material_of(prop: int) -> String:
return Tuning.PROP_KINDS[kind_name(prop)]["material"]
func is_standing(prop: int) -> bool:
return health[prop] > 0
func count_of(kind: String) -> int:
var code: int = KINDS.find(kind)
var total: int = 0
for value: int in kinds:
if value == code:
total += 1
return total
## Adds every prop's box to `ground` and remembers the solid IDs, so destroying a prop
## removes its collision. Call once.
func add_solids_to(ground: SimGround) -> void:
_ground = ground
solid_ids.resize(count())
for prop: int in count():
solid_ids[prop] = ground.add_solid(boxes[prop]) if is_standing(prop) else -1
if solid_ids[prop] >= 0:
_by_solid[solid_ids[prop]] = prop
## The prop whose box is ground solid `solid_id`, or -1 if that solid isn't a prop.
func prop_of_solid(solid_id: int) -> int:
return _by_solid.get(solid_id, -1)
## Takes `amount` health from a standing prop. Returns true if this destroyed it, which
## also removes its collision. Damage to an already destroyed prop does nothing.
func damage(prop: int, amount: int) -> bool:
if prop < 0 or prop >= count() or not is_standing(prop) or amount <= 0:
return false
health[prop] = maxi(health[prop] - amount, 0)
changed[prop] = true
if health[prop] > 0:
return false
destroyed.append(prop)
if _ground != null and solid_ids[prop] >= 0:
_ground.remove_solid(solid_ids[prop])
_by_solid.erase(solid_ids[prop])
solid_ids[prop] = -1
return true
## Standing props whose boxes come within `radius` of `point`, nearest first.
func near(point: Vector3, radius: float) -> PackedInt32Array:
var found: Array[Vector2] = []
for prop: int in count():
if not is_standing(prop):
continue
var gap: float = _distance_to_box(boxes[prop], point)
if gap <= radius:
found.append(Vector2(gap, prop))
found.sort()
var ids: PackedInt32Array = PackedInt32Array()
for entry: Vector2 in found:
ids.append(int(entry.y))
return ids
## SHA-256 hex digest of every prop's kind and box, millimetre-rounded. Two machines
## that agree on this see the same props in the same places.
func layout_hash() -> String:
var buffer: StreamPeerBuffer = StreamPeerBuffer.new()
buffer.big_endian = false
buffer.put_32(count())
buffer.put_data(kinds)
for box: AABB in boxes:
for value: float in [box.position.x, box.position.y, box.position.z, box.size.x, box.size.y, box.size.z]:
buffer.put_32(roundi(value * 1000.0))
for yaw: float in yaws:
buffer.put_32(roundi(yaw * 1000.0))
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
hasher.update(buffer.data_array)
return hasher.finish().hex_encode()
func _place(island: Island, placed: PoiSet) -> void:
var ground: SimGround = island.ground
var rng: RandomNumberGenerator = SimRng.new(island.match_seed).stream("props")
var grove: FastNoiseLite = FastNoiseLite.new()
grove.noise_type = FastNoiseLite.TYPE_SIMPLEX_SMOOTH
grove.seed = rng.randi()
grove.frequency = 1.0 / GROVE_METRES
var blocked: SimGround = _poi_keep_out(placed)
var mine: SimGround = SimGround.flat()
var per_side: int = floori(Tuning.WORLD_SIZE_METRES / CELL)
var cell_area_hectares: float = CELL * CELL / 10000.0
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(DRAWS)
for gz: int in per_side:
for gx: int in per_side:
for draw: int in DRAWS:
values[draw] = rng.randf()
var x: float = (gx + 0.15 + 0.7 * values[1]) * CELL
var z: float = (gz + 0.15 + 0.7 * values[2]) * CELL
var band: int = island.band_at(x, z)
if band == Island.Band.SEA:
continue
var densities: Dictionary = Tuning.PROP_DENSITY[BAND_NAMES[band]]
var growth: float = clampf(1.0 + grove.get_noise_2d(x, z) * GROVE_STRENGTH, 0.0, 2.2)
var pick: float = values[0]
var chosen: int = -1
for code: int in KINDS.size():
var kind: String = KINDS[code]
var chance: float = float(densities.get(kind, 0.0)) * cell_area_hectares
if kind == "pine" or kind == "scrub":
chance *= growth
if pick < chance:
chosen = code
break
pick -= chance
if chosen < 0:
continue
var box: AABB = _box_for(chosen, Vector2(x, z), values, ground)
if box.size == Vector3.ZERO:
continue
if _overlaps(blocked, box, Tuning.PROP_POI_CLEARANCE) or _overlaps(mine, box, 0.3):
continue
mine.add_solid(box)
kinds.append(chosen)
positions.append(Vector3(x, ground.terrain_height(x, z), z))
yaws.append(values[6] * TAU)
boxes.append(box)
health.append(Tuning.PROP_KINDS[KINDS[chosen]]["health"])
## The prop's collision box, or an empty box if the spot doesn't suit the kind.
func _box_for(code: int, at: Vector2, values: PackedFloat32Array, ground: SimGround) -> AABB:
var kind: String = KINDS[code]
var spec: Dictionary = Tuning.PROP_KINDS[kind]
var width: float = lerpf(spec["width"][0], spec["width"][1], values[3])
var height: float = lerpf(spec["height"][0], spec["height"][1], values[4])
var size: Vector3 = Vector3(width, height, width)
if kind == "wreck":
var length: float = lerpf(spec["length"][0], spec["length"][1], values[5])
# Wrecks lie along x or z, so the box stays axis-aligned.
size = Vector3(length, height, width) if values[6] < 0.5 else Vector3(width, height, length)
var half: Vector2 = Vector2(size.x, size.z) * 0.5
var lowest: float = INF
var highest: float = -INF
for corner: Vector2 in [Vector2(-1, -1), Vector2(1, -1), Vector2(-1, 1), Vector2(1, 1), Vector2.ZERO]:
var h: float = ground.terrain_height(at.x + corner.x * half.x, at.y + corner.y * half.y)
lowest = minf(lowest, h)
highest = maxf(highest, h)
var floor_min: float = WRECK_MIN_HEIGHT if kind == "wreck" else MIN_HEIGHT
if lowest < floor_min:
return AABB()
# Boulders and pines take slopes; the rest need somewhere flattish.
var tilt: float = highest - lowest
var max_tilt: float = TILT_LIMITS.get(kind, 0.6)
if tilt > max_tilt:
return AABB()
var base: float = lowest - SINK
# The box grows by the tilt, so its top stands `height - SINK` above the uphill
# corner too. Boulders sink deeper on slopes, so the uphill side isn't a wall.
if kind == "boulder":
base -= tilt * 0.4
size.y += tilt * 0.4
size.y += tilt if kind != "pine" else 0.0
return AABB(Vector3(at.x - half.x, base, at.y - half.y), size)
## A ground holding every POI solid, plus small boxes at loot markers and along walking
## routes, for keeping props out of the way.
func _poi_keep_out(placed: PoiSet) -> SimGround:
var keep_out: SimGround = SimGround.flat()
for poi: Poi in placed.pois:
for solid: AABB in poi.solids:
keep_out.add_solid(solid)
for at: Vector3 in poi.loot:
keep_out.add_solid(AABB(at - Vector3(0.5, 0.0, 0.5), Vector3(1.0, 2.0, 1.0)))
for route: Array in poi.routes:
for index: int in range(1, route.size()):
var a: Vector3 = route[index - 1]
var b: Vector3 = route[index]
var steps: int = maxi(ceili(a.distance_to(b) / 1.0), 1)
for step: int in steps + 1:
var at: Vector3 = a.lerp(b, float(step) / steps)
keep_out.add_solid(AABB(at - Vector3(0.5, 0.0, 0.5), Vector3(1.0, 2.0, 1.0)))
return keep_out
## True if `box`, grown sideways by `margin`, overlaps any solid in `ground`. Height is
## ignored: a prop under a pier deck still blocks the way to it.
func _overlaps(ground: SimGround, box: AABB, margin: float) -> bool:
var low: Vector2 = Vector2(box.position.x - margin, box.position.z - margin)
var high: Vector2 = Vector2(box.end.x + margin, box.end.z + margin)
for id: int in ground.solids_near(low.x, low.y, high.x, high.y):
var other: AABB = ground.solids[id]
if other.position.x < high.x and other.end.x > low.x and other.position.z < high.y and other.end.z > low.y:
return true
return false
static func _distance_to_box(box: AABB, point: Vector3) -> float:
var closest: Vector3 = point.clamp(box.position, box.end)
return closest.distance_to(point)