This commit is contained in:
Forrest 2026-10-04 12:07:36 -04:00
parent 276d43613d
commit 4298caf5cb
552 changed files with 42990 additions and 776 deletions

View file

@ -1,35 +1,77 @@
extends SceneTree
## Builds res://game/resources/player_animations.res: the KayKit Rig_Medium clips the farmer
## uses, copied out of the shared animation files into one AnimationLibrary so the player
## scene's AnimationPlayer can reference (and the editor can preview) them.
## Tracks for bones the mannequin lacks (handslot.l/.r) are dropped; loop flags are set here
## because every source clip is imported as non-looping. Source assets are not modified.
## Re-run after editing CLIPS (editor closed):
## Builds the KayKit animation libraries the game's characters use, copied out of the shared
## animation files into one AnimationLibrary per rig so AnimationPlayers can reference (and the
## editor can preview) them:
## res://game/resources/player_animations.res Rig_Medium: the scarecrow and ground thieves
## res://game/resources/breaker_animations.res Rig_Large: the fence breaker
## Tracks for bones the mannequin lacks (handslot.l/.r on the medium one) are dropped; loop flags
## are set here because every source clip is imported as non-looping. Source assets are not
## modified. Re-run after editing BUILDS (editor closed):
## godot --headless --path . --script res://game/tools/build_player_animations.gd
const MANNEQUIN := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
const ANIM_DIR := "res://assets/kaykit_characters/animations/Rig_Medium/"
const OUTPUT := "res://game/resources/player_animations.res"
const SKELETON_PATH := "Rig_Medium/Skeleton3D"
const KIT := "res://assets/kaykit_characters/"
## Per library: mannequin, animation folder, skeleton path, output, and clips (name as in
## KayKit -> [source file, loops]).
const BUILDS := [
{
"mannequin": KIT + "characters/Mannequin_Medium.glb",
"anims": KIT + "animations/Rig_Medium/",
"skeleton": "Rig_Medium/Skeleton3D",
"output": "res://game/resources/player_animations.res",
"clips": {
"Idle_A": ["Rig_Medium_General.glb", true],
"Idle_B": ["Rig_Medium_General.glb", true],
"Interact": ["Rig_Medium_General.glb", false],
"PickUp": ["Rig_Medium_General.glb", false],
"Use_Item": ["Rig_Medium_General.glb", false],
"Walking_A": ["Rig_Medium_MovementBasic.glb", true],
"Running_A": ["Rig_Medium_MovementBasic.glb", true],
"Sneaking": ["Rig_Medium_MovementAdvanced.glb", true],
"Digging": ["Rig_Medium_Tools.glb", true],
"Chopping": ["Rig_Medium_Tools.glb", true],
"Hammering": ["Rig_Medium_Tools.glb", true],
"Lockpicking": ["Rig_Medium_Tools.glb", true],
"Melee_Unarmed_Attack_Punch_A": ["Rig_Medium_CombatMelee.glb", true],
"Hit_A": ["Rig_Medium_General.glb", false],
"Waving": ["Rig_Medium_Simulation.glb", false],
"Cheering": ["Rig_Medium_Simulation.glb", true],
"Death_A": ["Rig_Medium_General.glb", false],
},
},
{
"mannequin": KIT + "characters/Mannequin_Large.glb",
"anims": KIT + "animations/Rig_Large/",
"skeleton": "Rig_Large/Skeleton3D",
"output": "res://game/resources/breaker_animations.res",
"clips": {
"Idle_A": ["Rig_Large_General.glb", true],
"Walking_A": ["Rig_Large_MovementBasic.glb", true],
"Running_A": ["Rig_Large_MovementBasic.glb", true],
"Melee_2H_Idle": ["Rig_Large_CombatMelee.glb", true],
"Melee_2H_Attack": ["Rig_Large_CombatMelee.glb", true],
"Melee_2H_Slam": ["Rig_Large_CombatMelee.glb", true],
"Hit_A": ["Rig_Large_General.glb", false],
"Death_A": ["Rig_Large_General.glb", false],
},
},
]
## Clip name (kept as in KayKit) -> [source file, loops].
const CLIPS := {
"Idle_A": ["Rig_Medium_General.glb", true],
"Idle_B": ["Rig_Medium_General.glb", true],
"Interact": ["Rig_Medium_General.glb", false],
"PickUp": ["Rig_Medium_General.glb", false],
"Use_Item": ["Rig_Medium_General.glb", false],
"Walking_A": ["Rig_Medium_MovementBasic.glb", true],
"Running_A": ["Rig_Medium_MovementBasic.glb", true],
"Digging": ["Rig_Medium_Tools.glb", true],
"Chopping": ["Rig_Medium_Tools.glb", true],
"Hammering": ["Rig_Medium_Tools.glb", true],
"Waving": ["Rig_Medium_Simulation.glb", false],
}
var _mannequin := ""
var _anim_dir := ""
var _output := ""
var _skeleton := ""
var _clips := {}
func _initialize() -> void:
var ok := _build()
var ok := true
for b: Dictionary in BUILDS:
_mannequin = b["mannequin"]
_anim_dir = b["anims"]
_output = b["output"]
_skeleton = b["skeleton"]
_clips = b["clips"]
ok = _build() and ok
quit(0 if ok else 1)
@ -41,10 +83,10 @@ func _build() -> bool:
var sources := {} # file -> instantiated scene root (freed at the end)
var dropped := 0
var ok := true
for clip: String in CLIPS:
var file: String = CLIPS[clip][0]
for clip: String in _clips:
var file: String = _clips[clip][0]
if not sources.has(file):
var scene := load(ANIM_DIR + file) as PackedScene
var scene := load(_anim_dir + file) as PackedScene
if scene == null:
push_error("missing animation file " + file)
ok = false
@ -58,36 +100,36 @@ func _build() -> bool:
var anim := player.get_animation(clip).duplicate(true) as Animation
for t in range(anim.get_track_count() - 1, -1, -1):
var path := anim.track_get_path(t)
var keep := String(path.get_concatenated_names()) == SKELETON_PATH \
var keep := String(path.get_concatenated_names()) == _skeleton \
and path.get_subname_count() == 1 and bones.has(String(path.get_subname(0)))
if not keep:
anim.remove_track(t)
dropped += 1
anim.loop_mode = Animation.LOOP_LINEAR if CLIPS[clip][1] else Animation.LOOP_NONE
anim.loop_mode = Animation.LOOP_LINEAR if _clips[clip][1] else Animation.LOOP_NONE
library.add_animation(clip, anim)
for file: String in sources:
(sources[file] as Node).free()
if not ok:
return false
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(OUTPUT.get_base_dir()))
var err := ResourceSaver.save(library, OUTPUT)
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(_output.get_base_dir()))
var err := ResourceSaver.save(library, _output)
if err != OK:
push_error("could not save %s (error %d)" % [OUTPUT, err])
push_error("could not save %s (error %d)" % [_output, err])
return false
print("saved %s: %d clips, %d foreign tracks dropped" % [OUTPUT, library.get_animation_list().size(), dropped])
print("saved %s: %d clips, %d foreign tracks dropped" % [_output, library.get_animation_list().size(), dropped])
return true
func _mannequin_bones() -> Dictionary:
var scene := load(MANNEQUIN) as PackedScene
var scene := load(_mannequin) as PackedScene
if scene == null:
push_error("missing mannequin " + MANNEQUIN)
push_error("missing mannequin " + _mannequin)
return {}
var root := scene.instantiate()
var skel := root.get_node_or_null(SKELETON_PATH) as Skeleton3D
var skel := root.get_node_or_null(_skeleton) as Skeleton3D
var bones := {}
if skel == null:
push_error("mannequin skeleton not found at " + SKELETON_PATH)
push_error("mannequin skeleton not found at " + _skeleton)
else:
for b in skel.get_bone_count():
bones[skel.get_bone_name(b)] = true

View file

@ -0,0 +1,10 @@
extends SceneTree
## Writes the game's UI theme (UiTheme.build()) to res://game/resources/ui_theme.tres, the
## project's default theme (gui/theme/custom). Re-run after editing UiTheme (editor closed):
## godot --headless --path . --script res://game/tools/build_ui_theme.gd
func _initialize() -> void:
var err := ResourceSaver.save(UiTheme.build(), "res://game/resources/ui_theme.tres")
print("build_ui_theme: save -> %s" % error_string(err))
quit(0 if err == OK else 1)

View file

@ -0,0 +1 @@
uid://v7qxh2v2w8q3

View file

@ -0,0 +1,72 @@
extends SceneTree
## Writes the game's InputMap actions into project.godot (the prototype's actions, set by
## prototype/tools/configure_project.gd, are left as they are). Idempotent: re-running replaces
## only these actions. Run with the editor closed:
## godot --headless --path . --script res://game/tools/configure_input.gd
##
## | Action | Keyboard / mouse | Gamepad | Used from |
## |--------------|------------------|----------------|-----------|
## | fear | Q | Left shoulder | Step 4 |
## | patch (hold) | F | Y | Step 4 |
## | interact | E | X | Step 5 |
## | build_mode | B | D-pad up | Step 6 |
## | rotate_left | Z | D-pad left | Step 6 |
## | rotate_right | C | D-pad right | Step 6 |
## | build_next | Tab | D-pad down | Step 6 |
## | build_1..4 | 1, 2, 3, 4 | - | Step 6 |
## | cancel | Right mouse | B | Step 6 |
## | pause | Escape | Start | Step 11 |
## | hide_tips | Backspace | Back | Step 11 |
## | toggle_mic | M | - | Co-op |
## | sprint (hold)| Shift | L3 (stick) | Sprint |
## | weapon_next | Tab | D-pad down | Weapons |
## | weapon_1..3 | 1, 2, 3 | - | Weapons |
## The weapon keys are build mode's (build_next, build_1..3): outside build mode they pick weapons.
func _initialize() -> void:
_action("fear", [_key(KEY_Q), _joy(JOY_BUTTON_LEFT_SHOULDER)])
_action("patch", [_key(KEY_F), _joy(JOY_BUTTON_Y)])
_action("interact", [_key(KEY_E), _joy(JOY_BUTTON_X)])
_action("build_mode", [_key(KEY_B), _joy(JOY_BUTTON_DPAD_UP)])
_action("rotate_left", [_key(KEY_Z), _joy(JOY_BUTTON_DPAD_LEFT)])
_action("rotate_right", [_key(KEY_C), _joy(JOY_BUTTON_DPAD_RIGHT)])
_action("build_next", [_key(KEY_TAB), _joy(JOY_BUTTON_DPAD_DOWN)])
var number_keys: Array[Key] = [KEY_1, KEY_2, KEY_3, KEY_4]
for i in 4:
_action("build_%d" % (i + 1), [_key(number_keys[i])])
_action("cancel", [_mouse(MOUSE_BUTTON_RIGHT), _joy(JOY_BUTTON_B)])
_action("pause", [_key(KEY_ESCAPE), _joy(JOY_BUTTON_START)])
_action("hide_tips", [_key(KEY_BACKSPACE), _joy(JOY_BUTTON_BACK)])
_action("toggle_mic", [_key(KEY_M)])
_action("sprint", [_key(KEY_SHIFT), _joy(JOY_BUTTON_LEFT_STICK)])
_action("weapon_next", [_key(KEY_TAB), _joy(JOY_BUTTON_DPAD_DOWN)])
for i in 3:
_action("weapon_%d" % (i + 1), [_key(number_keys[i])])
var err := ProjectSettings.save()
print("configure_input: save -> %s" % error_string(err))
quit(0 if err == OK else 1)
func _action(action_name: String, events: Array[InputEvent]) -> void:
for e in events:
e.device = -1 # all devices, matching events created in the editor
ProjectSettings.set_setting("input/" + action_name, {"deadzone": 0.5, "events": events})
func _key(code: Key) -> InputEventKey:
var e := InputEventKey.new()
e.physical_keycode = code
return e
func _mouse(button: MouseButton) -> InputEventMouseButton:
var e := InputEventMouseButton.new()
e.button_index = button
return e
func _joy(button: JoyButton) -> InputEventJoypadButton:
var e := InputEventJoypadButton.new()
e.button_index = button
return e

View file

@ -0,0 +1 @@
uid://b6hxj4xpi5h2a

160
game/tools/coop_smoke.gd Normal file
View file

@ -0,0 +1,160 @@
extends SceneTree
## Co-op over real GD-Sync (LAN mode, peer to peer on this machine): run two of these at once,
## a host and a partner. Each loads the game (main.tscn, with its own save and settings files),
## the host starts a vacation and opens a lobby, the partner finds it on the network and joins,
## and both play a day and a night with enemies. Each prints what it saw and exits 0 when it
## all checked out:
## godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=host &
## godot --headless --path . --script res://game/tools/coop_smoke.gd -- --role=join
## Options: --seconds=N how long to play once joined (default 20); --discover makes the partner
## find the host by GD-Sync's LAN announcements (broadcast) instead of joining by address
## (127.0.0.1), for networks where broadcasts reach this machine. --online plays over GD-Sync's
## servers instead (needs the API keys): the partner finds the host's lobby in the online list.
## --host-name=Ana names the host (and so its lobby, "Ana's farm"); give both sides the same one.
var role := "host"
var seconds := 20.0
var discover := false
var online := false
var host_name := "Ana"
## --shot=path: a screenshot at night with the enemies in (needs a window, not --headless).
var shot := ""
var main: Main
var failures: Array[String] = []
func _initialize() -> void:
for a in OS.get_cmdline_user_args():
if String(a).begins_with("--role="):
role = String(a).trim_prefix("--role=")
elif String(a).begins_with("--shot="):
shot = String(a).trim_prefix("--shot=")
elif String(a) == "--discover":
discover = true
elif String(a) == "--online":
online = true
elif String(a).begins_with("--host-name="):
host_name = String(a).trim_prefix("--host-name=")
elif String(a).begins_with("--seconds="):
seconds = float(String(a).trim_prefix("--seconds="))
_run.call_deferred()
func _say(text: String) -> void:
print("[%s %6.2f] %s" % [role, Time.get_ticks_msec() / 1000.0, text])
func _check(ok: bool, what: String) -> void:
_say(("OK " if ok else "FAIL ") + what)
if not ok:
failures.append(what)
func _run() -> void:
main = (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
main.save_path = "user://coop_smoke_%s_save.json" % role
main.settings_path = "user://coop_smoke_%s_settings.cfg" % role
root.add_child(main)
current_scene = main # as in the game: GD-Sync looks at the current scene
await process_frame
await process_frame
var lobby := main.lobby
var sim := main.sim
lobby.failed.connect(func(t: String) -> void: _say("lobby failed: " + t))
lobby.status_changed.connect(func(t: String) -> void:
if t != "":
_say("lobby: " + t))
if role == "host":
main.new_vacation()
lobby.host(CoopLobby.Mode.ONLINE if online else CoopLobby.Mode.LAN, host_name)
if not await _wait(func() -> bool: return sim.coop.is_host(), 60.0):
_check(false, "a partner joined within 60 s")
await _finish()
return
_check(true, "a partner joined: %s" % sim.coop.partner_name)
await _wait(func() -> bool: return false, 3.0)
sim.campaign.begin_day()
await _wait(func() -> bool: return false, 2.0)
sim.campaign.advance_phase()
sim.campaign.advance_phase()
for i in 24:
sim.spawn_enemy([EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER][i % 3])
await _wait(func() -> bool: return false, 8.0)
await _screenshot()
await _wait(func() -> bool: return false, seconds - 8.0)
_check(sim.partner != null and sim.partner.body.global_position.distance_to(Vector3(-4.0, 0.0, -2.0)) < 1.0,
"P2 walked where the partner moved it, twice (%s)" % [sim.partner.body.global_position if sim.partner != null else "gone"])
_check(sim.partner != null and sim.partner.combat.attacks() > 0, "P2's weapon attacked on the host (%d attacks)" % (sim.partner.combat.attacks() if sim.partner != null else 0))
_check(sim.campaign.state.coop, "co-op is on in the farm state")
_say("waiting for the partner to finish")
await _wait(func() -> bool: return not sim.coop.is_active(), 30.0)
_check(not sim.coop.is_active() and sim.partner == null, "the partner left; the host plays on alone")
else:
if discover or online:
var want := "%s's farm" % host_name
lobby.search(CoopLobby.Mode.ONLINE if online else CoopLobby.Mode.LAN, "Ben")
var found: Array = []
lobby.lobbies_found.connect(func(list: Array) -> void:
found.assign(list.filter(func(l: Dictionary) -> bool: return String(l["name"]) == want)))
if not await _wait(func() -> bool: return not found.is_empty(), 40.0):
_check(false, "found the host's game \"%s\" %s within 40 s" % [want, "online" if online else "on the network"])
await _finish()
return
_check(true, "found %s %s" % [found[0]["name"], "online" if online else "on the network"])
lobby.join(String(found[0]["name"]))
else:
lobby.join_address("127.0.0.1", "Ben")
if not await _wait(func() -> bool: return sim.coop.is_client() and sim.coop._is_welcomed, 40.0):
_check(false, "joined and got the farm within 40 s")
await _finish()
return
_check(main.screen == Main.Screen.PLAYING and sim.replica and sim.local_avatar.slot == 1, "joined: playing P2 on a replica of the host's farm")
sim.player.global_position = Vector3(4.0, 0.0, -8.0)
await _wait(func() -> bool: return sim.campaign.state.phase == CampaignController.Phase.NIGHT, 30.0)
_check(sim.campaign.state.phase == CampaignController.Phase.NIGHT, "the host's nightfall reached the partner")
Input.action_press("fire")
await _wait(func() -> bool: return false, 4.0)
Input.action_release("fire")
await _wait(func() -> bool: return sim.enemies.alive_count() >= 10, 10.0)
_check(sim.enemies.alive_count() >= 10, "the host's enemies show on the partner's farm (%d)" % sim.enemies.alive_count())
_check(sim.coop.voices.size() == 2, "voice chat is set up (a VoiceChat per player)")
sim.player.global_position = Vector3(-4.0, 0.0, -2.0) # off the host's screen: the arrow
await _wait(func() -> bool: return false, 2.0)
await _screenshot()
await _wait(func() -> bool: return false, seconds - 4.0)
_say("leaving")
lobby.leave()
await _wait(func() -> bool: return false, 2.0)
_finish()
func _screenshot() -> void:
if shot == "":
return
await RenderingServer.frame_post_draw
root.get_texture().get_image().save_png(shot)
_say("screenshot " + shot)
## Waits up to timeout seconds for done() (real time); returns whether it happened.
func _wait(done: Callable, timeout: float) -> bool:
var t0 := Time.get_ticks_msec()
while Time.get_ticks_msec() - t0 < timeout * 1000.0:
if done.call():
return true
await process_frame
return bool(done.call())
func _finish() -> void:
_say("%s: %d failed" % ["PASS" if failures.is_empty() else "FAILURES", failures.size()])
for p in ["save.json", "settings.cfg"]:
var path := "user://coop_smoke_%s_%s" % [role, p]
if FileAccess.file_exists(path):
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
if is_instance_valid(main):
main.lobby.leave()
main.queue_free()
await process_frame
await create_timer(0.3).timeout
quit(failures.size())

View file

@ -0,0 +1 @@
uid://d21h7dqshp4j8

505
game/tools/soak_night.gd Normal file
View file

@ -0,0 +1,505 @@
extends SceneTree
## Plays whole nights headless against the night thief trickle with a scripted scarecrow and
## reports each night, as supporting evidence for Step 4's exit gate (the gate itself is a
## human playtest). Days are skipped; each night runs its full night_length plus the dawn grace.
## godot --headless --path . --script res://game/tools/soak_night.gd -- --mode=guard
## Options:
## --mode=cycle plays whole cycles: by day it gathers until GATHER_UNTIL, then puts a
## gate back in the pen opening if it's gone and builds BUILD_PLAN in order
## (what it can afford, walking to each site), and at night it guards (as
## --mode=guard) against the night's plan. Reports each cycle (per target)
## and checks that structures, materials, and health carry over.
## --cycles=3 sets how many (5 plays the whole vacation, one night plan
## each); --build=0 skips building, --guard=0 leaves the night to the
## defenses. With materials left after the plan it buys upgrades
## (UPGRADE_ORDER) at the workbench; --upgrades=0 skips them.
## --mode=gather plays one day instead: the scarecrow walks (along the navigation
## grid) to the nearest gather point with charges, holds interact until it
## is used up or the pouch is full, stores the pouch at the shed, and
## reports how long gathering everything takes and what it yields.
## --mode=idle | guard idle: the scarecrow stands in the open doing nothing (baseline).
## guard: it goes for the most urgent threat (carriers, then thieves
## taking something, then dropped loot and loose animals, then other
## thieves), attacks thieves in range with a clear line with its best
## weapon (a pumpkin bomb into a crowd, the corn shooter once bought, else
## the pitchfork, closing in to stab), uses fear on a
## carrier or a crowd in range, leads animals following it back to the pen
## when no carrier is close, and patches up when hurt and nothing is close.
## --minutes=10 night time to play (rounded up to whole nights)
## --thieves=1 GameConfig.night_thieves (at most this many at once)
## --seed=1 randomizes thief targets and arrival points
const DT := 1.0 / 60.0
const GATHER_UNTIL := 115.0
## The scripted scarecrow's defenses, in order: automated defenses around the crop field's
## corners, slowing traps on the approaches, then fences down the field's east side.
const BUILD_PLAN := [
["automated_defense", Vector2(46.0, -15.0), 0],
["automated_defense", Vector2(34.0, 12.5), 0],
["slowing_trap", Vector2(43.5, -17.0), 0],
["automated_defense", Vector2(13.5, -15.0), 0],
["slowing_trap", Vector2(31.0, 11.5), 0],
["fence", Vector2(45.0, -15.5), 2], ["fence", Vector2(45.0, -13.5), 2], ["fence", Vector2(45.0, -11.5), 2],
["fence", Vector2(45.0, -9.5), 2], ["fence", Vector2(45.0, -7.5), 2], ["fence", Vector2(45.0, -5.5), 2],
["automated_defense", Vector2(13.5, 9.0), 0],
["automated_defense", Vector2(7.0, -3.5), 0],
["automated_defense", Vector2(9.5, -14.0), 0],
]
## The scripted scarecrow's upgrades, in order, bought with what's left after building.
const UPGRADE_ORDER: Array[String] = ["corn_shooter", "long_range", "rapid_fire", "heavy_seeds", "pumpkin_bomb",
"reinforced_fences", "quick_fear", "wide_fear", "sticky_tar", "straw_stuffing"]
const PEN_GATE := Vector2(4.0, -6.0)
const PEN_INSIDE := Vector2(-2.0, -6.0)
const HOME := Vector2(10.0, -8.0) # open ground between the pen, the shed, and the field
const SHOOT_RANGE := 11.0
var _sim: FarmSim
var _player: PlayerCharacter
var _mode := "guard"
var _fears: int = 0
var _shots: int = 0
func _initialize() -> void:
_run.call_deferred()
func _run() -> void:
var minutes := 10.0
var thieves := 1
var seed_value := 1
for a in OS.get_cmdline_user_args():
var arg := String(a)
if arg.begins_with("--mode="):
_mode = arg.trim_prefix("--mode=")
elif arg.begins_with("--minutes="):
minutes = float(arg.trim_prefix("--minutes="))
elif arg.begins_with("--thieves="):
thieves = int(arg.trim_prefix("--thieves="))
elif arg.begins_with("--seed="):
seed_value = int(arg.trim_prefix("--seed="))
var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
root.add_child(farm)
await process_frame
_sim = farm.get_node("FarmSim") as FarmSim
_sim.set_physics_process(false)
_player = farm.get_node("Player") as PlayerCharacter
_player.set_physics_process(false)
var c := _sim.campaign
var cfg := _sim.config
cfg.night_thieves = thieves
cfg.campaign_nights = 99
_sim.loot._rng.seed = seed_value
_sim.waves.rng.seed = seed_value
_player.global_position = Vector3(HOME.x, 0.0, HOME.y)
if _mode == "gather":
_gather_day()
_quit()
return
if _mode == "cycle":
var cycles := 3
for a in OS.get_cmdline_user_args():
if String(a).begins_with("--cycles="):
cycles = int(String(a).trim_prefix("--cycles="))
cfg.night_thieves = 0 # the night's plan
for a in OS.get_cmdline_user_args():
if String(a).begins_with("--thieves="):
cfg.night_thieves = int(String(a).trim_prefix("--thieves="))
for a in OS.get_cmdline_user_args():
if String(a) == "--build=0":
_do_build = false
elif String(a) == "--guard=0":
_do_guard = false
elif String(a) == "--upgrades=0":
_do_upgrades = false
_cycles(cycles)
_quit()
return
var nights := ceili(minutes * 60.0 / cfg.night_length)
print("soak: mode=%s, %d nights of %.0f s + %.0f s dawn, night_thieves=%d, seed=%d" % [
_mode, nights, cfg.night_length, cfg.dawn_grace, thieves, seed_value])
print("| Night | Stolen | Recovered | Lost | Crops left | Scarecrow HP | Fears | Attacks | Kills |")
print("|---|---|---|---|---|---|---|---|---|")
var t0 := Time.get_ticks_msec()
for n in nights:
c.begin_day()
c.advance_phase()
c.advance_phase()
var kills0 := _sim.enemies.kills
var fears0 := _fears
var shots0 := _shots
while c.state.phase != CampaignController.Phase.MORNING and not c.is_over():
if _mode == "guard":
_guard()
_sim.step(DT)
if c.is_over():
print("| %d | campaign over: %s |" % [c.state.night, CampaignController.Outcome.keys()[c.outcome]])
break
var e: Dictionary = c.state.night_log[c.state.night_log.size() - 1]
print("| %d | %d | %d | %d | %d/%d | %d/%d | %d | %d | %d |" % [e["night"], e["crops_stolen"], e["crops_recovered"],
e["crops_lost"], c.state.crops, c.state.crops_total, c.state.scarecrow_hp, c.state.scarecrow_max_hp,
_fears - fears0, _shots - shots0, _sim.enemies.kills - kills0])
Input.action_release("patch")
print("soak: %.1f s of wall time" % ((Time.get_ticks_msec() - t0) / 1000.0))
_quit()
## Frees the farm, then quits once the audio server has dropped its stopped sounds.
func _quit() -> void:
for n in root.get_children():
n.queue_free()
await process_frame
await create_timer(0.25).timeout
quit()
var _fields := {}
var _built := {} # BUILD_PLAN index -> true
var _do_build := true
var _do_guard := true
var _do_upgrades := true
var _carry_errors: Array[String] = []
func _cycles(n: int) -> void:
var c := _sim.campaign
var s := c.state
print("soak cycle: %d cycles, night plan '%s' (%d thieves), gather until %.0f s, build %s, guard %s" % [
n, _sim.waves.tonight().title, _sim.waves.tonight().total(), GATHER_UNTIL, _do_build, _do_guard])
print("| Night | Gathered | Built (total) | Upgrades | Crops: stolen / recovered / lost | Animals: grabbed / out / led back / lost | Supplies: taken / back / lost | Left | HP | Broken | Shed after |")
print("|---|---|---|---|---|---|---|---|---|---|")
var lost_by := {}
_sim.loot.loot_event.connect(func(kind: StringName, id: int, _p: Vector3) -> void:
if kind == &"lost" and _sim.loot.category[id] == LootSystem.Category.SUPPLY:
lost_by[_sim.loot.sack_material[id]] = int(lost_by.get(_sim.loot.sack_material[id], 0)) + _sim.loot.sack_amount[id])
var t0 := Time.get_ticks_msec()
for k in n:
if c.is_over():
break
var shed0: Dictionary = s.resources.shed.duplicate()
var built0 := _sim.structures.count()
var gathered := {"wood": 0, "scrap": 0, "straw": 0}
var cb := func(m: String, amount: int, _node: GatherNode) -> void: gathered[m] += amount
_sim.interactions.gathered.connect(cb)
c.begin_day()
var t := 0.0
while c.is_daytime():
var me := Vector2(_player.global_position.x, _player.global_position.z)
if not (t < GATHER_UNTIL and _gather_tick(me)):
Input.action_release("interact")
if _do_build:
_build_tick(me)
else:
_walk_field(Vector2(30.0, -3.0), me)
_sim.step(DT)
t += DT
Input.action_release("interact")
_sim.interactions.gathered.disconnect(cb)
# Night: guard. Record what should carry over.
var breaks: Array[int] = [] # a lambda can't add to a captured int
var cb2 := func(_i: int, _t: String, _at: Vector3) -> void: breaks.append(1)
_sim.structures.destroyed.connect(cb2)
var built_night := _sim.structures.count()
var res_night: Dictionary = s.resources.to_dict()
lost_by.clear()
var fears0 := _fears
if not _do_guard:
_player.global_position = Vector3(HOME.x, 0.0, HOME.y)
while s.phase != CampaignController.Phase.MORNING and not c.is_over():
if _do_guard:
_guard()
_sim.step(DT)
_sim.structures.destroyed.disconnect(cb2)
var broken := breaks.size()
Input.action_release("patch")
if c.is_over():
print("| %d | campaign over: %s |" % [k + 1, CampaignController.Outcome.keys()[c.outcome]])
break
# Carry-over checks: nothing is built at night, so structures only go down by breaks;
# wood and scrap only go down by what thieves carried off (straw also by patches).
if _sim.structures.count() != built_night - broken:
_carry_errors.append("cycle %d: %d structures at night - %d broken != %d in the morning" % [k + 1, built_night, broken, _sim.structures.count()])
var now := s.resources.to_dict()
for m in ["wood", "scrap"]:
var before := int(res_night["shed"][m]) + int(res_night["pouch"][m])
var after := int(now["shed"][m]) + int(now["pouch"][m])
if after != before - int(lost_by.get(m, 0)):
_carry_errors.append("cycle %d: %s %d -> %d overnight, %d carried off" % [k + 1, m, before, after, int(lost_by.get(m, 0))])
if s.supplies_in_transit != 0:
_carry_errors.append("cycle %d: %d supplies still in transit in the morning" % [k + 1, s.supplies_in_transit])
var e: Dictionary = s.night_log[s.night_log.size() - 1]
print("| %d %s | %s | %d (%d) | %d | %d / %d / %d | %d / %d / %d / %d | %d / %d / %d | %d crops, %d animals | %d/%d | %d | %s |" % [k + 1,
_sim.waves.plan_for(k + 1).title, ResourceStore.describe(gathered), built_night - built0, built_night, s.upgrades.size(),
e["crops_stolen"], e["crops_recovered"], e["crops_lost"],
e["animals_stolen"], e["animals_strayed"], e["animals_recovered"], e["animals_lost"], e["supplies_stolen"], e["supplies_recovered"],
e["supplies_lost"], s.crops, s.animals, s.scarecrow_hp, s.scarecrow_max_hp, broken, ResourceStore.describe(s.resources.shed)])
print("soak cycle: carry-over %s; %.1f s of wall time" % ["OK" if _carry_errors.is_empty() else "ERRORS %s" % [_carry_errors],
(Time.get_ticks_msec() - t0) / 1000.0])
## One gathering tick: walk to the nearest point with charges and gather, or store a full pouch.
## Returns false when nothing is left to gather or store.
func _gather_tick(me: Vector2) -> bool:
var it := _sim.interactions
var r := _sim.campaign.state.resources
var target: GatherNode = null
var best := INF
for n in it.nodes:
var d := Vector2(n.global_position.x, n.global_position.z).distance_to(me)
if it.charges(n) > 0 and d < best:
best = d
target = n
if target == null and r.pouch_total() == 0:
return false
if target == null or r.pouch_room() < target.yield_amount:
Input.action_release("interact")
var shed := _sim.zones.zone(FarmZone.Kind.SUPPLY_SHED)
_walk_field(Vector2(shed.global_position.x, shed.global_position.z + 3.0), me)
return true
if Vector2(target.global_position.x, target.global_position.z).distance_to(me) > target.reach - 0.1:
Input.action_release("interact")
_walk_field(_stand_spot(target), me)
else:
Input.action_press("interact")
return true
## One building tick: put a gate back in the pen opening if it's gone, else walk to the next
## BUILD_PLAN site it can afford and place it; otherwise wait in the middle of the crop field.
func _build_tick(me: Vector2) -> void:
var st := _sim.structures
var r := _sim.campaign.state.resources
if _sim.nav.structure_at[_sim.nav.cell_of(PEN_GATE.x, PEN_GATE.y)] < 0 and r.can_afford(_sim.config.costs["gate"]):
if PEN_GATE.distance_to(me) > 4.0:
_walk_field(PEN_GATE + Vector2(2.5, 0.0), me)
elif st.validate("gate", PEN_GATE.x, PEN_GATE.y, 2, me) == "":
st.place("gate", PEN_GATE.x, PEN_GATE.y, 2)
return
for i in BUILD_PLAN.size():
if _built.has(i):
continue
var part: Array = BUILD_PLAN[i]
if not r.can_afford(_sim.config.costs.get(part[0], {})):
continue
var at: Vector2 = part[1]
if at.distance_to(me) > 6.0:
_walk_field(at + Vector2(-2.0, 0.0), me)
return
var why := st.validate(part[0], at.x, at.y, part[2], me)
if why == "":
st.place(part[0], at.x, at.y, part[2])
else:
print("soak: can't build %s at %s: %s" % [part[0], at, why])
_built[i] = true # built, or impossible here: either way move on
return
if _do_upgrades and _upgrade_tick(me):
return
_walk_field(Vector2(30.0, -3.0), me)
## Walks to the workbench and buys the next upgrade it can afford. Returns false if there's none.
func _upgrade_tick(me: Vector2) -> bool:
var c := _sim.campaign
for id in UPGRADE_ORDER:
if Upgrades.blocker(c, id) != "":
continue
var bench := _sim.interactions.workbench
var at := Vector2(bench.global_position.x, bench.global_position.z)
if at.distance_to(me) > bench.reach - 0.3:
_walk_field(at, me)
else:
Upgrades.buy(c, id, _sim.structures)
return true
return false
func _gather_day() -> void:
var c := _sim.campaign
var it := _sim.interactions
var r := c.state.resources
var shed_start: Dictionary = r.shed.duplicate()
var shed := _sim.zones.zone(FarmZone.Kind.SUPPLY_SHED)
var drop_off := Vector2(shed.global_position.x, shed.global_position.z + 3.0)
c.begin_day()
var t := 0.0
var trips := 0
var walking := 0.0
var gathering := 0.0
var done_at := -1.0
while c.is_daytime():
var me := Vector2(_player.global_position.x, _player.global_position.z)
var target: GatherNode = null
var best := INF
for n in it.nodes:
var d := Vector2(n.global_position.x, n.global_position.z).distance_to(me)
if it.charges(n) > 0 and d < best:
best = d
target = n
if target == null and r.pouch_total() == 0:
done_at = t
break
var store := target == null or r.pouch_room() < target.yield_amount
if store:
Input.action_release("interact")
_walk_field(drop_off, me)
walking += DT
if r.pouch_total() == 0:
pass
else:
var at := Vector2(target.global_position.x, target.global_position.z)
if at.distance_to(me) > target.reach - 0.1:
Input.action_release("interact")
_walk_field(_stand_spot(target), me)
walking += DT
else:
Input.action_press("interact")
gathering += DT
var before := r.pouch_total()
_sim.step(DT)
if before > 0 and r.pouch_total() == 0:
trips += 1
t += DT
Input.action_release("interact")
var got := {}
for m in ResourceStore.MATERIALS:
got[m] = int(r.shed[m]) - int(shed_start[m])
print("gather: %s stored in %d trips; everything gathered and stored after %s (day %.0f s + dusk %.0f s)" % [
ResourceStore.describe(got), trips, ("%.0f s" % done_at) if done_at >= 0.0 else "the day ran out", _sim.config.day_length, _sim.config.dusk_length])
print("gather: %.0f s walking, %.0f s gathering" % [walking, gathering])
## The free spot closest to a gather point (where the bot stands to gather it).
func _stand_spot(n: GatherNode) -> Vector2:
var nav := _sim.nav
var c := Vector2(n.global_position.x, n.global_position.z)
var best := c
var best_d := INF
for cell in nav.free_cells_in(Rect2(c - Vector2.ONE * n.reach, Vector2.ONE * n.reach * 2.0)):
var d := nav.cell_center(cell).distance_to(c)
if d < best_d:
best_d = d
best = nav.cell_center(cell)
return best
## Walks along the navigation grid toward goal (one distance field per goal cell, cached).
func _walk_field(goal: Vector2, me: Vector2) -> void:
var nav := _sim.nav
var cell := nav.nearest_free(nav.cell_of(goal.x, goal.y))
if not _fields.has(cell):
_fields[cell] = nav.distance_field(PackedInt32Array([cell]))
var dir := PackedFloat32Array([0.0, 0.0])
if nav.flow_direction(_fields[cell], me.x, me.y, dir):
var next := me + Vector2(dir[0], dir[1]) * _player.run_speed * DT
_player.global_position = Vector3(next.x, 0.0, next.y)
func _guard() -> void:
var es := _sim.enemies
var loot := _sim.loot
var kit := _sim.scarecrow
var cfg := _sim.config
var me := Vector2(_player.global_position.x, _player.global_position.z)
# Most urgent threat: carriers, then thieves taking a crop, then dropped crops, then others.
var goal := HOME
var best := INF
var near := 0
var carrier_near := false
var nearest_thief := -1
var nearest_d := INF
for d in es.active_count:
if es.alive[d] == 0:
continue
var p := Vector2(es.pos_x[d], es.pos_z[d])
var dist := p.distance_to(me)
var urgency := dist
match es.state[d]:
ThiefBehavior.State.CARRY:
urgency -= 40.0
carrier_near = carrier_near or dist < cfg.fear_radius
ThiefBehavior.State.STEAL:
urgency -= 20.0
if urgency < best:
best = urgency
goal = p
if dist < cfg.fear_radius and es.state[d] != ThiefBehavior.State.FLEE:
near += 1
if dist < nearest_d and _sim.nav.line_clear(me.x, me.y, p.x, p.y):
nearest_d = dist
nearest_thief = d
for id in range(1, loot.item_count + 1):
if loot.status[id] == LootSystem.Status.DROPPED:
var at := loot.position_of(id)
var dist := at.distance_to(me) - 10.0
if loot.category[id] == LootSystem.Category.ANIMAL and loot.followers() >= cfg.max_following_animals:
continue
if dist < best:
best = dist
goal = at
# Lead followers home when no carrier is close.
if loot.followers() > 0 and best > -25.0:
goal = PEN_INSIDE
best = -25.0
var hurt := kit.hp() <= cfg.scarecrow_max_hp / 2
if hurt and nearest_d > 8.0:
Input.action_press("patch")
return
Input.action_release("patch")
if carrier_near or near >= 2:
if kit.use_fear() >= 0:
_fears += 1
if nearest_thief >= 0 and nearest_d < SHOOT_RANGE:
var target := Vector2(es.pos_x[nearest_thief], es.pos_z[nearest_thief])
var reach := _attack(target, me)
if nearest_d < reach:
return # hold ground and attack rather than walk into it
if _sim.combat.weapon == ScarecrowCombat.Weapon.PITCHFORK:
goal = target # close in to stab it
_walk_toward(goal, me)
## Attacks the thief at target with the best weapon owned: a pumpkin bomb into a crowd of three
## or more when one is ready, else the corn shooter, else the pitchfork (only within its reach).
## Returns the distance it holds ground at.
func _attack(target: Vector2, me: Vector2) -> float:
var c := _sim.combat
var cfg := _sim.config
var es := _sim.enemies
var crowd := 0
for d in es.active_count:
if es.alive[d] == 1 and Vector2(es.pos_x[d], es.pos_z[d]).distance_to(target) <= cfg.bomb_radius:
crowd += 1
var far := target.distance_to(me)
if crowd >= 3 and c.bomb_left == 0.0 and far >= cfg.bomb_min_range and far <= cfg.bomb_range and c.equip(ScarecrowCombat.Weapon.PUMPKIN_BOMB):
if c.attack_toward(target):
_shots += 1
if c.equip(ScarecrowCombat.Weapon.CORN_SHOOTER):
if c.attack_toward(target):
_shots += 1
return 3.0
c.equip(ScarecrowCombat.Weapon.PITCHFORK)
if far <= cfg.pitchfork_reach and c.attack_toward(target):
_shots += 1
return cfg.pitchfork_reach * 0.8
func _walk_toward(goal: Vector2, me: Vector2) -> void:
var inside := _sim.zones.playable.grow(-1.0) # the scarecrow can't leave the farm
goal = Vector2(clampf(goal.x, inside.position.x, inside.end.x), clampf(goal.y, inside.position.y, inside.end.y))
if not _sim.nav.line_clear(me.x, me.y, goal.x, goal.y, true) and goal.distance_to(me) > 2.0:
_walk_field((goal / 2.0).round() * 2.0, me) # around walls (gates and fences are no wall to it)
return
var to := goal - me
if to.length() < 0.5:
return
var step := to.normalized() * _player.run_speed * DT
var nav := _sim.nav
var next := me + step
if not nav.is_free(nav.cell_of(next.x, next.y)):
next = Vector2(me.x + step.x, me.y) if nav.is_free(nav.cell_of(me.x + step.x, me.y)) else Vector2(me.x, me.y + step.y)
if not nav.is_free(nav.cell_of(next.x, next.y)):
var side := Vector2(-step.y, step.x) # boxed in: sidestep
next = me + side
if not nav.is_free(nav.cell_of(next.x, next.y)):
return
_player.global_position = Vector3(next.x, 0.0, next.y)

View file

@ -0,0 +1 @@
uid://br30toryks4ty

302
game/tools/synth_audio.gd Normal file
View file

@ -0,0 +1,302 @@
extends SceneTree
## Synthesizes the sounds the Kenney CC0 packs don't have (assets/audio/kenney/) into
## assets/audio/synth/ as 16-bit mono WAV files, deterministically (fixed seeds):
## day_ambience.wav 24 s loop: soft wind, rustling leaves, birdsong
## night_ambience.wav 24 s loop: low wind, three crickets, an owl
## crow_caw_1/2.wav a crow's caw (arrivals), crow_squawk.wav (a crow shot down)
## truck_engine.wav 2 s loop: the farmers' truck idling / driving
## truck_horn.wav beep-beep (the farmers are home)
## pitchfork_whoosh.wav a quick swish through the air (a stab)
## pumpkin_boom.wav a deep thump, a burst of noise, and a wet splat (a pumpkin bomb)
## Loops carry a WAV 'smpl' loop point, so the importer's "Detect From WAV" loops them; every
## periodic part of a loop has a whole number of cycles in it and filtered noise is warmed up
## on the loop's own tail, so the seam is silent. Run with the editor closed, then let the
## editor import the files:
## godot --headless --path . --script res://game/tools/synth_audio.gd
const RATE := 22050
const OUT := "res://assets/audio/synth/"
var _rng := RandomNumberGenerator.new()
func _initialize() -> void:
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(OUT))
_rng.seed = 7
_write("day_ambience.wav", _day(24.0), true)
_rng.seed = 11
_write("night_ambience.wav", _night(24.0), true)
_rng.seed = 3
_write("crow_caw_1.wav", _caw(0.46, 560.0, 470.0, 1), false)
_write("crow_caw_2.wav", _caw(0.62, 640.0, 520.0, 2), false)
_write("crow_squawk.wav", _caw(0.2, 820.0, 610.0, 1), false)
_rng.seed = 5
_write("truck_engine.wav", _engine(2.0), true)
_write("truck_horn.wav", _horn(), false)
_rng.seed = 13
_write("pitchfork_whoosh.wav", _whoosh(0.22), false)
_write("pumpkin_boom.wav", _boom(0.9), false)
quit(0)
# --- Pieces -----------------------------------------------------------------------------------
## White noise through two one-pole low-passes, warmed up on the buffer's own tail so the start
## continues the end (seamless when looped).
func _noise_lowpass(n: int, cutoff: float) -> PackedFloat32Array:
var white := PackedFloat32Array()
white.resize(n)
for i in n:
white[i] = _rng.randf_range(-1.0, 1.0)
var a := exp(-TAU * cutoff / RATE)
var y1 := 0.0
var y2 := 0.0
var out := PackedFloat32Array()
out.resize(n)
for pass_i in 2:
for i in n:
y1 = a * y1 + (1.0 - a) * white[i]
y2 = a * y2 + (1.0 - a) * y1
if pass_i == 1:
out[i] = y2
return _normalize(out, 1.0)
func _normalize(buf: PackedFloat32Array, peak: float) -> PackedFloat32Array:
var top := 0.0
for v in buf:
top = maxf(top, absf(v))
if top > 0.0:
for i in buf.size():
buf[i] *= peak / top
return buf
## Adds a tone with a frequency glide and an envelope into buf at t0 (wrapping around the end).
func _tone(buf: PackedFloat32Array, t0: float, length: float, f0: float, f1: float, amp: float,
vibrato: float = 0.0, harmonics: PackedFloat32Array = PackedFloat32Array([1.0])) -> void:
var n := buf.size()
var count := int(length * RATE)
var phase := 0.0
var start := int(t0 * RATE)
for k in count:
var u := float(k) / count
var f := lerpf(f0, f1, u) * (1.0 + vibrato * sin(TAU * 6.0 * k / RATE))
phase += f / RATE
var env := sin(PI * u)
env *= env
var s := 0.0
for h in harmonics.size():
s += harmonics[h] * sin(TAU * phase * (h + 1))
buf[(start + k) % n] += amp * env * s
# --- Loops ------------------------------------------------------------------------------------
func _day(seconds: float) -> PackedFloat32Array:
var n := int(seconds * RATE)
var wind := _noise_lowpass(n, 480.0)
var leaves := _noise_lowpass(n, 2600.0)
var leaves_low := _noise_lowpass(n, 900.0)
var buf := PackedFloat32Array()
buf.resize(n)
for i in n:
var t := float(i) / n # 0..1 over the loop: whole cycles only
var gust := 0.55 + 0.45 * (0.5 + 0.5 * sin(TAU * 2.0 * t + 0.7)) * (0.7 + 0.3 * sin(TAU * 5.0 * t))
var rustle := 0.3 + 0.7 * pow(0.5 + 0.5 * sin(TAU * 7.0 * t + 1.9), 3.0)
buf[i] = 0.07 * gust * wind[i] + 0.025 * rustle * (leaves[i] - leaves_low[i])
var t := 0.6
while t < seconds:
_bird(buf, t)
t += _rng.randf_range(1.6, 3.8)
return _normalize(buf, 0.5)
func _bird(buf: PackedFloat32Array, t0: float) -> void:
var amp := _rng.randf_range(0.05, 0.12)
match _rng.randi_range(0, 2):
0: # rising chirps
var f := _rng.randf_range(2800.0, 3400.0)
for k in _rng.randi_range(3, 5):
_tone(buf, t0 + k * 0.11, 0.07, f, f * 1.35, amp)
1: # two-note whistle
var f := _rng.randf_range(2200.0, 2700.0)
_tone(buf, t0, 0.2, f, f * 1.02, amp, 0.01)
_tone(buf, t0 + 0.26, 0.24, f * 0.8, f * 0.78, amp, 0.01)
_: # trill
var f := _rng.randf_range(4600.0, 5400.0)
for k in 10:
_tone(buf, t0 + k * 0.04, 0.025, f, f * 0.95, amp * 0.7)
func _night(seconds: float) -> PackedFloat32Array:
var n := int(seconds * RATE)
var wind := _noise_lowpass(n, 320.0)
var buf := PackedFloat32Array()
buf.resize(n)
for i in n:
var t := float(i) / n
buf[i] = 0.05 * (0.6 + 0.4 * sin(TAU * 3.0 * t + 0.3)) * wind[i]
# Crickets: (carrier Hz, chirps per loop, level). A chirp is 3 short pulses.
var crickets := [[4400.0, 50, 0.07], [4800.0, 39, 0.05], [5150.0, 44, 0.04]]
for c: Array in crickets:
var period := seconds / int(c[1])
var offset := _rng.randf_range(0.0, period)
for k in int(c[1]):
var swell := 0.7 + 0.3 * sin(TAU * 2.0 * k / int(c[1]) + offset)
for p in 3:
_tone(buf, offset + k * period + p * 0.032, 0.016, c[0], c[0] * 0.99, c[2] * swell)
for at in [6.0, 17.5]: # the owl: hoo ... hoo-hoo
var h := PackedFloat32Array([1.0, 0.18, 0.05])
_tone(buf, at, 0.42, 410.0, 380.0, 0.08, 0.004, h)
_tone(buf, at + 0.75, 0.22, 400.0, 385.0, 0.065, 0.004, h)
_tone(buf, at + 1.05, 0.38, 395.0, 360.0, 0.07, 0.004, h)
return _normalize(buf, 0.45)
func _engine(seconds: float) -> PackedFloat32Array:
var n := int(seconds * RATE)
var rumble := _noise_lowpass(n, 180.0)
var buf := PackedFloat32Array()
buf.resize(n)
var f := 42.0 # 84 cycles in 2 s
for i in n:
var t := float(i) / RATE
var s := 0.0
for h in range(1, 9):
s += sin(TAU * f * h * t) / h
var throb := 0.8 + 0.2 * sin(TAU * 7.0 * t) # 14 cycles in 2 s
buf[i] = throb * (0.5 * s + 0.6 * rumble[i])
return _normalize(buf, 0.6)
# --- One-shots --------------------------------------------------------------------------------
## A crow: a harmonic-rich glide shaped by two formants, roughened by fast random amplitude
## wobble, with breathy noise; caws = how many in a row.
func _caw(length: float, f_start: float, f_end: float, caws: int) -> PackedFloat32Array:
var one := int(length * RATE)
var gap := int(0.09 * RATE)
var n := one * caws + gap * (caws - 1)
var buf := PackedFloat32Array()
buf.resize(n)
var breath := _noise_lowpass(n, 3000.0)
var breath_low := _noise_lowpass(n, 900.0)
for c in caws:
var start := c * (one + gap)
var phase := 0.0
var rough := 1.0
var shift := 1.0 - 0.06 * c
for k in one:
var u := float(k) / one
var f := lerpf(f_start, f_end, pow(u, 0.7)) * shift
phase += f / RATE
if k % 160 == 0:
rough = _rng.randf_range(0.45, 1.0)
var s := 0.0
for h in range(1, 13):
var hf := f * h
var formant := exp(-pow((hf - 1350.0) / 420.0, 2.0)) + 0.6 * exp(-pow((hf - 2500.0) / 600.0, 2.0)) + 0.12
s += formant / pow(h, 0.6) * sin(TAU * phase * h)
var env := minf(u / 0.04, 1.0) * (1.0 if u < 0.6 else exp(-(u - 0.6) * 9.0))
buf[start + k] = env * (rough * s + 0.5 * (breath[start + k] - breath_low[start + k]))
return _normalize(buf, 0.8)
## Noise swept through a resonant band that rises then falls, swelling and fading.
func _whoosh(length: float) -> PackedFloat32Array:
var n := int(length * RATE)
var white := PackedFloat32Array()
white.resize(n)
for i in n:
white[i] = _rng.randf_range(-1.0, 1.0)
var buf := PackedFloat32Array()
buf.resize(n)
var low := 0.0
var band := 0.0
for i in n:
var u := float(i) / n
var f := lerpf(500.0, 2400.0, sin(PI * pow(u, 0.7))) # the band's center
var q := 0.12
var w := TAU * f / RATE
# State-variable band-pass.
var high := white[i] - low - q * band
band += w * high
low += w * band
buf[i] = band * pow(sin(PI * u), 1.5)
return _normalize(buf, 0.7)
## A pumpkin bursting: a low sine thump dropping in pitch, a burst of low-passed noise, and a
## short splat of brighter noise just after.
func _boom(length: float) -> PackedFloat32Array:
var n := int(length * RATE)
var rumble := _noise_lowpass(n, 260.0)
var splat := _noise_lowpass(n, 2200.0)
var buf := PackedFloat32Array()
buf.resize(n)
var phase := 0.0
for i in n:
var t := float(i) / RATE
phase += lerpf(95.0, 38.0, minf(t / 0.35, 1.0)) / RATE
var attack := minf(t / 0.006, 1.0)
var thump := sin(TAU * phase) * exp(-t * 7.0)
var crack := rumble[i] * exp(-t * 5.5)
var wet := splat[i] * exp(-maxf(t - 0.03, 0.0) * 16.0) * (1.0 if t > 0.03 else 0.0)
buf[i] = attack * (1.0 * thump + 0.9 * crack + 0.35 * wet)
return _normalize(buf, 0.85)
func _horn() -> PackedFloat32Array:
var n := int(0.9 * RATE)
var buf := PackedFloat32Array()
buf.resize(n)
for beep in [[0.0, 0.3], [0.42, 0.34]]:
var start := int(beep[0] * RATE)
var count := int(beep[1] * RATE)
for k in count:
var t := float(k) / RATE
var env := minf(minf(t / 0.012, 1.0), minf((beep[1] - t) / 0.03, 1.0))
var s := 0.0
for f in [410.0, 520.0]:
for h in [1, 3, 5, 7]:
s += sin(TAU * f * h * t) / h
buf[start + k] = env * s
return _normalize(buf, 0.7)
# --- WAV --------------------------------------------------------------------------------------
func _write(file: String, buf: PackedFloat32Array, loop: bool) -> void:
var frames := buf.size()
var data := PackedByteArray()
data.resize(frames * 2)
for i in frames:
data.encode_s16(i * 2, clampi(roundi(buf[i] * 32767.0), -32768, 32767))
var smpl := PackedByteArray()
if loop:
smpl.resize(60)
var fields := [0, 0, int(1e9 / RATE), 60, 0, 0, 0, 1, 0, 0, 0, 0, frames - 1, 0, 0]
for i in fields.size():
smpl.encode_u32(i * 4, fields[i])
var f := FileAccess.open(OUT + file, FileAccess.WRITE)
f.store_buffer("RIFF".to_ascii_buffer())
f.store_32(4 + (8 + 16) + ((8 + smpl.size()) if loop else 0) + 8 + data.size())
f.store_buffer("WAVE".to_ascii_buffer())
f.store_buffer("fmt ".to_ascii_buffer())
f.store_32(16)
f.store_16(1) # PCM
f.store_16(1) # mono
f.store_32(RATE)
f.store_32(RATE * 2)
f.store_16(2)
f.store_16(16)
if loop:
f.store_buffer("smpl".to_ascii_buffer())
f.store_32(smpl.size())
f.store_buffer(smpl)
f.store_buffer("data".to_ascii_buffer())
f.store_32(data.size())
f.store_buffer(data)
f.close()
print("synth_audio: %s %.2f s%s" % [file, float(frames) / RATE, " (loop)" if loop else ""])

View file

@ -0,0 +1 @@
uid://smhouv51mdjq