Files
AppleHillsProduction/Assets/Scripts/UI/Tutorial/DivingTutorial.cs

234 lines
7.6 KiB
C#
Raw Normal View History

2025-10-21 12:51:24 +02:00
using System.Collections;
using Core;
Refactor interactions, introduce template-method lifecycle management, work on save-load system (#51) # Lifecycle Management & Save System Revamp ## Overview Complete overhaul of game lifecycle management, interactable system, and save/load architecture. Introduces centralized `ManagedBehaviour` base class for consistent initialization ordering and lifecycle hooks across all systems. ## Core Architecture ### New Lifecycle System - **`LifecycleManager`**: Centralized coordinator for all managed objects - **`ManagedBehaviour`**: Base class replacing ad-hoc initialization patterns - `OnManagedAwake()`: Priority-based initialization (0-100, lower = earlier) - `OnSceneReady()`: Scene-specific setup after managers ready - Replaces `BootCompletionService` (deleted) - **Priority groups**: Infrastructure (0-20) → Game Systems (30-50) → Data (60-80) → UI/Gameplay (90-100) - **Editor support**: `EditorLifecycleBootstrap` ensures lifecycle works in editor mode ### Unified SaveID System - Consistent format: `{ParentName}_{ComponentType}` - Auto-registration via `AutoRegisterForSave = true` - New `DebugSaveIds` editor tool for inspection ## Save/Load Improvements ### Enhanced State Management - **Extended SaveLoadData**: Unlocked minigames, card collection states, combination items, slot occupancy - **Async loading**: `ApplyCardCollectionState()` waits for card definitions before restoring - **New `SaveablePlayableDirector`**: Timeline sequences save/restore playback state - **Fixed race conditions**: Proper initialization ordering prevents data corruption ## Interactable & Pickup System - Migrated to `OnManagedAwake()` for consistent initialization - Template method pattern for state restoration (`RestoreInteractionState()`) - Fixed combination item save/load bugs (items in slots vs. follower hand) - Dynamic spawning support for combined items on load - **Breaking**: `Interactable.Awake()` now sealed, use `OnManagedAwake()` instead ## UI System Changes - **AlbumViewPage** and **BoosterNotificationDot**: Migrated to `ManagedBehaviour` - **Fixed menu persistence bug**: Menus no longer reappear after scene transitions - **Pause Menu**: Now reacts to all scene loads (not just first scene) - **Orientation Enforcer**: Enforces per-scene via `SceneManagementService` - **Loading Screen**: Integrated with new lifecycle ## ⚠️ Breaking Changes 1. **`BootCompletionService` removed** → Use `ManagedBehaviour.OnManagedAwake()` with priority 2. **`Interactable.Awake()` sealed** → Override `OnManagedAwake()` instead 3. **SaveID format changed** → Now `{ParentName}_{ComponentType}` consistently 4. **MonoBehaviours needing init ordering** → Must inherit from `ManagedBehaviour` Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com> Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com> Reviewed-on: https://homelab.tailf7f81b.ts.net/tschesky/AppleHillsProduction/pulls/51
2025-11-07 15:38:31 +00:00
using Core.Lifecycle;
2025-10-27 14:00:37 +01:00
using Core.SaveLoad;
2025-10-15 15:58:19 +02:00
using Input;
using Pixelplacement;
using UI.Core;
using UnityEngine;
2025-11-10 13:13:32 +01:00
using UnityEngine.Audio;
2025-10-15 15:58:19 +02:00
namespace UI.Tutorial
2025-10-15 15:58:19 +02:00
{
Refactor interactions, introduce template-method lifecycle management, work on save-load system (#51) # Lifecycle Management & Save System Revamp ## Overview Complete overhaul of game lifecycle management, interactable system, and save/load architecture. Introduces centralized `ManagedBehaviour` base class for consistent initialization ordering and lifecycle hooks across all systems. ## Core Architecture ### New Lifecycle System - **`LifecycleManager`**: Centralized coordinator for all managed objects - **`ManagedBehaviour`**: Base class replacing ad-hoc initialization patterns - `OnManagedAwake()`: Priority-based initialization (0-100, lower = earlier) - `OnSceneReady()`: Scene-specific setup after managers ready - Replaces `BootCompletionService` (deleted) - **Priority groups**: Infrastructure (0-20) → Game Systems (30-50) → Data (60-80) → UI/Gameplay (90-100) - **Editor support**: `EditorLifecycleBootstrap` ensures lifecycle works in editor mode ### Unified SaveID System - Consistent format: `{ParentName}_{ComponentType}` - Auto-registration via `AutoRegisterForSave = true` - New `DebugSaveIds` editor tool for inspection ## Save/Load Improvements ### Enhanced State Management - **Extended SaveLoadData**: Unlocked minigames, card collection states, combination items, slot occupancy - **Async loading**: `ApplyCardCollectionState()` waits for card definitions before restoring - **New `SaveablePlayableDirector`**: Timeline sequences save/restore playback state - **Fixed race conditions**: Proper initialization ordering prevents data corruption ## Interactable & Pickup System - Migrated to `OnManagedAwake()` for consistent initialization - Template method pattern for state restoration (`RestoreInteractionState()`) - Fixed combination item save/load bugs (items in slots vs. follower hand) - Dynamic spawning support for combined items on load - **Breaking**: `Interactable.Awake()` now sealed, use `OnManagedAwake()` instead ## UI System Changes - **AlbumViewPage** and **BoosterNotificationDot**: Migrated to `ManagedBehaviour` - **Fixed menu persistence bug**: Menus no longer reappear after scene transitions - **Pause Menu**: Now reacts to all scene loads (not just first scene) - **Orientation Enforcer**: Enforces per-scene via `SceneManagementService` - **Loading Screen**: Integrated with new lifecycle ## ⚠️ Breaking Changes 1. **`BootCompletionService` removed** → Use `ManagedBehaviour.OnManagedAwake()` with priority 2. **`Interactable.Awake()` sealed** → Override `OnManagedAwake()` instead 3. **SaveID format changed** → Now `{ParentName}_{ComponentType}` consistently 4. **MonoBehaviours needing init ordering** → Must inherit from `ManagedBehaviour` Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com> Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com> Reviewed-on: https://homelab.tailf7f81b.ts.net/tschesky/AppleHillsProduction/pulls/51
2025-11-07 15:38:31 +00:00
public class DivingTutorial : ManagedBehaviour, ITouchInputConsumer
2025-10-15 15:58:19 +02:00
{
public enum ProgressType
{
Manual, // Wait for player tap after animation loop
Auto // Automatically progress after animation loop
}
private StateMachine _stateMachine;
public bool playTutorial;
2025-11-10 13:13:32 +01:00
public AudioSource bottleAudioPlayer;
public AudioResource introVO;
public GameObject scoreCanvas;
2025-10-27 14:56:59 +01:00
[SerializeField] private ProgressType progressType = ProgressType.Auto;
2025-10-15 15:58:19 +02:00
// gating for input until current state's animation finishes first loop
[SerializeField] private GameObject tapPrompt;
2025-10-15 15:58:19 +02:00
private bool _canAcceptInput;
private Coroutine _waitLoopCoroutine;
2025-10-15 15:58:19 +02:00
Lifecycle System Refactor & Logging Centralization (#56) ## ManagedBehaviour System Refactor - **Sealed `Awake()`** to prevent override mistakes that break singleton registration - **Added `OnManagedAwake()`** for early initialization (fires during registration) - **Renamed lifecycle hook:** `OnManagedAwake()` → `OnManagedStart()` (fires after boot, mirrors Unity's Awake→Start) - **40 files migrated** to new pattern (2 core, 38 components) - Eliminated all fragile `private new void Awake()` patterns - Zero breaking changes - backward compatible ## Centralized Logging System - **Automatic tagging** via `CallerMemberName` and `CallerFilePath` - logs auto-tagged as `[ClassName][MethodName] message` - **Unified API:** Single `Logging.Debug/Info/Warning/Error()` replaces custom `LogDebugMessage()` implementations - **~90 logging call sites** migrated across 10 files - **10 redundant helper methods** removed - All logs broadcast via `Logging.OnLogEntryAdded` event for real-time monitoring ## Custom Log Console (Editor Window) - **Persistent filter popups** for multi-selection (classes, methods, log levels) - windows stay open during selection - **Search** across class names, methods, and message content - **Time range filter** with MinMaxSlider - **Export** filtered logs to timestamped `.txt` files - **Right-click context menu** for quick filtering and copy actions - **Visual improvements:** White text, alternating row backgrounds, color-coded log levels - **Multiple instances** supported for simultaneous system monitoring - Open via `AppleHills > Custom Log Console` Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com> Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com> Reviewed-on: https://homelab.tailf7f81b.ts.net/tschesky/AppleHillsProduction/pulls/56
2025-11-11 08:48:29 +00:00
internal override void OnManagedStart()
Refactor interactions, introduce template-method lifecycle management, work on save-load system (#51) # Lifecycle Management & Save System Revamp ## Overview Complete overhaul of game lifecycle management, interactable system, and save/load architecture. Introduces centralized `ManagedBehaviour` base class for consistent initialization ordering and lifecycle hooks across all systems. ## Core Architecture ### New Lifecycle System - **`LifecycleManager`**: Centralized coordinator for all managed objects - **`ManagedBehaviour`**: Base class replacing ad-hoc initialization patterns - `OnManagedAwake()`: Priority-based initialization (0-100, lower = earlier) - `OnSceneReady()`: Scene-specific setup after managers ready - Replaces `BootCompletionService` (deleted) - **Priority groups**: Infrastructure (0-20) → Game Systems (30-50) → Data (60-80) → UI/Gameplay (90-100) - **Editor support**: `EditorLifecycleBootstrap` ensures lifecycle works in editor mode ### Unified SaveID System - Consistent format: `{ParentName}_{ComponentType}` - Auto-registration via `AutoRegisterForSave = true` - New `DebugSaveIds` editor tool for inspection ## Save/Load Improvements ### Enhanced State Management - **Extended SaveLoadData**: Unlocked minigames, card collection states, combination items, slot occupancy - **Async loading**: `ApplyCardCollectionState()` waits for card definitions before restoring - **New `SaveablePlayableDirector`**: Timeline sequences save/restore playback state - **Fixed race conditions**: Proper initialization ordering prevents data corruption ## Interactable & Pickup System - Migrated to `OnManagedAwake()` for consistent initialization - Template method pattern for state restoration (`RestoreInteractionState()`) - Fixed combination item save/load bugs (items in slots vs. follower hand) - Dynamic spawning support for combined items on load - **Breaking**: `Interactable.Awake()` now sealed, use `OnManagedAwake()` instead ## UI System Changes - **AlbumViewPage** and **BoosterNotificationDot**: Migrated to `ManagedBehaviour` - **Fixed menu persistence bug**: Menus no longer reappear after scene transitions - **Pause Menu**: Now reacts to all scene loads (not just first scene) - **Orientation Enforcer**: Enforces per-scene via `SceneManagementService` - **Loading Screen**: Integrated with new lifecycle ## ⚠️ Breaking Changes 1. **`BootCompletionService` removed** → Use `ManagedBehaviour.OnManagedAwake()` with priority 2. **`Interactable.Awake()` sealed** → Override `OnManagedAwake()` instead 3. **SaveID format changed** → Now `{ParentName}_{ComponentType}` consistently 4. **MonoBehaviours needing init ordering** → Must inherit from `ManagedBehaviour` Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com> Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com> Reviewed-on: https://homelab.tailf7f81b.ts.net/tschesky/AppleHillsProduction/pulls/51
2025-11-07 15:38:31 +00:00
{
// Ensure prompt is hidden initially (even before tutorial initialization)
if (tapPrompt != null)
tapPrompt.SetActive(false);
2025-10-15 15:58:19 +02:00
2025-10-27 14:00:37 +01:00
if (playTutorial && !SaveLoadManager.Instance.currentSaveData.playedDivingTutorial)
{
2025-10-27 14:00:37 +01:00
// TODO: Possibly do it better, but for now just mark tutorial as played immediately
SaveLoadManager.Instance.currentSaveData.playedDivingTutorial = true;
// pause the game, hide UI, and register for input overrides
GameManager.Instance.RequestPause(this);
UIPageController.Instance.HideAllUI();
InputManager.Instance.RegisterOverrideConsumer(this);
2025-10-21 12:51:24 +02:00
// Setup references
_stateMachine = GetComponentInChildren<StateMachine>();
_stateMachine.OnLastStateExited.AddListener(RemoveTutorial);
2025-10-21 12:51:24 +02:00
// prepare gating for the initial active state
SetupInputGateForCurrentState();
// hide the score canvas gameobject
scoreCanvas.SetActive(false);
}
else
{
RemoveTutorial();
}
}
2025-10-21 12:51:24 +02:00
void RemoveTutorial()
{
2025-11-10 13:03:36 +01:00
Logging.Debug("Remove me!");
if (_waitLoopCoroutine != null)
{
StopCoroutine(_waitLoopCoroutine);
_waitLoopCoroutine = null;
}
2025-10-15 15:58:19 +02:00
// Unpause, unregister input, and show UI
InputManager.Instance.UnregisterOverrideConsumer(this);
UIPageController.Instance.ShowAllUI();
GameManager.Instance.ReleasePause(this);
2025-10-15 15:58:19 +02:00
// hide prompt if present
if (tapPrompt != null)
tapPrompt.SetActive(false);
2025-10-15 15:58:19 +02:00
Destroy(gameObject);
2025-11-10 13:13:32 +01:00
bottleAudioPlayer.resource = introVO;
bottleAudioPlayer.Play();
scoreCanvas.SetActive(true);
}
2025-10-21 12:51:24 +02:00
public void OnTap(Vector2 position)
2025-10-21 12:51:24 +02:00
{
if (!_canAcceptInput) return; // block taps until allowed
2025-10-21 12:51:24 +02:00
// consume this tap and immediately block further taps
SetInputEnabled(false);
2025-10-21 12:51:24 +02:00
// move to next state
_stateMachine.Next(true);
// after the state changes, set up gating for the new active state's animation
SetupInputGateForCurrentState();
2025-10-21 12:51:24 +02:00
}
public void OnHoldStart(Vector2 position)
2025-10-21 12:51:24 +02:00
{
}
public void OnHoldMove(Vector2 position)
2025-10-21 12:51:24 +02:00
{
}
public void OnHoldEnd(Vector2 position)
2025-10-21 12:51:24 +02:00
{
}
// centralize enabling/disabling input and the tap prompt
private void SetInputEnabled(bool allow)
2025-10-21 12:51:24 +02:00
{
_canAcceptInput = allow;
if (tapPrompt != null)
2025-10-21 12:51:24 +02:00
{
// Only show tap prompt in Manual mode
tapPrompt.SetActive(allow && progressType == ProgressType.Manual);
2025-10-21 12:51:24 +02:00
}
}
private void SetupInputGateForCurrentState()
2025-10-21 12:51:24 +02:00
{
if (_waitLoopCoroutine != null)
{
StopCoroutine(_waitLoopCoroutine);
_waitLoopCoroutine = null;
}
_waitLoopCoroutine = StartCoroutine(WaitForFirstLoopOnActiveState());
2025-10-21 12:51:24 +02:00
}
private IEnumerator WaitForFirstLoopOnActiveState()
2025-10-21 12:51:24 +02:00
{
// wait a frame to ensure StateMachine has activated the correct state GameObject
2025-10-21 12:51:24 +02:00
yield return null;
// find the active child under the StateMachine (the current state)
Transform smTransform = _stateMachine != null ? _stateMachine.transform : transform;
Transform activeState = null;
for (int i = 0; i < smTransform.childCount; i++)
{
var child = smTransform.GetChild(i);
if (child.gameObject.activeInHierarchy)
{
activeState = child;
break;
}
}
2025-10-21 12:51:24 +02:00
if (activeState == null)
2025-10-21 12:51:24 +02:00
{
// if we can't find an active state, fail open: allow input
SetInputEnabled(true);
yield break;
2025-10-21 12:51:24 +02:00
}
// look for a legacy Animation component on the active state
var anim = activeState.GetComponent<Animation>();
if (anim == null)
{
// no animation to wait for; allow input immediately
SetInputEnabled(true);
yield break;
}
// determine a clip/state to observe
string clipName = anim.clip != null ? anim.clip.name : null;
AnimationState observedState = null;
if (!string.IsNullOrEmpty(clipName))
{
observedState = anim[clipName];
}
else
{
// fallback: take the first enabled state in the Animation
foreach (AnimationState st in anim)
{
observedState = st;
break;
}
}
if (observedState == null)
{
// nothing to observe; allow input
SetInputEnabled(true);
yield break;
}
// wait until the animation starts playing the observed clip
float safetyTimer = 0f;
while (anim.isActiveAndEnabled && activeState.gameObject.activeInHierarchy && !anim.IsPlaying(observedState.name) && safetyTimer < 2f)
{
safetyTimer += Time.deltaTime;
yield return null;
}
// wait until the first loop completes (normalizedTime >= 1)
while (anim.isActiveAndEnabled && activeState.gameObject.activeInHierarchy)
{
// if state changed (not playing anymore), allow input to avoid deadlock
if (!anim.IsPlaying(observedState.name)) break;
if (observedState.normalizedTime >= 1f)
{
break;
}
yield return null;
}
// After first loop completes, handle based on progress type
if (progressType == ProgressType.Auto)
{
// Auto mode: immediately progress to next state
_stateMachine.Next(true);
SetupInputGateForCurrentState();
}
else
{
// Manual mode: enable input and wait for player tap
SetInputEnabled(true);
}
Refactor interactions, introduce template-method lifecycle management, work on save-load system (#51) # Lifecycle Management & Save System Revamp ## Overview Complete overhaul of game lifecycle management, interactable system, and save/load architecture. Introduces centralized `ManagedBehaviour` base class for consistent initialization ordering and lifecycle hooks across all systems. ## Core Architecture ### New Lifecycle System - **`LifecycleManager`**: Centralized coordinator for all managed objects - **`ManagedBehaviour`**: Base class replacing ad-hoc initialization patterns - `OnManagedAwake()`: Priority-based initialization (0-100, lower = earlier) - `OnSceneReady()`: Scene-specific setup after managers ready - Replaces `BootCompletionService` (deleted) - **Priority groups**: Infrastructure (0-20) → Game Systems (30-50) → Data (60-80) → UI/Gameplay (90-100) - **Editor support**: `EditorLifecycleBootstrap` ensures lifecycle works in editor mode ### Unified SaveID System - Consistent format: `{ParentName}_{ComponentType}` - Auto-registration via `AutoRegisterForSave = true` - New `DebugSaveIds` editor tool for inspection ## Save/Load Improvements ### Enhanced State Management - **Extended SaveLoadData**: Unlocked minigames, card collection states, combination items, slot occupancy - **Async loading**: `ApplyCardCollectionState()` waits for card definitions before restoring - **New `SaveablePlayableDirector`**: Timeline sequences save/restore playback state - **Fixed race conditions**: Proper initialization ordering prevents data corruption ## Interactable & Pickup System - Migrated to `OnManagedAwake()` for consistent initialization - Template method pattern for state restoration (`RestoreInteractionState()`) - Fixed combination item save/load bugs (items in slots vs. follower hand) - Dynamic spawning support for combined items on load - **Breaking**: `Interactable.Awake()` now sealed, use `OnManagedAwake()` instead ## UI System Changes - **AlbumViewPage** and **BoosterNotificationDot**: Migrated to `ManagedBehaviour` - **Fixed menu persistence bug**: Menus no longer reappear after scene transitions - **Pause Menu**: Now reacts to all scene loads (not just first scene) - **Orientation Enforcer**: Enforces per-scene via `SceneManagementService` - **Loading Screen**: Integrated with new lifecycle ## ⚠️ Breaking Changes 1. **`BootCompletionService` removed** → Use `ManagedBehaviour.OnManagedAwake()` with priority 2. **`Interactable.Awake()` sealed** → Override `OnManagedAwake()` instead 3. **SaveID format changed** → Now `{ParentName}_{ComponentType}` consistently 4. **MonoBehaviours needing init ordering** → Must inherit from `ManagedBehaviour` Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com> Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com> Reviewed-on: https://homelab.tailf7f81b.ts.net/tschesky/AppleHillsProduction/pulls/51
2025-11-07 15:38:31 +00:00
_waitLoopCoroutine = null;
}
2025-10-21 12:51:24 +02:00
}
2025-10-15 15:58:19 +02:00
}