B6: Weapon framework and damage model

Weapons fire from the server's own copy of the shooter's eye and look, at the
weapon's fire rate, from the loaded magazine. An empty trigger pull or the
reload button starts a reload of the weapon's reload time from carried
ammunition; switching slots cancels it. Each shot is one or more pellets
scattered evenly inside a spread cone from the "weapons" stream. Spread is the
hip spread (smaller when aiming), plus bloom that builds in sustained fire,
plus a moving or airborne penalty.

Hitscan pellets trace at once in 16 m segments; projectile weapons (the
whaler's longgun and line thrower) spawn entities that fly under gravity and
trace each tick. A trace stops at the first of terrain, a solid (built pieces
and props take the damage) or another player's body. Players lose armor first,
then health; the top of the body takes the weapon's headshot multiplier; and
damage falls off linearly from range_full to range_max. Stats come from
ItemDef, so adding a weapon is a Tuning entry only.

Closes #20

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 17:19:51 -05:00
co-authored by Claude Opus 5.5
parent e58d6140cc
commit ed46b6e19f
5 changed files with 598 additions and 0 deletions
+275
View File
@@ -0,0 +1,275 @@
## Firing, reloading and damage for slot weapons. Stats come from ItemDef, built from
## Tuning.WEAPONS, so a new weapon is a table entry and needs no code.
##
## The client only presses fire, aim and reload. The server fires from its own copy of
## the player's eye and look, at the weapon's fire rate, from the loaded magazine.
##
## A shot is one or more pellets, each turned by a random angle inside the spread cone
## from the "weapons" stream. Spread is the weapon's hip spread (times its aim factor
## when aiming), plus bloom from recent shots, plus a penalty for moving or being in the
## air. Hitscan pellets trace at once to the weapon's range; projectile pellets become
## entities that fly under gravity and trace each tick's path.
##
## A trace stops at the first of terrain, a solid (a built piece, a prop or a point of
## interest) or another player's body. Players lose armor first, then health; the top
## Tuning.HEAD_HEIGHT of the body takes the weapon's headshot multiplier. Damage falls
## off linearly with distance, see ItemDef.damage_at().
class_name Weapons
extends RefCounted
## What a trace hit.
const HIT_NONE: int = 0
const HIT_TERRAIN: int = 1
const HIT_SOLID: int = 2
const HIT_PIECE: int = 3
const HIT_PROP: int = 4
const HIT_PLAYER: int = 5
## Traces are checked in pieces this long, so long shots stop early and don't query a
## huge area of solids at once.
const TRACE_SEGMENT_METRES: float = 16.0
## The result of a trace.
class Hit:
extends RefCounted
var kind: int = HIT_NONE
## Fraction of the traced segment, 1.0 when nothing was hit.
var fraction: float = 1.0
var point: Vector3 = Vector3.ZERO
## Piece ID, prop index or player entity ID.
var target: int = -1
var headshot: bool = false
## Counts down reloads and bloom. Called every tick for a player on foot, after the
## action cooldown. Bloom only recovers on ticks the weapon is ready to fire, so
## sustained fire builds it up and a pause clears it.
static func update(player: SimEntity) -> void:
if player.action_cooldown == 0:
player.bloom = maxf(player.bloom - Tuning.BLOOM_DECAY_DEGREES_PER_SECOND / Tuning.TICK_RATE_HZ, 0.0)
if player.reload_ticks > 0:
player.reload_ticks -= 1
if player.reload_ticks == 0:
_finish_reload(player)
## Starts reloading the held weapon if it has room and there's ammunition. Returns true
## if a reload started.
static func start_reload(player: SimEntity) -> bool:
var def: ItemDef = Inventory.held_def(player)
if def == null or not def.uses_magazine() or player.reload_ticks > 0:
return false
var slot: int = Inventory.held_slot(player)
if player.slot_rounds[slot] >= def.magazine:
return false
if player.ammo[Inventory.ammo_index(def.ammo_code)] <= 0:
return false
player.reload_ticks = maxi(def.reload_ticks(), 1)
return true
static func _finish_reload(player: SimEntity) -> void:
var def: ItemDef = Inventory.held_def(player)
if def == null or not def.uses_magazine():
return
var slot: int = Inventory.held_slot(player)
var index: int = Inventory.ammo_index(def.ammo_code)
var loaded: int = mini(def.magazine - player.slot_rounds[slot], player.ammo[index])
player.slot_rounds[slot] += loaded
player.ammo[index] -= loaded
## Fires the held weapon if it's ready. Returns true if a shot was fired. An empty
## magazine starts a reload instead. Thrown weapons are handled by explosives (B8).
static func fire(sim: Simulation, player: SimEntity, aiming: bool) -> bool:
var def: ItemDef = Inventory.held_def(player)
if def == null or not def.is_weapon() or def.thrown:
return false
if player.action_cooldown > 0 or player.reload_ticks > 0:
return false
var slot: int = Inventory.held_slot(player)
if def.uses_magazine():
if player.slot_rounds[slot] <= 0:
start_reload(player)
return false
player.slot_rounds[slot] -= 1
player.action_cooldown = def.fire_interval_ticks()
var cone: float = spread_degrees(player, def, aiming)
player.bloom = minf(player.bloom + def.bloom_degrees, Tuning.MAX_BLOOM_DEGREES)
var from: Vector3 = Harvest.eye(player)
var look: Vector3 = Harvest.look_direction(player)
var stream: RandomNumberGenerator = sim.rng.stream("weapons")
sim.events.append({"type": "shot", "player": player.id, "item": def.code, "from": from, "direction": look})
for _pellet: int in def.pellets:
var direction: Vector3 = scatter(look, cone, stream)
if def.projectile_speed > 0.0:
_launch(sim, player, def, slot, from, direction)
else:
var to: Vector3 = from + direction * def.range_max
var hit: Hit = trace(sim, from, to, player.id)
_apply_hit(sim, player.id, def, player.slot_tiers[slot], hit, from.distance_to(hit.point))
return true
## The cone half-angle a shot would have now, in degrees.
static func spread_degrees(player: SimEntity, def: ItemDef, aiming: bool) -> float:
var cone: float = def.spread_degrees * (def.aim_spread_factor if aiming else 1.0)
cone += player.bloom
if not player.on_ground or player.swimming:
cone += Tuning.AIRBORNE_SPREAD_DEGREES
elif Vector2(player.velocity.x, player.velocity.z).length() > 0.5:
cone += Tuning.MOVING_SPREAD_DEGREES
return cone
## A direction within `cone_degrees` of `look`, spread evenly over the cone's area.
static func scatter(look: Vector3, cone_degrees: float, stream: RandomNumberGenerator) -> Vector3:
var u: float = stream.randf()
var v: float = stream.randf()
if cone_degrees <= 0.0:
return look
var angle: float = deg_to_rad(cone_degrees) * sqrt(u)
var around: float = TAU * v
var side: Vector3 = look.cross(Vector3.UP)
if side.length_squared() < 0.000001:
side = Vector3.RIGHT
side = side.normalized()
var up: Vector3 = side.cross(look).normalized()
var offset: Vector3 = (side * cos(around) + up * sin(around)) * sin(angle)
return (look * cos(angle) + offset).normalized()
## The first thing between `from` and `to`, skipping the player `ignore_id`.
static func trace(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int = 0) -> Hit:
var length: float = from.distance_to(to)
var pieces: int = maxi(ceili(length / TRACE_SEGMENT_METRES), 1)
for index: int in pieces:
var start: float = float(index) / pieces
var end: float = float(index + 1) / pieces
var hit: Hit = _trace_segment(sim, from.lerp(to, start), from.lerp(to, end), ignore_id)
if hit.kind != HIT_NONE:
hit.fraction = lerpf(start, end, hit.fraction)
return hit
var miss: Hit = Hit.new()
miss.point = to
return miss
static func _trace_segment(sim: Simulation, from: Vector3, to: Vector3, ignore_id: int) -> Hit:
var hit: Hit = Hit.new()
var ground: SimGround = sim.ground
# The nearest solid, and what it belongs to.
for solid_id: int in ground.solids_near(minf(from.x, to.x), minf(from.z, to.z), maxf(from.x, to.x), maxf(from.z, to.z)):
var t: float = ground.ray_box(from, to, ground.solids[solid_id])
if t < hit.fraction or (t == hit.fraction and hit.kind != HIT_NONE and solid_id < hit.target):
hit.fraction = t
hit.kind = HIT_SOLID
hit.target = solid_id
if hit.kind == HIT_SOLID:
var piece: int = sim.structures.piece_of_solid(hit.target)
var prop: int = sim.props.prop_of_solid(hit.target)
if piece != 0:
hit.kind = HIT_PIECE
hit.target = piece
elif prop >= 0:
hit.kind = HIT_PROP
hit.target = prop
# Terrain in front of the solid.
var terrain: float = ground.raycast(from, to)
if terrain < hit.fraction - 0.0001:
hit.fraction = terrain
hit.kind = HIT_TERRAIN
hit.target = -1
# Players in front of both.
for entity: SimEntity in sim.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER or entity.id == ignore_id or entity.eliminated:
continue
if entity.drop_state == Drop.ABOARD:
continue
var box: AABB = body_box(entity)
var t: float = ground.ray_box(from, to, box)
if t < hit.fraction:
hit.fraction = t
hit.kind = HIT_PLAYER
hit.target = entity.id
var point: Vector3 = from.lerp(to, t)
hit.headshot = point.y >= box.end.y - Tuning.HEAD_HEIGHT
hit.point = from.lerp(to, hit.fraction)
return hit
## The box a player's body occupies.
static func body_box(player: SimEntity) -> AABB:
var radius: float = Tuning.PLAYER_RADIUS
return AABB(player.position - Vector3(radius, 0.0, radius), Vector3(radius * 2.0, Movement.body_height(player), radius * 2.0))
## Applies a pellet's hit. `distance` is from where the shot started.
static func _apply_hit(sim: Simulation, attacker: int, def: ItemDef, tier: int, hit: Hit, distance: float) -> void:
sim.events.append({"type": "impact", "player": attacker, "item": def.code, "point": hit.point, "hit": hit.kind, "target": hit.target})
if def.damage <= 0:
return
var amount: float = def.damage_at(distance) * tier_multiplier(tier)
match hit.kind:
HIT_PLAYER:
if hit.headshot:
amount *= def.headshot_multiplier
damage_player(sim, sim.entities.find(hit.target), roundi(amount), attacker, hit.headshot)
HIT_PIECE:
sim.damage_piece(hit.target, roundi(amount * Tuning.WEAPON_STRUCTURE_FACTOR), "weapon")
HIT_PROP:
if sim.damage_prop(hit.target, roundi(amount * Tuning.WEAPON_STRUCTURE_FACTOR)):
sim.events.append({"type": "prop_destroyed", "prop": hit.target})
## Damage multiplier for a quality tier. Tiers arrive with the weapon roster (B7).
static func tier_multiplier(_tier: int) -> float:
return 1.0
## Takes `amount` from armor, then health. Returns the damage actually done.
static func damage_player(sim: Simulation, victim: SimEntity, amount: int, attacker: int, headshot: bool = false) -> int:
if victim == null or victim.eliminated or amount <= 0:
return 0
var to_armor: int = mini(victim.armor, amount)
victim.armor -= to_armor
var to_health: int = mini(victim.health, amount - to_armor)
victim.health -= to_health
if attacker != 0 and attacker != victim.id:
victim.last_attacker = attacker
sim.events.append({
"type": "player_hit", "player": attacker, "victim": victim.id,
"armor": to_armor, "health": to_health, "headshot": headshot,
})
return to_armor + to_health
static func _launch(sim: Simulation, player: SimEntity, def: ItemDef, slot: int, from: Vector3, direction: Vector3) -> void:
var shot: SimEntity = sim.entities.create(SimEntity.ARCHETYPE_PROJECTILE)
shot.position = from
shot.origin = from
shot.velocity = direction * def.projectile_speed
shot.owner_id = player.id
shot.item = def.code
shot.item_tier = player.slot_tiers[slot]
sim.projectiles.append(shot.id)
## Moves every projectile one tick and resolves what they hit.
static func advance_projectiles(sim: Simulation) -> void:
var dt: float = Simulation.SECONDS_PER_TICK
for shot_id: int in sim.projectiles.duplicate():
var shot: SimEntity = sim.entities.find(shot_id)
var def: ItemDef = ItemCatalog.get_def(shot.item)
shot.velocity.y -= def.projectile_gravity * dt
var to: Vector3 = shot.position + shot.velocity * dt
var hit: Hit = trace(sim, shot.position, to, shot.owner_id)
var travelled: float = shot.origin.distance_to(hit.point)
var out_of_world: bool = to.y < Tuning.BUILD_MIN_LEVEL * Tuning.BUILD_LEVEL_METRES - 10.0
if hit.kind != HIT_NONE:
_apply_hit(sim, shot.owner_id, def, shot.item_tier, hit, travelled)
if hit.kind != HIT_NONE or travelled >= def.range_max or out_of_world:
sim.entities.remove(shot_id)
sim.projectiles.erase(shot_id)
else:
shot.position = to