A7: Visual effects, hit marker and hurt flash

EffectsView (src/client/effects/) draws muzzle flashes at the held
weapon's muzzle, tracer ribbons to each pellet's impact (and streaks
behind projectiles in flight), hit bursts on players, chips and dust by
material or ground, keg blasts with fireball, debris, smoke and a light,
build dust, collapse clouds for broken pieces, splashes and surge spray.

Particles are simulated on the CPU in packed arrays and drawn by two
MultiMeshes (blended and added) through a small billboard shader that
reads each particle's size from custom data (the stock billboard modes
drop the instance scale) and converts Palette's sRGB colours. Pools are
allocated once at the preset's budget (256/512/1024 particles, 64
tracers, 4 lights): three draw calls whatever happens.

The HUD gains a reticle, four ticks round it when your shot strikes a
player (HitFeedback), and a rust flash at the screen's edge when hurt.

Tests: test_effects_view (12), including a 24-shooter stress scene that
stays inside each budget and never adds nodes. Captures: make
effects-captures (fight, blast, work, stress), checked by eye, and the
blast in the Compatibility renderer.

Closes #47

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 11:45:19 -05:00
co-authored by Claude Opus 5.5
parent 8af068c625
commit e8414fde9a
22 changed files with 1506 additions and 12 deletions
+1
View File
@@ -65,6 +65,7 @@ continuity.
| `make figure-captures` | Renders the player figure in every movement state, every action, and close up holding a carbine (`captures/figure_*.png`, about 1.5 min). Needs Docker. Look at them. | | `make figure-captures` | Renders the player figure in every movement state, every action, and close up holding a carbine (`captures/figure_*.png`, about 1.5 min). Needs Docker. Look at them. |
| `make sea-captures` | Renders the sea after every tide phase from out at sea, a calm beach, the last land in the gale and the view under water (`captures/sea_*.png`), and three of them in the Compatibility renderer (`*_compat.png`), about 6 min. Needs Docker. Look at them. | | `make sea-captures` | Renders the sea after every tide phase from out at sea, a calm beach, the last land in the gale and the view under water (`captures/sea_*.png`), and three of them in the Compatibility renderer (`*_compat.png`), about 6 min. Needs Docker. Look at them. |
| `make item-captures` | Renders items held in a row, over the shoulder, lying on the ground and the four tiers (`captures/items_*.png`, about 3 min). Needs Docker. Look at them. | | `make item-captures` | Renders items held in a row, over the shoulder, lying on the ground and the four tiers (`captures/items_*.png`, about 3 min). Needs Docker. Look at them. |
| `make effects-captures` | Renders the visual effects (A7): a shot striking a player over the shoulder with the HUD's hit marker, a keg blast beside a collapsing wall, build dust, chips and a splash, and 24 players firing with kegs going off at the largest particle budget (`captures/effects_*.png`, about 6 min). Needs Docker. Look at them. |
| `make audio` | Regenerates every sound and the score's layers in `assets/audio/` from `tools/audio/` (about 6 s), with `manifest.json`. Commit the WAVs it changes. | | `make audio` | Regenerates every sound and the score's layers in `assets/audio/` from `tools/audio/` (about 6 s), with `manifest.json`. Commit the WAVs it changes. |
| `make audio-check` | Checks each file in `assets/audio/` matches its manifest hash and its loudness target, and the mix order (tide loudest). Also run by `test_audio_assets`, which regenerates everything and compares. | | `make audio-check` | Checks each file in `assets/audio/` matches its manifest hash and its loudness target, and the mix order (tide loudest). Also run by `test_audio_assets`, which regenerates everything and compares. |
| `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. | | `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. |
+6 -1
View File
@@ -1,7 +1,7 @@
# Tidewall build entry points. Everything runs headless with the repo-local engine. # Tidewall build entry points. Everything runs headless with the repo-local engine.
GODOT := tools/godot.sh GODOT := tools/godot.sh
.PHONY: app-icon deb deb-check bench dist dist-check build-captures poi-captures art figure figure-captures sea-captures models item-captures audio audio-check check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine balance bot-matches match match-captures client-check client-captures hud-captures style-captures menu-captures chart-captures discovery-check fuzz stability soak soak-selfcheck server-package-check .PHONY: effects-captures app-icon deb deb-check bench dist dist-check build-captures poi-captures art figure figure-captures sea-captures models item-captures audio audio-check check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine balance bot-matches match match-captures client-check client-captures hud-captures style-captures menu-captures chart-captures discovery-check fuzz stability soak soak-selfcheck server-package-check
## A8: regenerates every sound in assets/audio/ from tools/audio/ (about 6 s). ## A8: regenerates every sound in assets/audio/ from tools/audio/ (about 6 s).
audio: import audio: import
@@ -41,6 +41,11 @@ sea-captures: import
item-captures: import item-captures: import
@for stage in held shoulder ground tiers; do tools/capture.sh items_$$stage captures/items_$$stage.png; done @for stage in held shoulder ground tiers; do tools/capture.sh items_$$stage captures/items_$$stage.png; done
## A7: renders the visual effects: a hit over the shoulder, a keg blast and collapse, the
## quieter effects, and the stress scene at the largest budget (about 6 min).
effects-captures: import
@for stage in fight blast work stress; do tools/capture.sh effects_$$stage captures/effects_$$stage.png; done
## H1: server tick times and client draw calls, triangles and memory against the budgets ## H1: server tick times and client draw calls, triangles and memory against the budgets
## in docs/ARCHITECTURE.md (about 3 minutes; the client half needs Docker). ## in docs/ARCHITECTURE.md (about 3 minutes; the client half needs Docker).
bench: import bench: import
+6
View File
@@ -484,6 +484,12 @@ weights from the island's elevation bands, with rock on steep ground.
sea, points of interest, props, built pieces and `EntityView`, which draws players, the sea, points of interest, props, built pieces and `EntityView`, which draws players, the
barge, items and chests. All of it reads one `Simulation` and never writes to it, and a barge, items and chests. All of it reads one `Simulation` and never writes to it, and a
new match gets a new view. The camera sits on a player's shoulder through `CameraRig`. new match gets a new view. The camera sits on a player's shoulder through `CameraRig`.
`EffectsView` (`src/client/effects/`, A7) draws the match's visual effects from the
server's FX records and from changes it sees in the world (pieces gone, players in the
water, surges). Its particles are simulated on the CPU in packed arrays and drawn by
two MultiMeshes (blended and added) of camera-facing quads, sized per instance by a
small shader, with tracers as a third; everything is allocated once at the preset's
budget, so a big fight costs a fixed three draw calls and never adds nodes or grows buffers.
The figures, barge and items are stand-in shapes for the art pass to replace. The figures, barge and items are stand-in shapes for the art pass to replace.
In play, the simulation it reads is the client's own copy of the world: the In play, the simulation it reads is the client's own copy of the world: the
+8 -5
View File
@@ -132,11 +132,14 @@ you set it). Delete that file to go back to the defaults.
Settings → Graphics → Quality. Settings → Graphics → Quality.
| Preset | Sun shadows | Shadow cascades | 3D resolution | Anti-aliasing | | Preset | Sun shadows | Shadow cascades | 3D resolution | Anti-aliasing | Effect particles |
|---|---|---|---|---| |---|---|---|---|---|---|
| Low | Off | n/a | 75% of the window | FXAA | | Low | Off | n/a | 75% of the window | FXAA | 256 at once |
| Medium | Up to 200 m | 2 | 100% | FXAA | | Medium | Up to 200 m | 2 | 100% | FXAA | 512 |
| High (default) | Up to 400 m | 4 | 100% | MSAA 2x | | High (default) | Up to 400 m | 4 | 100% | MSAA 2x | 1,024 |
The particle budget only limits how much smoke, dust and spray a big fight shows at
once. Muzzle flashes, tracers, hit flashes and the hit marker are there on every preset.
No preset changes how far trees, rocks, wrecks or built pieces are drawn. A lower No preset changes how far trees, rocks, wrecks or built pieces are drawn. A lower
preset never lets anyone see a player through cover that a higher one would still preset never lets anyone see a player through cover that a higher one would still
+22
View File
@@ -190,6 +190,28 @@ collision box, give or take a few centimetres of lap or trim.
- Layout is Tidewall's own. The tide gauge sits top centre, because the tide is the - Layout is Tidewall's own. The tide gauge sits top centre, because the tide is the
clock. clock.
## Effects (A7)
Effects are painted, not photographic: round soft spots of flat Palette colour and thin
gilt streaks, so they sit with the woodcut print pass rather than fight it.
- **Muzzle flash:** a small `LAMP` core with `OILSKIN` petals along the aim and a wisp
of `STONE` smoke that drifts off the line, so the shooter's own view stays clear.
- **Tracers:** a short `GILT` streak running from the muzzle to where each pellet
landed; projectiles in flight trail `OILSKIN`.
- **Hits on a player:** a `LAMP` flash, a ring of `SALT` puffs and `OILSKIN` sparks.
No blood: folk are knocked about, not wounded on screen. The shooter also gets four
paper ticks round the reticle (a shape, not only a colour).
- **Hits on things:** chips and dust in the material's colour (driftwood, dressed stone,
salvage iron with gilt sparks; bark for trees; the ground's own colour; foam on water).
- **Building and collapse:** a ring of dust where a piece is set down; a piece that
breaks comes apart in a cloud of its material's dust and falling chips.
- **Powder keg:** a `LAMP` flash, an `OCHRE_RED` to `OILSKIN` fireball, `TAR` debris and
a column of weathered smoke, with a light that lights the ground for a moment.
- **Water:** `SEA_FOAM` splashes when someone goes in, and spray along the shore round
the camera when a surge starts.
- **Being hurt:** the screen's edge flushes `WARNING` and fades; the health number falls too.
## Audio palette ## Audio palette
All synthesized by scripts in the repository. All synthesized by scripts in the repository.
+15 -3
View File
@@ -44,6 +44,8 @@ var _viewed: Simulation = null
var _status: Label = null var _status: Label = null
## ClientGame.fx_received when the figures last heard the FX. ## ClientGame.fx_received when the figures last heard the FX.
var _fx_seen: int = 0 var _fx_seen: int = 0
## The hit marker and hurt flash (A7).
var feedback: HitFeedback = HitFeedback.new()
func _init() -> void: func _init() -> void:
@@ -158,13 +160,20 @@ func _process(delta: float) -> void:
if _status != null: if _status != null:
_status.text = status_text() _status.text = status_text()
if hud != null: if hud != null:
hud.show_state(hud_state()) var state: HudState = hud_state()
feedback.update(state.health if state.playing else -1, delta)
state.hit = feedback.hit()
state.hurt = feedback.hurt()
hud.show_state(state)
_show_charts(delta) _show_charts(delta)
## What the HUD should show now. ## What the HUD should show now.
func hud_state() -> HudState: func hud_state() -> HudState:
return HudState.from_client(game, input, own_handle()) var state: HudState = HudState.from_client(game, input, own_handle())
state.hit = feedback.hit()
state.hurt = feedback.hurt()
return state
func _unhandled_input(event: InputEvent) -> void: func _unhandled_input(event: InputEvent) -> void:
@@ -221,7 +230,10 @@ func _show(delta: float) -> void:
var fresh: int = mini(game.fx_received - _fx_seen, game.fx.size()) var fresh: int = mini(game.fx_received - _fx_seen, game.fx.size())
_fx_seen = game.fx_received _fx_seen = game.fx_received
if fresh > 0: if fresh > 0:
view.entities.hear(game.fx.slice(game.fx.size() - fresh)) var records: Array[Dictionary] = game.fx.slice(game.fx.size() - fresh)
view.entities.hear(records)
view.effects.hear(records)
feedback.hear(records, mirror.own_id)
_show_ghost() _show_ghost()
if mirror.own_id != 0: if mirror.own_id != 0:
# The player's own look is newer than any command made from it. # The player's own look is newer than any command made from it.
+798
View File
@@ -0,0 +1,798 @@
## Visual effects (A7): muzzle flashes, tracers, where shots land, chips and dust from
## harvesting, building and collapse, powder-keg blasts, splashes and the tide's surge.
##
## Everything is pooled and drawn in a fixed number of draw calls, whatever is going on:
##
## - Particles live in packed arrays, simulated here on the CPU, and are drawn by two
## MultiMeshes of camera-facing quads: one blended ("soft": dust, smoke, spray,
## chips) and one added ("glow": flashes, sparks, fire). Their instance counts are
## allocated once, at the budget, and only the visible count changes. A burst that
## would go over the budget is cut short; no node or buffer is ever added in play.
## - Tracers are a third MultiMesh of thin boxes: a short streak runs from the muzzle to
## where each pellet landed (or to the weapon's range), and every projectile in
## flight trails one.
## - A few OmniLights, reused oldest first, light up flashes and blasts.
##
## What happens comes from two places. hear() takes the server's FX records (NetFx):
## shots, impacts (keg blasts are impacts of the keg), harvest swings and pieces
## placed. sync() compares the client's world with the last frame for the rest:
## pieces that broke, players who fell into the water or landed hard, projectiles in
## flight and surges starting. Both only read; the view changes nothing in the world.
##
## The randomness here is the client's own, for looks only, and never touches the
## simulation's seeded streams. Colours all come from Palette.
class_name EffectsView
extends Node3D
## The most particles the pool can ever hold, on any preset.
const MAX_PARTICLES: int = 1024
const MAX_TRACERS: int = 64
const MAX_LIGHTS: int = 4
## Floats per particle instance: a 3x4 transform, a colour and custom data (its size).
const STRIDE: int = 20
## Floats per tracer instance: a 3x4 transform (its middle), a colour and custom data
## (the streak from tail to head, and its width).
const TRACER_STRIDE: int = 20
const SOFT: int = 0
const GLOW: int = 1
## Tracer streaks: how fast they run and how long they are, in metres.
const TRACER_SPEED: float = 420.0
const TRACER_LENGTH: float = 7.0
const TRACER_WIDTH: float = 0.045
## Hitscan shots that hit nothing are drawn to this far at most.
const TRACER_MISS_METRES: float = 90.0
## Effects further than this from the camera aren't started at all.
const DRAW_METRES: float = 260.0
## How far the surge's spray is looked for around the camera, and how many places.
const SURGE_METRES: float = 70.0
const SURGE_SPOTS: int = 14
const LANDING_SPEED: float = 9.0
const TELEPORT_METRES: float = 6.0
## How many particles may be alive at once (the preset's budget, at most MAX_PARTICLES).
var budget: int = 512:
set(value):
budget = clampi(value, 0, MAX_PARTICLES)
## When true, _process() steps everything by the frame's time. Captures turn it off
## and call advance() themselves, so a picture shows a chosen moment.
var live: bool = true
## Where the camera is, for skipping what's too far to see and placing the surge.
var eye: Vector3 = Vector3.ZERO
## Where a player's drawn weapon has its muzzle: func(player_id: int) -> Vector3, or
## Vector3.INF when they have no figure to ask. MatchView points it at the figures, so
## the flash is at the gun in their hands rather than at the eye, where the simulation
## starts the shot. The tracer starts there too.
var muzzle_of: Callable = Callable()
## Particles started since the view was made, and those refused for the budget.
var started: int = 0
var dropped: int = 0
## The most particles alive at once since the view was made.
var peak: int = 0
var _count: int = 0
var _pos: PackedVector3Array = PackedVector3Array()
var _vel: PackedVector3Array = PackedVector3Array()
var _colour: PackedColorArray = PackedColorArray()
## life left, whole life, size at birth, size at death, gravity, drag
var _life: PackedFloat32Array = PackedFloat32Array()
var _span: PackedFloat32Array = PackedFloat32Array()
var _size0: PackedFloat32Array = PackedFloat32Array()
var _size1: PackedFloat32Array = PackedFloat32Array()
var _gravity: PackedFloat32Array = PackedFloat32Array()
var _drag: PackedFloat32Array = PackedFloat32Array()
var _layer: PackedByteArray = PackedByteArray()
var _tracer_count: int = 0
var _tracer_from: PackedVector3Array = PackedVector3Array()
var _tracer_to: PackedVector3Array = PackedVector3Array()
var _tracer_run: PackedFloat32Array = PackedFloat32Array()
var _soft: MultiMeshInstance3D
var _glow: MultiMeshInstance3D
var _tracers: MultiMeshInstance3D
var _soft_buffer: PackedFloat32Array = PackedFloat32Array()
var _glow_buffer: PackedFloat32Array = PackedFloat32Array()
var _tracer_buffer: PackedFloat32Array = PackedFloat32Array()
var _lights: Array[OmniLight3D] = []
var _light_life: PackedFloat32Array = PackedFloat32Array()
var _light_span: PackedFloat32Array = PackedFloat32Array()
var _light_energy: PackedFloat32Array = PackedFloat32Array()
var _next_light: int = 0
var _rng: RandomNumberGenerator = RandomNumberGenerator.new()
var _world: Simulation = null
var _pieces: Dictionary = {}
var _players: Dictionary = {}
var _tide_tick: int = -1
func _init() -> void:
name = "Effects"
_rng.seed = 0x7DE
_pos.resize(MAX_PARTICLES)
_vel.resize(MAX_PARTICLES)
_colour.resize(MAX_PARTICLES)
_life.resize(MAX_PARTICLES)
_span.resize(MAX_PARTICLES)
_size0.resize(MAX_PARTICLES)
_size1.resize(MAX_PARTICLES)
_gravity.resize(MAX_PARTICLES)
_drag.resize(MAX_PARTICLES)
_layer.resize(MAX_PARTICLES)
_tracer_from.resize(MAX_TRACERS)
_tracer_to.resize(MAX_TRACERS)
_tracer_run.resize(MAX_TRACERS)
_soft_buffer.resize(MAX_PARTICLES * STRIDE)
_glow_buffer.resize(MAX_PARTICLES * STRIDE)
_tracer_buffer.resize(MAX_TRACERS * 2 * TRACER_STRIDE)
_soft = _field(_quad(false), MAX_PARTICLES, "Soft", true)
_glow = _field(_quad(true), MAX_PARTICLES, "Glow", true)
_tracers = _field(_streak(), MAX_TRACERS * 2, "Tracers", true)
for index: int in MAX_LIGHTS:
var light: OmniLight3D = OmniLight3D.new()
light.shadow_enabled = false
light.light_color = Palette.LAMP
light.visible = false
add_child(light)
_lights.append(light)
_light_life.resize(MAX_LIGHTS)
_light_span.resize(MAX_LIGHTS)
_light_energy.resize(MAX_LIGHTS)
func _process(delta: float) -> void:
if live:
advance(delta)
## How many particles are alive now.
func particle_count() -> int:
return _count
## How many tracer streaks are running now (projectiles in flight not counted).
func tracer_count() -> int:
return _tracer_count
## How many of the pooled lights are lit now.
func light_count() -> int:
var lit: int = 0
for light: OmniLight3D in _lights:
lit += 1 if light.visible else 0
return lit
## The alive particles' positions, for tests.
func particle_positions() -> PackedVector3Array:
return _pos.slice(0, _count)
## Clears everything, for a new world.
func clear() -> void:
_count = 0
_tracer_count = 0
for light: OmniLight3D in _lights:
light.visible = false
_draw()
# --- What happened -----------------------------------------------------------------
## Starts the effects for FX records from the server, as ClientGame keeps them.
func hear(records: Array[Dictionary]) -> void:
for index: int in records.size():
var record: Dictionary = records[index]
var at: Vector3 = record["position"]
if at.distance_to(eye) > DRAW_METRES:
continue
match int(record["kind"]):
NetFx.SHOT:
_shot(record, records, index)
NetFx.IMPACT:
_impact(record)
NetFx.HARVEST:
_harvest(record)
NetFx.PLACE:
_placed(record)
## Compares the world with the last frame and starts what it shows: pieces broken,
## splashes, hard landings and the surge. Draws projectiles in flight. `camera` is
## where the camera is.
func sync(world: Simulation, camera: Vector3) -> void:
eye = camera
if world != _world:
_begin(world)
return
if world == null:
return
_sync_pieces(world)
_sync_players(world)
_sync_surge(world)
_tide_tick = world.tick
func _begin(world: Simulation) -> void:
_world = world
_pieces.clear()
_players.clear()
clear()
if world == null:
return
for piece_id: int in world.structures.pieces:
_pieces[piece_id] = _piece_record(world.structures.pieces[piece_id])
for entity: SimEntity in world.entities.entities():
if entity.archetype == SimEntity.ARCHETYPE_PLAYER:
_players[entity.id] = [entity.position, entity.swimming, entity.on_ground, 0.0]
_tide_tick = world.tick
func _piece_record(piece: StructureSet.Piece) -> Array:
var box: AABB = AABB()
for index: int in piece.boxes.size():
box = piece.boxes[index] if index == 0 else box.merge(piece.boxes[index])
return [piece.material, box]
func _sync_pieces(world: Simulation) -> void:
var pieces: Dictionary = world.structures.pieces
for piece_id: int in pieces:
if not _pieces.has(piece_id):
_pieces[piece_id] = _piece_record(pieces[piece_id])
for piece_id: int in _pieces.keys():
if not pieces.has(piece_id):
var gone: Array = _pieces[piece_id]
_pieces.erase(piece_id)
collapse(int(gone[0]), gone[1])
func _sync_players(world: Simulation) -> void:
var seen: Dictionary = {}
for entity: SimEntity in world.entities.entities():
if entity.archetype != SimEntity.ARCHETYPE_PLAYER:
continue
seen[entity.id] = true
var was: Array = _players.get(entity.id, [])
var fall: float = 0.0
if not was.is_empty() and not entity.eliminated:
var moved: Vector3 = entity.position - Vector3(was[0])
if moved.length() <= TELEPORT_METRES:
fall = float(was[3])
if not entity.on_ground and not entity.swimming:
# Kept per frame in metres; the landing below compares a speed.
fall = maxf(fall, -moved.y)
var near: bool = entity.position.distance_to(eye) <= DRAW_METRES
if entity.swimming and not bool(was[1]) and near:
splash(Vector3(entity.position.x, world.water_level_at(entity.position), entity.position.z), 1.0)
elif entity.on_ground and not bool(was[2]) and not entity.swimming:
if near and fall * 30.0 >= LANDING_SPEED and entity.drop_state == Drop.NONE:
dust_ring(entity.position, 0.9, Palette.STONE)
fall = 0.0
if entity.on_ground or entity.swimming:
fall = 0.0
_players[entity.id] = [entity.position, entity.swimming, entity.on_ground, fall]
for entity_id: int in _players.keys():
if not seen.has(entity_id):
_players.erase(entity_id)
func _sync_surge(world: Simulation) -> void:
if world.tide == null or _tide_tick < 0 or world.tick <= _tide_tick:
return
for t: int in range(maxi(_tide_tick + 1, world.tick - 64), world.tick + 1):
if world.tide.surge_starts(t):
surge(world)
return
# --- Recipes -------------------------------------------------------------------------
func _shot(record: Dictionary, records: Array[Dictionary], index: int) -> void:
var item: int = int(record["item"])
var def: ItemDef = ItemCatalog.get_def(item) if item >= 0 else null
# The boathook's swing and a keg's throw show on the figure, not here.
if def == null or def.kind != ItemDef.WEAPON or Explosives.is_charge(def):
return
var from: Vector3 = record["position"]
var aim: Vector3 = NetFx.aim(record)
var start: Vector3 = from + aim * 0.55
if muzzle_of.is_valid():
var held: Vector3 = muzzle_of.call(int(record["player"]))
if held != Vector3.INF and held.distance_to(from) < 2.0:
start = held
muzzle(start, aim)
if def.projectile_speed > 0.0:
return
# A streak to each pellet's landing: impacts by the same player on the same tick.
var ends: Array[Vector3] = []
for other: int in range(index + 1, records.size()):
var later: Dictionary = records[other]
if int(later["kind"]) == NetFx.IMPACT and int(later["player"]) == int(record["player"]) and int(later["tick"]) == int(record["tick"]):
ends.append(later["position"])
elif int(later["tick"]) != int(record["tick"]):
break
var pellets: int = maxi(def.pellets, 1)
for pellet: int in pellets:
if pellet < ends.size():
tracer(start, ends[pellet])
elif pellet == 0 or pellets <= 2:
tracer(start, from + aim * minf(def.range_max, TRACER_MISS_METRES))
func _impact(record: Dictionary) -> void:
var at: Vector3 = record["position"]
var item: int = int(record["item"])
var def: ItemDef = ItemCatalog.get_def(item) if item >= 0 else null
if def != null and Explosives.is_charge(def):
blast(at)
return
var normal: Vector3 = (eye - at).normalized() if eye.distance_to(at) > 0.01 else Vector3.UP
match int(record.get("hit", Weapons.HIT_NONE)):
Weapons.HIT_PLAYER:
hit_player(at, normal)
Weapons.HIT_PIECE:
var material: int = Materials.DRIFTWOOD
var piece: Variant = _pieces.get(int(record.get("target", 0)))
if piece != null:
material = int((piece as Array)[0])
chips(at, normal, material_colour(material), 7, material != Materials.DRIFTWOOD)
Weapons.HIT_PROP:
chips(at, normal, Palette.BARK, 6, false)
_:
if _world != null and _world.water_level_at(at) >= at.y - 0.15:
splash(at, 0.45)
else:
chips(at, normal, ground_colour(at), 5, false)
func _harvest(record: Dictionary) -> void:
var at: Vector3 = Vector3(record["position"]) + Vector3(0.0, 1.0, 0.0)
var colour: Color = Palette.BARK
var piece_id: int = int(record.get("piece", 0))
if piece_id > 0 and _pieces.has(piece_id):
var piece: Array = _pieces[piece_id]
colour = material_colour(int(piece[0]))
at = (piece[1] as AABB).get_center()
elif _world != null and int(record.get("prop", -1)) >= 0:
var prop: int = int(record["prop"])
if prop < _world.props.count():
var kind: String = _world.props.kind_name(prop)
colour = Palette.STONE if kind.contains("rock") or kind.contains("boulder") else Palette.CRATE_WOOD if kind.contains("crate") else Palette.BARK
chips(at, Vector3.UP, colour, 5, false)
func _placed(record: Dictionary) -> void:
var piece_id: int = int(record.get("piece", 0))
if _world != null and _world.structures.pieces.has(piece_id):
var piece: StructureSet.Piece = _world.structures.pieces[piece_id]
var box: AABB = _piece_record(piece)[1]
dust_ring(Vector3(box.get_center().x, box.position.y, box.get_center().z), maxf(box.size.x, box.size.z) * 0.5, material_colour(piece.material).lerp(Palette.PAPER, 0.35))
else:
dust_ring(record["position"], 1.2, Palette.PLANK_BLEACHED)
## The flash at a muzzle: a hot core, a few sparks along the aim and a little smoke.
func muzzle(at: Vector3, aim: Vector3) -> void:
_spawn(GLOW, at, aim * 2.0, Palette.LAMP, 0.05, 0.22, 0.38, 0.0, 0.0)
for petal: int in 3:
_spawn(SOFT, at + aim * (0.08 + petal * 0.12), aim * 3.0, Palette.OILSKIN.lerp(Palette.LAMP, petal * 0.4), 0.05, 0.26 - petal * 0.06, 0.12, 0.0, 0.0)
for _index: int in 4:
_spawn(GLOW, at, aim * _rng.randf_range(10.0, 18.0) + _jitter(2.5), Palette.GILT, 0.09, 0.09, 0.03, 4.0, 2.0)
for _index: int in 2:
_spawn(SOFT, at + aim * 0.3, aim * 2.0 + Vector3(0.0, 0.6, 0.0) + _jitter(0.3), _alpha(Palette.STONE, 0.22), _rng.randf_range(0.5, 0.8), 0.1, 0.45, -0.3, 2.0)
_light(at, 3.0, 7.0, 0.06)
## A tracer streak from `from` to `to`.
func tracer(from: Vector3, to: Vector3) -> void:
if _tracer_count >= MAX_TRACERS or from.distance_to(to) < 0.5:
return
_tracer_from[_tracer_count] = from
_tracer_to[_tracer_count] = to
_tracer_run[_tracer_count] = 0.0
_tracer_count += 1
## A shot striking a player: a bright burst of sparks, a pale puff and a ring of flash,
## made to be seen across a fight. No blood: Tidewall's folk are knocked about, not
## wounded on screen.
func hit_player(at: Vector3, normal: Vector3) -> void:
_spawn(GLOW, at, Vector3.ZERO, Palette.LAMP, 0.1, 0.5, 1.0, 0.0, 0.0)
for index: int in 6:
var angle: float = TAU * index / 6.0
var side: Vector3 = normal.cross(Vector3.UP).normalized() if absf(normal.y) < 0.95 else Vector3.RIGHT
var out: Vector3 = (side * cos(angle) + Vector3.UP * sin(angle)) * 3.5 + normal
_spawn(SOFT, at, out, _alpha(Palette.SALT, 0.9), 0.28, 0.32, 0.55, 0.0, 6.0)
for _index: int in 10:
_spawn(SOFT, at, normal * 3.0 + _jitter(5.0), Palette.OILSKIN, _rng.randf_range(0.15, 0.3), 0.16, 0.06, 9.0, 1.5)
## Chips and a puff of dust where something was struck. `sparks` adds a few hot sparks,
## for stone and iron.
func chips(at: Vector3, normal: Vector3, colour: Color, count: int, sparks: bool) -> void:
for _index: int in count:
var speed: Vector3 = normal * _rng.randf_range(1.5, 4.0) + _jitter(2.5) + Vector3(0.0, 1.5, 0.0)
_spawn(SOFT, at, speed, colour.darkened(_rng.randf_range(0.0, 0.3)), _rng.randf_range(0.4, 0.8), 0.14, 0.1, 12.0, 0.5)
for _index: int in 2:
_spawn(SOFT, at, normal * 0.6 + _jitter(0.4), _alpha(colour.lerp(Palette.PAPER, 0.3), 0.75), _rng.randf_range(0.6, 1.0), 0.3, 1.1, -0.1, 2.5)
if sparks:
for _index: int in 4:
_spawn(GLOW, at, normal * 2.0 + _jitter(4.0), Palette.GILT, 0.12, 0.07, 0.02, 9.0, 1.0)
## A powder keg going off: flash, fireball, debris and a column of smoke, and a light
## that lights the ground for a moment.
func blast(at: Vector3) -> void:
var radius: float = 6.0
# Smoke first, so the fire drawn after it shows through: within a layer, particles
# are drawn in the order they were started.
for _index: int in 18:
var out: Vector3 = _direction() * _rng.randf_range(1.0, 3.5)
out.y = absf(out.y) + 1.2
_spawn(SOFT, at + _jitter(1.0), out, _alpha(Palette.TAR_WEATHERED.lerp(Palette.STONE, _rng.randf() * 0.5), 0.85), _rng.randf_range(1.8, 2.8), 0.9, 5.0, -0.6, 1.4)
for _index: int in 22:
var out: Vector3 = _direction() * _rng.randf_range(3.0, 9.0)
out.y = absf(out.y) * 0.8 + 1.0
var fire: Color = Palette.OCHRE_RED.lerp(Palette.OILSKIN, _rng.randf())
_spawn(SOFT, at, out, fire, _rng.randf_range(0.35, 0.6), 1.3, 2.2, -1.0, 4.0)
for _index: int in 16:
var out: Vector3 = _direction() * _rng.randf_range(6.0, 14.0)
out.y = absf(out.y) + 3.0
_spawn(SOFT, at, out, Palette.TAR.lerp(Palette.BARK, _rng.randf()), _rng.randf_range(0.8, 1.4), 0.24, 0.18, 14.0, 0.3)
_spawn(GLOW, at, Vector3.ZERO, Palette.LAMP, 0.2, 2.5, radius * 0.9, 0.0, 0.0)
for _index: int in 10:
var out: Vector3 = _direction() * _rng.randf_range(2.0, 6.0)
out.y = absf(out.y) + 0.5
_spawn(GLOW, at, out, Palette.OILSKIN.lerp(Palette.LAMP, _rng.randf()), _rng.randf_range(0.2, 0.35), 1.0, 1.6, -1.0, 4.0)
_light(at + Vector3(0.0, 1.0, 0.0), 9.0, 16.0, 0.35)
## Water thrown up where something went in. `strength` 1 is a person falling in.
func splash(at: Vector3, strength: float) -> void:
var drops: int = roundi(14.0 * strength)
for _index: int in drops:
var out: Vector3 = Vector3(_rng.randf_range(-1.6, 1.6), _rng.randf_range(3.0, 6.0), _rng.randf_range(-1.6, 1.6)) * sqrt(strength)
_spawn(SOFT, at, out, _alpha(Palette.SEA_FOAM, 0.95), _rng.randf_range(0.5, 0.9), 0.22, 0.12, 9.8, 0.4)
for index: int in roundi(6.0 * strength):
var angle: float = TAU * index / (6.0 * strength)
var out: Vector3 = Vector3(cos(angle), 0.0, sin(angle))
_spawn(SOFT, at + out * 0.3, out * 1.4 * strength, _alpha(Palette.SEA_FOAM, 0.8), _rng.randf_range(0.7, 1.0), 0.45, 1.4 * strength, 0.0, 2.0)
## Dust kicked up around `at`, `radius` metres out: a piece set down, a hard landing.
func dust_ring(at: Vector3, radius: float, colour: Color) -> void:
var count: int = clampi(roundi(radius * 6.0), 6, 14)
for index: int in count:
var angle: float = TAU * index / count + _rng.randf() * 0.4
var out: Vector3 = Vector3(cos(angle), 0.0, sin(angle))
_spawn(SOFT, at + out * radius + Vector3(0.0, 0.15, 0.0), out * _rng.randf_range(0.8, 1.6) + Vector3(0.0, 0.4, 0.0), _alpha(colour, 0.8), _rng.randf_range(0.7, 1.1), 0.45, 1.3, -0.1, 2.0)
## A piece breaking up: dust through its whole box and chips falling out of it.
func collapse(material: int, box: AABB) -> void:
if box.get_center().distance_to(eye) > DRAW_METRES:
return
var colour: Color = material_colour(material)
var volume: float = maxf(box.size.x, 0.3) * maxf(box.size.y, 0.3) * maxf(box.size.z, 0.3)
var puffs: int = clampi(roundi(volume * 1.5), 6, 20)
for _index: int in puffs:
var at: Vector3 = box.position + Vector3(_rng.randf() * box.size.x, _rng.randf() * box.size.y, _rng.randf() * box.size.z)
_spawn(SOFT, at, _jitter(0.8) + Vector3(0.0, 0.3, 0.0), _alpha(colour.lerp(Palette.PAPER, 0.1), 0.85), _rng.randf_range(1.2, 1.8), 0.8, 2.4, -0.1, 1.6)
for _index: int in puffs:
var at: Vector3 = box.position + Vector3(_rng.randf() * box.size.x, _rng.randf() * box.size.y, _rng.randf() * box.size.z)
_spawn(SOFT, at, _jitter(2.0) + Vector3(0.0, 1.0, 0.0), colour.darkened(_rng.randf_range(0.0, 0.35)), _rng.randf_range(0.7, 1.2), 0.26, 0.2, 12.0, 0.2)
## The surge: spray thrown up along the shore around the camera.
func surge(world: Simulation) -> void:
var level: float = world.water_level_at(eye)
var found: int = 0
for index: int in 48:
if found >= SURGE_SPOTS:
break
var angle: float = TAU * index / 48.0 + 0.37 * (index % 3)
var reach: float = SURGE_METRES * (0.25 + 0.75 * float((index * 7) % 11) / 10.0)
var x: float = eye.x + cos(angle) * reach
var z: float = eye.z + sin(angle) * reach
var ground: float = world.ground.terrain_height(x, z)
if absf(ground - level) > 0.8:
continue
found += 1
var at: Vector3 = Vector3(x, level, z)
for _drop: int in 7:
var out: Vector3 = Vector3(_rng.randf_range(-1.0, 1.0), _rng.randf_range(4.0, 7.5), _rng.randf_range(-1.0, 1.0))
_spawn(SOFT, at + _jitter(1.5), out, _alpha(Palette.SEA_FOAM, 0.9), _rng.randf_range(0.9, 1.4), 0.5, 1.8, 9.8, 0.6)
## The colour of a building material's chips and dust.
static func material_colour(material: int) -> Color:
match material:
Materials.STONE:
return Palette.DRESSED_STONE
Materials.SALVAGE_IRON:
return Palette.SALVAGE_IRON
return Palette.DRIFTWOOD
## The colour of the ground's dust where a shot landed.
func ground_colour(at: Vector3) -> Color:
if _world == null or _world.island == null:
return Palette.STONE
match _world.island.band_at(at.x, at.z):
Island.Band.SEA, Island.Band.BEACH:
return Palette.CANVAS
Island.Band.HIGHLAND, Island.Band.SUMMIT:
return Palette.STONE
Island.Band.MARSH:
return Palette.OILSKIN_MOSS
return Palette.LICHEN
# --- The pool ----------------------------------------------------------------------
func _spawn(layer: int, at: Vector3, velocity: Vector3, colour: Color, life: float, size_from: float, size_to: float, gravity: float, drag: float) -> void:
if _count >= budget:
dropped += 1
return
var index: int = _count
_count += 1
started += 1
peak = maxi(peak, _count)
_pos[index] = at
_vel[index] = velocity
_colour[index] = colour
_life[index] = life
_span[index] = life
_size0[index] = size_from
_size1[index] = size_to
_gravity[index] = gravity
_drag[index] = drag
_layer[index] = layer
func _light(at: Vector3, energy: float, reach: float, life: float) -> void:
var index: int = _next_light
_next_light = (_next_light + 1) % MAX_LIGHTS
var light: OmniLight3D = _lights[index]
light.position = at
light.omni_range = reach
light.light_energy = energy
light.visible = true
_light_life[index] = life
_light_span[index] = life
_light_energy[index] = energy
## Steps every particle, tracer and light by `delta` seconds and redraws them.
func advance(delta: float) -> void:
var index: int = 0
while index < _count:
var life: float = _life[index] - delta
if life <= 0.0:
_count -= 1
_copy(_count, index)
continue
_life[index] = life
var velocity: Vector3 = _vel[index]
velocity.y -= _gravity[index] * delta
velocity *= maxf(1.0 - _drag[index] * delta, 0.0)
_vel[index] = velocity
_pos[index] += velocity * delta
index += 1
index = 0
while index < _tracer_count:
var run: float = _tracer_run[index] + TRACER_SPEED * delta
if run - TRACER_LENGTH >= _tracer_from[index].distance_to(_tracer_to[index]):
_tracer_count -= 1
_tracer_from[index] = _tracer_from[_tracer_count]
_tracer_to[index] = _tracer_to[_tracer_count]
_tracer_run[index] = _tracer_run[_tracer_count]
continue
_tracer_run[index] = run
index += 1
for light_index: int in MAX_LIGHTS:
var light: OmniLight3D = _lights[light_index]
if not light.visible:
continue
var left: float = _light_life[light_index] - delta
_light_life[light_index] = left
if left <= 0.0:
light.visible = false
else:
light.light_energy = _light_energy[light_index] * left / _light_span[light_index]
_draw()
func _copy(from: int, to: int) -> void:
_pos[to] = _pos[from]
_vel[to] = _vel[from]
_colour[to] = _colour[from]
_life[to] = _life[from]
_span[to] = _span[from]
_size0[to] = _size0[from]
_size1[to] = _size1[from]
_gravity[to] = _gravity[from]
_drag[to] = _drag[from]
_layer[to] = _layer[from]
func _draw() -> void:
var soft: int = 0
var glow: int = 0
for index: int in _count:
var age: float = 1.0 - _life[index] / _span[index]
var size: float = lerpf(_size0[index], _size1[index], age)
var colour: Color = _colour[index]
# In quickly, out slowly.
colour.a *= minf(age * 20.0, 1.0) * (1.0 - age * age) if _layer[index] == SOFT else (1.0 - age)
var at: Vector3 = _pos[index]
if _layer[index] == SOFT:
_put(SOFT, soft * STRIDE, size, at, colour)
soft += 1
else:
_put(GLOW, glow * STRIDE, size, at, colour)
glow += 1
_soft.multimesh.buffer = _soft_buffer
_soft.multimesh.visible_instance_count = soft
_glow.multimesh.buffer = _glow_buffer
_glow.multimesh.visible_instance_count = glow
var streaks: int = 0
for index: int in _tracer_count:
var from: Vector3 = _tracer_from[index]
var to: Vector3 = _tracer_to[index]
var length: float = from.distance_to(to)
var head: float = minf(_tracer_run[index], length)
var tail: float = clampf(_tracer_run[index] - TRACER_LENGTH, 0.0, length)
if head - tail > 0.01:
_put_streak(streaks, from.lerp(to, tail / length), from.lerp(to, head / length), Palette.GILT)
streaks += 1
if _world != null:
for projectile_id: int in _world.projectiles:
if streaks >= MAX_TRACERS * 2:
break
var projectile: SimEntity = _world.entities.find(projectile_id)
if projectile == null or Explosives.is_charge(ItemCatalog.get_def(projectile.item)) or projectile.velocity.length() < 1.0:
continue
var back: Vector3 = projectile.position - projectile.velocity.normalized() * 2.5
_put_streak(streaks, back, projectile.position, Palette.OILSKIN)
streaks += 1
_tracers.multimesh.buffer = _tracer_buffer
_tracers.multimesh.visible_instance_count = streaks
## Writes one particle into its layer's buffer: where it is, its colour, and its size in
## the custom data, which the billboard shader reads (the engine's own billboards drop
## an instance's scale). Members are written in place: packed arrays passed as
## arguments would be copied on write.
func _put(layer: int, slot: int, size: float, at: Vector3, colour: Color) -> void:
var values: Array[float] = [1.0, 0.0, 0.0, at.x, 0.0, 1.0, 0.0, at.y, 0.0, 0.0, 1.0, at.z,
colour.r, colour.g, colour.b, colour.a, size, 0.0, 0.0, 0.0]
if layer == SOFT:
for offset: int in STRIDE:
_soft_buffer[slot + offset] = values[offset]
else:
for offset: int in STRIDE:
_glow_buffer[slot + offset] = values[offset]
## A streak from `tail` to `head`: its middle in the transform, the run from tail to
## head and its width in the custom data, for the ribbon shader.
func _put_streak(index: int, tail: Vector3, head: Vector3, colour: Color) -> void:
var middle: Vector3 = (tail + head) * 0.5
var along: Vector3 = head - tail
var values: Array[float] = [1.0, 0.0, 0.0, middle.x, 0.0, 1.0, 0.0, middle.y, 0.0, 0.0, 1.0, middle.z,
colour.r, colour.g, colour.b, 0.95, along.x, along.y, along.z, TRACER_WIDTH]
var slot: int = index * TRACER_STRIDE
for offset: int in TRACER_STRIDE:
_tracer_buffer[slot + offset] = values[offset]
func _jitter(amount: float) -> Vector3:
return Vector3(_rng.randf_range(-amount, amount), _rng.randf_range(-amount, amount), _rng.randf_range(-amount, amount))
func _direction() -> Vector3:
var out: Vector3 = Vector3(_rng.randfn(), _rng.randfn(), _rng.randfn())
return out.normalized() if out.length() > 0.001 else Vector3.UP
static func _alpha(colour: Color, alpha: float) -> Color:
return Color(colour.r, colour.g, colour.b, alpha)
# --- Drawing -------------------------------------------------------------------------
func _field(mesh: Mesh, capacity: int, label: String, sized: bool) -> MultiMeshInstance3D:
var multimesh: MultiMesh = MultiMesh.new()
multimesh.transform_format = MultiMesh.TRANSFORM_3D
multimesh.use_colors = true
multimesh.use_custom_data = sized
multimesh.mesh = mesh
multimesh.instance_count = capacity
multimesh.visible_instance_count = 0
var field: MultiMeshInstance3D = MultiMeshInstance3D.new()
field.name = label
field.multimesh = multimesh
field.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
# Effects go anywhere on the island; never cull them by a stale box.
field.custom_aabb = AABB(Vector3(-4096.0, -512.0, -4096.0), Vector3(8192.0, 2048.0, 8192.0))
add_child(field)
return field
## A camera-facing quad with a soft round spot painted on it, sized per instance.
static func _quad(additive: bool) -> QuadMesh:
var quad: QuadMesh = QuadMesh.new()
quad.size = Vector2.ONE
var shader: Shader = Shader.new()
shader.code = PARTICLE_SHADER.replace("BLEND", "blend_add" if additive else "blend_mix") \
.replace("EDGE", "0.0" if additive else "0.3")
var material: ShaderMaterial = ShaderMaterial.new()
material.shader = shader
quad.material = material
return quad
## The particles' shader: each instance faces the camera at its own size (custom.x),
## coloured by its instance colour, as a round spot solid out to EDGE of its radius.
const PARTICLE_SHADER: String = """
shader_type spatial;
render_mode unshaded, BLEND, cull_disabled, depth_draw_never, shadows_disabled, skip_vertex_transform;
void vertex() {
vec3 centre = (MODEL_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
float size = INSTANCE_CUSTOM.x;
vec3 world = centre + (INV_VIEW_MATRIX[0].xyz * VERTEX.x + INV_VIEW_MATRIX[1].xyz * VERTEX.y) * size;
VERTEX = (VIEW_MATRIX * vec4(world, 1.0)).xyz;
NORMAL = vec3(0.0, 0.0, 1.0);
}
void fragment() {
float from_middle = length(UV - vec2(0.5)) * 2.0;
// Palette colours are sRGB; the shader works in linear light.
ALBEDO = mix(COLOR.rgb / 12.92, pow((COLOR.rgb + vec3(0.055)) / 1.055, vec3(2.4)), step(vec3(0.04045), COLOR.rgb));
ALPHA = COLOR.a * (1.0 - smoothstep(EDGE, 1.0, from_middle));
}
"""
## A ribbon for tracers, turned about its own line to face the camera, so a streak
## reads from any side. Unlit and blended, so it shows against sky and ground alike.
static func _streak() -> QuadMesh:
var quad: QuadMesh = QuadMesh.new()
quad.size = Vector2.ONE
var shader: Shader = Shader.new()
shader.code = TRACER_SHADER
var material: ShaderMaterial = ShaderMaterial.new()
material.shader = shader
quad.material = material
return quad
const TRACER_SHADER: String = """
shader_type spatial;
render_mode unshaded, blend_mix, cull_disabled, depth_draw_never, shadows_disabled, skip_vertex_transform;
void vertex() {
vec3 middle = (MODEL_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
vec3 along = INSTANCE_CUSTOM.xyz;
vec3 to_eye = normalize(INV_VIEW_MATRIX[3].xyz - middle);
vec3 side = cross(along, to_eye);
side = length(side) > 0.0001 ? normalize(side) : INV_VIEW_MATRIX[0].xyz;
vec3 world = middle + along * VERTEX.y + side * VERTEX.x * INSTANCE_CUSTOM.w;
VERTEX = (VIEW_MATRIX * vec4(world, 1.0)).xyz;
NORMAL = vec3(0.0, 0.0, 1.0);
}
void fragment() {
// Bright down the middle, soft at the sides; fading toward the tail.
float across = 1.0 - abs(UV.x - 0.5) * 2.0;
// Palette colours are sRGB; the shader works in linear light.
ALBEDO = mix(COLOR.rgb / 12.92, pow((COLOR.rgb + vec3(0.055)) / 1.055, vec3(2.4)), step(vec3(0.04045), COLOR.rgb));
ALPHA = COLOR.a * smoothstep(0.0, 0.6, across) * mix(0.25, 1.0, 1.0 - UV.y);
}
"""
+1
View File
@@ -0,0 +1 @@
uid://bd3ho3rln30at
+9 -3
View File
@@ -19,12 +19,13 @@ const QUALITY_HIGH: int = 2
## render_scale the 3D resolution against the window's ## render_scale the 3D resolution against the window's
## msaa multisample anti-aliasing (a Viewport.MSAA_ value) ## msaa multisample anti-aliasing (a Viewport.MSAA_ value)
## fxaa the cheap screen-space anti-aliasing, for presets without MSAA ## fxaa the cheap screen-space anti-aliasing, for presets without MSAA
## particles how many effect particles (A7) may be alive at once
## Nothing here changes what can be seen: trees, rocks and pieces are drawn as far on ## Nothing here changes what can be seen: trees, rocks and pieces are drawn as far on
## every preset, so a lower one never shows a player through cover. ## every preset, so a lower one never shows a player through cover.
const QUALITY: Array[Dictionary] = [ const QUALITY: Array[Dictionary] = [
{"shadow_distance": 0.0, "shadow_splits": 1, "render_scale": 0.75, "msaa": Viewport.MSAA_DISABLED, "fxaa": true}, {"shadow_distance": 0.0, "shadow_splits": 1, "render_scale": 0.75, "msaa": Viewport.MSAA_DISABLED, "fxaa": true, "particles": 256},
{"shadow_distance": 200.0, "shadow_splits": 2, "render_scale": 1.0, "msaa": Viewport.MSAA_DISABLED, "fxaa": true}, {"shadow_distance": 200.0, "shadow_splits": 2, "render_scale": 1.0, "msaa": Viewport.MSAA_DISABLED, "fxaa": true, "particles": 512},
{"shadow_distance": 400.0, "shadow_splits": 4, "render_scale": 1.0, "msaa": Viewport.MSAA_2X, "fxaa": false}, {"shadow_distance": 400.0, "shadow_splits": 4, "render_scale": 1.0, "msaa": Viewport.MSAA_2X, "fxaa": false, "particles": 1024},
] ]
const WINDOW_MODES: Array[String] = ["Windowed", "Fullscreen", "Exclusive fullscreen"] const WINDOW_MODES: Array[String] = ["Windowed", "Fullscreen", "Exclusive fullscreen"]
## Frame caps offered, 0 for none. ## Frame caps offered, 0 for none.
@@ -76,6 +77,11 @@ func shadow_distance() -> float:
return float(QUALITY[quality]["shadow_distance"]) return float(QUALITY[quality]["shadow_distance"])
## How many effect particles (A7) may be alive at once.
func particle_budget() -> int:
return int(QUALITY[quality]["particles"])
func render_scale() -> float: func render_scale() -> float:
return float(QUALITY[quality]["render_scale"]) return float(QUALITY[quality]["render_scale"])
+43
View File
@@ -0,0 +1,43 @@
## Hit feedback for the client's own player (A7): a marker round the reticle when one of
## their shots strikes another player, and a flash at the screen's edge when they're
## hurt. It reads the server's FX records and the player's health; HudState carries
## what it decides to the HUD as two strengths from 1 (just now) to 0 (gone).
class_name HitFeedback
extends RefCounted
## How long the hit marker and the hurt flash last, in seconds.
const HIT_SECONDS: float = 0.3
const HURT_SECONDS: float = 0.6
var _hit_left: float = 0.0
var _hurt_left: float = 0.0
var _health: int = -1
## Takes fresh FX records. `own_id` is the client's own player.
func hear(records: Array[Dictionary], own_id: int) -> void:
if own_id == 0:
return
for record: Dictionary in records:
if int(record["kind"]) == NetFx.IMPACT and int(record["player"]) == own_id \
and int(record.get("hit", Weapons.HIT_NONE)) == Weapons.HIT_PLAYER and int(record.get("target", 0)) != own_id:
_hit_left = HIT_SECONDS
## One frame. `health` is the player's health now, or -1 when they aren't playing.
func update(health: int, delta: float) -> void:
_hit_left = maxf(_hit_left - delta, 0.0)
_hurt_left = maxf(_hurt_left - delta, 0.0)
if health >= 0 and _health >= 0 and health < _health:
_hurt_left = HURT_SECONDS
_health = health
## 1 just after a hit, falling to 0.
func hit() -> float:
return _hit_left / HIT_SECONDS
## 1 just after being hurt, falling to 0.
func hurt() -> float:
return _hurt_left / HURT_SECONDS
+1
View File
@@ -0,0 +1 @@
uid://xa8incllrk4t
+76
View File
@@ -24,6 +24,8 @@ var _vitals: Vitals
var _hotbar: HBoxContainer var _hotbar: HBoxContainer
var _materials: VBoxContainer var _materials: VBoxContainer
var _build: Label var _build: Label
var _reticle: Reticle
var _hurt: HurtEdge
## When a feed line was first shown (msec), so lines fade after HudState.FEED_SECONDS. ## When a feed line was first shown (msec), so lines fade after HudState.FEED_SECONDS.
var _feed_seen: Dictionary = {} var _feed_seen: Dictionary = {}
## Captures turn this off to keep every line of the feed. ## Captures turn this off to keep every line of the feed.
@@ -35,6 +37,16 @@ func _init() -> void:
set_anchors_preset(Control.PRESET_FULL_RECT) set_anchors_preset(Control.PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_IGNORE mouse_filter = Control.MOUSE_FILTER_IGNORE
# Under everything else: the hurt flash at the screen's edge, then the reticle.
_hurt = HurtEdge.new()
_hurt.set_anchors_preset(Control.PRESET_FULL_RECT)
add_child(_hurt)
_reticle = Reticle.new()
_reticle.set_anchors_preset(Control.PRESET_CENTER)
_reticle.size = Vector2(64.0, 64.0)
_reticle.position = Vector2(-32.0, -32.0)
add_child(_reticle)
_tide = TidePost.new() _tide = TidePost.new()
_tide.set_anchors_preset(Control.PRESET_CENTER_TOP) _tide.set_anchors_preset(Control.PRESET_CENTER_TOP)
_tide.custom_minimum_size = Vector2(330.0, 104.0) _tide.custom_minimum_size = Vector2(330.0, 104.0)
@@ -114,6 +126,13 @@ func show_state(shown: HudState) -> void:
if shown.feed.is_empty(): if shown.feed.is_empty():
_feed_seen.clear() _feed_seen.clear()
_reticle.visible = shown.playing and shown.reticle
_reticle.hit = shown.hit
_reticle.queue_redraw()
_hurt.visible = shown.hurt > 0.0
_hurt.strength = shown.hurt
_hurt.queue_redraw()
_vitals.visible = shown.playing _vitals.visible = shown.playing
_vitals.health = shown.health _vitals.health = shown.health
_vitals.armor = shown.armor _vitals.armor = shown.armor
@@ -367,3 +386,60 @@ class SlotBox:
if pip <= tier: if pip <= tier:
draw_circle(centre, 3.5, Palette.GILT if tier >= 2 else Palette.INK) draw_circle(centre, 3.5, Palette.GILT if tier >= 2 else Palette.INK)
draw_arc(centre, 3.5, 0.0, TAU, 12, Palette.INK, 1.0) draw_arc(centre, 3.5, 0.0, TAU, 12, Palette.INK, 1.0)
## The aiming reticle at the screen's centre: a small paper ring and dot, outlined in
## ink so it reads on sky and sand alike. A shot that strikes someone puts four ticks
## round it, which fly out and fade (A7): a shape, not only a colour.
class Reticle:
extends Control
var hit: float = 0.0
func _init() -> void:
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _draw() -> void:
var middle: Vector2 = size * 0.5
draw_arc(middle, 7.0, 0.0, TAU, 24, Palette.OUTLINE, 3.5, true)
draw_arc(middle, 7.0, 0.0, TAU, 24, Palette.PAPER, 1.5, true)
draw_circle(middle, 2.2, Palette.OUTLINE)
draw_circle(middle, 1.3, Palette.PAPER)
if hit <= 0.0:
return
var spread: float = 11.0 + (1.0 - hit) * 6.0
var length: float = 9.0
var alpha: float = clampf(hit * 1.6, 0.0, 1.0)
for corner: int in 4:
var angle: float = PI * 0.25 + corner * PI * 0.5
var way: Vector2 = Vector2(cos(angle), sin(angle))
var from: Vector2 = middle + way * spread
var to: Vector2 = middle + way * (spread + length)
draw_line(from, to, Color(Palette.OUTLINE, alpha), 5.0, true)
draw_line(from, to, Color(Palette.PAPER, alpha), 2.5, true)
## Being hurt: the screen's edge flushes rust red and fades (A7). The health number
## falling says the same thing without colour.
class HurtEdge:
extends Control
var strength: float = 0.0
func _init() -> void:
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _draw() -> void:
if strength <= 0.0:
return
var band: float = minf(size.x, size.y) * 0.12
var steps: int = 8
for step: int in steps:
var inset: float = band * step / steps
var alpha: float = 0.42 * strength * (1.0 - float(step) / steps)
var colour: Color = Color(Palette.WARNING, alpha / steps * 2.0)
var width: float = band / steps
draw_rect(Rect2(inset, inset, size.x - inset * 2.0, width), colour)
draw_rect(Rect2(inset, size.y - inset - width, size.x - inset * 2.0, width), colour)
draw_rect(Rect2(inset, inset + width, width, size.y - (inset + width) * 2.0), colour)
draw_rect(Rect2(size.x - inset - width, inset + width, width, size.y - (inset + width) * 2.0), colour)
+8
View File
@@ -25,6 +25,12 @@ var standing: int = 0
var total: int = 0 var total: int = 0
## Lines for the kill feed, oldest first: {"text", "you"}. ## Lines for the kill feed, oldest first: {"text", "you"}.
var feed: Array[Dictionary] = [] var feed: Array[Dictionary] = []
## True when the aiming reticle is shown: playing, on foot or swimming.
var reticle: bool = false
## Hit feedback (A7, HitFeedback): the marker for a shot that struck someone and the
## flash for being hurt, each 1 just after and 0 when gone.
var hit: float = 0.0
var hurt: float = 0.0
## The HUD for a client: its own predicted player, the world's tide and the server's feed. ## The HUD for a client: its own predicted player, the world's tide and the server's feed.
@@ -44,6 +50,7 @@ static func from_client(game: ClientGame, input: ClientInput, own_handle: int, f
state.playing = true state.playing = true
state.health = drawn.health if drawn != null else me.health state.health = drawn.health if drawn != null else me.health
state.armor = drawn.armor if drawn != null else me.armor state.armor = drawn.armor if drawn != null else me.armor
state.reticle = me.drop_state == Drop.NONE
_fill_carried(state, me) _fill_carried(state, me)
state.build = build_of(input.build_mode, input.build_kind, input.material, me.materials) state.build = build_of(input.build_mode, input.build_kind, input.material, me.materials)
return state return state
@@ -71,6 +78,7 @@ static func from_match(flow: Match, handle: int, build_mode: bool = false, build
state.playing = true state.playing = true
state.health = me.health state.health = me.health
state.armor = me.armor state.armor = me.armor
state.reticle = me.drop_state == Drop.NONE
_fill_carried(state, me) _fill_carried(state, me)
state.build = build_of(build_mode, build_kind, material, me.materials) state.build = build_of(build_mode, build_kind, material, me.materials)
return state return state
+21
View File
@@ -22,6 +22,8 @@ var print_pass: MeshInstance3D
var sun: DirectionalLight3D var sun: DirectionalLight3D
## The sky, light, haze, rain and murk of the moment (A6). ## The sky, light, haze, rain and murk of the moment (A6).
var weather: WeatherView var weather: WeatherView
## Flashes, tracers, dust, blasts and spray (A7).
var effects: EffectsView
## Applies the player's graphics settings: the sun's shadows and the print pass. ## Applies the player's graphics settings: the sun's shadows and the print pass.
@@ -34,6 +36,8 @@ func apply_settings(settings: GameSettings) -> void:
sun.directional_shadow_mode = splits.get(settings.shadow_splits(), DirectionalLight3D.SHADOW_PARALLEL_4_SPLITS) sun.directional_shadow_mode = splits.get(settings.shadow_splits(), DirectionalLight3D.SHADOW_PARALLEL_4_SPLITS)
if print_pass != null: if print_pass != null:
print_pass.visible = settings.print_pass print_pass.visible = settings.print_pass
if effects != null:
effects.budget = settings.particle_budget()
## Builds the scene for `simulation`. `local_id` is the player this client plays, or 0. ## Builds the scene for `simulation`. `local_id` is the player this client plays, or 0.
@@ -77,6 +81,9 @@ func setup(simulation: Simulation, local_id: int = 0) -> void:
entities.local_id = local_id entities.local_id = local_id
entities.setup(sim) entities.setup(sim)
add_child(entities) add_child(entities)
effects = EffectsView.new()
effects.muzzle_of = muzzle_of
add_child(effects)
sync() sync()
@@ -88,6 +95,20 @@ func sync() -> void:
props.sync() props.sync()
structures.sync() structures.sync()
entities.sync() entities.sync()
effects.sync(sim, camera.transform.origin)
## Where the weapon in a player's drawn hands has its muzzle (its model's +Z end), or
## Vector3.INF when they have no figure showing a held item.
func muzzle_of(entity_id: int) -> Vector3:
var figure: FigureRig = entities.figure_of(entity_id) if entities != null else null
if figure == null or not figure.visible or not figure.is_inside_tree():
return Vector3.INF
var held: MeshInstance3D = figure.held()
if held == null or held.mesh == null or not held.is_visible_in_tree():
return Vector3.INF
var box: AABB = held.mesh.get_aabb()
return held.global_transform * Vector3(box.get_center().x, box.get_center().y, box.end.z)
## Puts the camera on a player's shoulder, looking where they look. `pitch` replaces ## Puts the camera on a player's shoulder, looking where they look. `pitch` replaces
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/effects_scene.gd" id="1"]
[node name="CaptureEffects" type="Node3D"]
script = ExtResource("1")
stage = "blast"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/effects_scene.gd" id="1"]
[node name="CaptureEffects" type="Node3D"]
script = ExtResource("1")
stage = "fight"
+215
View File
@@ -0,0 +1,215 @@
## Capture scenario for visual effects (A7), on seed 2's island in the real MatchView.
## Effects are stepped by hand to a chosen moment (EffectsView.live off), so each
## picture shows the same instant every time.
##
## - fight: over the shoulder of a player firing a carbine at another 11 m off: the
## muzzle flash, the tracer on its way and the burst on the target, with the HUD's
## reticle and hit marker.
## - blast: a powder keg going off beside a stone wall, while a driftwood wall nearby
## comes down in dust, seen from the side.
## - work: the quieter effects together: a piece set down in a ring of dust, chips
## from a harvest swing, shots striking stone and ground, and a splash.
## - stress: 24 players emptying repeaters at a fort while kegs go off, with the
## effects pool at its largest budget; the capture's render line reports the draw
## calls, and the log line the particles alive against the budget.
extends Node3D
@export var stage: String = "fight"
@export var match_seed: int = 2
const FRAME: float = 1.0 / 60.0
var sim: Simulation
var view: MatchView
var spot: Vector3
func _ready() -> void:
sim = Simulation.new(match_seed)
spot = _open_ground()
var shooter: SimEntity = null
var target: SimEntity = null
var walls: Array[StructureSet.Piece] = []
match stage:
"fight":
shooter = _player(spot, "dock_carbine", 0)
target = _player(spot + Vector3(1.2, 0.0, 11.0), "rivet_repeater", 32768)
"blast":
walls.append(_wall(spot + Vector3(0.0, 0.0, 6.0), Materials.STONE))
walls.append(_wall(spot + Vector3(-6.0, 0.0, 6.0), Materials.DRIFTWOOD))
"work":
_player(spot + Vector3(-2.0, 0.0, 4.0), "", 0)
walls.append(_wall(spot + Vector3(2.0, 0.0, 8.0), Materials.STONE))
"stress":
for index: int in 6:
walls.append(_wall(spot + Vector3(index * 4.0 - 10.0, 0.0, 16.0), index % 3))
for index: int in 24:
_player(spot + Vector3(index * 1.2 - 14.0, 0.0, -2.0 - (index % 2) * 2.0), "rivet_repeater", 0)
view = MatchView.new()
view.setup(sim, 0)
add_child(view)
view.effects.live = false
view.entities.animate_live = false
view.sync()
match stage:
"fight":
view.rig.aim_blend = 1.0
view.follow(shooter.id, deg_to_rad(2.0))
"blast":
view.look_from(spot + Vector3(-4.0, 3.5, -10.0), spot + Vector3(-3.0, 1.6, 5.0))
"work":
view.look_from(spot + Vector3(-5.0, 3.2, -4.5), spot + Vector3(0.5, 0.8, 5.0))
"stress":
view.look_from(spot + Vector3(-22.0, 9.0, -14.0), spot + Vector3(0.0, 1.0, 8.0))
view.settle()
view.entities.animate(0.5)
view.effects.sync(sim, view.camera.global_position)
await get_tree().process_frame
match stage:
"fight":
_fight(shooter, target)
"blast":
_blast(walls)
"work":
_work(walls[0])
"stress":
_stress(walls)
var effects: EffectsView = view.effects
print(JSON.stringify({"stage": stage, "particles": effects.particle_count(), "budget": effects.budget,
"peak": effects.peak, "dropped": effects.dropped, "tracers": effects.tracer_count(), "lights": effects.light_count()}))
func _fight(shooter: SimEntity, target: SimEntity) -> void:
var eye: Vector3 = Harvest.eye(shooter)
var chest: Vector3 = target.position + Vector3(0.0, 1.25, 0.0)
var aim: Vector3 = (chest - eye).normalized()
var records: Array[Dictionary] = [
{"kind": NetFx.SHOT, "tick": 10, "player": shooter.id, "item": ItemCatalog.code_of("dock_carbine"), "position": eye,
"yaw": atan2(aim.x, aim.z), "pitch": asin(aim.y)},
{"kind": NetFx.IMPACT, "tick": 10, "player": shooter.id, "item": ItemCatalog.code_of("dock_carbine"), "position": chest - aim * 0.25,
"hit": Weapons.HIT_PLAYER, "target": target.id},
]
view.effects.hear(records)
view.effects.advance(0.025)
var hud: Hud = Hud.new()
add_child(hud)
var state: HudState = HudState.new()
state.playing = true
state.reticle = true
state.health = 100
state.hit = 0.85
hud.show_state(state)
func _blast(walls: Array[StructureSet.Piece]) -> void:
var at: Vector3 = spot + Vector3(-1.5, 0.0, 2.5)
at.y = sim.ground.terrain_height(at.x, at.z) + 0.3
view.effects.hear([{"kind": NetFx.IMPACT, "tick": 10, "player": 1, "item": ItemCatalog.code_of("powder_keg"),
"position": at, "hit": Weapons.HIT_NONE, "target": 0}] as Array[Dictionary])
view.effects.advance(0.08)
sim.structures.remove(walls[1].id, sim.ground)
view.sync()
view.effects.advance(0.1)
func _work(wall: StructureSet.Piece) -> void:
var effects: EffectsView = view.effects
var floor_at: Vector3 = spot + Vector3(-2.5, 0.0, 9.0)
var g: float = Tuning.GRID_CELL_METRES
var cell: Vector3i = Vector3i(floori(floor_at.x / g), floori(floor_at.y / Tuning.BUILD_LEVEL_METRES), floori(floor_at.z / g))
var placed: StructureSet.Piece = sim.structures.add(StructureSet.FLOOR, Materials.DRIFTWOOD, Vector4i(cell.x, cell.y, cell.z, StructureSet.SLOT_FLOOR), 0, 0, sim.tick, sim.ground)
placed.build_ticks_left = 0
view.sync()
var stone: Vector3 = wall.boxes[0].get_center() + Vector3(0.0, 0.4, -wall.boxes[0].size.z * 0.5)
var ground: Vector3 = spot + Vector3(1.0, 0.0, 3.0)
ground.y = sim.ground.terrain_height(ground.x, ground.z)
var records: Array[Dictionary] = [
{"kind": NetFx.PLACE, "tick": 10, "player": 1, "item": -1, "position": placed.boxes[0].get_center(), "piece": placed.id},
{"kind": NetFx.HARVEST, "tick": 10, "player": 1, "item": -1, "position": spot + Vector3(-2.0, sim.ground.terrain_height(spot.x - 2.0, spot.z + 4.0) - spot.y, 4.0) + Vector3(0.0, 0.0, 0.8), "prop": -1, "piece": wall.id},
{"kind": NetFx.IMPACT, "tick": 10, "player": 1, "item": ItemCatalog.code_of("dock_carbine"), "position": stone + Vector3(1.2, 0.3, 0.0), "hit": Weapons.HIT_PIECE, "target": wall.id},
{"kind": NetFx.IMPACT, "tick": 10, "player": 1, "item": ItemCatalog.code_of("dock_carbine"), "position": ground, "hit": Weapons.HIT_TERRAIN, "target": 0},
]
effects.hear(records)
var water: Vector3 = spot + Vector3(3.5, 0.0, 2.0)
effects.splash(Vector3(water.x, sim.ground.terrain_height(water.x, water.z) + 0.05, water.z), 1.0)
effects.advance(0.15)
func _stress(walls: Array[StructureSet.Piece]) -> void:
var effects: EffectsView = view.effects
effects.budget = EffectsView.MAX_PARTICLES
var shooters: Array[SimEntity] = []
for entity: SimEntity in sim.entities.entities():
if entity.archetype == SimEntity.ARCHETYPE_PLAYER:
shooters.append(entity)
var tick: int = 10
for frame: int in 90:
var records: Array[Dictionary] = []
for shooter: SimEntity in shooters:
var eye: Vector3 = Harvest.eye(shooter)
var wall: StructureSet.Piece = walls[shooter.id % walls.size()]
var to: Vector3 = wall.boxes[0].get_center() + Vector3(0.0, (shooter.id % 5) * 0.3 - 0.6, -wall.boxes[0].size.z * 0.5)
var aim: Vector3 = (to - eye).normalized()
records.append({"kind": NetFx.SHOT, "tick": tick, "player": shooter.id, "item": ItemCatalog.code_of("rivet_repeater"),
"position": eye, "yaw": atan2(aim.x, aim.z), "pitch": asin(aim.y)})
records.append({"kind": NetFx.IMPACT, "tick": tick, "player": shooter.id, "item": ItemCatalog.code_of("rivet_repeater"),
"position": to, "hit": Weapons.HIT_PIECE, "target": wall.id})
if frame % 15 == 0:
var keg: Vector3 = spot + Vector3(frame * 0.2 - 8.0, 0.0, 12.0)
keg.y = sim.ground.terrain_height(keg.x, keg.z) + 0.3
records.append({"kind": NetFx.IMPACT, "tick": tick, "player": shooters[0].id, "item": ItemCatalog.code_of("powder_keg"),
"position": keg, "hit": Weapons.HIT_NONE, "target": 0})
effects.hear(records)
effects.advance(FRAME)
tick += 1
func _player(at: Vector3, item: String, yaw: int) -> SimEntity:
var player: SimEntity = sim.entities.find(sim.add_player())
player.position = Vector3(at.x, sim.ground.terrain_height(at.x, at.z), at.z)
player.drop_state = Drop.NONE
player.on_ground = true
player.health = 100
player.yaw = yaw
if item != "":
player.slot_items[0] = ItemCatalog.code_of(item)
player.slot_counts[0] = 1
player.slot_tiers[0] = 1
player.selected = 1
return player
func _wall(at: Vector3, material: int) -> StructureSet.Piece:
var g: float = Tuning.GRID_CELL_METRES
var y: float = sim.ground.terrain_height(at.x, at.z)
var cell: Vector3i = Vector3i(floori(at.x / g), floori(y / Tuning.BUILD_LEVEL_METRES), floori(at.z / g))
var wall: StructureSet.Piece = sim.structures.add(StructureSet.WALL, material, Vector4i(cell.x, cell.y, cell.z, StructureSet.SLOT_WALL_Z), 0, 0, sim.tick, sim.ground)
wall.build_ticks_left = 0
wall.health = wall.max_health
return wall
## Fairly flat, open ground above the sea near the middle of the island.
func _open_ground() -> Vector3:
var size: float = Tuning.WORLD_SIZE_METRES
for ring: int in 60:
for step: int in 24:
var angle: float = TAU * step / 24.0
var x: float = size * 0.5 + cos(angle) * ring * 12.0
var z: float = size * 0.5 + sin(angle) * ring * 12.0
var feet: Vector3 = Vector3(x, sim.ground.terrain_height(x, z), z)
if feet.y < sim.sea_level + 3.0 or sim.ground.terrain_normal(x, z).y < 0.985:
continue
if not sim.props.near(feet, 16.0).is_empty():
continue
var level: bool = true
for dz: float in [-7.0, 0.0, 9.0, 16.0]:
if absf(sim.ground.terrain_height(x - 2.0, z + dz) - feet.y) > 0.8:
level = false
# Open sky and a clear line down the range: not inside a building.
var chest: Vector3 = feet + Vector3(0.0, 1.4, 0.0)
if level and sim.ground.raycast(chest + Vector3(0.0, 30.0, 0.0), chest) >= 1.0 \
and sim.ground.raycast(chest, chest + Vector3(0.0, 0.0, 16.0)) >= 1.0 \
and sim.ground.raycast(chest + Vector3(-12.0, 0.0, 0.0), chest + Vector3(12.0, 0.0, 0.0)) >= 1.0:
return feet
return Vector3(size * 0.5, 0.0, size * 0.5)
+1
View File
@@ -0,0 +1 @@
uid://ca84ct4lwvmb8
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/effects_scene.gd" id="1"]
[node name="CaptureEffects" type="Node3D"]
script = ExtResource("1")
stage = "stress"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/effects_scene.gd" id="1"]
[node name="CaptureEffects" type="Node3D"]
script = ExtResource("1")
stage = "work"
+246
View File
@@ -0,0 +1,246 @@
extends TestCase
## A7: visual effects. Every effect comes from a pool with a hard budget, starts from
## what the server's FX records and the client's world say happened, and is gone again
## once it has played.
const FRAME: float = 1.0 / 60.0
var tree: SceneTree
var effects: EffectsView
var world: Simulation
func before_each() -> void:
super.before_each()
tree = Engine.get_main_loop() as SceneTree
effects = EffectsView.new()
effects.live = false
tree.root.add_child(effects)
world = Simulation.new(5, SimGround.flat(0.0))
world.sea_level = -5.0
effects.sync(world, Vector3(0.0, 2.0, -10.0))
func after_each() -> void:
effects.free()
super.after_each()
static func _shot(item: String, at: Vector3, aim: Vector3, tick: int = 10, player: int = 1) -> Dictionary:
return {"kind": NetFx.SHOT, "tick": tick, "player": player, "item": ItemCatalog.code_of(item), "position": at,
"yaw": atan2(aim.x, aim.z), "pitch": asin(aim.normalized().y)}
static func _impact(item: String, at: Vector3, hit: int, target: int = 0, tick: int = 10, player: int = 1) -> Dictionary:
return {"kind": NetFx.IMPACT, "tick": tick, "player": player, "item": ItemCatalog.code_of(item), "position": at, "hit": hit, "target": target}
func _play_out(seconds: float) -> void:
var left: float = seconds
while left > 0.0:
effects.advance(FRAME)
left -= FRAME
func test_a_shot_flashes_at_the_muzzle_runs_a_tracer_and_lights_up_then_is_gone() -> void:
var records: Array[Dictionary] = [_shot("dock_carbine", Vector3(0.0, 1.5, 0.0), Vector3.FORWARD)]
effects.hear(records)
assert_true(effects.particle_count() > 0, "a muzzle flash")
assert_eq(effects.tracer_count(), 1, "one tracer for a missed single shot")
assert_eq(effects.light_count(), 1, "the flash lights its surroundings")
effects.advance(FRAME)
for at: Vector3 in effects.particle_positions():
assert_true(at.distance_to(Vector3(0.0, 1.5, 0.0)) < 2.5, "the flash is at the muzzle: %s" % at)
_play_out(1.5)
assert_eq(effects.particle_count(), 0, "every particle has died")
assert_eq(effects.tracer_count(), 0, "the tracer has run out")
assert_eq(effects.light_count(), 0, "the light is out")
func test_tracers_run_to_where_each_pellet_landed() -> void:
var from: Vector3 = Vector3(0.0, 1.5, 0.0)
var records: Array[Dictionary] = [_shot("fowling_piece", from, Vector3.FORWARD)]
var pellets: int = ItemCatalog.get_def(ItemCatalog.code_of("fowling_piece")).pellets
assert_true(pellets > 1, "the fowling piece throws a spread")
for pellet: int in pellets:
records.append(_impact("fowling_piece", from + Vector3(pellet * 0.2, 0.0, -12.0), Weapons.HIT_TERRAIN))
effects.hear(records)
assert_eq(effects.tracer_count(), pellets, "a streak per pellet")
# A streak per pellet, and each gone once it has run its 12 m.
_play_out(0.02)
assert_eq(effects.tracer_count(), pellets, "still running after 8 m")
_play_out(0.1)
assert_eq(effects.tracer_count(), 0, "all reached their impacts")
func test_projectile_weapons_and_swings_draw_no_hitscan_tracer() -> void:
var projectile: String = ""
for id: String in ["harpoon_gun", "line_thrower"]:
if ItemCatalog.get_def(ItemCatalog.code_of(id)).projectile_speed > 0.0:
projectile = id
assert_ne(projectile, "", "a projectile weapon exists")
var swing: Dictionary = {"kind": NetFx.SHOT, "tick": 1, "player": 1, "item": -1, "position": Vector3.ZERO, "yaw": 0.0, "pitch": 0.0}
var records: Array[Dictionary] = [_shot(projectile, Vector3(0.0, 1.5, 0.0), Vector3.FORWARD), swing]
effects.hear(records)
assert_eq(effects.tracer_count(), 0, "the projectile draws its own streak in flight; the boathook nothing")
assert_true(effects.particle_count() > 0, "the projectile weapon still flashes")
func test_a_hit_on_a_player_bursts_bright_and_a_splash_rises_from_the_water() -> void:
effects.hear([_impact("dock_carbine", Vector3(3.0, 1.2, 0.0), Weapons.HIT_PLAYER, 7)] as Array[Dictionary])
var burst: int = effects.particle_count()
assert_true(burst >= 10, "a hit on a player is a big, bright burst: %d" % burst)
effects.clear()
world.sea_level = 0.5
effects.hear([_impact("dock_carbine", Vector3(3.0, 0.4, 0.0), Weapons.HIT_TERRAIN)] as Array[Dictionary])
_play_out(0.2)
var above: int = 0
for at: Vector3 in effects.particle_positions():
above += 1 if at.y > 0.8 else 0
assert_true(above > 0, "a shot into the shallows throws water up")
func test_a_keg_blast_is_a_fireball_with_smoke_and_a_light() -> void:
effects.hear([_impact("powder_keg", Vector3(0.0, 0.5, 5.0), Weapons.HIT_NONE)] as Array[Dictionary])
assert_true(effects.particle_count() >= 50, "flash, fire, debris and smoke: %d" % effects.particle_count())
assert_eq(effects.light_count(), 1)
_play_out(1.0)
var high: float = -INF
for at: Vector3 in effects.particle_positions():
high = maxf(high, at.y)
assert_true(high > 2.0, "smoke still rising after a second: %.1f" % high)
_play_out(3.0)
assert_eq(effects.particle_count(), 0, "and gone after four")
func test_pieces_that_break_collapse_in_dust_and_the_first_sync_starts_nothing() -> void:
var piece: StructureSet.Piece = world.structures.add(StructureSet.WALL, Materials.STONE, Vector4i(1, 0, 1, StructureSet.SLOT_WALL_X), 0, 0, 0, world.ground)
var fresh: EffectsView = EffectsView.new()
tree.root.add_child(fresh)
fresh.live = false
fresh.sync(world, Vector3.ZERO)
assert_eq(fresh.particle_count(), 0, "what was already there when the view began isn't news")
world.structures.remove(piece.id, world.ground)
fresh.sync(world, Vector3.ZERO)
assert_true(fresh.particle_count() >= 12, "the wall comes down in dust and chips: %d" % fresh.particle_count())
fresh.free()
func test_a_player_falling_into_the_sea_splashes() -> void:
var player: SimEntity = world.entities.find(world.add_player())
player.drop_state = Drop.NONE
player.position = Vector3(2.0, -5.0, 2.0)
effects.sync(world, Vector3.ZERO)
effects.sync(world, Vector3.ZERO)
assert_eq(effects.particle_count(), 0, "a player who was already there")
player.swimming = true
world.tick += 1
effects.sync(world, Vector3.ZERO)
assert_true(effects.particle_count() >= 10, "they went in with a splash")
func test_effects_far_from_the_camera_are_not_started() -> void:
effects.eye = Vector3.ZERO
var far: Vector3 = Vector3(EffectsView.DRAW_METRES + 50.0, 0.0, 0.0)
effects.hear([_impact("powder_keg", far, Weapons.HIT_NONE), _shot("dock_carbine", far, Vector3.FORWARD)] as Array[Dictionary])
assert_eq(effects.particle_count(), 0)
assert_eq(effects.tracer_count(), 0)
## The stress scene: 24 players emptying their weapons into a fort while kegs go off,
## for two seconds. The pool never goes over its budget, draws in a fixed number of
## draw calls, never adds a node, and one frame's work on a full pool stays cheap.
func test_a_firefight_stays_inside_the_budget() -> void:
for budget: int in [256, 512, EffectsView.MAX_PARTICLES]:
effects.clear()
effects.budget = budget
effects.peak = 0
effects.dropped = 0
var nodes: int = effects.get_child_count()
var tick: int = 100
for frame: int in 120:
var records: Array[Dictionary] = []
for shooter: int in 24:
var from: Vector3 = Vector3(shooter * 2.0 - 24.0, 1.5, -20.0)
records.append(_shot("rivet_repeater", from, Vector3(0.0, 0.0, 1.0), tick, shooter + 1))
records.append(_impact("rivet_repeater", from + Vector3(0.0, 0.0, 30.0), Weapons.HIT_PIECE if shooter % 2 == 0 else Weapons.HIT_PLAYER, 3, tick, shooter + 1))
if frame % 10 == 0:
records.append(_impact("powder_keg", Vector3(frame * 0.1, 0.5, 8.0), Weapons.HIT_NONE, 0, tick, 1))
effects.hear(records)
effects.advance(FRAME)
tick += 1
assert_true(effects.particle_count() <= budget, "alive within the budget")
assert_true(effects.tracer_count() <= EffectsView.MAX_TRACERS, "tracers within theirs")
assert_true(effects.light_count() <= EffectsView.MAX_LIGHTS, "lights within theirs")
assert_eq(effects.peak, budget, "the stress scene fills the pool")
assert_true(effects.dropped > 0, "and the rest is cut, not allocated")
assert_eq(effects.get_child_count(), nodes, "no node was added in play")
# One frame on a full pool. Headless and shared, so the bound is loose; it's
# here to catch a step that grows with something it shouldn't.
var started: int = Time.get_ticks_usec()
effects.advance(FRAME)
var spent: float = (Time.get_ticks_usec() - started) / 1000.0
print("effects: one frame of %d particles and %d tracers took %.2f ms" % [effects.particle_count(), effects.tracer_count(), spent])
assert_true(spent < 12.0, "a full pool's frame took %.2f ms" % spent)
func test_the_presets_set_rising_budgets_and_the_match_view_takes_them() -> void:
var settings: GameSettings = GameSettings.new()
var last: int = 0
for quality: int in GameSettings.QUALITY.size():
settings.quality = quality
assert_true(settings.particle_budget() > last, "each preset allows more")
assert_true(settings.particle_budget() <= EffectsView.MAX_PARTICLES)
last = settings.particle_budget()
var view: MatchView = MatchView.new()
view.setup(world, 0)
tree.root.add_child(view)
settings.quality = GameSettings.QUALITY_LOW
view.apply_settings(settings)
assert_eq(view.effects.budget, settings.particle_budget())
view.free()
func test_hit_feedback_marks_own_hits_and_flashes_when_hurt() -> void:
var feedback: HitFeedback = HitFeedback.new()
feedback.update(100, FRAME)
feedback.hear([_impact("dock_carbine", Vector3.ZERO, Weapons.HIT_PLAYER, 9, 1, 4)] as Array[Dictionary], 3)
assert_eq(feedback.hit(), 0.0, "someone else's hit isn't ours")
feedback.hear([_impact("dock_carbine", Vector3.ZERO, Weapons.HIT_PIECE, 9, 1, 3)] as Array[Dictionary], 3)
assert_eq(feedback.hit(), 0.0, "hitting a wall isn't a hit marker")
feedback.hear([_impact("dock_carbine", Vector3.ZERO, Weapons.HIT_PLAYER, 9, 1, 3)] as Array[Dictionary], 3)
assert_eq(feedback.hit(), 1.0, "our shot struck someone")
feedback.update(100, HitFeedback.HIT_SECONDS * 0.5)
assert_near(feedback.hit(), 0.5, 0.01, "and it fades")
assert_eq(feedback.hurt(), 0.0)
feedback.update(80, FRAME)
assert_eq(feedback.hurt(), 1.0, "losing health flashes the edge")
feedback.update(-1, 1.0)
feedback.update(100, FRAME)
assert_eq(feedback.hurt(), 0.0, "coming back into a match isn't being hurt")
func test_the_hud_shows_the_reticle_and_marker_only_while_playing() -> void:
var hud: Hud = Hud.new()
tree.root.add_child(hud)
var state: HudState = HudState.new()
hud.show_state(state)
var reticle: Control = null
var edge: Control = null
for child: Node in hud.get_children():
if child is Hud.Reticle:
reticle = child
elif child is Hud.HurtEdge:
edge = child
assert_not_null(reticle)
assert_false(reticle.visible, "no reticle in the lobby")
state.playing = true
state.reticle = true
state.hit = 0.7
state.hurt = 0.4
hud.show_state(state)
assert_true(reticle.visible)
assert_eq((reticle as Hud.Reticle).hit, 0.7)
assert_true(edge.visible)
hud.free()
+1
View File
@@ -0,0 +1 @@
uid://einp7grxp557