B1: Harvesting and materials

Boathook swings harvest props. The client only presses fire with the
boathook selected; the server casts the swing from its own copy of the
player's eye and look, so range and swing rate are enforced by
construction. Each hit damages the prop and gives its material
(driftwood, stone or salvage iron), capped per material.

- Materials: material codes and add/spend helpers; carried stock lives
  on SimEntity.materials and is part of the state hash.
- Harvest: swing interval from the boathook's fire rate, reach from its
  range plus slack, nearest prop along the ray, blocked by terrain or
  other solids. Emits harvest and prop_destroyed events.
- Simulation: per-tick events list, a shared action cooldown, and fire
  with selection 0 outside build mode swings.
- Tuning: HARVEST_DAMAGE, HARVEST_REACH_SLACK, HARVEST_AIM_SLACK.
- 12 tests: yields per kind, rate limit, reach, blocking, nearest prop,
  caps, destruction clearing collision, state gating and determinism on
  a real island.

Closes #15

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 14:11:15 -05:00
co-authored by Claude Opus 5.5
parent 21559a637d
commit b847ba9695
12 changed files with 376 additions and 1 deletions
+8 -1
View File
@@ -152,7 +152,14 @@ Pieces snap to a grid of `GRID_CELL_METRES` cells.
`BUILD_PIECES` holds what each piece costs. `MATERIALS` holds each material's `health`
and `build_seconds`, and materials trade speed for strength. A piece goes up quickly but
reaches full health only after its `build_seconds` have passed. Pieces with no connection
to the ground collapse. Each boathook hit harvests `HARVEST_PER_HIT` material.
to the ground collapse.
**Harvesting.** Holding fire with the boathook swings once every `1 / fire_rate` seconds.
A swing reaches the boathook's `range_max` plus `HARVEST_REACH_SLACK` from the eye, and
hits the nearest standing prop it passes within `HARVEST_AIM_SLACK` of, unless terrain or
a solid is in the way. Each hit does `HARVEST_DAMAGE` to the prop and gives
`HARVEST_PER_HIT` of the prop's material, up to `MATERIAL_CAP`. A player at the cap still
damages props. The server works all of this out itself; a client only says "fire".
**Breakwaters.** Each holds up to `BREAKWATER_MAX_HEAD` metres of water above its base.
Every second under pressure it loses `BREAKWATER_WEAR_PER_METRE` health per metre of
+81
View File
@@ -0,0 +1,81 @@
## Boathook swings that harvest props. The client only presses fire; the server works
## out what the swing hits from its own copy of the player's position and look, so
## range and rate are validated by construction.
##
## A swing is a ray from the eye along the look direction, reaching the boathook's
## range plus Tuning.HARVEST_REACH_SLACK. It hits the nearest standing prop whose box,
## grown by Tuning.HARVEST_AIM_SLACK, the ray enters, unless terrain or another solid is
## in the way first. Each hit does Tuning.HARVEST_DAMAGE to the prop and gives the
## player Tuning.HARVEST_PER_HIT of the prop's material, up to Tuning.MATERIAL_CAP.
class_name Harvest
extends RefCounted
## The eye sits this far below the top of the body.
const EYE_BELOW_TOP: float = 0.2
## Ticks between swings, from the boathook's fire rate.
static func swing_interval_ticks() -> int:
return ceili(Tuning.TICK_RATE_HZ / float(Tuning.WEAPONS["boathook"]["fire_rate"]))
static func reach() -> float:
return float(Tuning.WEAPONS["boathook"]["range_max"]) + Tuning.HARVEST_REACH_SLACK
static func eye(player: SimEntity) -> Vector3:
return player.position + Vector3(0.0, Movement.body_height(player) - EYE_BELOW_TOP, 0.0)
## The look direction for an entity's yaw and pitch: +z at yaw 0, positive pitch up.
static func look_direction(player: SimEntity) -> Vector3:
var yaw: float = float(player.yaw) / PlayerCommand.YAW_STEPS * TAU
var pitch: float = float(player.pitch) / PlayerCommand.PITCH_MAX * (PI * 0.5)
return Vector3(sin(yaw) * cos(pitch), sin(pitch), cos(yaw) * cos(pitch))
## True if the player is in a state that allows swinging: on foot, alive, not swimming.
static func can_swing(player: SimEntity) -> bool:
return player.health > 0 and player.drop_state == Drop.NONE and not player.swimming
## The prop a swing from the player's current pose would hit, or -1.
static func target(player: SimEntity, ground: SimGround, props: PropSet) -> int:
var from: Vector3 = eye(player)
var to: Vector3 = from + look_direction(player) * reach()
var slack: float = Tuning.HARVEST_AIM_SLACK
var best: int = -1
var best_t: float = 1.0
for solid_id: int in ground.solids_near(
minf(from.x, to.x) - slack, minf(from.z, to.z) - slack,
maxf(from.x, to.x) + slack, maxf(from.z, to.z) + slack):
var prop: int = props.prop_of_solid(solid_id)
if prop < 0 or not props.is_standing(prop):
continue
var t: float = ground.ray_box(from, to, props.boxes[prop].grow(slack))
if t < best_t or (t == best_t and best >= 0 and prop < best):
best_t = t
best = prop
if best < 0:
return -1
# Anything nearer than the prop's grown box blocks the swing.
if ground.raycast(from, to) < best_t - 0.0001:
return -1
return best
## Swings if the player can and isn't cooling down. Returns the prop hit, or -1.
## Appends "harvest" and "prop_destroyed" events to `events`.
static func swing(player: SimEntity, ground: SimGround, props: PropSet, events: Array[Dictionary]) -> int:
if player.action_cooldown > 0 or not can_swing(player):
return -1
player.action_cooldown = swing_interval_ticks()
var prop: int = target(player, ground, props)
if prop < 0:
return -1
var code: int = Materials.code_of(props.material_of(prop))
var gained: int = Materials.add(player, code, Tuning.HARVEST_PER_HIT)
events.append({"type": "harvest", "player": player.id, "prop": prop, "material": code, "amount": gained})
if props.damage(prop, Tuning.HARVEST_DAMAGE):
events.append({"type": "prop_destroyed", "prop": prop})
return prop
+1
View File
@@ -0,0 +1 @@
uid://b560mwnfowr3y
+37
View File
@@ -0,0 +1,37 @@
## The three building materials and the helpers for a player's carried stock. A player
## carries each up to Tuning.MATERIAL_CAP; stock lives on SimEntity.materials.
class_name Materials
extends RefCounted
const DRIFTWOOD: int = 0
const STONE: int = 1
const SALVAGE_IRON: int = 2
## Material codes index this list. Each name is a key of Tuning.MATERIALS.
const NAMES: Array[String] = ["driftwood", "stone", "salvage_iron"]
## The code for a material name, or -1 if there is no such material.
static func code_of(material_name: String) -> int:
return NAMES.find(material_name)
static func is_valid(code: int) -> bool:
return code >= 0 and code < NAMES.size()
## Adds up to `amount` of a material, stopping at the cap. Returns how much was added.
static func add(player: SimEntity, code: int, amount: int) -> int:
if not is_valid(code) or amount <= 0:
return 0
var added: int = mini(amount, Tuning.MATERIAL_CAP - player.materials[code])
added = maxi(added, 0)
player.materials[code] += added
return added
## Spends `amount` if the player has it. Returns false, spending nothing, if not.
static func spend(player: SimEntity, code: int, amount: int) -> bool:
if not is_valid(code) or amount < 0 or player.materials[code] < amount:
return false
player.materials[code] -= amount
return true
+1
View File
@@ -0,0 +1 @@
uid://isgf8ukj4ob0
+10
View File
@@ -47,6 +47,8 @@ var solid_ids: PackedInt32Array = PackedInt32Array()
var destroyed: PackedInt32Array = PackedInt32Array()
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.
@@ -88,6 +90,13 @@ func add_solids_to(ground: SimGround) -> void:
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
@@ -101,6 +110,7 @@ func damage(prop: int, amount: int) -> bool:
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
+4
View File
@@ -22,6 +22,10 @@ var stamina_ticks: int = 0
var drown_ticks: int = 0
## Where the player is in the drop: Drop.NONE, ABOARD, FREEFALL or GLIDING.
var drop_state: int = 0
## Carried building materials, indexed like Materials.NAMES.
var materials: PackedInt32Array = PackedInt32Array([0, 0, 0])
## Ticks until the player may swing, fire or place again.
var action_cooldown: int = 0
func _init(entity_id: int, entity_archetype: int) -> void:
+6
View File
@@ -203,6 +203,12 @@ func point_inside(point: Vector3, margin: float = 0.0) -> bool:
return false
## Where the segment from `from` to `to` enters `box`, as a fraction of the way, or 1.0
## for a miss. 0 if `from` is inside the box.
func ray_box(from: Vector3, to: Vector3, box: AABB) -> float:
return _ray_box(from, to, box)
func _inside_footprint(box: AABB, x: float, z: float, radius: float) -> bool:
return (
x > box.position.x - radius and x < box.end.x + radius
+17
View File
@@ -7,6 +7,8 @@ extends RefCounted
const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ
const SPAWN_ATTEMPTS: int = 64
## The command selection that holds the boathook, which every player always carries.
const BOATHOOK_SLOT: int = 0
var tick: int = 0
var entities: EntityRegistry = EntityRegistry.new()
@@ -29,6 +31,10 @@ var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"]
## The sky barge, from start_drop() on. Null in matches and tests that start on foot.
var drop: Drop = null
## What happened during the last step(): harvests, destroyed props, placed pieces.
## Each is a Dictionary with a "type". Cleared at the start of every step.
var events: Array[Dictionary] = []
## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {}
## Player entity IDs, ascending.
@@ -102,6 +108,7 @@ func start_drop() -> void:
## Advances the simulation by one tick.
func step() -> void:
events.clear()
for player_id: int in _players:
var queued: Dictionary = _pending[player_id]
var command: PlayerCommand = queued.get(tick)
@@ -136,6 +143,14 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Movement.step(player, command, ground, sea_level)
var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT)
Water.update(player, sea_level, drown_dps, sprinting)
if player.action_cooldown > 0:
player.action_cooldown -= 1
if command == null or not command.is_pressed(PlayerCommand.BUTTON_FIRE):
return
if command.is_pressed(PlayerCommand.BUTTON_BUILD):
return
if command.selection == BOATHOOK_SLOT:
Harvest.swing(player, ground, props, events)
## Moves the sea surface. Takes effect on the next step.
@@ -170,6 +185,8 @@ func state_hash() -> String:
buffer.put_32(entity.stamina_ticks)
buffer.put_32(entity.drown_ticks)
buffer.put_u8(entity.drop_state)
buffer.put_data(entity.materials.to_byte_array())
buffer.put_32(entity.action_cooldown)
for value: float in [entity.position.x, entity.position.y, entity.position.z]:
buffer.put_64(roundi(value * 1000.0))
for value: float in [entity.velocity.x, entity.velocity.y, entity.velocity.z]:
+9
View File
@@ -177,8 +177,17 @@ const TIDE_PHASES: Array[Dictionary] = [
# Building
const GRID_CELL_METRES: float = 4.0
## The most of each material a player can carry.
const MATERIAL_CAP: int = 500
## Material gained per boathook hit on a prop, whatever the prop.
const HARVEST_PER_HIT: int = 15
## Damage a boathook hit does to a prop. Players take the boathook's `damage` instead.
const HARVEST_DAMAGE: int = 50
## A swing reaches this far past the boathook's range, from the eye, so a prop the body
## is touching is always in reach.
const HARVEST_REACH_SLACK: float = 0.4
## Props are hit if the swing passes within this distance of their box.
const HARVEST_AIM_SLACK: float = 0.25
## Material units each piece costs. Health and build time come from MATERIALS.
const BUILD_PIECES: Dictionary = {
"wall": {"cost": 10},
+201
View File
@@ -0,0 +1,201 @@
extends TestCase
## Harvesting from issue B1: server-side range and swing rate, yields, caps, and props
## destroyed by harvesting.
const PINE: int = 0
const BOULDER: int = 2
const WRECK: int = 3
## A flat world with the given props, as [kind code, AABB] pairs, and one player at
## `feet` looking along +z.
func _world(entries: Array, feet: Vector3 = Vector3(100.0, 0.0, 100.0)) -> Simulation:
var ground: SimGround = SimGround.flat()
var sim: Simulation = Simulation.new(7, ground)
var props: PropSet = PropSet.new()
for entry: Array in entries:
var box: AABB = entry[1]
props.kinds.append(entry[0])
props.positions.append(Vector3(box.get_center().x, 0.0, box.get_center().z))
props.yaws.append(0.0)
props.boxes.append(box)
props.health.append(Tuning.PROP_KINDS[PropSet.KINDS[entry[0]]]["health"])
props.add_solids_to(ground)
sim.props = props
var id: int = sim.add_player()
sim.entities.find(id).position = feet
return sim
## A pine trunk whose near face is `gap` metres in front of the player's body (+z).
func _pine_ahead(gap: float) -> Array:
var near_z: float = 100.0 + Tuning.PLAYER_RADIUS + gap
return [PINE, AABB(Vector3(99.7, -0.25, near_z), Vector3(0.6, 9.0, 0.6))]
## Holds fire with the boathook for `ticks` ticks, looking along `pitch` radians.
func _swing_for(sim: Simulation, ticks: int, pitch: float = 0.0, buttons: int = PlayerCommand.BUTTON_FIRE, selection: int = 0) -> int:
var hits: int = 0
for _i: int in ticks:
var command: PlayerCommand = PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, pitch, buttons, selection)
sim.submit_command(1, command)
sim.step()
for event: Dictionary in sim.events:
if event["type"] == "harvest":
hits += 1
return hits
func test_a_hit_yields_the_props_material_and_damages_it() -> void:
var sim: Simulation = _world([_pine_ahead(0.5)])
var player: SimEntity = sim.entities.find(1)
assert_eq(_swing_for(sim, 1), 1, "one swing should land")
assert_eq(player.materials[Materials.DRIFTWOOD], Tuning.HARVEST_PER_HIT)
assert_eq(player.materials[Materials.STONE], 0)
assert_eq(sim.props.health[0], 200 - Tuning.HARVEST_DAMAGE)
assert_eq(sim.events[0]["material"], Materials.DRIFTWOOD)
func test_each_prop_kind_gives_its_own_material() -> void:
for entry: Array in [[BOULDER, Materials.STONE], [WRECK, Materials.SALVAGE_IRON], [PINE, Materials.DRIFTWOOD]]:
var prop: Array = _pine_ahead(0.3)
prop[0] = entry[0]
var sim: Simulation = _world([prop])
_swing_for(sim, 1)
var player: SimEntity = sim.entities.find(1)
assert_eq(player.materials[entry[1]], Tuning.HARVEST_PER_HIT, PropSet.KINDS[entry[0]])
func test_swing_rate_is_enforced_by_the_server() -> void:
var sim: Simulation = _world([_pine_ahead(0.5)])
var interval: int = Harvest.swing_interval_ticks()
assert_eq(interval, ceili(30.0 / 1.5))
# Holding fire for three intervals swings exactly three times, however often the
# client says fire.
assert_eq(_swing_for(sim, interval * 3), 3)
assert_eq(sim.entities.find(1).materials[Materials.DRIFTWOOD], Tuning.HARVEST_PER_HIT * 3)
func test_out_of_range_props_are_not_hit() -> void:
var reach_gap: float = Harvest.reach() - Tuning.PLAYER_RADIUS
var far: Simulation = _world([_pine_ahead(reach_gap + Tuning.HARVEST_AIM_SLACK + 0.3)])
assert_eq(_swing_for(far, 1), 0, "a pine beyond reach must not be hit")
assert_eq(far.entities.find(1).materials[Materials.DRIFTWOOD], 0)
assert_eq(far.props.health[0], 200)
var near: Simulation = _world([_pine_ahead(reach_gap - 0.2)])
assert_eq(_swing_for(near, 1), 1, "a pine just inside reach should be hit")
func test_looking_away_misses() -> void:
var sim: Simulation = _world([_pine_ahead(0.5)])
var hits: int = 0
for _i: int in 1:
sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2.ZERO, PI, 0.0, PlayerCommand.BUTTON_FIRE))
sim.step()
hits += sim.events.size()
assert_eq(hits, 0)
func test_a_solid_in_the_way_blocks_the_swing() -> void:
var sim: Simulation = _world([_pine_ahead(1.2)])
# A wall between the player and the pine.
sim.ground.add_solid(AABB(Vector3(98.0, 0.0, 100.0 + Tuning.PLAYER_RADIUS + 0.4), Vector3(4.0, 3.0, 0.2)))
assert_eq(_swing_for(sim, 1), 0)
assert_eq(sim.props.health[0], 200)
func test_nearest_prop_takes_the_hit() -> void:
var near: Array = _pine_ahead(0.3)
var far: Array = [BOULDER, AABB(Vector3(99.0, -0.25, 101.5), Vector3(2.0, 2.0, 1.0))]
var sim: Simulation = _world([far, near])
_swing_for(sim, 1)
assert_eq(sim.props.health[1], 200 - Tuning.HARVEST_DAMAGE)
assert_eq(sim.props.health[0], 400)
func test_carry_cap_stops_gains_but_not_damage() -> void:
var sim: Simulation = _world([[BOULDER, AABB(Vector3(99.0, -0.25, 100.6), Vector3(2.0, 2.0, 2.0))]])
var player: SimEntity = sim.entities.find(1)
player.materials[Materials.STONE] = Tuning.MATERIAL_CAP - 5
_swing_for(sim, 1)
assert_eq(player.materials[Materials.STONE], Tuning.MATERIAL_CAP)
assert_eq(sim.events[0]["amount"], 5, "the event reports what was actually gained")
_swing_for(sim, Harvest.swing_interval_ticks())
assert_eq(player.materials[Materials.STONE], Tuning.MATERIAL_CAP, "never over the cap")
assert_eq(sim.props.health[0], 400 - Tuning.HARVEST_DAMAGE * 2, "capped players still damage props")
func test_materials_add_and_spend() -> void:
var player: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER)
assert_eq(Materials.add(player, Materials.STONE, 30), 30)
assert_eq(Materials.add(player, Materials.STONE, Tuning.MATERIAL_CAP), Tuning.MATERIAL_CAP - 30)
assert_eq(Materials.add(player, 9, 10), 0, "unknown material")
assert_false(Materials.spend(player, Materials.DRIFTWOOD, 1))
assert_true(Materials.spend(player, Materials.STONE, 100))
assert_eq(player.materials[Materials.STONE], Tuning.MATERIAL_CAP - 100)
assert_false(Materials.spend(player, Materials.STONE, -5), "negative spends are refused")
for name: String in Materials.NAMES:
assert_true(Tuning.MATERIALS.has(name), name + " must be in Tuning.MATERIALS")
func test_harvesting_destroys_a_prop_and_clears_its_collision() -> void:
var sim: Simulation = _world([_pine_ahead(0.5)])
var hits_needed: int = ceili(200.0 / Tuning.HARVEST_DAMAGE)
var destroyed: int = 0
for _i: int in hits_needed * Harvest.swing_interval_ticks():
sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0, PlayerCommand.BUTTON_FIRE))
sim.step()
for event: Dictionary in sim.events:
if event["type"] == "prop_destroyed":
destroyed += 1
assert_eq(destroyed, 1)
assert_false(sim.props.is_standing(0))
assert_eq(sim.entities.find(1).materials[Materials.DRIFTWOOD], Tuning.HARVEST_PER_HIT * hits_needed)
assert_eq(sim.props.prop_of_solid(0), -1)
# The player can now walk through where the trunk stood.
for _i: int in 30:
sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), 0.0, 0.0))
sim.step()
assert_true(sim.entities.find(1).position.z > 102.0, "the felled pine should no longer block")
# Further swings at the empty spot do nothing.
assert_eq(_swing_for(sim, Harvest.swing_interval_ticks()), 0)
func test_no_harvesting_in_build_mode_with_another_slot_or_while_swimming() -> void:
var sim: Simulation = _world([_pine_ahead(0.5)])
assert_eq(_swing_for(sim, 1, 0.0, PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD), 0, "build mode")
assert_eq(_swing_for(sim, 1, 0.0, PlayerCommand.BUTTON_FIRE, 2), 0, "another slot")
sim.entities.find(1).swimming = true
assert_false(Harvest.can_swing(sim.entities.find(1)))
sim.entities.find(1).swimming = false
sim.entities.find(1).drop_state = Drop.GLIDING
assert_false(Harvest.can_swing(sim.entities.find(1)))
func test_harvesting_on_a_real_island_is_deterministic() -> void:
var hashes: Array[String] = []
for _run: int in 2:
var sim: Simulation = Simulation.new(11)
var id: int = sim.add_player()
var player: SimEntity = sim.entities.find(id)
# Stand just west of the first pine and face it.
var tree: int = -1
for prop: int in sim.props.count():
if sim.props.kind_name(prop) == "pine":
var box: AABB = sim.props.boxes[prop]
var feet: Vector3 = Vector3(box.position.x - 0.8, 0.0, box.get_center().z)
feet.y = sim.ground.terrain_height(feet.x, feet.z)
if not sim.ground.body_blocked(feet, Tuning.PLAYER_RADIUS, Tuning.PLAYER_HEIGHT, Tuning.STEP_HEIGHT):
player.position = feet
tree = prop
break
assert_true(tree >= 0)
var gained: int = 0
for _i: int in Harvest.swing_interval_ticks() * 2:
sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2.ZERO, PI * 0.5, 0.0, PlayerCommand.BUTTON_FIRE))
sim.step()
gained = player.materials[Materials.DRIFTWOOD]
assert_eq(gained, Tuning.HARVEST_PER_HIT * 2, "two swings at a real pine")
hashes.append(sim.state_hash())
assert_eq(hashes[0], hashes[1])
+1
View File
@@ -0,0 +1 @@
uid://b1a8hli2erupa