diff --git a/README.md b/README.md index 1400fe6..7b849a4 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,21 @@ pack (`assets/farm/ithappy/farm/prefabs/assets/`). (`example_morning_day_2.tres`, the Scarecrow and a Little Green Alien) uses the HUD's painted icons as placeholder portraits (`DialogueSpeaker.icon`) until real pictures are set. +* **The opening intro** — every New vacation opens with a cutscene, about 70 s (`OpeningIntro`, + `game/scripts/opening_intro.gd`): on a summer morning the farmers load up their station wagon + and drive off to the Bon Jovi concert; that night a bickering UFO crew loses control over the + farm, a glowing part falls off, and its blue flash brings the scarecrow to life (the faint blue + glow in its chest from then on); then a loading screen (`LoadingScreen`) and the first + morning's sign. Hold Space / Enter / A (or E, or the mouse button) for a second to skip it + (straight to the sign); Escape pauses it, and Restart the night skips it. Continue never plays + it, and hosting co-op skips it. Its lines are talking-head conversations in + `game/resources/dialogue/intro/` (`departure.tres`, `flight.tres`, `uh_oh.tres`; edit the lines + and speakers there: that folder never plays by itself), shown in the intro's own box, where + they go on by themselves and a tap hurries them. It shares the car, the farmers, and the camera + moves with the ending (`CutsceneKit`). Its staging points are in + [`game/LAYOUT.md`](game/LAYOUT.md). To review it shot by shot, `game/tools/capture_intro.gd` + saves a frame at every stage (its header has the command). + * **Menus and saving** — `Main` (`game/scripts/main.gd`, `game/scenes/main.tscn`) hosts the farm under the menus. `MainMenu` is the title screen (Continue, New vacation, Settings, Quit) over the paused farm, with a camera circling it. `PauseMenu` (Escape / Start) pauses the whole tree @@ -316,6 +331,7 @@ pack (`assets/farm/ithappy/farm/prefabs/assets/`). | Pause / resume | Escape | Start | | Hide the tips | Backspace | Back | | Mute / unmute your microphone (co-op) | M | - | +| Skip the opening intro (hold 1 s) | Space, Enter, E, or left mouse | A, X, or right trigger | | Skip the farmers' return | Space, Enter, E, or click | A or X | | Menus and end screens | Click, arrows + Enter, Escape to go back | D-pad + A, B to go back | @@ -610,8 +626,8 @@ damaged, rule-breaking, non-morning, newer, and too-old saves refused with a rea save upgraded, the autosave every morning, retry restoring the saved morning, the save deleted when the vacation is finished, settings saved, loaded, clamped, and applied (bus volumes, dead zones), and the final assessment's score, tiers, and renormalized weights. The flow suite plays -the game through `main.tscn`: the title screen over the paused farm, New vacation and Continue -(and their questions), pausing freezing the simulation tick, settings applying and saving from +the game through `main.tscn`: the title screen over the paused farm, New vacation (its intro +skipped) and Continue (and their questions), pausing freezing the simulation tick, settings applying and saving from the pause menu, Restart the night and Save & quit leaving the save untouched, a damaged save refused, the failure screens and Retry, the farmers' return to the final assessment (and skipping it), the first day's and night's tips, and the sounds hooked to the game. The co-op suite @@ -619,6 +635,12 @@ runs a host and a partner in one process (the partner's farm in its own world, o link): the join, the partner's requests, moves, gathering, and shots, enemies, loot, and shots arriving, the fall rule and Retry, a crowd with dropped packets and message sizes, and either side leaving. `game/tools/coop_smoke.gd` plays the same over real GD-Sync between two processes. +The intro suite plays the opening intro through `main.tscn`: New vacation starts it, and Continue +and hosting don't; stepped through, it visits every stage in order with the farm held (no sign, +no HUD, the scarecrow frozen on its post) and ends on the focused morning sign; and a skip from +every stage, holding to skip, Restart the night, and Save & quit during it each leave the farm +exactly as a new vacation's first morning (the scarecrow at its start with input and glow, the +light and sounds given back, the game camera, nothing of the intro left). Prototype: 107 checks, ~1.5 s. Covers pool acquire/release/exhaustion and swap identities, slot reuse hygiene and stale handles, U-shape routing, corner cutting, unreachable spawns, octile costs, diff --git a/game/LAYOUT.md b/game/LAYOUT.md index cfaa084..da4ad8a 100644 --- a/game/LAYOUT.md +++ b/game/LAYOUT.md @@ -264,6 +264,34 @@ Its largest slice stays about 3 ms. - **What to avoid:** the tractor parked east of the house (about (30, −25)) hides anything at the house's east side from the south-east. +## The opening intro (#33) + +`OpeningIntro` (`game/scripts/opening_intro.gd`) stages its shots on the same map: +- **The car** waits at the end of the ending's route, (32.8, −29.5), facing north (nose-out), and + drives the route backwards: north along the yard road, east out of GapDriveway (the horn), then + south down the road at x 52 to z 80, well past the map's south edge. +- **The farmers** come out of the front door, (19.6, −29.8). The farmer walks along z ≈ −31 to the + car's left door, (31.45, −29.95). The wife goes round the car's nose (z −33.7) to its right + door, (34.15, −29.95). +- **The departure shot** looks south over the yard from the north, (26.2, 13.5, −59), at + (26.2, 1, −30.5). The porch and the car stand side by side in the middle of the frame, clear of + the talking heads at its sides. The scrap heap's props between the camera and the yard are low + enough to look over. +- **The drive** follows behind the car until 6 m before the gap. Then the camera stops by + GapDriveway, at (46.8, 3, −43.6), and watches the car go south down the road. +- **The scarecrow's post** stands at the scarecrow's start, (3, −13). The scarecrow hangs 0.6 m up + on it, facing east over the crop field. It drops off 0.6 m in front of the post, which tips over + to its left. At the end it stands at its start again, facing north. +- **The UFO** comes from (125, 62, −150), bends over (70, 40, −40), and stops over the scarecrow at + (5, 19, −13). The part lands 0.8 m in front of the scarecrow. After the flash the UFO backs off to + (26, 15, −16), then leaves up and away to the east-north-east. +- **The night shots:** the flight and the wobble look up from the south-west, low, at + (−9, 1.5, 19), far enough off to see the saucer from the side. The drop and the flash look at + the scarecrow from the east (the barn behind it). The uh-oh and the escape look over the + scarecrow's right shoulder from behind it. +- **What to avoid:** the woodlot's trees block any view of the yard from the east, and the pen + (x −10…4, z −11…−1) is right under low cameras south-west of the scarecrow. + ## Outside the fence The scarecrow can leave through the fence's gaps or across the open south and west sides. The invisible walls (`Zones/Perimeter/PlayerBounds`) diff --git a/game/PLAYTEST.md b/game/PLAYTEST.md index eb4a24f..57f7a0d 100644 --- a/game/PLAYTEST.md +++ b/game/PLAYTEST.md @@ -396,3 +396,23 @@ so a whole vacation is about 3¼ hours, and losses still carry over. The nights, biggest step. - Rewrite the draft titles and hints of nights 6–29 (in the files, or in `make_nights.gd`'s lists followed by `--force`). + +## The opening intro (2026-10-07) + +New vacation now opens with a cutscene (#33, `OpeningIntro`); README has the story and LAYOUT.md +the staging. When nothing is skipped and no line is hurried, it lasts 69 s. The stages, in +seconds: leave 12.2, board 2.2, drive 12, card 3.6, flight 13, wobble 4, drop 2.6, flash 5.4, +uh-oh 7.1, escape 2.6, loading 4.1. `test_intro` checks that every stage plays in order, and +that a skip from any of them, Restart the night, or Save & quit leaves the farm exactly as a new +vacation's first morning. `game/tools/capture_intro.gd` saves a frame at each stage for the +timing review (#34). + +**For the playtest:** +- Watch it once from New vacation, all the way to the first morning's sign. +- Start another and hold Space / Enter / A partway through. Does it skip cleanly to the sign? Is + the hint ("Hold ... to skip", with its ring) easy to find? +- Tap through a few lines: do they hurry as expected, and do the shots still keep up? +- Press Escape mid-intro. Does the pause menu work over it, and does Restart the night take you + to the sign? +- Is anything important hidden behind the dialogue box? Is the UFO easy to read against the night + sky? diff --git a/game/RULES.md b/game/RULES.md index bf6426b..8a38528 100644 --- a/game/RULES.md +++ b/game/RULES.md @@ -545,6 +545,12 @@ shed counts as raided when a thief takes the last of its stock, and storing anyt ## Menus, pause, and settings - **Title screen:** Continue, New vacation, Settings, Quit, over the farm standing still. +- **The opening intro.** New vacation plays a cutscene (about 70 s) before the first morning's + sign: the farmers leave, and that night a UFO's lost part brings the scarecrow to life. Holding + Space / Enter / A (or E, or the mouse button) for a second skips it, straight to the sign. + Continue never plays it, and hosting co-op skips it. It changes nothing in the farm: the new + vacation is saved before it starts, so quitting during it continues at that morning without + it, and Restart the night during it skips it. Escape pauses it like the game. - **Pause** (Escape / Start, any phase) freezes the whole simulation: timers, enemies, shots, and game sounds. The menus and the ambience keep running. Its options are Resume, Restart the night, Settings, Save & quit to menu, and Quit the game. Restarting and quitting ask first, with diff --git a/game/scripts/dialogue_director.gd b/game/scripts/dialogue_director.gd index beb225a..aab3f27 100644 --- a/game/scripts/dialogue_director.gd +++ b/game/scripts/dialogue_director.gd @@ -10,6 +10,9 @@ extends Node ## starts while a menu is up (the shops, or Main's: DialogueBox.blocked) or the vacation is over, ## and a new morning (or a retry) takes down whatever was up. play() shows a conversation from ## code at any time; replay() (debug: F5) plays this phase's again. +## The opening intro (OpeningIntro) holds all of it: nothing starts while it's on screen (play() +## waits) and the sign stays down while it has the farm; at its end (intro_over()) night 1's +## morning conversations play, then the sign comes up. const DIR := "res://game/resources/dialogue/" @@ -73,9 +76,9 @@ func due(n: int, phase: CampaignController.Phase) -> Array[Conversation]: return out -## Shows conversation c now, or after the one that's up. +## Shows conversation c now, or after the one that's up (or the opening intro). func play(c: Conversation) -> void: - if is_playing(): + if is_playing() or _intro_busy(): _asked.append(c) return _played[c] = true @@ -98,6 +101,17 @@ func replay() -> void: play(c) +## Whether a conversation would start now (the intro keeps the sign down for it). +func has_due() -> bool: + return not _asked.is_empty() or (not _queue.is_empty() and _elapsed() >= _queue[0].delay) + + +## The opening intro is over: this morning's conversations now, then the sign. +func intro_over() -> void: + if not is_playing(): + _next() + + ## Takes down whatever is up and forgets what was due. func stop() -> void: _queue.clear() @@ -120,7 +134,7 @@ func _exit_tree() -> void: func _process(_delta: float) -> void: - if _queue.is_empty() or is_playing() or box.is_blocked() or sim.campaign.is_over() or sim._menu_open(): + if _queue.is_empty() or is_playing() or box.is_blocked() or sim.campaign.is_over() or sim._menu_open() or _intro_busy(): return if _elapsed() >= _queue[0].delay: play(_queue.pop_front()) @@ -146,6 +160,11 @@ func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Ph func _on_finished(_c: Conversation) -> void: _release() + _next() + + +## The next conversation (asked for, or due), or the sign. +func _next() -> void: if not _asked.is_empty(): play(_asked.pop_front()) elif not _queue.is_empty() and _elapsed() >= _queue[0].delay: @@ -155,10 +174,10 @@ func _on_finished(_c: Conversation) -> void: ## The morning sign steps aside while a conversation is up, and comes back (with the focus on -## Start the day) after it. +## Start the day) after it (not while the opening intro has the farm). func _sign(show: bool) -> void: var review := sim.review_panel if sim != null else null - if review == null: + if review == null or (show and sim.intro != null and sim.intro.running): return if show: review.refresh() @@ -167,6 +186,10 @@ func _sign(show: bool) -> void: review.mouse_filter = Control.MOUSE_FILTER_IGNORE +func _intro_busy() -> bool: + return sim != null and sim.intro != null and sim.intro.busy() + + ## Stops the farm for a conversation that pauses the game: the whole tree solo, this machine's ## scarecrow in co-op. func _hold(pause: bool) -> void: diff --git a/game/scripts/dialogue_speaker.gd b/game/scripts/dialogue_speaker.gd index 6f69ad7..e37a347 100644 --- a/game/scripts/dialogue_speaker.gd +++ b/game/scripts/dialogue_speaker.gd @@ -16,7 +16,8 @@ enum Align { SIDE, LEFT, CENTER, RIGHT } ## Optional mouth flaps: shown in turn with portrait while the words are being written. @export var talk_frames: Array[Texture2D] = [] ## Placeholder art while there's no portrait: one of Sketch.ICONS ("portrait" is the scarecrow, -## "thief" an alien, "breaker" a robot, "crow", "ufo"). +## "thief" an alien, "breaker" a robot, "crow", "ufo", "farmer" the farmer in his straw hat, +## "farmers_wife" the farmer's wife). @export var icon := "" @export var side: HeadSide = HeadSide.LEFT diff --git a/game/scripts/farm_audio.gd b/game/scripts/farm_audio.gd index 99e063d..afba47d 100644 --- a/game/scripts/farm_audio.gd +++ b/game/scripts/farm_audio.gd @@ -17,7 +17,9 @@ extends Node3D ## * 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 +## whistle, and the flash that brings the scarecrow to life. While it plays it holds the +## ambience and the music (set_scene: its morning, then its night) whatever the phase, and it +## stops new_campaign()'s morning stinger (stop_cue) to play it with the sign instead ## * 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. @@ -168,6 +170,8 @@ var _bell_left: float = -1.0 var music_track := "" var _music := {} var _music_level := {} +## A cutscene holds the ambience and the music (set_scene); the phase gets them back at end_scene(). +var scene := false func _ready() -> void: @@ -369,6 +373,36 @@ func wire_buttons(node: Node) -> void: button.pressed.connect(func() -> void: ui("ui_click")) +## A cutscene's ambience (day, night levels, 0..1; they crossfade to it) and music track ("" for +## none), whatever the phase, until end_scene(). +func set_scene(ambience: Vector2, track: String) -> void: + scene = true + _ambience_target = ambience + music_track = track + + +## Gives the ambience (at once) and the music back to the phase. +func end_scene() -> void: + if not scene: + return + scene = false + var phase := sim.campaign.state.phase if sim != null else CampaignController.Phase.MORNING + _ambience_target = AMBIENCE.get(phase, Vector2(1.0, 0.0)) + _ambience = _ambience_target + music_track = MUSIC_FOR.get(phase, "") + + +## Stops whatever a cue is playing now. +func stop_cue(cue: String) -> void: + for p in _voices_3d: + if p.playing and p.get_meta(&"cue", "") == cue: + p.stop() + for pool: Array[AudioStreamPlayer] in [_voices_ui, _voices_game]: + for p in pool: + if p.playing and p.get_meta(&"cue", "") == cue: + p.stop() + + ## The first stream of a cue (for looping players the cutscene owns). func stream_of(cue: String) -> AudioStream: var list: Array = streams.get(cue, []) @@ -432,6 +466,8 @@ func _process(delta: float) -> void: func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void: + if scene: + return # the cutscene's (it gives them back at its end) _ambience_target = AMBIENCE.get(phase, Vector2(1.0, 0.0)) music_track = MUSIC_FOR.get(phase, "") match phase: diff --git a/game/scripts/farm_sim.gd b/game/scripts/farm_sim.gd index c904585..e6a7753 100644 --- a/game/scripts/farm_sim.gd +++ b/game/scripts/farm_sim.gd @@ -25,7 +25,8 @@ extends Node ## combat, and interactions are that machine's own scarecrow's (player 2's). ## FarmAudio plays every sound, Tutorial shows the first ## day's and night's tips, DialogueDirector the talking-head conversations (game/resources/ -## dialogue/), and FarmersReturn plays the ending. Debug: T / G / H send in a +## dialogue/), OpeningIntro the cutscene before a new vacation's first morning (Main starts it), +## and FarmersReturn plays the ending. Debug: T / G / H send in a ## thief / a crow / a fence breaker at any time. const SCARECROW_RADIUS := 0.4 @@ -86,6 +87,7 @@ var audio: FarmAudio var tutorial: Tutorial var dialogue: DialogueDirector var ending: FarmersReturn +var intro: OpeningIntro ## Flow-field rebuild after a structure change: running, and stats of the last one. var rebuilding := false var rebuilds: int = 0 @@ -313,6 +315,12 @@ func _ready() -> void: ending.name = "FarmersReturn" add_child(ending) ending.setup(self) + intro = OpeningIntro.new() + intro.name = "OpeningIntro" + add_child(intro) + intro.setup(self) + if review_panel != null: + review_panel.intro = intro if end_panel != null: end_panel.setup(campaign) end_panel.ending = ending diff --git a/game/scripts/main.gd b/game/scripts/main.gd index cfad0d0..e559309 100644 --- a/game/scripts/main.gd +++ b/game/scripts/main.gd @@ -5,6 +5,9 @@ extends Node ## circles the farm behind the menu; the HUD is hidden. ## * New vacation (asks first when it would replace a save), Continue (the saved morning, ## SaveGame; refused with the reason when the save can't be used), Settings, Quit. +## * A new vacation opens with the intro (OpeningIntro; held down, it skips) before its first +## morning's sign. Continue never plays it, nor does hosting co-op. Restart the night during +## it skips it; Save & quit to menu takes it down (the save is that first morning already). ## * During play, Escape / Start pauses (PauseMenu): the tree pauses, so the simulation tick, ## timers, enemies, and game sounds all freeze. Resume, Restart the night (asks first), ## Settings, Save & quit to menu, Quit the game (asks first). @@ -65,6 +68,8 @@ func _ready() -> void: sim.tutorial.enabled = settings.show_tips if sim.dialogue != null: sim.dialogue.box.blocked = func() -> bool: return screen != Screen.PLAYING + if sim.intro != null: + sim.intro.blocked = func() -> bool: return screen != Screen.PLAYING main_menu.continue_requested.connect(continue_vacation) main_menu.new_requested.connect(_ask_new_vacation) main_menu.settings_requested.connect(_open_settings) @@ -158,10 +163,13 @@ func continue_vacation() -> bool: return true -## New vacation: a fresh farm, the morning of night 1 (saved at once, replacing any save). -func new_vacation() -> void: +## New vacation: a fresh farm, the morning of night 1 (saved at once, replacing any save), and +## the opening intro before its sign (unless intro is false: hosting co-op). +func new_vacation(intro := true) -> void: _play() sim.campaign.new_campaign() + if intro and sim.intro != null: + sim.intro.start() func pause() -> void: @@ -188,7 +196,7 @@ func resume() -> void: pause_menu.close() screen = Screen.PLAYING get_tree().paused = false - if sim.local_frozen: + if sim.local_frozen and not (sim.intro != null and sim.intro.running): # (the intro's freeze is its own) sim.freeze_local(false) if sim.dialogue != null: sim.dialogue.hold() # a conversation that was up stops the farm again @@ -196,6 +204,9 @@ func resume() -> void: func restart_night() -> void: resume() + if sim.intro != null and sim.intro.running: + sim.intro.skip() # its night is the first morning already: straight to it + return sim.campaign.retry_night() @@ -204,6 +215,8 @@ func restart_night() -> void: func to_menu() -> void: confirm.close() settings_menu.close() + if sim.intro != null: + sim.intro.clear() if sim.coop.is_client(): _leave_as_partner("") return @@ -262,7 +275,7 @@ func _host_coop(mode: CoopLobby.Mode, player: String, resume: bool) -> void: if not continue_vacation(): return else: - new_vacation() + new_vacation(false) # no intro: the friend can join any time lobby.host(mode, player) if not resume and SaveGame.read(save_path).status == SaveGame.Status.OK: confirm.ask("Start a new vacation? It replaces your saved one.", "New vacation", go) diff --git a/game/scripts/opening_intro.gd b/game/scripts/opening_intro.gd new file mode 100644 index 0000000..736e743 --- /dev/null +++ b/game/scripts/opening_intro.gd @@ -0,0 +1,1536 @@ +class_name OpeningIntro +extends Node3D +## The opening intro, at the start of every New vacation (Main.new_vacation; never on Continue or +## when hosting co-op; solo and local, so nothing of it is sent or saved). Stages (stage): +## leave A summer morning (DayNight.forced). The farmers come out of the house's front door +## (the house is one mesh, so no door swings: a creak) and walk to their station wagon, +## parked nose-out in the yard with the luggage piled on its roof (CutsceneKit), talking +## (intro/departure.tres); they wait at its doors until they're done. +## board They get in (a door slam each, the luggage jiggles) and the engine starts. +## drive The car drives the ending's route backwards and on down the road south; the camera +## follows it out of GapDriveway (a toot of the horn), stops there and watches it go. +## card Black: "Later that night...." is written in the handwritten font; the night falls +## under it (DayNight.forced, the lanterns kept dark, the night ambience). +## flight A big UFO (EnemySystem.build_ufo_mesh at UFO_SCALE, ufo.gdshader) comes over from the +## north-east, jerking and banking at each line of its crew's squabble over the controls +## (intro/flight.tres). +## wobble HANDS OFF! Over the scarecrow it sways harder and faster and spins up, whining. +## drop A part flies off its rim and tumbles down, trailing blue, in front of the scarecrow, +## which hangs on a wooden post (its arms out: the mannequin's rest pose is a T-pose). +## flash The part pulses, then a blue flash (a light spike, the screen, a ring over the +## ground); it streaks into the scarecrow's chest (its core glow comes on), and the +## scarecrow drops off the post, alive: its lantern lights, it looks around, then up. +## uh_oh The crew (intro/uh_oh.tres), the UFO shifting guiltily. +## escape It tilts and zooms off, its lights streaking. +## loading Black, then the LoadingScreen. Under it the farm is put back as new_campaign() left +## it: the scarecrow idle at its start, its input, the HUD, the light, the game camera, +## the sounds; then the first morning's sign shows and the screen fades out. +## end finished is emitted; DialogueDirector plays night 1's morning conversations (if any) +## before the sign. +## running: from start() until the farm is handed back (the morning sign, the tips, and the +## talking-head conversations wait meanwhile: ReviewPanel, Tutorial, DialogueDirector); busy(): +## until the end. The HUD layer hides behind letterbox bars, the scarecrow takes no input +## (FarmSim.freeze_local), and the listener follows the shot (FarmAudio.focus, set_scene). +## The lines play in its own DialogueBox, in its overlay: they go on by themselves, a tap hurries +## them, Backspace skips one conversation. Holding Space / Enter / A (or E, or the mouse button) +## for SKIP_HOLD seconds skips the rest: a fade to black, then straight to the sign (no loading +## screen), the farm left exactly as at the normal end; skip() does the same from code (Main's +## Restart the night). Escape pauses it with the farm (the pause menu over it; its box waits: +## blocked). Everything is built in start() and freed by the end or clear() (Main's Save & quit +## to menu), so nothing of it exists during play. step(delta), from _process, drives all of it, +## its box and loading screen included, so tests can step it by hand. + +signal finished + +const STAGES: Array[String] = ["leave", "board", "drive", "card", "flight", "wobble", "drop", "flash", "uh_oh", + "escape", "loading", "end"] +const DEPARTURE := "res://game/resources/dialogue/intro/departure.tres" +const FLIGHT_LINES := "res://game/resources/dialogue/intro/flight.tres" +const UH_OH_LINES := "res://game/resources/dialogue/intro/uh_oh.tres" + +## The scarecrow's start (farm.tscn's Player, game/LAYOUT.md), where it stands after the intro, +## facing north as it does there. Its post stands there too, the scarecrow hung POST_LIFT up on it +## facing FACING (east, over the crop field). +const START := Vector3(3.0, 0.0, -13.0) +const START_YAW := 0.0 +const FACING := Vector3(1.0, 0.0, 0.0) +const POST_LIFT := 0.6 +## The farmers come out of the front door (the porch steps on the house's north side, +## FarmersReturn.DOOR) and walk round to the car's doors along these points (the farmer to its +## left door, the wife round its nose to its right one), starting OUT_AT seconds in. +const DOOR := Vector3(19.6, 0.0, -29.8) +const OUT_AT: Array[float] = [0.3, 0.9] +const WALK_SPEED := 1.9 +## The car's way out: the ending's route backwards (the car parks nose-out at its end), then on +## south down the road past the farm. GapDriveway is where the camera stops. +const ROAD_SOUTH: Array[Vector3] = [Vector3(52.0, 0.0, 40.0), Vector3(52.0, 0.0, 80.0)] +const GAP := Vector3(48.0, 0.0, -39.5) +const DRIVE_SPEED := 11.0 +const DRIVE_ACCEL := 4.5 +## The UFO: its size (EnemySystem.build_ufo_mesh's scale), where it comes from, the bend of its +## way in, where it stops (over the scarecrow), where it backs off to after the flash, and the way +## it leaves (up and away to the east-north-east). +const UFO_SCALE := 8.0 +const UFO_FROM := Vector3(125.0, 62.0, -150.0) +const UFO_BEND := Vector3(70.0, 40.0, -40.0) +const HOVER := Vector3(5.0, 19.0, -13.0) +const HOVER_AFTER := Vector3(26.0, 15.0, -16.0) +const ESCAPE_DIR := Vector3(0.74, 0.46, -0.49) +## Its lights underneath (the hull hides the rim's from below): how many, how far out, and their +## colors (the rim's), and the glow of its drive in the middle. +const UFO_LIGHTS := 10 +const UFO_LIGHT_COLORS: Array[Color] = [Color(1.0, 0.72, 0.2), Color(0.4, 1.0, 0.35)] +const UFO_DRIVE_COLOR := Color(0.55, 1.0, 0.85, 0.75) + +## The shots: camera positions and the subjects they look at. The departure looks south over the +## yard from the north (the porch and the car side by side, clear of the box's heads); the night +## looks up from the south-west, far enough off that the UFO is seen from the side; the uh-oh looks +## over the scarecrow's right shoulder (it stands at the frame's left edge, off the box). +const LEAVE_CAMERA := Vector3(26.2, 13.5, -59.0) +const LEAVE_SUBJECT := Vector3(26.2, 1.0, -30.5) +const LEAVE_LIFT := 7.0 +const GAP_CAMERA := Vector3(46.8, 3.0, -43.6) +const FLIGHT_CAMERA := Vector3(-9.0, 1.5, 19.0) +const UH_OH_BACK := 3.2 +const UH_OH_SIDE := 4.0 +const UH_OH_HEIGHT := 1.2 +const UH_OH_FOV := 55.0 +## The scarecrow comes down this far in front of its post, which tips over (to its left). +const HOP := 0.6 + +## Seconds: the departure's lines start; boarding; the drive (the camera leaves the car this far +## before the gap); the card (its fade, its writing, the fade out of its words); the flight's +## lines start and how long it takes to come over; the wobble; the part's fall; the flash's +## beats; the escape; the loading screen and its fade, the skip's fade to black and back. +const LINES_AT := 1.2 +const BOARD_TIME := 2.2 +const DRIVE_TIME := 12.0 +const GAP_LEAD := 6.0 +const CARD_FADE := 0.5 +const CARD_TEXT := "Later that night...." +const CARD_LETTERS := 12.0 +const CARD_DOT := 0.22 +const CARD_TIME := 3.6 +const FLIGHT_FADE := 0.8 +const FLIGHT_LINES_AT := 2.0 +const FLIGHT_TIME := 13.0 +const WOBBLE_TIME := 4.0 +const DROP_CUT := 0.45 +const FALL_TIME := 2.0 +const DROP_AFTER := 0.6 +const FLASH_AT := 1.2 +const STREAK_AT := 1.3 +const STREAK_TIME := 0.25 +const HOP_AT := 1.85 +const LOOK_AROUND_AT := 2.6 +const LOOK_UP_AT := 4.7 +const FLASH_TIME := 5.4 +const ESCAPE_TIME := 2.6 +const LOADING_BLACK := 0.5 +const LOADING_TIME := 3.0 +const LOADING_FADE := 0.6 +const SKIP_HOLD := 1.0 +const SKIP_FADE := 0.4 +const REVEAL_FADE := 0.5 +## What holding skips: Space / Enter / A (ui_accept), E / X (interact), the mouse button / RT +## (fire). +const SKIP_ACTIONS: Array[StringName] = [&"ui_accept", &"interact", &"fire"] +## Degrees the lines' shots look under their subject, so it stands in the frame's upper half, +## clear of the dialogue box. +const LINE_LIFT := 10.0 +const PART_BLUE := Color(0.45, 0.78, 1.0) +const FLASH_COLOR := Color(0.8, 0.92, 1.0) + +var sim: FarmSim +## The intro has the farm (start() until it's handed back under the loading screen or the +## skip's black), it's over (finished emitted), and its stage (STAGES; "" when idle). +var running := false +var done := false +var stage := "" +## Seconds since start() (game time; it stops while the game is paused). +var elapsed: float = 0.0 +## Set by Main: whether a menu is up over it (its box waits; holding doesn't skip). +var blocked: Callable + +var _t: float = 0.0 # seconds into the stage +var _took := false # the farm is the intro's (put it back) +var _skipping := false +var _revealing := false +var _hold: float = 0.0 +var _armed := false +var _last_frame: int = 0 +var _talked := false +var _line: int = -1 +var _quiet: float = 0.0 + +# The world (freed when the farm is handed back) and the screen (freed at the end). +var _world: Node3D +var _ears: Node3D +var _camera: Camera3D +var _overlay: CutsceneKit.Letterbox +var _ring: SkipRing +var _box: DialogueBox +var _flash: ColorRect +var _black: ColorRect +var _card: Label +var _loading_layer: CanvasLayer +var _loading: LoadingScreen + +# The departure. +var _car: Node3D +var _engine: AudioStreamPlayer3D +var _curve: Curve3D +var _driven: float = 0.0 +var _speed: float = 0.0 +var _gap_at: float = 0.0 +var _past_gap := false +var _farmers: Array[Node3D] = [] +var _anims: Array[AnimationPlayer] = [] +var _paths: Array[PackedVector3Array] = [] +var _legs: Array[int] = [0, 0] +var _doors: Array[Vector3] = [] +var _shake: float = 0.0 + +# The night. +var _night := false +var _ufo: MeshInstance3D +var _ufo_mat: ShaderMaterial +var _hum: AudioStreamPlayer3D +var _ufo_light: SpotLight3D +var _streak: CPUParticles3D +var _ufo_lamps: Array[StandardMaterial3D] = [] +var _chase: float = 6.0 +var _lamp_phase: float = 0.0 +var _u: float = 0.0 +var _lurch: float = 0.0 +var _tug := Vector2.ZERO +var _tug_speed := Vector2.ZERO +var _spin: float = 0.0 +var _spin_rate: float = 1.0 +var _phase: float = 0.0 +var _sway: float = 0.0 +var _center := Vector3.ZERO +var _escape_speed: float = 0.0 +var _post: Node3D +var _post_down := false +var _ropes: Array[Node3D] = [] +var _part: Node3D +var _core_mat: StandardMaterial3D +var _part_light: OmniLight3D +var _trail: Trail +var _dust: CPUParticles3D +var _part_from := Vector3.ZERO +var _part_velocity := Vector3.ZERO +var _part_spin := Vector3.ZERO +var _landed := false +var _land := Vector3.ZERO +var _ground: float = 0.0 +var _burst: OmniLight3D +var _ring_mesh: MeshInstance3D +var _ring_mat: ShaderMaterial +var _look: LookAtModifier3D +var _skeleton: Skeleton3D +var _marker_was := true +var _alive_step: int = 0 # how far the flash stage has got (its one-off beats) + +static var _dot: GradientTexture2D + + +## A fading trail of glowing specks behind whatever it's under (in world space): while emitting, +## a speck every SPACING along the way it moved (so a fast fall leaves an even line), each +## shrinking and fading over life seconds. step() moves it on. +class Trail extends MultiMeshInstance3D: + const COUNT := 64 + const SPACING := 0.1 + var emitting := false + var color := Color.WHITE + var size: float = 0.3 + var life: float = 0.5 + var _specks: Array[Vector4] = [] # x, y, z, age + var _last := Vector3.INF + + func _init(p_color: Color, p_size: float, p_life: float) -> void: + color = p_color + size = p_size + life = p_life + top_level = true + cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + var quad := QuadMesh.new() + quad.size = Vector2.ONE + multimesh = MultiMesh.new() + multimesh.transform_format = MultiMesh.TRANSFORM_3D + multimesh.use_colors = true + multimesh.mesh = quad + multimesh.instance_count = COUNT + multimesh.visible_instance_count = 0 + material_override = OpeningIntro._glow_material(Color.WHITE, BaseMaterial3D.BILLBOARD_ENABLED) + + func step(delta: float, at: Vector3) -> void: + var kept: Array[Vector4] = [] + for s in _specks: + if s.w + delta < life: + kept.append(Vector4(s.x, s.y, s.z, s.w + delta)) + _specks = kept + if emitting: + if _last == Vector3.INF: + _last = at + var n := mini(floori(_last.distance_to(at) / SPACING), COUNT) + for i in n: + var p := _last.lerp(at, float(i + 1) / n) + _specks.append(Vector4(p.x, p.y, p.z, delta * (1.0 - float(i + 1) / n))) + if n > 0: + _last = at + else: + _last = Vector3.INF + while _specks.size() > COUNT: + _specks.pop_front() + multimesh.visible_instance_count = _specks.size() + for i in _specks.size(): + var s := _specks[i] + var k := 1.0 - s.w / life + multimesh.set_instance_transform(i, Transform3D(Basis.from_scale(Vector3.ONE * size * (0.35 + 0.65 * k)), Vector3(s.x, s.y, s.z))) + multimesh.set_instance_color(i, Color(color, color.a * k)) + + +## The skip hint's ring, filling while the skip is held. +class SkipRing extends Control: + var progress: float = 0.0 + + func set_progress(p: float) -> void: + if not is_equal_approx(p, progress): + progress = p + queue_redraw() + + func _draw() -> void: + var c := size * 0.5 + var r := minf(size.x, size.y) * 0.5 - 3.0 + draw_arc(c, r, 0.0, TAU, 40, Color(1.0, 1.0, 1.0, 0.28), 3.0, true) + if progress > 0.0: + draw_arc(c, r, -PI * 0.5, -PI * 0.5 + TAU * clampf(progress, 0.0, 1.0), 40, Color(0.95, 0.85, 0.55), 4.5, true) + + +func setup(p_sim: FarmSim) -> void: + sim = p_sim + sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, _p: CampaignController.Phase) -> void: + if busy() and phase != CampaignController.Phase.MORNING: + clear()) # it's the first morning's (debug phase skips end it) + + +## Whether it's still on screen (start() until the end). +func busy() -> bool: + return stage != "" and not done + + +## Plays it from the top (solo only: never while a co-op session is up). +func start() -> void: + if sim == null or (sim.coop != null and sim.coop.is_active()): + return + clear() + running = true + done = false + elapsed = 0.0 + _took = true + _armed = false + _last_frame = Engine.get_process_frames() + _world = Node3D.new() + _world.name = "World" + add_child(_world) + _ears = Node3D.new() + _ears.name = "Ears" + _world.add_child(_ears) + _build_departure() + _build_night() + _build_screen() + # The farm: the scarecrow up on its post, frozen, no glow; a summer morning; no HUD. + _mount_scarecrow() + if not sim.local_frozen: + sim.freeze_local(true) + var dn := sim.day_night + if dn != null: + dn.forced = "morning" + dn.lanterns_dark = true + dn.snap() + CutsceneKit.set_hud(sim, false) + if sim.review_panel != null: + sim.review_panel.refresh() # down until the intro's over + _camera = CutsceneKit.make_camera(_world, 45.0) + CutsceneKit.move_camera(_camera, LEAVE_CAMERA, _lifted(LEAVE_CAMERA, LEAVE_SUBJECT, LEAVE_LIFT), 1.0, 1.0) + if sim.audio != null: + sim.audio.stop_cue("morning") # new_campaign()'s stinger: it plays with the sign instead + sim.audio.set_scene(Vector2(1.0, 0.0), "farm") + sim.audio.focus = _ears + sim.audio.play("door_creak", DOOR + Vector3(0.0, 1.2, 0.0)) + _enter("leave") + + +## Skips the rest: a fade to black, and the farm is put back; then the sign. +func skip() -> void: + if not busy() or _skipping or not running: + return + _skipping = true + if _box != null: + _box.stop() + if _ring != null: + _ring.visible = false + _overlay.hint.visible = false + if stage == "loading" and _loading != null and _loading.visible: + _hand_back(true) + _loading.fade_out(LOADING_FADE) + + +## Takes it all down at once and gives the farm back, without the sign (Main's Save & quit to +## menu; a new start()). +func clear() -> void: + if _took: + _hand_back(false) + for n in get_children(): + remove_child(n) + n.queue_free() + running = false + done = false + stage = "" + _skipping = false + _revealing = false + _world = null + _ears = null + _camera = null + _overlay = null + _ring = null + _box = null + _flash = null + _black = null + _card = null + _loading_layer = null + _loading = null + _forget_world() + + +func _process(delta: float) -> void: + if busy(): + step(delta) + + +func _exit_tree() -> void: + for p in find_children("*", "AudioStreamPlayer3D", true, false): + (p as AudioStreamPlayer3D).stop() + + +## Moves it on delta seconds. +func step(delta: float) -> void: + if not busy() or delta <= 0.0: + return + elapsed += delta + _t += delta + if _box != null: + _box._process(delta) + if _loading != null: + _loading.step(delta) + if running and not _skipping and not _revealing: + _poll_skip(delta) + if _revealing: + _reveal(delta) + return + if _skipping: + _black.color.a = move_toward(_black.color.a, 1.0, delta / SKIP_FADE) + if _black.color.a >= 1.0: + _hand_back(true) + return + match stage: + "leave": + _leave(delta) + "board": + _board(delta) + "drive": + _drive(delta) + "card": + _card_step(delta) + "flight": + _flight(delta) + "wobble": + _wobble(delta) + "drop": + _drop(delta) + "flash": + _flash_step(delta) + "uh_oh": + _uh_oh(delta) + "escape": + _escape(delta) + "loading": + _loading_step(delta) + _hear() + _light_ufo(delta) + + +## The UFO's night glow (as DayNight gives the enemies'), and its lamps chasing round underneath. +func _light_ufo(delta: float) -> void: + if _ufo_mat == null or not _night: + return + if sim.day_night != null: + _ufo_mat.set_shader_parameter("night_glow", float(sim.day_night.current["glow"])) + _ufo_mat.set_shader_parameter("chase_speed", _chase) + _lamp_phase += _chase * delta + for k in _ufo_lamps.size(): + var a := TAU * k / _ufo_lamps.size() + var pulse := 0.4 + 0.6 * maxf(sin(a * 2.0 - _lamp_phase), 0.0) + _ufo_lamps[k].albedo_color.a = pulse + + +func _enter(next: String) -> void: + stage = next + _t = 0.0 + _talked = false + _line = -1 + _quiet = 0.0 + + +# --- The stages ---------------------------------------------------------------------------------- + +func _leave(delta: float) -> void: + CutsceneKit.move_camera(_camera, LEAVE_CAMERA, _lifted(LEAVE_CAMERA, LEAVE_SUBJECT, LEAVE_LIFT), delta, 0.6) + CutsceneKit.sway_luggage(_car, delta, 0.0, 0.0) + for i in 2: + _walk(i, delta) + if _t >= LINES_AT and not _talked: + _talk(DEPARTURE) + if _t >= 3.0 and _arrived(0) and _arrived(1) and _talked and not _box.is_playing(): + _quiet += delta + if _quiet >= 0.3: + _enter("board") + + +func _board(delta: float) -> void: + CutsceneKit.move_camera(_camera, LEAVE_CAMERA, _lifted(LEAVE_CAMERA, LEAVE_SUBJECT, LEAVE_LIFT), delta, 0.6) + var luggage := CutsceneKit.luggage_of(_car) + for i in 2: + if _farmers[i].visible and _t >= 0.15 + 0.6 * i: + _farmers[i].visible = false # in, and the door slams + if sim.audio != null: + sim.audio.play("car_door", _doors[i] + Vector3(0.0, 1.0, 0.0)) + if luggage != null: + luggage.nudge(Vector2(0.15, 0.6 if i == 0 else -0.6)) + if _t >= 1.3 and _engine == null: + _engine = CutsceneKit.add_engine(_car, sim.audio) + if luggage != null: + luggage.nudge(Vector2(-0.5, 0.35)) + if _engine != null and luggage != null: + _shake -= delta + if _shake <= 0.0: # the engine idling under it + _shake = 0.11 + luggage.nudge(Vector2(randf_range(-0.05, 0.05), randf_range(-0.07, 0.07))) + CutsceneKit.sway_luggage(_car, delta, 0.0, 0.0) + if _t >= BOARD_TIME: + _enter("drive") + _speed = 0.0 + + +func _drive(delta: float) -> void: + var length := _curve.get_baked_length() + var was := _driven + var heading := _car.rotation.y + var last := _speed + _speed = minf(_speed + DRIVE_ACCEL * delta, DRIVE_SPEED) + _driven = minf(_driven + _speed * delta, length) + CutsceneKit.place_on_curve(_car, _curve, _driven) + var moved := (_driven - was) / delta + CutsceneKit.sway_luggage(_car, delta, angle_difference(heading, _car.rotation.y) / delta, (moved - last) / delta) + if not _past_gap and _driven >= _gap_at: + _past_gap = true + if sim.audio != null: + sim.audio.play("horn", _car.global_position + Vector3(0.0, 1.0, 0.0)) + if _driven < _gap_at - GAP_LEAD: + CutsceneKit.follow_camera(_camera, _car, delta if _t > delta else 1.0) # (cut in behind it) + else: # it stops at the gap and watches the car go + CutsceneKit.move_camera(_camera, GAP_CAMERA, _car.global_position + Vector3(0.0, 1.0, 0.0), delta, 1.8) + if _t >= DRIVE_TIME or _driven >= length: + _enter("card") + if sim.audio != null: + sim.audio.set_scene(Vector2(0.0, 1.0), "") # the night comes in under the black + + +func _card_step(_delta: float) -> void: + _black.color.a = clampf(_t / CARD_FADE, 0.0, 1.0) + if _t >= CARD_FADE and not _night: + _go_night() + _card.visible = _t >= CARD_FADE + _card.visible_characters = _card_letters(_t - CARD_FADE - 0.15) + _card.modulate.a = clampf((CARD_TIME - _t) / 0.3, 0.0, 1.0) + if _t >= CARD_TIME: + _card.visible = false + _enter("flight") + _u = 0.0 + + +func _flight(delta: float) -> void: + _black.color.a = clampf(1.0 - _t / FLIGHT_FADE, 0.0, 1.0) + if _t >= FLIGHT_LINES_AT and not _talked: + _talk(FLIGHT_LINES) + if _talked and _box.is_playing() and _box.index != _line: + _line = _box.index + _tug_line(_line) + _lurch = maxf(_lurch - delta, 0.0) + _u = minf(_u + delta / FLIGHT_TIME * (1.0 + _lurch * 1.6), 1.0) + var k := _u * _u * (3.0 - 2.0 * _u) + var at := _bezier(UFO_FROM, UFO_BEND, HOVER, k) + var ahead := _bezier(UFO_FROM, UFO_BEND, HOVER, minf(k + 0.02, 1.0)) - _bezier(UFO_FROM, UFO_BEND, HOVER, maxf(k - 0.02, 0.0)) + ahead.y = 0.0 + var fwd := ahead.normalized() if ahead.length_squared() > 1e-6 else Vector3.FORWARD + _step_tug(delta, 5.0, 1.8) + var side := fwd.cross(Vector3.UP).normalized() + _spin += _spin_rate * delta + var bank := clampf(-_tug_speed.x * 0.045 + _tug.x * 0.01, -0.6, 0.6) + var pitch := clampf(0.12 * (1.0 - k) + _tug_speed.y * 0.03, -0.4, 0.4) + _place_ufo(at + side * _tug.x + Vector3.UP * _tug.y, fwd, bank, pitch) + _track(FLIGHT_CAMERA, _ufo.global_position, delta, 3.0) + if _talked and (_box.index >= 4 or not _box.is_playing()): + _enter("wobble") + _center = _ufo.global_position + _phase = 0.0 + if sim.audio != null: + sim.audio.play("ufo_whine", _ufo.global_position) + + +func _wobble(delta: float) -> void: + var k := clampf(_t / WOBBLE_TIME, 0.0, 1.0) + _phase += TAU * lerpf(0.45, 2.4, k * k) * delta + _center = _center.lerp(HOVER, 1.0 - exp(-2.5 * delta)) + _sway = sin(_phase) * lerpf(1.2, 3.0, k) + _spin_rate = lerpf(1.5, 30.0, k * k * k) + _spin += _spin_rate * delta + var across := _across() + var tilt := cos(_phase) * deg_to_rad(20.0) * lerpf(0.5, 1.0, k) + _place_ufo(_center + across * _sway, across.cross(Vector3.UP), tilt, 0.0) + _chase = lerpf(6.0, 26.0, k) + if _hum != null: + _hum.pitch_scale = lerpf(1.0, 1.7, k) + _track(FLIGHT_CAMERA, _center, delta, 3.0) + if _t >= WOBBLE_TIME and not _box.is_playing(): + _enter("drop") + _pop_part() + + +func _drop(delta: float) -> void: + # The UFO lurches still and slows down. + _sway *= exp(-3.0 * delta) + _spin_rate = lerpf(_spin_rate, 1.2, 1.0 - exp(-2.0 * delta)) + _spin += _spin_rate * delta + _center = _center.lerp(HOVER, 1.0 - exp(-2.0 * delta)) + var across := _across() + _place_ufo(_center + across * _sway, across.cross(Vector3.UP), _sway / 3.0 * deg_to_rad(12.0), 0.0) + _chase = lerpf(_chase, 6.0, 1.0 - exp(-2.0 * delta)) + if _hum != null: + _hum.pitch_scale = lerpf(_hum.pitch_scale, 1.0, 1.0 - exp(-2.0 * delta)) + if _t < DROP_CUT: + _track(FLIGHT_CAMERA, _center, delta, 3.0) + else: # cut to the scarecrow on its post looking up at the part; down with it as it falls + var right := FACING.cross(Vector3.UP) + var frame := START + FACING * 0.4 + Vector3(0.0, _ground + 1.5, 0.0) + var high := clampf((_part.global_position.y - _ground - 2.5) / 10.0, 0.0, 1.0) if not _landed else 0.0 + CutsceneKit.move_camera(_camera, START + FACING * 5.4 + right * 1.0 + Vector3(0.0, _ground + 1.4, 0.0), + frame.lerp(_part.global_position, high * high * (3.0 - 2.0 * high)), 1.0 if _t - delta < DROP_CUT else delta, 7.0) + if not _landed: + var t := minf(_t, FALL_TIME) + _part.global_position = _part_from + _part_velocity * t + Vector3(0.0, -4.9, 0.0) * t * t + _part.rotation += _part_spin * delta + if _t >= FALL_TIME: + _land_part() + elif _t >= FALL_TIME + DROP_AFTER: + _enter("flash") + _alive_step = 0 + if _trail != null: + _trail.step(delta, _part.global_position) + + +func _flash_step(delta: float) -> void: + var right := FACING.cross(Vector3.UP) + CutsceneKit.move_camera(_camera, START + FACING * 5.2 - right * 0.9 + Vector3(0.0, _ground + 1.5, 0.0), + START + FACING * 0.6 + Vector3(0.0, _ground + 1.3, 0.0), 1.0 if _t <= delta else delta, 0.5) + _hover_ufo(delta) + var body := sim.player + if _t < FLASH_AT: # three pulses + var p := absf(sin(_t / FLASH_AT * 3.0 * PI)) + _pulse_part(1.0 + 3.0 * p * p) + if _alive_step == 0 and _t >= FLASH_AT: + _alive_step = 1 + _burst.light_energy = 16.0 + _flash.color.a = 0.92 + _ring_mesh.visible = true + if sim.audio != null: + sim.audio.play("life_flash", _land + Vector3(0.0, 0.5, 0.0)) + if _alive_step >= 1: + _burst.light_energy = maxf(_burst.light_energy - delta * 18.0, 0.0) + _flash.color.a = maxf(_flash.color.a - delta / 0.9, 0.0) + _ring_mat.set_shader_parameter("t", clampf((_t - FLASH_AT) / 1.2, 0.0, 1.0)) + if _alive_step == 1 and _t >= STREAK_AT: # into the chest + var chest := body.core_glow.global_position if body.core_glow != null else body.global_position + Vector3(0.0, 1.0, 0.0) + var k := clampf((_t - STREAK_AT) / STREAK_TIME, 0.0, 1.0) + _part.global_position = _land.lerp(chest, k * k) + _part.scale = Vector3.ONE * lerpf(1.0, 0.3, k) + _pulse_part(3.0) + if k >= 1.0: + _alive_step = 2 + _part.visible = false + body.set_core_glow(true) + if _alive_step == 2 and _t >= HOP_AT: # off the post + _alive_step = 3 + body.animation_player.play(&"Hit_A", 0.05) + _post_ropes_off() + if _alive_step == 3: + var fall := _t - HOP_AT + var y := _ground + POST_LIFT + 1.4 * fall - 8.0 * fall * fall # a little hop, then down + var ahead := minf(fall / 0.45, 1.0) * HOP + if y <= _ground and fall > 0.1: + y = _ground + _alive_step = 4 + if sim.audio != null: + sim.audio.play("fall", _stand()) + if sim.day_night != null: + sim.day_night.lanterns_dark = false # its lantern lights + body.global_position = START + FACING * ahead + Vector3(0.0, y, 0.0) + if _alive_step >= 3 and _post != null: # the post tips over + var k := clampf((_t - HOP_AT - 0.15) / 0.7, 0.0, 1.0) + _post.rotation.z = 1.5 * k * k + if k >= 1.0 and not _post_down: + _post_down = true + if sim.audio != null: + sim.audio.play("dismantle", START - FACING.cross(Vector3.UP) * 1.5) + if _alive_step == 4 and _t >= LOOK_AROUND_AT: + _alive_step = 5 + body.animation_player.play(&"Idle_B", 0.25) + if _alive_step == 5 and _t >= LOOK_UP_AT: + _alive_step = 6 + body.animation_player.play(body.idle_animation, 0.3) + _look_up() + if _look != null: + _look.influence = move_toward(_look.influence, 0.75, delta * 1.2) + if _t >= FLASH_TIME: + _enter("uh_oh") + _ring_mesh.visible = false + + +func _uh_oh(delta: float) -> void: + _uh_oh_shot(delta, 1.0 if _t <= delta else delta, 1.5) + if _t >= 0.4 and not _talked: + _talk(UH_OH_LINES) + if _talked and _box.is_playing() and _box.index != _line: + _line = _box.index + _shuffle(_line) + _center = _center.lerp(HOVER_AFTER, 1.0 - exp(-0.7 * delta)) + _step_tug(delta, 7.0, 2.4) + _spin += _spin_rate * delta + var across := _across() + var fidget := sin(_t * 2.3) * 0.5 + sin(_t * 5.1) * 0.15 + _place_ufo(_center + across * (_tug.x + fidget) + Vector3.UP * _tug.y, across.cross(Vector3.UP), + clampf(-_tug_speed.x * 0.05, -0.35, 0.35) + fidget * 0.05, 0.05) + if _look != null: + _look.influence = move_toward(_look.influence, 0.75, delta * 1.2) + if _talked and not _box.is_playing(): + _quiet += delta + if _quiet >= 0.3: + _enter("escape") + _escape_speed = 0.0 + + +func _escape(delta: float) -> void: + _uh_oh_shot(delta, delta, 0.4) + var tip := clampf(_t / 0.4, 0.0, 1.0) + _spin_rate = lerpf(_spin_rate, 6.0, 1.0 - exp(-3.0 * delta)) + _spin += _spin_rate * delta + var away := ESCAPE_DIR.normalized() + var flat := Vector3(away.x, 0.0, away.z).normalized() + if _t >= 0.35: + if not _streak.emitting: + _streak.emitting = true + _ufo_mat.set_shader_parameter("glow_energy", 3.5) + if sim.audio != null: + sim.audio.play("ufo_zoom", _ufo.global_position) + _escape_speed += 70.0 * delta + _center += away * _escape_speed * delta + else: + _center += Vector3.UP * 1.5 * delta # gathers itself + _place_ufo(_center, flat, 0.0, -deg_to_rad(28.0) * tip) + if _look != null: + _look.influence = move_toward(_look.influence, 0.6, delta) + if _t >= ESCAPE_TIME: + _enter("loading") + + +func _loading_step(_delta: float) -> void: + if not _loading.visible: + _black.color.a = clampf(_t / LOADING_BLACK, 0.0, 1.0) + if _t >= LOADING_BLACK: + _loading.play(LOADING_TIME) + return + if not _loading.running: # the bar's full: the farm is put back under it, then it fades + _hand_back(true) + _loading.fade_out(LOADING_FADE) + + +## After the farm's back: the black (a skip's) and the loading screen fade away; then the end. +func _reveal(delta: float) -> void: + _black.color.a = move_toward(_black.color.a, 0.0, delta / REVEAL_FADE) + if _black.color.a <= 0.0 and not _loading.visible: + _finish() + + +func _finish() -> void: + stage = "end" + done = true + _skipping = false + _revealing = false + for n in get_children(): + remove_child(n) + n.queue_free() + _overlay = null + _ring = null + _box = null + _flash = null + _black = null + _card = null + _loading_layer = null + _loading = null + if sim.dialogue != null: + sim.dialogue.intro_over() # night 1's morning conversations (none today), then the sign + finished.emit() + + +# --- Putting the farm back ----------------------------------------------------------------------- + +## The farm as new_campaign() left it: the intro's world gone, the scarecrow idle at its start +## with its input and glow, the HUD, the light un-forced and snapped, the game camera, the sounds; +## with show_sign, the morning sign (unless a conversation comes first) and its stinger. +func _hand_back(show_sign: bool) -> void: + if not _took: + return + _took = false + running = false + if _world != null: + for p in _world.find_children("*", "AudioStreamPlayer3D", true, false): + (p as AudioStreamPlayer3D).stop() + remove_child(_world) + _world.queue_free() + _world = null + _ears = null + _camera = null + _forget_world() + if _look != null: + if is_instance_valid(_look): + _look.get_parent().remove_child(_look) + _look.queue_free() + _look = null + var body := sim.player + body.set_physics_process(true) + body.velocity = Vector3.ZERO + body.global_position = START + body.model.rotation = Vector3(0.0, START_YAW, 0.0) + body.net_position = START + body.net_yaw = START_YAW + body.stop_channel() + body.animation_player.speed_scale = 1.0 + body.animation_player.play(body.idle_animation) + body.set_core_glow(true) + body.reset_physics_interpolation() + sim.scarecrow.alive = true + sim.combat.show_marker = _marker_was + if sim.local_frozen: + sim.freeze_local(false) + var dn := sim.day_night + if dn != null: + dn.forced = "" + dn.lanterns_dark = false + dn.snap() + CutsceneKit.set_hud(sim, true) + if sim.camera != null: + sim.camera.make_current() + if sim.camera is FollowCamera: + (sim.camera as FollowCamera).snap_to_target() + if sim.audio != null: + sim.audio.focus = sim.player + sim.audio.end_scene() + if _overlay != null: # only the black stays (a skip's, faded out next) + for n in _overlay.get_children(): + (n as CanvasItem).visible = n == _black + if _loading != null and _loading.visible: + _black.color.a = 0.0 + _revealing = true + if not show_sign: + return + if sim.audio != null: + sim.audio.play("morning") + if sim.review_panel != null and (sim.dialogue == null or not sim.dialogue.has_due()): + sim.review_panel.refresh() + + +func _forget_world() -> void: + _car = null + _engine = null + _curve = null + _farmers.clear() + _anims.clear() + _paths.clear() + _doors.clear() + _ufo = null + _ufo_mat = null + _hum = null + _ufo_light = null + _streak = null + _post = null + _post_down = false + _ropes.clear() + _ufo_lamps.clear() + _part = null + _core_mat = null + _part_light = null + _trail = null + _dust = null + _burst = null + _ring_mesh = null + _ring_mat = null + _skeleton = null + _night = false + _landed = false + _past_gap = false + + +# --- Building it --------------------------------------------------------------------------------- + +## The car, nose-out at the end of the ending's route, its way out, and the farmers (hidden until +## they come out of the door). +func _build_departure() -> void: + var route := CutsceneKit.reversed(FarmersReturn.ROUTE) + route.append_array(ROAD_SOUTH) + _curve = CutsceneKit.route_curve(route) + _gap_at = _curve.get_closest_offset(GAP) + _driven = 0.0 + _speed = 0.0 + _car = CutsceneKit.make_car(_world) + CutsceneKit.place_on_curve(_car, _curve, 0.0) + var left := _car.global_basis.x + var ahead := _car.global_basis.z + _doors = [_car.global_position + left * 1.35 + ahead * 0.45, _car.global_position - left * 1.35 + ahead * 0.45] + # Off the porch, then along the yard (the farmer to the left door; the wife round the nose). + var nose := _car.global_position + ahead * 4.2 + _paths = [ + PackedVector3Array([DOOR + Vector3(0.6, 0.0, -1.2), _doors[0] + Vector3(-1.2, 0.0, -1.0), _doors[0]]), + PackedVector3Array([DOOR + Vector3(1.4, 0.0, -1.8), nose + left * 1.2, nose - left * 1.6, _doors[1] + ahead * 1.6, _doors[1]]), + ] + _legs = [0, 0] + for i in 2: + var farmer := CutsceneKit.make_farmer(_world, CutsceneKit.FARMER_TINTS[i]) + farmer.name = "Farmer" if i == 0 else "FarmersWife" + farmer.global_position = DOOR + farmer.visible = false + _farmers.append(farmer) + _anims.append(CutsceneKit.anim_of(farmer)) + + +## The UFO (hidden till the night), the part, the ground ring, and the flash's light. +func _build_night() -> void: + _ufo = MeshInstance3D.new() + _ufo.name = "Ufo" + _ufo.mesh = EnemySystem.build_ufo_mesh(UFO_SCALE) + _ufo_mat = ShaderMaterial.new() + _ufo_mat.shader = load("res://game/resources/ufo.gdshader") as Shader + _ufo_mat.set_shader_parameter("bob_amount", 0.25) + _ufo_mat.set_shader_parameter("spin_speed", 0.0) # the node turns it (and its lamps) + _ufo.material_override = _ufo_mat + _ufo.extra_cull_margin = 4.0 # the shader bobs it + _ufo.visible = false + _world.add_child(_ufo) + _ufo.global_position = UFO_FROM + _hum = AudioStreamPlayer3D.new() + _hum.name = "Hum" + _hum.bus = &"SFX" + _hum.unit_size = 28.0 + _hum.max_distance = 600.0 + _hum.volume_db = -4.0 + _hum.attenuation_filter_cutoff_hz = 20500.0 + _chase = 6.0 + if sim.audio != null: + _hum.stream = sim.audio.stream_of("ufo_hum") + _ufo.add_child(_hum) + _ufo_light = SpotLight3D.new() # a cold light under it, on whatever it's over + _ufo_light.light_color = Color(0.7, 1.0, 0.85) + _ufo_light.light_energy = 2.0 + _ufo_light.spot_range = 40.0 + _ufo_light.spot_angle = 32.0 + _ufo_light.spot_attenuation = 0.6 + _ufo_light.shadow_enabled = false + _ufo_light.rotation.x = -PI / 2.0 + _ufo_light.position = Vector3(0.0, -1.2, 0.0) + _ufo.add_child(_ufo_light) + var lamp := QuadMesh.new() + lamp.size = Vector2(1.7, 1.7) + for k in UFO_LIGHTS: + var a := TAU * k / UFO_LIGHTS + var mi := MeshInstance3D.new() + mi.mesh = lamp + var m := _glow_material(UFO_LIGHT_COLORS[k % 2], BaseMaterial3D.BILLBOARD_ENABLED) + mi.material_override = m + mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + mi.position = Vector3(cos(a), 0.0, sin(a)) * 0.63 * UFO_SCALE + Vector3(0.0, -0.06 * UFO_SCALE, 0.0) + _ufo.add_child(mi) + _ufo_lamps.append(m) + var drive := QuadMesh.new() + drive.size = Vector2(0.75, 0.75) * UFO_SCALE + var glow := MeshInstance3D.new() + glow.name = "Drive" + glow.mesh = drive + glow.material_override = _glow_material(UFO_DRIVE_COLOR, BaseMaterial3D.BILLBOARD_ENABLED) + glow.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + glow.position = Vector3(0.0, -0.16 * UFO_SCALE, 0.0) + _ufo.add_child(glow) + _streak = _particles(Color(1.0, 0.8, 0.4), 0.9, 120, 0.5) + _streak.emission_shape = CPUParticles3D.EMISSION_SHAPE_RING + _streak.emission_ring_axis = Vector3.UP + _streak.emission_ring_radius = 0.76 * UFO_SCALE + _streak.emission_ring_inner_radius = 0.7 * UFO_SCALE + _streak.emission_ring_height = 0.2 + _ufo.add_child(_streak) + _part = _make_part() + _part.visible = false + _world.add_child(_part) + _dust = _particles(Color(0.62, 0.52, 0.38, 0.6), 0.9, 22, 0.9, false) + _dust.one_shot = true + _dust.explosiveness = 0.95 + _dust.direction = Vector3.UP + _dust.spread = 80.0 + _dust.initial_velocity_min = 1.0 + _dust.initial_velocity_max = 2.4 + _dust.gravity = Vector3(0.0, -1.5, 0.0) + _dust.damping_min = 2.0 + _dust.damping_max = 3.0 + _world.add_child(_dust) + _ring_mat = ShaderMaterial.new() + _ring_mat.shader = load("res://game/resources/fear_burst.gdshader") as Shader + _ring_mat.set_shader_parameter("color", Color(0.6, 0.85, 1.0, 1.0)) + var plane := PlaneMesh.new() + plane.size = Vector2(16.0, 16.0) + _ring_mesh = MeshInstance3D.new() + _ring_mesh.name = "Ring" + _ring_mesh.mesh = plane + _ring_mesh.material_override = _ring_mat + _ring_mesh.visible = false + _world.add_child(_ring_mesh) + _burst = OmniLight3D.new() + _burst.name = "Burst" + _burst.light_color = Color(0.6, 0.85, 1.0) + _burst.omni_range = 14.0 + _burst.light_energy = 0.0 + _burst.shadow_enabled = false + _world.add_child(_burst) + + +## The overlay (letterbox, the skip hint and its ring, the box, the flash, the black, the card) +## and the loading screen over it. +func _build_screen() -> void: + _overlay = CutsceneKit.make_letterbox(self, "", "Hold [Space / Enter / A] to skip", 5) + _overlay.name = "Overlay" + _overlay.caption.visible = false + _ring = SkipRing.new() + _ring.mouse_filter = Control.MOUSE_FILTER_IGNORE + _overlay.add_child(_ring) + _ring.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_RIGHT) + _ring.offset_left = -404.0 + _ring.offset_right = -372.0 + _ring.offset_top = -68.0 + _ring.offset_bottom = -36.0 + _box = DialogueBox.new() + _box.name = "DialogueBox" + _overlay.add_child(_box) + _box.set_process(false) # stepped by step() + _box.blocked = blocked + _flash = _screen_rect(FLASH_COLOR) + _black = _screen_rect(Color.BLACK) + _card = Label.new() + _card.name = "Card" + Sketch.style(_card, 84, Sketch.TEXT, 0) + _card.text = CARD_TEXT + _card.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + _card.vertical_alignment = VERTICAL_ALIGNMENT_CENTER + _card.visible_characters = 0 + _card.visible = false + _overlay.add_child(_card) + _card.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + _loading_layer = CanvasLayer.new() + _loading_layer.name = "Loading" + _loading_layer.layer = 8 # over the overlay, under the menus + add_child(_loading_layer) + _loading = LoadingScreen.new() + _loading_layer.add_child(_loading) + _loading.set_process(false) # stepped by step() + + +func _screen_rect(color: Color) -> ColorRect: + var r := ColorRect.new() + r.color = Color(color, 0.0) + r.mouse_filter = Control.MOUSE_FILTER_IGNORE + _overlay.add_child(r) + r.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + return r + + +## Player 1's scarecrow hung on its post at START: lifted POST_LIFT, facing FACING, arms out (the +## mannequin's rest pose, a T-pose: the animation stopped), its physics off; a wooden post behind +## it with a crossbar behind its arms, tied at the wrists. +func _mount_scarecrow() -> void: + var body := sim.player + _ground = _ground_at(START) + body.set_physics_process(false) + body.velocity = Vector3.ZERO + body.stop_channel() + var yaw := atan2(-FACING.x, -FACING.z) + body.global_position = START + Vector3(0.0, _ground + POST_LIFT, 0.0) + body.model.rotation = Vector3(0.0, yaw, 0.0) + body.net_position = body.global_position + body.net_yaw = yaw + body.animation_player.stop() + body.set_core_glow(false) + # Not alive yet as far as the game goes: no fear ring at its feet, no prompts, no aim marker. + sim.scarecrow.alive = false + _marker_was = sim.combat.show_marker + sim.combat.show_marker = false + var skeletons := body.model.find_children("*", "Skeleton3D", true, false) + _skeleton = skeletons[0] as Skeleton3D if not skeletons.is_empty() else null + if _skeleton != null: + _skeleton.reset_bone_poses() + body.reset_physics_interpolation() + # The post: behind the body, up to its neck; the crossbar behind the arms. + var wood := StandardMaterial3D.new() + wood.albedo_color = Color(0.45, 0.31, 0.18) + var rope := StandardMaterial3D.new() + rope.albedo_color = Color(0.7, 0.58, 0.36) + _post = Node3D.new() + _post.name = "Post" + _world.add_child(_post) + _post.global_position = START + Vector3(0.0, _ground, 0.0) - FACING * 0.3 + _post.rotation.y = yaw + var top := POST_LIFT + 1.62 + var arms := POST_LIFT + _arm_height() + _cylinder(_post, 0.075, top + 0.25, Vector3(0.0, (top - 0.25) * 0.5, 0.0), Vector3.ZERO, wood) + _cylinder(_post, 0.06, 2.0, Vector3(0.0, arms, -0.1), Vector3(0.0, 0.0, PI / 2.0), wood) + for x: float in [-0.72, 0.72]: # rope round each wrist + var ring := TorusMesh.new() + ring.inner_radius = 0.13 + ring.outer_radius = 0.17 + var r := MeshInstance3D.new() + r.name = "Rope%d" % _ropes.size() + _ropes.append(r) + r.mesh = ring + r.rotation = Vector3(0.0, 0.0, PI / 2.0) + r.position = Vector3(x, arms, -0.3) + r.material_override = rope + _post.add_child(r) + + +## The ropes come loose as it drops off the post. +func _post_ropes_off() -> void: + for r in _ropes: + if is_instance_valid(r): + r.visible = false + + +## The height of the scarecrow's arms over its feet (its upper arm in the rest pose). +func _arm_height() -> float: + if _skeleton != null: + var bone := _skeleton.find_bone("upperarm.l") + if bone >= 0: + return _skeleton.get_bone_global_rest(bone).origin.y + return 1.1 + + +## The part: a dark metal capsule with a gyroscope ring round a glowing blue core (unshaded, so +## the toon look leaves it bright), a halo, a small light, and its trail (off till it falls). +func _make_part() -> Node3D: + var root := Node3D.new() + root.name = "Part" + var metal := StandardMaterial3D.new() + metal.albedo_color = Color(0.22, 0.23, 0.27) + metal.metallic = 0.75 + metal.roughness = 0.35 + var trim := StandardMaterial3D.new() + trim.albedo_color = Color(0.5, 0.52, 0.58) + trim.metallic = 0.8 + trim.roughness = 0.3 + _cylinder(root, 0.08, 0.46, Vector3.ZERO, Vector3.ZERO, metal) + _cylinder(root, 0.11, 0.05, Vector3(0.0, 0.2, 0.0), Vector3.ZERO, trim) + _cylinder(root, 0.11, 0.05, Vector3(0.0, -0.2, 0.0), Vector3.ZERO, trim) + var torus := TorusMesh.new() + torus.inner_radius = 0.17 + torus.outer_radius = 0.215 + var ring := MeshInstance3D.new() + ring.mesh = torus + ring.rotation.x = PI / 2.0 + ring.material_override = trim + root.add_child(ring) + _core_mat = StandardMaterial3D.new() + _core_mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + _core_mat.albedo_color = PART_BLUE + var sphere := SphereMesh.new() + sphere.radius = 0.12 + sphere.height = 0.24 + var core := MeshInstance3D.new() + core.name = "Core" + core.mesh = sphere + core.material_override = _core_mat + core.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + root.add_child(core) + var quad := QuadMesh.new() + quad.size = Vector2(1.0, 1.0) + var halo := MeshInstance3D.new() + halo.name = "Halo" + halo.mesh = quad + halo.material_override = _glow_material(Color(PART_BLUE, 0.8), BaseMaterial3D.BILLBOARD_ENABLED) + halo.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + root.add_child(halo) + _part_light = OmniLight3D.new() + _part_light.light_color = PART_BLUE + _part_light.omni_range = 3.5 + _part_light.light_energy = 1.2 + _part_light.shadow_enabled = false + root.add_child(_part_light) + _trail = Trail.new(Color(0.35, 0.65, 1.0, 0.85), 0.34, 0.5) + root.add_child(_trail) + return root + + +## Loose glowing specks (additive) or puffs (not): emitted in world space, so they stay behind +## what emits them; they shrink and fade over their life. +func _particles(color: Color, size: float, amount: int, life: float, additive := true) -> CPUParticles3D: + var p := CPUParticles3D.new() + p.emitting = false + p.amount = amount + p.lifetime = life + p.local_coords = false + var quad := QuadMesh.new() + quad.size = Vector2(size, size) + var mat := _glow_material(Color.WHITE, BaseMaterial3D.BILLBOARD_PARTICLES) + if not additive: + mat.blend_mode = BaseMaterial3D.BLEND_MODE_MIX + quad.material = mat + p.mesh = quad + p.direction = Vector3.UP + p.spread = 180.0 + p.initial_velocity_min = 0.05 + p.initial_velocity_max = 0.4 + p.gravity = Vector3.ZERO + var curve := Curve.new() + curve.add_point(Vector2(0.0, 1.0)) + curve.add_point(Vector2(1.0, 0.25 if additive else 1.6)) + p.scale_amount_curve = curve + var ramp := Gradient.new() + ramp.set_color(0, color) + ramp.set_color(1, Color(color.lightened(0.3), 0.0)) + p.color_ramp = ramp + return p + + +static func _glow_material(color: Color, billboard: BaseMaterial3D.BillboardMode) -> StandardMaterial3D: + var m := StandardMaterial3D.new() + m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + m.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA + m.blend_mode = BaseMaterial3D.BLEND_MODE_ADD + m.albedo_color = color + m.albedo_texture = _soft_dot() + m.vertex_color_use_as_albedo = true + m.billboard_mode = billboard + m.billboard_keep_scale = true + m.cull_mode = BaseMaterial3D.CULL_DISABLED + m.disable_receive_shadows = true + return m + + +## A soft round dot (white, fading out to the edge). +static func _soft_dot() -> GradientTexture2D: + if _dot == null: + var g := Gradient.new() + g.set_color(0, Color(1.0, 1.0, 1.0, 1.0)) + g.set_color(1, Color(1.0, 1.0, 1.0, 0.0)) + _dot = GradientTexture2D.new() + _dot.gradient = g + _dot.fill = GradientTexture2D.FILL_RADIAL + _dot.fill_from = Vector2(0.5, 0.5) + _dot.fill_to = Vector2(1.0, 0.5) + _dot.width = 64 + _dot.height = 64 + return _dot + + +static func _cylinder(parent: Node3D, radius: float, height: float, at: Vector3, rot: Vector3, mat: Material) -> MeshInstance3D: + var mesh := CylinderMesh.new() + mesh.top_radius = radius + mesh.bottom_radius = radius + mesh.height = height + mesh.radial_segments = 12 + var mi := MeshInstance3D.new() + mi.mesh = mesh + mi.position = at + mi.rotation = rot + mi.material_override = mat + parent.add_child(mi) + return mi + + +# --- Pieces of the action ------------------------------------------------------------------------ + +## A farmer steps out (at OUT_AT) and walks their path to the car's door, then faces the car. +func _walk(i: int, delta: float) -> void: + var f := _farmers[i] + if not f.visible: + if _t < OUT_AT[i]: + return + f.visible = true + f.global_position = DOOR + _anims[i].play(&"Walking_A", 0.1) + var path := _paths[i] + if _legs[i] >= path.size(): + return + var to := path[_legs[i]] - f.global_position + to.y = 0.0 + var step := WALK_SPEED * delta + if to.length() <= step: + f.global_position = path[_legs[i]] + _legs[i] += 1 + if _legs[i] >= path.size(): + CutsceneKit.face(f, _car.global_position) + _anims[i].play(&"Idle_A", 0.25) + return + f.global_position += to.normalized() * step + var turn := atan2(to.x, to.z) + f.rotation.y = lerp_angle(f.rotation.y, turn, 1.0 - exp(-10.0 * delta)) + + +func _arrived(i: int) -> bool: + return _legs[i] >= _paths[i].size() + + +func _talk(path: String) -> void: + _talked = true + var c := load(path) as Conversation + if c == null or not _box.play(c): + _box.stop() + + +## The farm at night under the black: the car and the farmers gone, the night look snapped with +## the lanterns dark, the UFO far off with its hum, the camera low on the farm. +func _go_night() -> void: + _night = true + if _engine != null: + _engine.stop() + if _car != null: + _car.queue_free() + _car = null + _engine = null + for f in _farmers: + f.queue_free() + _farmers.clear() + _anims.clear() + var dn := sim.day_night + if dn != null: + dn.forced = "night" + dn.lanterns_dark = true + dn.snap() + _ufo.visible = true + _spin_rate = 1.0 + _tug = Vector2.ZERO + _tug_speed = Vector2.ZERO + _place_ufo(UFO_FROM, (HOVER - UFO_FROM).normalized(), 0.0, 0.0) + if _hum.stream != null: + _hum.play() + CutsceneKit.move_camera(_camera, FLIGHT_CAMERA, _lifted(FLIGHT_CAMERA, UFO_FROM, LINE_LIFT), 1.0, 1.0) + + +## A jerk on the controls at each new line: alternately to one side and the other (who's got the +## stick), a dip or a climb, and a lurch forward. +func _tug_line(line: int) -> void: + var side := 1.0 if line % 2 == 0 else -1.0 + _tug_speed += Vector2(side * 12.0, -5.0 if line % 2 == 0 else 4.0) + _lurch = 0.6 + _spin_rate = 1.0 + 4.0 * side + + +## A smaller, guilty shuffle at each line of the uh-oh. +func _shuffle(line: int) -> void: + var side := -1.0 if line % 2 == 0 else 1.0 + _tug_speed += Vector2(side * 4.0, 1.5) + _spin_rate = 1.0 - 1.5 * side + + +## The tug's spring (stiffness, damping) back to the path. +func _step_tug(delta: float, stiffness: float, damping: float) -> void: + var left := minf(delta, 0.25) + while left > 0.0: + var h := minf(left, 1.0 / 60.0) + _tug_speed += (-_tug * stiffness - _tug_speed * damping) * h + _tug += _tug_speed * h + left -= h + _spin_rate = lerpf(_spin_rate, 1.0, 1.0 - exp(-1.5 * delta)) + + +## Puts the UFO at `at`, tilted (bank: about fwd, its travel; pitch: nose down about its side), spun. +func _place_ufo(at: Vector3, fwd: Vector3, bank: float, pitch: float) -> void: + var f := Vector3(fwd.x, 0.0, fwd.z) + f = f.normalized() if f.length_squared() > 1e-6 else Vector3.FORWARD + var side := f.cross(Vector3.UP).normalized() + var tilt := Basis(f, bank) * Basis(side, -pitch) + _ufo.global_transform = Transform3D(tilt * Basis(Vector3.UP, _spin), at) + + +## The UFO hanging over the farm (the flash stage), settling; once the flash has gone off it backs +## away (out of the shot) to where it hangs, guilty, for the uh-oh. +func _hover_ufo(delta: float) -> void: + _sway *= exp(-3.0 * delta) + _spin += _spin_rate * delta + _center = _center.lerp(HOVER_AFTER if _alive_step >= 1 else HOVER, 1.0 - exp(-1.2 * delta)) + var across := _across() + _place_ufo(_center + across * _sway, across.cross(Vector3.UP), 0.0, 0.0) + + +## Across the shot (the camera's right, level). +func _across() -> Vector3: + var r := _camera.global_basis.x + r.y = 0.0 + return r.normalized() if r.length_squared() > 1e-6 else Vector3.RIGHT + + +## The part pops off the rim on the scarecrow's side, a little round from the camera, and +## tumbles down to land in front of it; the trail comes on, and a falling whistle. +func _pop_part() -> void: + _land = START + FACING * 0.8 + _land.y = _ground_at(_land) + 0.12 + var toward := Vector3(_land.x - _center.x, 0.0, _land.z - _center.z) + toward = toward.normalized() if toward.length_squared() > 1e-6 else -FACING + var rim := toward * 0.78 * UFO_SCALE + _part_from = _ufo.global_position + rim + Vector3(0.0, -0.4, 0.0) + # From there to the landing spot in FALL_TIME, falling at 9.8 m/s². + _part_velocity = (_land - _part_from - Vector3(0.0, -4.9, 0.0) * FALL_TIME * FALL_TIME) / FALL_TIME + _part_spin = Vector3(7.0, 4.0, 9.0) + _part.global_position = _part_from + _part.visible = true + _trail.emitting = true + _pulse_part(1.0) + if sim.audio != null: + sim.audio.play("part_fall", _part_from) + + +func _land_part() -> void: + _landed = true + _part.global_position = _land + _part.rotation = Vector3(0.0, 0.4, deg_to_rad(78.0)) # on its side + _trail.emitting = false + _dust.global_position = _land + _dust.restart() + _dust.emitting = true + _burst.global_position = _land + Vector3(0.0, 0.6, 0.0) + _ring_mesh.global_position = Vector3(_land.x, _ground + 0.03, _land.z) + if sim.audio != null: + sim.audio.play("fall", _land) + + +## The part's core and light at strength k (1 at rest). +func _pulse_part(k: float) -> void: + if _core_mat != null: + _core_mat.albedo_color = PART_BLUE.lerp(Color.WHITE, clampf((k - 1.0) / 3.0, 0.0, 0.8)) + if _part_light != null: + _part_light.light_energy = 1.2 * k + + +## Its head turns up toward the UFO (a LookAtModifier3D on the head, easing in). +func _look_up() -> void: + if _skeleton == null or _ufo == null: + return + _look = LookAtModifier3D.new() + _look.name = "IntroLookUp" + _look.bone_name = "head" + _look.influence = 0.0 + _look.duration = 0.6 + _skeleton.add_child(_look) + _look.target_node = _look.get_path_to(_ufo) + + +## Low behind the scarecrow's right shoulder, looking up past it at the UFO (rate: how closely it +## follows the UFO). +func _uh_oh_shot(_delta: float, rate_delta: float, rate: float) -> void: + var right := FACING.cross(Vector3.UP) + var at := _stand() - FACING * UH_OH_BACK + right * UH_OH_SIDE + Vector3(0.0, UH_OH_HEIGHT, 0.0) + _camera.fov = UH_OH_FOV + CutsceneKit.move_camera(_camera, at, _lifted(at, _ufo.global_position, LINE_LIFT), rate_delta, rate) + + +## Where the scarecrow stands once it's off its post. +func _stand() -> Vector3: + return START + FACING * HOP + Vector3(0.0, _ground, 0.0) + + +## Eases the camera at `at` to look under target by LINE_LIFT degrees (the target in the upper +## half of the frame, over the box's lines). +func _track(at: Vector3, target: Vector3, delta: float, rate: float) -> void: + CutsceneKit.move_camera(_camera, at, _lifted(at, target, LINE_LIFT), delta, rate) + + +static func _lifted(from: Vector3, target: Vector3, degrees: float) -> Vector3: + var d := target - from + var right := d.cross(Vector3.UP) + if right.length_squared() < 1e-6: + return target + return from + d.rotated(right.normalized(), -deg_to_rad(degrees)) + + +## Where the listener is: on the shot's subject. +func _hear() -> void: + if _ears == null: + return + match stage: + "leave": + _ears.global_position = (DOOR + _doors[0]) * 0.5 if not _doors.is_empty() else DOOR + "board": + _ears.global_position = _car.global_position + "drive": + _ears.global_position = _car.global_position if _driven < _gap_at - GAP_LEAD else _camera.global_position + "card", "flight", "wobble": + _ears.global_position = _camera.global_position + _: + _ears.global_position = _stand() + + +## How many letters of the card are written t seconds into it. +static func _card_letters(t: float) -> int: + var at := 0.0 + for i in CARD_TEXT.length(): + at += CARD_DOT if CARD_TEXT[i] == "." else 1.0 / CARD_LETTERS + if at > t: + return i + return CARD_TEXT.length() + + +static func _bezier(a: Vector3, b: Vector3, c: Vector3, t: float) -> Vector3: + return a.lerp(b, t).lerp(b.lerp(c, t), t) + + +## The ground's height at (x, z) (the farm's collision; 0 where there's none). +func _ground_at(at: Vector3) -> float: + var space := get_world_3d().direct_space_state if is_inside_tree() else null + if space == null: + return 0.0 + var q := PhysicsRayQueryParameters3D.create(Vector3(at.x, 20.0, at.z), Vector3(at.x, -5.0, at.z), 1) + var hit := space.intersect_ray(q) + return float((hit["position"] as Vector3).y) if not hit.is_empty() else 0.0 + + +func _poll_skip(delta: float) -> void: + var frame := Engine.get_process_frames() + if frame > _last_frame + 2: + _armed = false # back from a pause: a key still down from the menu doesn't count + _last_frame = frame + var held := false + for action in SKIP_ACTIONS: + held = held or Input.is_action_pressed(action) + if not held or (blocked.is_valid() and bool(blocked.call())): + _armed = _armed or not held + _hold = 0.0 + elif _armed: + _hold += delta + if _hold >= SKIP_HOLD: + skip() + if _ring != null: + _ring.set_progress(_hold / SKIP_HOLD) diff --git a/game/scripts/opening_intro.gd.uid b/game/scripts/opening_intro.gd.uid new file mode 100644 index 0000000..96418ca --- /dev/null +++ b/game/scripts/opening_intro.gd.uid @@ -0,0 +1 @@ +uid://cppgmcqeukqgy diff --git a/game/scripts/review_panel.gd b/game/scripts/review_panel.gd index 4b05a53..623ca4a 100644 --- a/game/scripts/review_panel.gd +++ b/game/scripts/review_panel.gd @@ -7,7 +7,8 @@ extends CenterContainer ## * the enemies defeated, by type; ## * the materials gathered over the day and night. ## Each row has its icon; a type or material with none isn't listed. "Start the day" (focused, -## so Enter / A work) ends it. The first morning explains the vacation instead of results. +## so Enter / A work) ends it. The first morning explains the vacation instead of results. It +## stays down while the opening intro has the farm (intro.running). const CATEGORIES := ["Crops", "Animals", "Supplies"] const ENEMY_TYPES := [EnemySystem.TYPE_CROW, EnemySystem.TYPE_THIEF, EnemySystem.TYPE_BREAKER, EnemySystem.TYPE_UFO] @@ -19,8 +20,9 @@ const BOTTOM := 70.0 const WIDTH := 880.0 var campaign: CampaignController -## Set by FarmSim: the night plans (last night's title). +## Set by FarmSim: the night plans (last night's title), and the opening intro. var waves: WaveDirector +var intro: OpeningIntro var _board: PanelContainer var _title: Label @@ -151,7 +153,7 @@ static func backing() -> StyleBoxFlat: func refresh() -> void: if campaign == null: return - visible = campaign.state.phase == CampaignController.Phase.MORNING + visible = campaign.state.phase == CampaignController.Phase.MORNING and not (intro != null and intro.running) mouse_filter = Control.MOUSE_FILTER_STOP if visible else Control.MOUSE_FILTER_IGNORE if not visible: return @@ -177,7 +179,14 @@ func refresh() -> void: _fill_list(_enemies, _no_enemies, func(t: int) -> int: return int(e.get("killed_" + EnemySystem.TYPE_NAMES[t], 0))) _fill_list(_materials, _no_materials, func(m: String) -> int: return int(e.get("gathered_" + m, 0))) _board.queue_redraw() - _start.grab_focus.call_deferred() + _focus_start.call_deferred() + + +## Start the day takes the focus (unless the sign went down again meanwhile: a hidden button +## would still take Enter). +func _focus_start() -> void: + if is_visible_in_tree(): + _start.grab_focus() ## The results table as text, one row per category ("Crops 4 3 1"), for tests. diff --git a/game/scripts/tutorial.gd b/game/scripts/tutorial.gd index 8ec6a08..2962c7a 100644 --- a/game/scripts/tutorial.gd +++ b/game/scripts/tutorial.gd @@ -10,6 +10,7 @@ extends Control ## [Backspace / Back] hides them until the game is restarted; Settings turns them off. ## Finished tips stay finished for the session, so a retry or a second vacation doesn't repeat ## them. +## None show while a talking-head conversation or the opening intro is up. const TEXT := { "move": "Move with [W A S D] or the left stick. You're the scarecrow: keep the farm safe until the farmers are back.", @@ -93,7 +94,7 @@ func _process(delta: float) -> void: return var s := sim.campaign.state if not enabled or dismissed or s.night != 1 or sim.campaign.is_over() or sim._menu_open() \ - or (sim.dialogue != null and sim.dialogue.is_playing()): + or (sim.dialogue != null and sim.dialogue.is_playing()) or (sim.intro != null and sim.intro.busy()): _show("") return _check_done() diff --git a/game/tests/run_tests.gd b/game/tests/run_tests.gd index 22b73b7..962c373 100644 --- a/game/tests/run_tests.gd +++ b/game/tests/run_tests.gd @@ -26,6 +26,7 @@ const SUITES := [ "res://game/tests/test_look.gd", "res://game/tests/test_dialogue.gd", "res://game/tests/test_loading.gd", + "res://game/tests/test_intro.gd", ] const TICK := 1.0 / 60.0 ## Points on the farm's edge (FarmZones.edge) for tests that send an enemy in from a known side: diff --git a/game/tests/test_flow.gd b/game/tests/test_flow.gd index b3dc705..5a15d71 100644 --- a/game/tests/test_flow.gd +++ b/game/tests/test_flow.gd @@ -1,6 +1,7 @@ extends RefCounted ## The whole game through its entry scene (main.tscn, with test save and settings paths): the -## main menu over the paused farm; New vacation, Continue, and their questions; pausing freezes +## main menu over the paused farm; New vacation (its opening intro, skipped here: test_intro +## covers it), Continue, and their questions; pausing freezes ## the simulation tick; settings apply and persist from the pause menu; Restart the night and ## Save & quit to menu put the farm back at the saved morning without touching the save; a ## damaged save can't be continued; quitting a hosted co-op game from the pause menu leaves the @@ -62,6 +63,15 @@ func _press(action: String) -> void: await r.process_frame +## New vacation's opening intro, skipped to its end (the first morning's sign). +func _skip_intro() -> void: + sim.intro.skip() + var t := 0.0 + while sim.intro.busy() and t < 10.0: + sim.intro.step(DT) + t += DT + + func _hud_visible() -> bool: return (main.farm.get_node("Hud") as CanvasLayer).visible @@ -85,9 +95,12 @@ func _title_screen() -> void: "the UI theme is the project's default") main.main_menu.new_button.pressed.emit() var saved := SaveGame.read(SAVE) + r.check(main.screen == Main.Screen.PLAYING and not r.paused and sim.intro.running and c.state.phase == P.MORNING, + "New vacation (no save to replace) starts at once, with the opening intro") + _skip_intro() r.check(main.screen == Main.Screen.PLAYING and not r.paused and _hud_visible() and c.state.phase == P.MORNING and sim.review_panel.visible and main.get_viewport().get_camera_3d() == sim.camera, - "New vacation (no save to replace) starts at once: the morning screen, the HUD, the follow camera") + "after it, the morning screen, the HUD, the follow camera") r.check(saved.status == SaveGame.Status.OK and saved.state.night == 1, "and saves the new vacation's first morning") @@ -197,6 +210,7 @@ func _continue_and_new() -> void: main.main_menu.new_button.pressed.emit() r.check(main.screen == Main.Screen.PLAYING and SaveGame.read(SAVE).status == SaveGame.Status.OK, "New vacation doesn't ask about a damaged save and replaces it") + _skip_intro() ## Hosting co-op, the pause menu freezes only this scarecrow; quitting to the menu from it must @@ -414,6 +428,7 @@ func _audio() -> void: r.check(audio._day.playing and audio._night.playing and (audio._day.stream as AudioStreamWAV).loop_mode == AudioStreamWAV.LOOP_FORWARD and audio._day.bus == &"Ambience", "the day and night ambience loop on the Ambience bus") main.new_vacation() + _skip_intro() var before := audio.played.duplicate() var count := func(cue: String) -> int: return int(audio.played.get(cue, 0)) - int(before.get(cue, 0)) sim.combat.fired.emit() diff --git a/game/tests/test_intro.gd b/game/tests/test_intro.gd new file mode 100644 index 0000000..4269fb1 --- /dev/null +++ b/game/tests/test_intro.gd @@ -0,0 +1,273 @@ +extends RefCounted +## The opening intro (OpeningIntro) through the game's entry scene (main.tscn, with test save and +## settings paths): New vacation plays it, Continue and hosting co-op don't. Stepped through, it +## visits every stage in order while it holds the farm (no morning sign, no HUD, the scarecrow +## frozen on its post without its glow, the light forced), and it ends on the first morning's sign +## (focused) with the farm exactly as new_campaign() leaves it. Skipping it from any stage +## (pressing or holding), Restart the night, and Save & quit to menu leave it just as clean. + +const SAVE := "user://test_intro_save.json" +const SETTINGS := "user://test_intro_settings.cfg" +const DT := 1.0 / 30.0 +const LIMIT := 120.0 # seconds of stepping before a run counts as stuck + +var r: GameTestRunner +var main: Main +var sim: FarmSim +var intro: OpeningIntro + + +func run(p_r: GameTestRunner) -> void: + r = p_r + _clean() + main = (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main + main.save_path = SAVE + main.settings_path = SETTINGS + r.root.add_child(main) + await r.process_frame + await r.physics_frame + sim = main.sim + intro = sim.intro + intro.set_process(false) # stepped by hand + await _new_and_continue() + await _whole_intro() + await _skips() + await _hold_to_skip() + await _restart_and_quit() + await _hosting() + main.queue_free() + r.paused = false + await r.process_frame + _clean() + + +func _clean() -> void: + for p in [SAVE, SAVE + ".tmp", SETTINGS]: + if FileAccess.file_exists(p): + DirAccess.remove_absolute(ProjectSettings.globalize_path(p)) + + +func _hud_visible() -> bool: + return (main.farm.get_node("Hud") as CanvasLayer).visible + + +## New vacation (from the menu; it asks over a save). +func _new_vacation() -> void: + main.main_menu.new_button.pressed.emit() + if main.confirm.is_open: + main.confirm.yes_button.pressed.emit() + + +## Steps until the stage is `until` (or it's over); returns false if it never got there. +func _step_to(until: String) -> bool: + var t := 0.0 + while intro.stage != until and not intro.done and t < LIMIT: + intro.step(DT) + t += DT + return intro.stage == until + + +func _step_to_end() -> bool: + var t := 0.0 + while intro.busy() and t < LIMIT: + intro.step(DT) + t += DT + return intro.done + + +## The farm held by the intro: no sign, no HUD, the intro's camera, the scarecrow frozen. +func _held() -> bool: + return intro.running and not sim.review_panel.visible and not _hud_visible() and sim.local_frozen \ + and not sim.player.input_enabled and not sim.player.is_physics_processing() \ + and main.get_viewport().get_camera_3d() != sim.camera + + +## The farm as new_campaign() leaves it, and the first morning's sign up (focused). +func _check_clean(what: String) -> void: + var p := sim.player + var dn := sim.day_night + var morning := DayNight.morning() + var light := dn.forced == "" and not dn.lanterns_dark and is_equal_approx(float(dn.current["elev"]), float(morning["elev"])) \ + and is_equal_approx(float(dn.current["energy"]), float(morning["energy"])) \ + and is_equal_approx(float(dn.target()["energy"]), float(morning["energy"])) + var body := p.global_position.distance_to(OpeningIntro.START) < 0.01 and is_zero_approx(p.model.rotation.y) \ + and p.is_physics_processing() and p.input_enabled and not sim.local_frozen and p.core_glow.visible \ + and p.find_children("*", "LookAtModifier3D", true, false).is_empty() and sim.scarecrow.alive and sim.combat.show_marker + var gone := intro.done and not intro.running and intro.stage == "end" and intro.get_child_count() == 0 + var screen := _hud_visible() and main.get_viewport().get_camera_3d() == sim.camera and sim.review_panel.visible \ + and sim.campaign.state.phase == CampaignController.Phase.MORNING and sim.campaign.state.night == 1 + var sound := sim.audio.focus == p and not sim.audio.scene and sim.audio.music_track == "farm" + await r.process_frame + await r.process_frame + var focus := sim.review_panel._start.has_focus() + r.check(gone and body and light and screen and sound and focus, + "%s: the farm's as new_campaign() left it (intro gone %s, scarecrow at its start with input and glow %s, the morning light %s, HUD / game camera / sign %s, sounds %s, Start focused %s)" + % [what, gone, body, light, screen, sound, focus]) + + +## New vacation plays it, holding the farm; Save & quit to menu takes it down; Continue doesn't +## play it. +func _new_and_continue() -> void: + _new_vacation() + r.check(main.screen == Main.Screen.PLAYING and intro.running and intro.stage == "leave" and _held(), + "New vacation starts the intro: no sign, no HUD, its own camera, the scarecrow frozen") + var p := sim.player + var on_post := absf(p.global_position.y - OpeningIntro.POST_LIFT) < 0.2 and not p.core_glow.visible \ + and not p.animation_player.is_playing() and sim.day_night.forced == "morning" and sim.day_night.lanterns_dark \ + and not sim.scarecrow.alive and not sim.combat.show_marker + r.check(on_post, "the scarecrow hangs on its post (raised, T-pose: no animation), not alive yet (no chest glow, fear ring, or aim marker), a forced morning, lantern dark") + var at := p.global_position + Input.action_press(&"move_forward") + for i in 6: + await r.physics_frame + Input.action_release(&"move_forward") + r.check(p.global_position == at and intro.running, "and the scarecrow can't move") + r.check(not sim.tutorial._box.visible, "no tips meanwhile") + main.to_menu() + r.check(main.screen == Main.Screen.MENU and not intro.busy() and intro.get_child_count() == 0 and not sim.local_frozen + and sim.player.is_physics_processing() and sim.day_night.forced == "" and sim.player.core_glow.visible, + "Save & quit to menu mid-intro: nothing of it left, the scarecrow given back") + main.main_menu.continue_button.pressed.emit() + r.check(main.screen == Main.Screen.PLAYING and not intro.busy() and sim.review_panel.visible and _hud_visible(), + "Continue plays no intro: straight to the saved morning's sign") + main.to_menu() + + +## The whole intro, stepped: every stage in order, the farm held until it's handed back. +func _whole_intro() -> void: + var audio := sim.audio + var before := audio.played.duplicate() + var count := func(cue: String) -> int: return int(audio.played.get(cue, 0)) - int(before.get(cue, 0)) + var fired: Array[int] = [0] + var on_finished := func() -> void: fired[0] += 1 + intro.finished.connect(on_finished) + _new_vacation() + var stinger := false + for v in audio._voices_ui: + stinger = stinger or (v.playing and v.get_meta(&"cue", "") == "morning") + r.check(count.call("morning") == 1 and not stinger, "new_campaign()'s morning stinger is stopped under the intro") + var seen: Array[String] = [intro.stage] + var length := {intro.stage: 0.0} + var held := true + var night_ok := false + var part_ok := false + var flash_ok := false + var t := 0.0 + while intro.busy() and t < LIMIT: + intro.step(DT) + t += DT + if intro.stage != seen[-1]: + seen.append(intro.stage) + length[intro.stage] = 0.0 + match intro.stage: + "flight": + night_ok = sim.day_night.forced == "night" and sim.day_night.lanterns_dark and intro._ufo.visible \ + and audio.music_track == "" and audio._ambience_target == Vector2(0.0, 1.0) + "flash": + part_ok = intro._part.visible and intro._part.global_position.distance_to(OpeningIntro.START + OpeningIntro.FACING * 0.8) < 0.3 + "uh_oh": + flash_ok = sim.player.core_glow.visible and not sim.day_night.lanterns_dark \ + and absf(sim.player.global_position.y - intro._ground) < 0.01 and not intro._part.visible + else: + length[intro.stage] = float(length[intro.stage]) + DT + if intro.running and not _held(): + held = false + r.check(seen == OpeningIntro.STAGES, "it visits every stage in order (%s)" % [seen]) + r.check(held, "and holds the farm all along (no sign, no HUD, the scarecrow frozen) until it's handed back") + r.check(night_ok, "the night falls under the card: forced night, the lantern dark, the UFO up, night ambience, no music") + r.check(part_ok, "the part lands in front of the scarecrow") + r.check(flash_ok, "after the flash the scarecrow is down off its post, glowing, its lantern lit, the part gone into it") + r.check(fired[0] == 1 and t > 50.0 and t < 100.0, "finished once, %.1f s in all" % t) + var parts := PackedStringArray() + for s: String in seen: + parts.append("%s %.1f" % [s, float(length[s])]) + r.info("intro stages (s): %s; %.1f s in all" % [", ".join(parts), t]) + var cues := ["door_creak", "car_door", "horn", "ufo_whine", "part_fall", "life_flash", "ufo_zoom", "morning"] + var counts := [] + for c: String in cues: + counts.append(count.call(c)) + r.check(counts == [1, 2, 1, 1, 1, 1, 1, 2], "its sounds: %s = %s (the morning stinger with the sign)" % [cues, counts]) + intro.finished.disconnect(on_finished) + await _check_clean("at the end") + main.to_menu() + + +## A skip from any stage fades straight to the sign, the farm just as clean. +func _skips() -> void: + for stage in OpeningIntro.STAGES: + if stage == "end": + continue + _new_vacation() + var got := _step_to(stage) + var t := 0.0 + while got and intro.stage == stage and t < 0.6: + intro.step(DT) + t += DT + var at := intro.stage + intro.skip() + var ended := _step_to_end() + r.check(got and ended and intro._loading == null, "a skip in %s ends it" % at) + await _check_clean("skipped in " + at) + main.to_menu() + + +## Holding Space / Enter / A for a second skips it (a key already down at the start doesn't). +func _hold_to_skip() -> void: + Input.action_press(&"ui_accept") + _new_vacation() + for i in 45: + intro.step(DT) + var ignored := not intro._skipping + Input.action_release(&"ui_accept") + intro.step(DT) + Input.action_press(&"ui_accept") + for i in 20: + intro.step(DT) + var early := intro._skipping + for i in 12: + intro.step(DT) + var skipping := intro._skipping + Input.action_release(&"ui_accept") + _step_to_end() + r.check(ignored and not early and skipping, "holding [Space / Enter / A] a second skips (a key held from the menu doesn't count)") + await _check_clean("held to skip") + main.to_menu() + + +## The pause menu over it: Restart the night skips it; Save & quit to menu takes it down. +func _restart_and_quit() -> void: + _new_vacation() + var morning := SaveGame.read(SAVE).state.to_dict() + _step_to("flight") + main.pause() + r.check(main.screen == Main.Screen.PAUSED and r.paused and intro._box.is_blocked(), "Escape pauses it (its box waits)") + main.pause_menu.restart_button.pressed.emit() + main.confirm.yes_button.pressed.emit() + r.check(main.screen == Main.Screen.PLAYING and not r.paused and intro._skipping and sim.local_frozen, + "Restart the night during it skips it (still held while it fades)") + _step_to_end() + await _check_clean("restarted") + r.check(JSON.stringify(SaveGame.read(SAVE).state.to_dict()) == JSON.stringify(morning), "the save is still the first morning") + main.to_menu() + _new_vacation() + _step_to("uh_oh") + main.pause() + main.pause_menu.menu_button.pressed.emit() + var p := sim.player + r.check(main.screen == Main.Screen.MENU and not intro.busy() and intro.get_child_count() == 0 and not sim.local_frozen + and p.global_position.distance_to(OpeningIntro.START) < 0.01 and p.is_physics_processing() and p.core_glow.visible + and p.find_children("*", "LookAtModifier3D", true, false).is_empty() and sim.day_night.forced == "" + and not sim.day_night.lanterns_dark and not sim.audio.scene, "Save & quit to menu late in it leaves nothing behind") + + +## Hosting co-op starts the vacation without the intro. +func _hosting() -> void: + var gd := main.lobby.gdsync + main.lobby.gdsync = null # (no network in the test: the lobby just fails) + main._host_coop(CoopLobby.Mode.LAN, "Ana", false) + if main.confirm.is_open: + main.confirm.yes_button.pressed.emit() + r.check(main.screen == Main.Screen.PLAYING and not intro.busy() and sim.review_panel.visible and _hud_visible() + and not sim.local_frozen, "hosting co-op starts a new vacation without the intro") + main.lobby.gdsync = gd + main.to_menu() diff --git a/game/tests/test_intro.gd.uid b/game/tests/test_intro.gd.uid new file mode 100644 index 0000000..c36fc05 --- /dev/null +++ b/game/tests/test_intro.gd.uid @@ -0,0 +1 @@ +uid://cn413pm2x21au diff --git a/game/tools/capture_intro.gd b/game/tools/capture_intro.gd new file mode 100644 index 0000000..12f5ddb --- /dev/null +++ b/game/tools/capture_intro.gd @@ -0,0 +1,96 @@ +extends SceneTree +## Captures the opening intro (OpeningIntro) for review: runs the real game (main.tscn, so the +## toon look and the pixel outlines are on, as ToonLook comes with Main) in a window, starts a New +## vacation, and saves a PNG at the start of every stage and every --every seconds of it, then one +## of the first morning's sign, and quits. It needs a window (not --headless) and must not run +## fullscreen (the project's default), so pass --windowed and a resolution; a hidden window with +## VSync on crawls on some desktops, so keep it visible and pass --disable-vsync. --fixed-fps +## makes every frame the same game time, so the shots don't depend on the machine's speed: +## godot --path . --windowed --resolution 1600x900 --disable-vsync --fixed-fps 30 \ +## --script res://game/tools/capture_intro.gd -- --out=/tmp/hs-intro --every=2 +## Options (after --): --out=dir (default /tmp/hs-intro/), --every=seconds (default 2; 0: stage +## starts only), --prefix=text (default "intro"), --skip-at=stage (skips half a second into that +## stage, to look at the skip). It saves to its own user://capture_intro_* files, so the player's +## save and settings are never touched. + +const SAVE := "user://capture_intro_save.json" +const SETTINGS := "user://capture_intro_settings.cfg" +const LIMIT := 240.0 # seconds of intro before giving up + +var _out := "/tmp/hs-intro/" +var _every := 2.0 +var _prefix := "intro" +var _skip_at := "" +var _count: int = 0 + + +func _initialize() -> void: + for a in OS.get_cmdline_user_args(): + var arg := String(a) + if arg.begins_with("--out="): + _out = arg.trim_prefix("--out=") + elif arg.begins_with("--every="): + _every = float(arg.trim_prefix("--every=")) + elif arg.begins_with("--prefix="): + _prefix = arg.trim_prefix("--prefix=") + elif arg.begins_with("--skip-at="): + _skip_at = arg.trim_prefix("--skip-at=") + if not _out.ends_with("/"): + _out += "/" + _run.call_deferred() + + +func _run() -> void: + DirAccess.make_dir_recursive_absolute(_out) + var main := (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main + main.save_path = SAVE + main.settings_path = SETTINGS + root.add_child(main) + for i in 5: + await process_frame + main.new_vacation() + var intro := main.sim.intro if main.sim != null else null + if intro == null or not intro.busy(): + printerr("capture_intro: the intro didn't start") + quit(1) + return + var last := "" + var next_shot := 0.0 + var skipped := false + while intro.busy() and intro.elapsed < LIMIT: + await process_frame + if intro.stage != last: + last = intro.stage + await _shot(intro, "start") + elif _every > 0.0 and intro.elapsed >= next_shot: + next_shot = intro.elapsed + _every + await _shot(intro, "") + if _skip_at != "" and not skipped and intro.stage == _skip_at and intro.elapsed > 0.0: + skipped = true + for i in 15: + await process_frame + intro.skip() + for i in 30: # the sign settles + await process_frame + await _shot(intro, "sign") + print("capture_intro: %d shots in %s (%.1f s of intro)" % [_count, _out, intro.elapsed]) + main.queue_free() + await process_frame + await create_timer(0.3).timeout + _clean() + quit() + + +func _shot(intro: OpeningIntro, tag: String) -> void: + await RenderingServer.frame_post_draw + var image := root.get_texture().get_image() + var stage := intro.stage if intro.stage != "" else "none" + var file := "%s%s_%03d_%05.1fs_%s%s.png" % [_out, _prefix, _count, intro.elapsed, stage, "_" + tag if tag != "" else ""] + image.save_png(file) + _count += 1 + + +func _clean() -> void: + for p in [SAVE, SAVE + ".tmp", SETTINGS]: + if FileAccess.file_exists(p): + DirAccess.remove_absolute(ProjectSettings.globalize_path(p)) diff --git a/game/tools/capture_intro.gd.uid b/game/tools/capture_intro.gd.uid new file mode 100644 index 0000000..43f576e --- /dev/null +++ b/game/tools/capture_intro.gd.uid @@ -0,0 +1 @@ +uid://tmmr78wn70ce