harvest/game/scripts/farm_audio.gd
Forrest 4b86f655c4 #30: forced lighting, intro sounds, scarecrow chest glow
- DayNight.forced ("" / "morning" / "night") overrides target(); snap()
  still works. DayNight.morning() is the MORNING phase's look.
  lanterns_dark keeps every lantern at 0.
- synth_audio.gd: ufo_hum (4 s loop), ufo_whine, part_fall, life_flash,
  ufo_zoom, car_door, each on its own seed (existing wavs unchanged).
  FarmAudio cues for those plus door_creak (kenney creak1/2), all in
  LOCAL_CUES.
- PlayerCharacter: a blue core glow on the chest bone (BoneAttachment3D):
  an unshaded gem, an additive halo pulled toward the camera, and a weak
  pulsing OmniLight3D. On for every scarecrow; set_core_glow(on) hides
  it. set_tint skips it; the hit flash overlay and ToonLook leave it alone.
- test_look: forced/lanterns_dark, the intro cues, the glow on both
  scarecrows, hit flash intact, set_core_glow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 21:51:14 -04:00

529 lines
24 KiB
GDScript

class_name FarmAudio
extends Node3D
## Every sound in the game, by cue name (CUES), routed through the audio buses (Music: phase
## stingers and outcomes; SFX: everything else; Ambience: the day and night loops). FarmSim
## creates it and setup() connects it to the farm's systems:
## * scarecrow: footsteps, its weapons (a pitchfork's whoosh and what it strikes, corn shots,
## the propane torch's roar, the alien ray's hum, a pumpkin bomb's toss and burst), hurt,
## fall, fear and fear ready, patching and patched
## * enemies: crow caws and thieves' / fence breakers' / UFOs' arrivals (from where they come
## in), hits and deaths by type
## * theft: grabbed, dropped, recovered, carried off (with an alarm tone), animals following
## * building: placed, refused, dismantled, hit, broken (with a breach alarm), repaired,
## automated defenses firing, traps springing, the repair hammering
## * gathering: chopping, rustling straw, clanking scrap; stored at the shed; upgrades bought
## * phases: the dusk bell, stingers at dusk, nightfall, sunrise, and morning; game over;
## the day and night ambience (crossfading through dusk and dawn)
## * UI: hover, click, back, open, close, error (ui(), also from the menus)
## * the opening intro (OpeningIntro, solo only, so never sent): the farmhouse door's creak, the
## car doors, the big UFO's hum (a loop), spin-up whine, and zoom away, the part's falling
## whistle, and the flash that brings the scarecrow to life
## * Music (the Music bus), by phase: "On the Farm" on the title screen (the farm's morning
## behind it), the morning, and by day, and when the farmers are back; "Purgatory" at night;
## none at dusk, at dawn, or after a Game Over (only the ambience). Tracks crossfade.
## Positional cues play where they happen and are heard from an AudioListener3D at the
## scarecrow (or the cutscene's focus) facing the way the camera does, so left and right on
## screen are left and right in the ears. Each cue has a volume, a random pitch spread, a
## minimum gap between plays, and a voice limit, so twenty crows don't make twenty caws.
## UI, stinger, and ambience players keep playing while the game is paused; the rest pause.
## Co-op: every world sound the host plays is also sent to the partner (forward), whose game
## plays only those (remote_cues) plus what it makes itself: its footsteps and channels, the UI,
## the phase stingers, and the music (LOCAL_CUES).
## Sources: Kenney's CC0 packs (assets/audio/kenney/, with their licenses) and sounds made by
## game/tools/synth_audio.gd (assets/audio/synth/). A '*' in a file name stands for 0..9.
const ROOT := "res://assets/audio/"
const CUES := {
# UI
"ui_hover": {"files": ["kenney/ui/rollover2.ogg"], "db": -16.0, "gap": 0.03, "ui": true},
"ui_click": {"files": ["kenney/interface/click_002.ogg"], "db": -8.0, "ui": true},
"ui_back": {"files": ["kenney/interface/back_001.ogg"], "db": -8.0, "ui": true},
"ui_open": {"files": ["kenney/interface/open_001.ogg"], "db": -10.0, "ui": true},
"ui_close": {"files": ["kenney/interface/close_001.ogg"], "db": -10.0, "ui": true},
"error": {"files": ["kenney/interface/error_004.ogg"], "db": -8.0, "gap": 0.25, "ui": true},
# Scarecrow
"step": {"files": ["kenney/impact/footstep_grass_00*.ogg"], "db": -15.0, "pitch": 0.08},
"shot": {"files": ["kenney/interface/pluck_00*.ogg"], "db": -9.0, "pitch": 0.12, "max": 3},
"stab": {"files": ["synth/pitchfork_whoosh.wav"], "db": -6.0, "pitch": 0.12, "max": 3},
# The Propane Torch: one roar per tick, each longer than a tick, so a held torch roars on.
"burn": {"files": ["synth/torch_roar.wav"], "db": -7.0, "pitch": 0.08, "gap": 0.1, "max": 3},
# The Alien Ray: one hum per tick, likewise longer than a tick, so a held ray hums on.
"zap": {"files": ["synth/alien_beam.wav"], "db": -10.0, "pitch": 0.04, "gap": 0.07, "max": 3},
"throw": {"files": ["kenney/rpg/cloth*.ogg"], "db": -4.0, "pitch": 0.1},
"boom": {"files": ["synth/pumpkin_boom.wav"], "db": 0.0, "pitch": 0.08, "gap": 0.05, "max": 4},
"hurt": {"files": ["kenney/impact/impactSoft_heavy_00*.ogg"], "db": -1.0, "pitch": 0.1, "gap": 0.1},
"fall": {"files": ["kenney/impact/impactSoft_heavy_004.ogg"], "db": 0.0, "pitch": 0.0},
"fear": {"files": ["kenney/digital/phaserDown2.ogg"], "db": -5.0, "pitch": 0.05},
"fear_ready": {"files": ["kenney/interface/maximize_003.ogg"], "db": -12.0},
"patching": {"files": ["kenney/rpg/cloth*.ogg"], "db": -10.0, "pitch": 0.1},
"patched": {"files": ["kenney/rpg/clothBelt.ogg"], "db": -4.0},
# Weapon and enemies
"hit": {"files": ["kenney/impact/impactPunch_medium_00*.ogg"], "db": -8.0, "pitch": 0.1, "gap": 0.03, "max": 4},
"hit_crow": {"files": ["kenney/impact/impactSoft_medium_00*.ogg"], "db": -6.0, "pitch": 0.15, "gap": 0.03, "max": 4},
"hit_world": {"files": ["kenney/impact/impactGeneric_light_00*.ogg"], "db": -14.0, "pitch": 0.15, "gap": 0.05, "max": 3},
"crow_arrive": {"files": ["synth/crow_caw_1.wav", "synth/crow_caw_2.wav"], "db": 2.0, "pitch": 0.08, "gap": 0.7, "max": 2},
"crow_die": {"files": ["synth/crow_squawk.wav"], "db": -2.0, "pitch": 0.1, "gap": 0.05, "max": 3},
"thief_arrive": {"files": ["kenney/rpg/creak*.ogg"], "db": 0.0, "pitch": 0.1, "gap": 0.8},
"breaker_arrive": {"files": ["kenney/impact/impactWood_heavy_000.ogg"], "db": 4.0, "pitch": 0.0, "gap": 0.8},
"ufo_arrive": {"files": ["kenney/digital/powerUp2.ogg"], "db": -3.0, "pitch": 0.06, "gap": 0.7, "max": 2},
"enemy_die": {"files": ["kenney/impact/impactPunch_heavy_00*.ogg"], "db": -3.0, "pitch": 0.1, "gap": 0.05, "max": 3},
# Theft and alerts
"grab": {"files": ["kenney/rpg/handleSmallLeather.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.1},
"theft_alert": {"files": ["kenney/digital/lowThreeTone.ogg"], "db": -10.0, "gap": 2.5, "ui": true},
"drop": {"files": ["kenney/rpg/dropLeather.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.05},
"recover": {"files": ["kenney/interface/confirmation_002.ogg"], "db": -6.0, "pitch": 0.05, "gap": 0.08},
"follow": {"files": ["kenney/interface/confirmation_001.ogg"], "db": -8.0, "pitch": 0.1, "gap": 0.08},
"lost": {"files": ["kenney/digital/lowDown.ogg"], "db": -6.0, "gap": 1.0, "ui": true},
"breach": {"files": ["kenney/digital/twoTone1.ogg"], "db": -8.0, "gap": 2.0, "ui": true},
# Building
"build": {"files": ["kenney/impact/impactPlank_medium_00*.ogg"], "db": -3.0, "pitch": 0.08},
"dismantle": {"files": ["kenney/impact/impactWood_light_00*.ogg"], "db": -4.0, "pitch": 0.1},
"structure_hit": {"files": ["kenney/impact/impactWood_medium_00*.ogg"], "db": -4.0, "pitch": 0.1, "gap": 0.12, "max": 3},
"smash": {"files": ["kenney/impact/impactWood_heavy_00*.ogg"], "db": 2.0, "pitch": 0.08},
"hammer": {"files": ["kenney/impact/impactWood_light_00*.ogg"], "db": -7.0, "pitch": 0.12},
"repaired": {"files": ["kenney/interface/confirmation_001.ogg"], "db": -6.0},
"turret": {"files": ["kenney/interface/drop_00*.ogg"], "db": -11.0, "pitch": 0.1, "gap": 0.05, "max": 3},
"trap": {"files": ["kenney/impact/impactSoft_medium_00*.ogg"], "db": -4.0, "pitch": 0.2, "gap": 0.1},
# Gathering and upgrades
"chop": {"files": ["kenney/rpg/chop.ogg"], "db": -4.0, "pitch": 0.1},
"rustle": {"files": ["kenney/rpg/cloth*.ogg"], "db": -6.0, "pitch": 0.15},
"clank": {"files": ["kenney/impact/impactMetal_light_00*.ogg"], "db": -8.0, "pitch": 0.1},
"gathered": {"files": ["kenney/rpg/handleSmallLeather2.ogg"], "db": -8.0, "pitch": 0.05},
"deposit": {"files": ["kenney/rpg/bookPlace*.ogg"], "db": -4.0, "pitch": 0.08, "gap": 0.3},
"upgrade": {"files": ["kenney/jingles/jingles_PIZZI16.ogg"], "db": -6.0, "ui": true},
# Phases and outcomes (stingers on the Music bus)
"bell": {"files": ["kenney/impact/impactBell_heavy_00*.ogg"], "db": -4.0, "pitch": 0.0, "ui": true},
"dusk": {"files": ["kenney/jingles/jingles_PIZZI07.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"night": {"files": ["kenney/jingles/jingles_PIZZI14.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"dawn": {"files": ["kenney/jingles/jingles_PIZZI10.ogg"], "db": -6.0, "bus": "Music", "ui": true},
"morning": {"files": ["kenney/jingles/jingles_PIZZI12.ogg"], "db": -9.0, "bus": "Music", "ui": true},
"game_over": {"files": ["kenney/jingles/jingles_PIZZI01.ogg"], "db": -4.0, "bus": "Music", "ui": true},
"victory": {"files": ["kenney/jingles/jingles_PIZZI02.ogg"], "db": -4.0, "bus": "Music", "ui": true},
"assessment": {"files": ["kenney/jingles/jingles_PIZZI15.ogg"], "db": -5.0, "bus": "Music", "ui": true},
"horn": {"files": ["synth/truck_horn.wav"], "db": -4.0},
"truck_engine": {"files": ["synth/truck_engine.wav"], "db": -6.0},
"day_ambience": {"files": ["synth/day_ambience.wav"], "bus": "Ambience"},
"night_ambience": {"files": ["synth/night_ambience.wav"], "bus": "Ambience"},
# The opening intro ("ufo_hum" loops: play it on a player of its own, with stream_of)
"door_creak": {"files": ["kenney/rpg/creak1.ogg", "kenney/rpg/creak2.ogg"], "db": -2.0, "pitch": 0.05},
"car_door": {"files": ["synth/car_door.wav"], "db": -3.0, "pitch": 0.06},
"ufo_hum": {"files": ["synth/ufo_hum.wav"], "db": -6.0},
"ufo_whine": {"files": ["synth/ufo_whine.wav"], "db": -6.0},
"part_fall": {"files": ["synth/part_fall.wav"], "db": -6.0},
"life_flash": {"files": ["synth/life_flash.wav"], "db": -2.0},
"ufo_zoom": {"files": ["synth/ufo_zoom.wav"], "db": -4.0},
}
## Cues each machine plays for itself in co-op (never sent, never skipped).
const LOCAL_CUES: Array[String] = ["ui_hover", "ui_click", "ui_back", "ui_open", "ui_close", "error", "step", "chop",
"rustle", "clank", "hammer", "patching", "bell", "dusk", "night", "dawn", "morning", "game_over", "victory",
"assessment", "horn", "truck_engine", "day_ambience", "night_ambience", "upgrade", "fear_ready", "door_creak",
"car_door", "ufo_hum", "ufo_whine", "part_fall", "life_flash", "ufo_zoom"]
const VOICES_3D := 20
const VOICES_UI := 10
## Seconds of channel between repeats of the gather / repair / patch sounds, and meters per
## footstep.
const CHANNEL_REPEAT := 0.5
const STRIDE := 1.55
## Ambience levels (day, night) per phase, and the crossfade speed (share per second).
const AMBIENCE := {
CampaignController.Phase.MORNING: Vector2(1.0, 0.0), CampaignController.Phase.DAY: Vector2(1.0, 0.0),
CampaignController.Phase.DUSK: Vector2(0.55, 0.45), CampaignController.Phase.NIGHT: Vector2(0.0, 1.0),
CampaignController.Phase.DAWN: Vector2(0.6, 0.4), CampaignController.Phase.FARMERS_RETURN: Vector2(1.0, 0.0),
CampaignController.Phase.GAME_OVER: Vector2(0.0, 0.6),
}
const FADE_RATE := 0.25
const MUSIC := {"farm": "music/on_the_farm.wav", "night": "music/purgatory.ogg"}
const MUSIC_FOR := {
CampaignController.Phase.MORNING: "farm", CampaignController.Phase.DAY: "farm", CampaignController.Phase.DUSK: "",
CampaignController.Phase.NIGHT: "night", CampaignController.Phase.DAWN: "", CampaignController.Phase.FARMERS_RETURN: "farm",
CampaignController.Phase.GAME_OVER: "",
}
const MUSIC_DB := -5.0
const MUSIC_FADE := 2.5
var sim: FarmSim
## Where the listener sits (the scarecrow; the cutscene moves it).
var focus: Node3D
## Cue name -> streams, and cue name -> how many times it played (tests read this).
var streams := {}
var played := {}
## Co-op host: called with (cue, at) for every world sound, to send it to the partner.
var forward: Callable
## Co-op partner: world sounds come only from the host (play_remote).
var remote_cues := false
var _voices_3d: Array[AudioStreamPlayer3D] = []
var _voices_ui: Array[AudioStreamPlayer] = []
var _voices_game: Array[AudioStreamPlayer] = []
var _last := {} # cue -> msec of the last play
var _listener: AudioListener3D
var _day: AudioStreamPlayer
var _night: AudioStreamPlayer
var _ambience := Vector2.ZERO
var _ambience_target := Vector2(1.0, 0.0)
var _channel_left: float = 0.0
var _stride_left: float = STRIDE
var _bell_left: float = -1.0
## The track playing or fading in ("" = none), and each track's player and level (0..1).
var music_track := ""
var _music := {}
var _music_level := {}
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS # music and ambience fade on the paused title screen
for track: String in MUSIC:
var m := AudioStreamPlayer.new()
m.bus = &"Music"
m.stream = load(ROOT + MUSIC[track]) as AudioStream
m.volume_db = -80.0
add_child(m)
_music[track] = m
_music_level[track] = 0.0
for cue: String in CUES:
var list: Array[AudioStream] = []
for f: String in CUES[cue]["files"]:
for path in _expand(ROOT + f):
var s := load(path) as AudioStream
if s != null:
list.append(s)
if list.is_empty():
push_warning("FarmAudio: no sound for cue '%s'" % cue)
streams[cue] = list
for i in VOICES_3D:
var p := AudioStreamPlayer3D.new()
p.bus = &"SFX"
p.unit_size = 9.0
p.max_distance = 90.0
p.panning_strength = 0.7
p.attenuation_filter_cutoff_hz = 20500.0 # no muffling with distance
p.process_mode = Node.PROCESS_MODE_PAUSABLE # game sounds stop while paused
add_child(p)
_voices_3d.append(p)
for i in VOICES_UI:
var p := AudioStreamPlayer.new()
p.process_mode = Node.PROCESS_MODE_ALWAYS
add_child(p)
_voices_ui.append(p)
var g := AudioStreamPlayer.new()
g.process_mode = Node.PROCESS_MODE_PAUSABLE
add_child(g)
_voices_game.append(g)
_day = _loop_player("day_ambience")
_night = _loop_player("night_ambience")
_listener = AudioListener3D.new()
_listener.top_level = true
add_child(_listener)
_listener.make_current()
func setup(p_sim: FarmSim) -> void:
sim = p_sim
focus = sim.player
var c := sim.campaign
c.phase_changed.connect(_on_phase)
c.campaign_ended.connect(func(outcome: CampaignController.Outcome) -> void:
if outcome != CampaignController.Outcome.VACATION_COMPLETE:
play("game_over"))
_ambience_target = AMBIENCE.get(c.state.phase, Vector2(1.0, 0.0))
_ambience = _ambience_target
music_track = MUSIC_FOR.get(c.state.phase, "")
_wire_weapons(sim.combat, Callable())
sim.bombs.burst.connect(func(at: Vector3, _n: int) -> void: play("boom", at))
sim.projectiles.hit.connect(func(at: Vector3, type: int) -> void:
play("hit_world" if type < 0 else "hit_crow" if type == EnemySystem.TYPE_CROW else "hit", at))
sim.enemies.enemy_removed.connect(_on_removed)
sim.waves.arrived.connect(func(h: int, at: Vector2) -> void:
var d := sim.enemies.resolve_handle(h)
var type := sim.enemies.type[d] if d >= 0 else EnemySystem.TYPE_THIEF
# thief, crow, breaker, UFO
var arrive_cues := ["thief_arrive", "crow_arrive", "breaker_arrive", "ufo_arrive"]
play(arrive_cues[type], Vector3(at.x, 0.0, at.y)))
var kit := sim.scarecrow
kit.damaged.connect(func(hp: int) -> void: play("fall" if hp <= 0 else "hurt"))
kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: play("fear"))
kit.fear_ready.connect(func() -> void: play("fear_ready"))
kit.patched.connect(func(_hp: int) -> void: play("patched"))
kit.patch_denied.connect(func(_m: Dictionary) -> void: play("error"))
sim.interactions.gathered.connect(func(_m: String, _a: int, n: GatherNode) -> void: play("gathered", n.global_position))
sim.interactions.deposited.connect(func(_moved: Dictionary) -> void: play("deposit", sim.player.global_position))
var st := sim.structures
st.built.connect(func(id: int, _type: String) -> void: play("build", _structure_at(id)))
st.destroyed.connect(func(_id: int, _type: String, at: Vector3) -> void:
play("smash", at)
play("breach"))
st.hurt.connect(func(_id: int, at: Vector3) -> void: play("structure_hit", at))
st.repaired.connect(func(id: int) -> void: play("repaired", _structure_at(id)))
st.turret_fired.connect(func(at: Vector3) -> void: play("turret", at))
st.trap_sprung.connect(func(at: Vector3) -> void: play("trap", at))
sim.build.refused.connect(func(_why: String) -> void: play("error"))
sim.build.dismantled.connect(func(_type: String) -> void: play("dismantle", Vector3(sim.build.cursor.x, 0.5, sim.build.cursor.y)))
sim.build.toggled.connect(func(on: bool) -> void: play("ui_open" if on else "ui_close"))
sim.loot.loot_event.connect(_on_loot)
if sim.upgrade_panel != null:
sim.upgrade_panel.bought.connect(func(_id: String) -> void: play("upgrade"))
wire_buttons(sim.upgrade_panel)
if sim.shed_panel != null:
sim.shed_panel.bought.connect(func(_id: String) -> void: play("upgrade"))
wire_buttons(sim.shed_panel)
if sim.review_panel != null:
wire_buttons(sim.review_panel)
if sim.end_panel != null:
wire_buttons(sim.end_panel)
## Stops every voice, so no playback outlives the farm (the audio server holds on to playing
## ones until its next mix; Main.quit_game() gives it that moment).
func silence() -> void:
for p in get_children():
if p is AudioStreamPlayer or p is AudioStreamPlayer3D:
p.stop()
p.stream = null
func _exit_tree() -> void:
silence()
## Plays a cue: where it happens (positional) when at is given, else straight to the ears.
## Returns false when the cue is resting (its gap) or has no sound.
func play(cue: String, at: Vector3 = Vector3.INF) -> bool:
var local := LOCAL_CUES.has(cue)
if remote_cues and not local:
return false
if forward.is_valid() and not local:
forward.call(cue, at)
return _play(cue, at)
## A world sound the host played (co-op partner).
func play_remote(cue: String, at: Vector3 = Vector3.INF) -> bool:
return _play(cue, at)
## Sounds for a scarecrow other than the first (co-op): its gun, hurt, fall, fear, and patch,
## where it is.
func wire_avatar(a: Avatar) -> void:
_wire_weapons(a.combat, func() -> Vector3: return a.body.global_position)
a.kit.damaged.connect(func(hp: int) -> void: play("fall" if hp <= 0 else "hurt", a.body.global_position))
a.kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: play("fear", a.body.global_position))
a.kit.patched.connect(func(_hp: int) -> void: play("patched", a.body.global_position))
## A scarecrow's weapons: where (at) for another scarecrow than this machine's, which is heard
## from right here.
func _wire_weapons(combat: ScarecrowCombat, at: Callable) -> void:
var where := func() -> Vector3: return at.call() if at.is_valid() else Vector3.INF
combat.fired.connect(func() -> void: play("shot", where.call()))
combat.stabbed.connect(func(_n: int) -> void: play("stab", where.call()))
combat.burned.connect(func(_n: int) -> void: play("burn", where.call()))
combat.zapped.connect(func(_n: int) -> void: play("zap", where.call()))
combat.struck.connect(func(p: Vector3, type: int) -> void: play("hit_crow" if type == EnemySystem.TYPE_CROW else "hit", p))
combat.threw.connect(func(_to: Vector3) -> void: play("throw", where.call()))
func _play(cue: String, at: Vector3) -> bool:
var def: Dictionary = CUES.get(cue, {})
var list: Array = streams.get(cue, [])
if def.is_empty() or list.is_empty():
return false
var now := Time.get_ticks_msec()
if now - int(_last.get(cue, -1000000000)) < int(float(def.get("gap", 0.0)) * 1000.0):
return false
_last[cue] = now
played[cue] = int(played.get(cue, 0)) + 1
var stream: AudioStream = list[randi() % list.size()]
var pitch := 1.0 + randf_range(-1.0, 1.0) * float(def.get("pitch", 0.0))
var db := float(def.get("db", 0.0))
var bus := StringName(def.get("bus", "SFX"))
var limit := int(def.get("max", 4))
if is_finite(at.x) and not bool(def.get("ui", false)):
var p := _free_voice(_voices_3d, cue, limit) as AudioStreamPlayer3D
p.global_position = at
p.bus = bus
_start(p, stream, db, pitch, cue)
else:
var pool := _voices_ui if bool(def.get("ui", false)) else _voices_game
var p := _free_voice(pool, cue, limit) as AudioStreamPlayer
p.bus = bus
_start(p, stream, db, pitch, cue)
return true
## UI sounds (they play while paused).
func ui(cue: String) -> void:
play(cue)
## Gives every Button under node a hover and a click sound (call again after adding buttons).
func wire_buttons(node: Node) -> void:
for b in node.find_children("*", "BaseButton", true, false):
if b.has_meta(&"sounds"):
continue
b.set_meta(&"sounds", true)
var button := b as BaseButton
button.mouse_entered.connect(func() -> void:
if not button.disabled:
ui("ui_hover"))
button.focus_entered.connect(func() -> void: ui("ui_hover"))
button.pressed.connect(func() -> void: ui("ui_click"))
## The first stream of a cue (for looping players the cutscene owns).
func stream_of(cue: String) -> AudioStream:
var list: Array = streams.get(cue, [])
return list[0] if not list.is_empty() else null
func _physics_process(dt: float) -> void:
if sim == null or sim.campaign.is_over() or get_tree().paused:
return
var p := sim.player
if sim.scarecrow.alive and p.is_on_floor():
var v := Vector2(p.velocity.x, p.velocity.z).length()
if v > 1.0:
_stride_left -= v * dt
if _stride_left <= 0.0:
_stride_left = STRIDE
play("step", p.global_position)
else:
_stride_left = minf(_stride_left, STRIDE * 0.3)
var it := sim.interactions
var channel := ""
var at := p.global_position
if it.gathering != null:
channel = {"wood": "chop", "straw": "rustle", "scrap": "clank"}.get(it.gathering.material, "rustle")
at = it.gathering.global_position
elif it.repairing >= 0:
channel = "hammer"
at = _structure_at(it.repairing)
elif sim.scarecrow.patching:
channel = "patching"
if channel == "":
_channel_left = 0.15
return
_channel_left -= dt
if _channel_left <= 0.0:
_channel_left = CHANNEL_REPEAT
play(channel, at)
func _process(delta: float) -> void:
var cam := get_viewport().get_camera_3d()
if cam != null and focus != null and is_instance_valid(focus):
_listener.global_transform = Transform3D(cam.global_transform.basis, focus.global_position + Vector3(0.0, 1.5, 0.0))
for track: String in _music:
var m := _music[track] as AudioStreamPlayer
var level := move_toward(float(_music_level[track]), 1.0 if track == music_track else 0.0, delta / MUSIC_FADE)
_music_level[track] = level
m.volume_db = MUSIC_DB + linear_to_db(maxf(level, 0.0001))
if level > 0.0 and not m.playing and m.stream != null:
m.play()
elif level <= 0.0 and m.playing:
m.stop()
_ambience = _ambience.move_toward(_ambience_target, FADE_RATE * delta)
_day.volume_db = linear_to_db(maxf(_ambience.x, 0.0001))
_night.volume_db = linear_to_db(maxf(_ambience.y, 0.0001))
if _bell_left >= 0.0:
_bell_left -= delta
if _bell_left < 0.0:
_last.erase("bell")
play("bell")
func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
_ambience_target = AMBIENCE.get(phase, Vector2(1.0, 0.0))
music_track = MUSIC_FOR.get(phase, "")
match phase:
CampaignController.Phase.MORNING:
_ambience = _ambience_target # a retry or a load jumps straight to morning
play("morning")
CampaignController.Phase.DUSK:
play("bell")
_bell_left = 1.3 # and a second strike
play("dusk")
CampaignController.Phase.NIGHT:
play("night")
CampaignController.Phase.DAWN:
play("dawn")
func _on_removed(handle: int, reason: EnemySystem.Removal, x: float, z: float, _carry: int, _target: int) -> void:
if reason != EnemySystem.Removal.KILLED:
return
var d := sim.enemies.resolve_handle(handle)
var crow := d >= 0 and sim.enemies.type[d] == EnemySystem.TYPE_CROW
play("crow_die" if crow else "enemy_die", Vector3(x, 1.0, z))
func _on_loot(kind: StringName, _id: int, at: Vector3) -> void:
match kind:
&"stolen":
play("grab", at)
play("theft_alert")
&"dropped":
play("drop", at)
&"recovered":
play("recover", at)
&"following":
play("follow", at)
&"lost":
play("lost")
&"follow_full":
play("error")
func _structure_at(id: int) -> Vector3:
var e := sim.campaign.state.structure(id)
return Vector3(e["x"], 0.5, e["z"]) if not e.is_empty() else sim.player.global_position
func _loop_player(cue: String) -> AudioStreamPlayer:
var p := AudioStreamPlayer.new()
p.process_mode = Node.PROCESS_MODE_ALWAYS
p.bus = &"Ambience"
p.stream = stream_of(cue)
p.volume_db = -80.0
add_child(p)
if p.stream != null:
p.play()
return p
## Prefers an idle voice; else the oldest of this cue's once it's at its limit; else the oldest.
func _free_voice(pool: Array, cue: String, limit: int) -> Node:
var oldest: Node = pool[0]
var oldest_same: Node = null
var same := 0
for v: Node in pool:
var playing: bool = v.playing
if not playing:
return v
if v.get_meta(&"cue", "") == cue:
same += 1
if oldest_same == null or int(v.get_meta(&"t")) < int(oldest_same.get_meta(&"t")):
oldest_same = v
if int(v.get_meta(&"t")) < int(oldest.get_meta(&"t")):
oldest = v
return oldest_same if same >= limit and oldest_same != null else oldest
func _start(p: Node, stream: AudioStream, db: float, pitch: float, cue: String) -> void:
p.set(&"stream", stream)
p.set(&"volume_db", db)
p.set(&"pitch_scale", pitch)
p.set_meta(&"cue", cue)
p.set_meta(&"t", Time.get_ticks_usec())
p.call(&"play")
static func _expand(path: String) -> Array[String]:
var out: Array[String] = []
if not path.contains("*"):
out.append(path)
return out
for i in 10:
var p := path.replace("*", str(i))
if ResourceLoader.exists(p):
out.append(p)
return out