From 8cb611ac1ab9cd7530e3e1fd530106b2ffd85f28 Mon Sep 17 00:00:00 2001 From: Wickedness Date: Fri, 19 Jun 2026 19:59:08 +0900 Subject: [PATCH] Animate pixel unit idle stances --- docs/ARCHITECTURE.md | 2 +- scripts/scenes/battle_scene.gd | 52 +++++++++++++++++++++------- tools/smoke_chapter_one_polish.gd | 57 +++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 13 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0c762b9..61e25f0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -59,7 +59,7 @@ Joined officers gate whether `requires_joined` player deployments are loaded at Inventory and campaign flags are copied from `CampaignState` into `BattleState` when a scenario starts. The pre-battle Chapters overview reads `CampaignState` chapter progress and can load completed or current battles without mutating the save. Briefings preview first-clear rewards, can expose `briefing.camp_conversations` through a selectable Talk menu with `briefing.camp_dialogue` as a fallback, can filter those conversations by saved campaign flags, can claim saved one-time camp conversation supply effects through `CampaignState` and refresh the loaded battle inventory copy, and show completed replay rewards as already claimed. The pre-battle Save menu can write the current campaign state to `user://campaign_manual_save.json`, and loading that checkpoint restores it into `user://campaign_save.json` before re-entering the same pending-choice, completion, or current-briefing branch as startup. Pre-battle shop stock comes from the loaded scenario's `shop.items` list plus matching `shop.conditional_items` blocks, with optional finite limits from item entries or `stock` maps, and `shop.merchant` lines are presentation-only camp flavor. Shop purchases and 50% sell-back are campaign transactions: they update saved gold, unequipped inventory, and finite-stock purchase counts immediately, write the save file, and refresh the already-loaded battle inventory before the player begins the battle. Camp conversation supply claims are also campaign transactions: they save a per-scenario conversation claim ledger and inventory immediately, then refresh the already-loaded battle inventory. Pre-battle Armory equipment changes use the same equipment rules as battle HUD equipment changes, then immediately save merged roster equipment/stat snapshots and inventory stock. Pre-battle Roster uses scenario `roster.max_units`, `roster.required_officers`, and `roster.required_units` to mark optional player deployments as sortie or reserve; reserve units remain in the candidate list but are excluded from board occupancy, drawing, selection, AI targeting, and living-unit victory checks. Non-controllable player units can act as protected escort targets: enemies can attack them and conditions can reference them, but they are skipped by player selection, Armory, Formation, counterattacks, and campaign roster progression snapshots when `persist_progression` is false. Scenario `ai_target_priority` nudges enemy movement and damage-skill scoring toward important targets such as envoys without overriding defeat bonuses or range checks, and `set_ai_target_priority` events can retune that battle-only pressure after an ambush, gate closure, or escort exposure. Pre-battle Formation uses the loaded scenario's `formation.cells` and only mutates current battle unit positions before battle-begin events fire. Destination victory cells from `unit_reaches_tile` conditions are exposed to the scene for objective overlays and tile info, and can be expressed as one `pos` or a multi-cell `cells` list; gated victory conditions can also expose the `unit_reaches_tile` event that unlocks them as the next visible objective marker. Rewarding movement events that grant items or gold can expose optional battlefield side markers and Korean tile-info labels through `when.label`, without being treated as victory objectives. Movement-triggered `unit_reaches_tile` events receive the unit that just moved, so ambushes and pickup events fire on entry rather than from units already standing on a marker; `unit_defeated` events receive the fallen unit before final victory/defeat checks, allowing named-officer reactions and last-moment reinforcements. Briefing data can append matching `briefing.conditional_lines`, and scenario events can use `when.campaign_flags` to branch dialogue, objective changes, item and gold pickups, AI target-priority shifts, and reinforcements from saved campaign choices or `when.after_event` to wait for earlier scenario beats. Consumable use can restore HP or MP, cure matching poison/seal/snare/disarm statuses, or cleanse negative stat debuffs, and in-battle item use, event pickup grants, event gold pickups, plus equipment swaps mutate only the battle copy until victory; defeats and restarts do not spend saved items, keep picked-up items or gold, or preserve in-battle gear changes. Post-battle choices write campaign `flags` only after the result-panel button is pressed; if the player reloads after rewards are saved but before selecting, the pending scenario id restores the victory choice panel without replaying rewards. The next battle button stays locked until the campaign choice save succeeds. Equipment rewards share the same `item_id -> count` inventory stock, cover weapon, armor, and accessory slots, can be equipped from the side HUD before the selected unit moves or acts, and do not appear in the consumable action menu. Named equipment currently uses the same stock model with a presentation-only rarity tag rather than unique item instances. Already completed scenarios can be replayed without granting duplicate rewards, choices, replay inventory consumption, event gold pickups, save writes, current-scenario advancement, finite-stock purchases, or camp conversation supply claims; pre-battle Shop, Armory, Roster, Formation, and Save are disabled on completed-scenario replays to avoid side effects. -The battle scene owns presentation feedback: briefing and result states use menu BGM, briefing headers combine `CampaignState` chapter ranges, campaign order, and title data with `BattleState` briefing, objective text, condition-progress text, and defeat-risk text, active battles use battle BGM and show an objective/progress/risk panel fed by `BattleState`, objective-update signals show a short HUD notice and refresh the objective panel immediately, dialogue lines can show optional cached portrait textures or speaker-initial fallback panels in an expanded visual-novel-style panel, can place the portrait on the left or right side of that panel, and expose progress plus previous-line controls while a sequence is open, the side HUD reuses cached officer portrait textures or class sprites for the selected unit or hovered unit and formats focus text with role, movement type, facing, current terrain move cost, defense/avoid bonuses, core stats, status effects, guard-zone AI hints, and gear, board maps can draw a scenario background texture under translucent terrain overlays, connected road segments, terrain detail patterns, shoreline/castle/forest/hill edge blends, compact recovery markers for healing terrain, compact side-event markers for visible item/gold pickups, and move-attack target badges for enemies that can be struck after movement, board units render class sprite tokens or generic-enemy transparent class cutouts, team rings, class badges, facing markers, generic-enemy marks, officer pins, low-HP warning rings, HP bar color states, and active support/debuff/poison/seal/snare/disarm status pips from battle state fields, item buttons can show optional cached item icons, hover previews are rendered as target badges from existing `BattleState` forecast APIs, equipment option menus show stat/range/effect deltas, result and inventory summaries show named equipment with compact rarity tags, selected area tactics highlight their affected cells, the Threat toggle overlays enemy physical and hostile tactic reach while tile info names threat sources, estimates physical damage, and summarizes hostile tactic damage or status effects against occupied cells, log/result hooks trigger placeholder SFX, support, debuff, poison, seal, snare, disarm, objective updates, AI target-focus changes, and item/gold pickup effects use distinct feedback, `BattleState.unit_motion_requested` asks the scene to interpolate a unit's draw position during movement, `BattleState.unit_action_motion_requested` keeps its rules-facing signal shape while the scene maps attacker class ids to infantry, archer, cavalry, command, and heavy attack presentation profiles, and `BattleState.combat_feedback_requested` asks the scene to draw transient floating combat text without changing battle rules. +The battle scene owns presentation feedback: briefing and result states use menu BGM, briefing headers combine `CampaignState` chapter ranges, campaign order, and title data with `BattleState` briefing, objective text, condition-progress text, and defeat-risk text, active battles use battle BGM and show an objective/progress/risk panel fed by `BattleState`, objective-update signals show a short HUD notice and refresh the objective panel immediately, dialogue lines can show optional cached portrait textures or speaker-initial fallback panels in an expanded visual-novel-style panel, can place the portrait on the left or right side of that panel, and expose progress plus previous-line controls while a sequence is open, the side HUD reuses cached officer portrait textures or class sprites for the selected unit or hovered unit and formats focus text with role, movement type, facing, current terrain move cost, defense/avoid bonuses, core stats, status effects, guard-zone AI hints, and gear, board maps can draw a scenario background texture under translucent terrain overlays, connected road segments, terrain detail patterns, shoreline/castle/forest/hill edge blends, compact recovery markers for healing terrain, compact side-event markers for visible item/gold pickups, and move-attack target badges for enemies that can be struck after movement, board units render class sprite tokens or generic-enemy transparent class cutouts, team rings, class badges, facing markers, generic-enemy marks, officer pins, low-HP warning rings, HP bar color states, active support/debuff/poison/seal/snare/disarm status pips, and a scene-clocked idle stance whose intensity reacts to selected, acted, and low-HP unit state, item buttons can show optional cached item icons, hover previews are rendered as target badges from existing `BattleState` forecast APIs, equipment option menus show stat/range/effect deltas, result and inventory summaries show named equipment with compact rarity tags, selected area tactics highlight their affected cells, the Threat toggle overlays enemy physical and hostile tactic reach while tile info names threat sources, estimates physical damage, and summarizes hostile tactic damage or status effects against occupied cells, log/result hooks trigger placeholder SFX, support, debuff, poison, seal, snare, disarm, objective updates, AI target-focus changes, and item/gold pickup effects use distinct feedback, `BattleState.unit_motion_requested` asks the scene to interpolate a unit's draw position during movement, `BattleState.unit_action_motion_requested` keeps its rules-facing signal shape while the scene maps attacker class ids to infantry, archer, cavalry, command, and heavy attack presentation profiles, and `BattleState.combat_feedback_requested` asks the scene to draw transient floating combat text without changing battle rules. Large tactical maps are presented through a fixed visible map window rather than by shrinking the whole board. `BattleScene` keeps a clamped `board_scroll_offset`, scrolls the board while the mouse is near or slightly outside the visible map edge, brightens the scrollable frame edge under the cursor, ignores board clicks outside the visible map window, and draws a small minimap plate inside the map view; clicking or dragging the minimap recenters the tactical viewport, while action feedback can focus the board on off-screen cells before motion or combat effects play. diff --git a/scripts/scenes/battle_scene.gd b/scripts/scenes/battle_scene.gd index c010ca7..25c91ad 100644 --- a/scripts/scenes/battle_scene.gd +++ b/scripts/scenes/battle_scene.gd @@ -59,6 +59,7 @@ const MAP_FOCUS_MARGIN := 96.0 const BATTLE_PRESENTATION_STEP_GAP := 0.08 const BATTLE_PRESENTATION_FEEDBACK_LAG := 0.10 const UNIT_MOVE_ANIMATION_DURATION := 0.18 +const UNIT_IDLE_PHASE_SPEED := 2.4 const TARGET_PREVIEW_BADGE_SIZE := Vector2(104, 22) const LOW_HP_WARNING_RATIO := 0.35 const UNIT_STATUS_MARKER_RADIUS := 6.0 @@ -442,6 +443,7 @@ var ui_regular_font: Font var ui_bold_font: Font var board_scroll_offset := Vector2.ZERO var minimap_dragging := false +var unit_idle_time := 0.0 func _ready() -> void: @@ -2636,7 +2638,8 @@ func _handle_key(event: InputEventKey) -> void: func _process(delta: float) -> void: var needs_redraw := false var had_sequence_presentation := _has_active_battle_presentation_sequence() - if battle_started and state.battle_status == BattleState.STATUS_ACTIVE and not _is_dialogue_visible(): + if _should_animate_unit_idle(): + unit_idle_time += delta needs_redraw = true if _update_edge_scroll(delta): needs_redraw = true @@ -2688,6 +2691,10 @@ func _process(delta: float) -> void: queue_redraw() +func _should_animate_unit_idle() -> bool: + return battle_started and state.battle_status == BattleState.STATUS_ACTIVE and not _is_dialogue_visible() + + func _can_select(unit: Dictionary) -> bool: if unit.is_empty(): return false @@ -3738,8 +3745,9 @@ func _draw_pixel_unit_sprite(rect: Rect2, unit: Dictionary, team_color: Color, m var profile := _pixel_unit_sprite_profile(unit) var family := str(profile.get("family", _unit_class_family(unit))) var phase := _unit_idle_phase(unit) - var bob := _unit_idle_bob(family, phase) - var step := _unit_idle_step(family, phase) + var idle_intensity := _unit_idle_intensity(unit) + var bob := _unit_idle_bob(family, phase, idle_intensity) + var step := _unit_idle_step(family, phase, idle_intensity) var pixel := float(profile.get("pixel", 3.0)) var safe_facing := -1 if facing < 0 else 1 var origin := Vector2(roundf(rect.position.x + 12.0), roundf(rect.position.y + 5.0 + bob)) @@ -3790,22 +3798,39 @@ func _unit_idle_phase(unit: Dictionary) -> float: var unit_id := str(unit.get("id", "unit")) for index in range(unit_id.length()): seed += unit_id.unicode_at(index) * (index + 1) - return float(Time.get_ticks_msec()) * 0.0024 + float(seed % 360) * 0.01745 + return unit_idle_time * UNIT_IDLE_PHASE_SPEED + float(seed % 360) * 0.01745 -func _unit_idle_bob(family: String, phase: float) -> float: +func _unit_idle_intensity(unit: Dictionary) -> float: + if unit.is_empty(): + return 1.0 + var intensity := 1.0 + if bool(unit.get("acted", false)): + intensity *= 0.34 + var max_hp: int = max(1, int(unit.get("max_hp", 1))) + var hp_ratio := float(unit.get("hp", max_hp)) / float(max_hp) + if hp_ratio <= LOW_HP_WARNING_RATIO: + intensity *= 0.58 + if str(unit.get("id", "")) == state.selected_unit_id and not bool(unit.get("acted", false)): + intensity *= 1.18 + return clampf(intensity, 0.18, 1.22) + + +func _unit_idle_bob(family: String, phase: float, intensity := 1.0) -> float: if family == "cavalry": - return roundf(sin(phase * 1.55) * 0.75) + return roundf(sin(phase * 1.55) * 0.75 * intensity) if family == "ranged": - return roundf(sin(phase * 1.10) * 0.75) + return roundf(sin(phase * 1.10) * 0.75 * intensity) if family == "tactic": - return roundf(sin(phase * 0.82) * 0.65) + return roundf(sin(phase * 0.82) * 0.65 * intensity) if family == "heavy": - return roundf(sin(phase * 0.72) * 0.45) - return roundf(sin(phase) * 1.15) + return roundf(sin(phase * 0.72) * 0.45 * intensity) + return roundf(sin(phase) * 1.15 * intensity) -func _unit_idle_step(family: String, phase: float) -> float: +func _unit_idle_step(family: String, phase: float, intensity := 1.0) -> float: + if intensity < 0.40: + return 0.0 var rate := 1.65 if family == "cavalry": rate = 2.15 @@ -5297,8 +5322,11 @@ func _edge_scroll_next_offset(current_offset: Vector2, mouse_position: Vector2, func _update_edge_scroll(delta: float) -> bool: if _is_input_locked(): return false + var viewport := get_viewport() + if viewport == null: + return false var view_rect := _map_view_rect() - var mouse_position := get_viewport().get_mouse_position() + var mouse_position := viewport.get_mouse_position() if minimap_dragging or (_is_minimap_visible() and _minimap_rect().has_point(mouse_position)): return false var velocity := _edge_scroll_velocity_for_position(mouse_position, view_rect) diff --git a/tools/smoke_chapter_one_polish.gd b/tools/smoke_chapter_one_polish.gd index 0770fbe..e895427 100644 --- a/tools/smoke_chapter_one_polish.gd +++ b/tools/smoke_chapter_one_polish.gd @@ -1447,8 +1447,11 @@ func _check_pixel_unit_helpers(failures: Array[String]) -> void: for method_name in [ "_draw_pixel_unit_sprite", "_pixel_unit_sprite_profile", + "_unit_idle_phase", "_unit_idle_bob", "_unit_idle_step", + "_unit_idle_intensity", + "_should_animate_unit_idle", "_draw_pixel_shield", "_draw_pixel_spear", "_draw_pixel_bow", @@ -1469,6 +1472,7 @@ func _check_pixel_unit_helpers(failures: Array[String]) -> void: failures.append("missing pixel-map unit helper: %s" % method_name) _check_pixel_unit_profiles(scene, failures) _check_pixel_unit_class_labels(scene, failures) + _check_pixel_unit_idle_state(scene, failures) scene.free() @@ -1528,3 +1532,56 @@ func _check_pixel_unit_class_labels(scene, failures: Array[String]) -> void: var label := str(scene._unit_class_abbrev({"class_id": class_id})) if label != str(expected_labels[class_id]): failures.append("pixel unit class badge should use Hangul label for %s: %s" % [class_id, label]) + + +func _check_pixel_unit_idle_state(scene, failures: Array[String]) -> void: + if not scene.state.load_battle("res://data/scenarios/001_yellow_turbans.json"): + failures.append("could not load opening battle for pixel idle state helpers") + return + var cao_cao: Dictionary = scene.state.get_unit("cao_cao") + var base_phase: float = scene._unit_idle_phase(cao_cao) + scene._process(0.35) + if absf(scene._unit_idle_phase(cao_cao) - base_phase) > 0.001: + failures.append("pixel idle phase should not advance before battle starts") + + scene.battle_started = true + scene.state.battle_status = BattleStateScript.STATUS_ACTIVE + scene._process(0.35) + if scene.unit_idle_time < 0.34: + failures.append("pixel idle clock should advance during active battle: %.3f" % scene.unit_idle_time) + var active_phase: float = scene._unit_idle_phase(cao_cao) + if active_phase <= base_phase: + failures.append("pixel idle phase should advance from scene idle clock") + var expected_phase_delta := 0.35 * BattleSceneScript.UNIT_IDLE_PHASE_SPEED + if absf((active_phase - base_phase) - expected_phase_delta) > 0.01: + failures.append("pixel idle phase should advance by the scene clock speed: %.3f vs %.3f" % [active_phase - base_phase, expected_phase_delta]) + if not scene._should_animate_unit_idle(): + failures.append("pixel idle animation should be active during player battle control") + + var base_intensity: float = scene._unit_idle_intensity(cao_cao) + scene.state.selected_unit_id = "cao_cao" + var selected_intensity: float = scene._unit_idle_intensity(cao_cao) + if selected_intensity <= base_intensity: + failures.append("selected active unit should idle with a livelier stance") + cao_cao["acted"] = true + var acted_intensity: float = scene._unit_idle_intensity(cao_cao) + if acted_intensity >= base_intensity: + failures.append("acted unit idle should settle below active stance") + cao_cao["acted"] = false + cao_cao["hp"] = maxi(1, int(cao_cao.get("max_hp", 1)) / 4) + var wounded_intensity: float = scene._unit_idle_intensity(cao_cao) + if wounded_intensity >= base_intensity: + failures.append("low-HP unit idle should be subdued") + if scene._unit_idle_step("infantry", 0.25, acted_intensity) != 0.0: + failures.append("settled acted unit should not keep marching feet") + + scene.dialogue_panel = PanelContainer.new() + scene.dialogue_panel.visible = true + if scene._should_animate_unit_idle(): + failures.append("pixel idle animation should pause behind dialogue") + var paused_idle_time: float = scene.unit_idle_time + scene._process(0.35) + if absf(scene.unit_idle_time - paused_idle_time) > 0.001: + failures.append("pixel idle clock should not advance while dialogue is visible") + scene.dialogue_panel.free() + scene.dialogue_panel = null