Files
AppleHillsProduction/Assets/Scripts/PuzzleS/PuzzleManager.cs
Michal Pikulski d2c6c5df38 stash work
2025-10-16 16:18:04 +02:00

455 lines
17 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using AppleHills.Core.Settings;
using Bootstrap;
using Core;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using Utils;
namespace PuzzleS
{
/// <summary>
/// Manages puzzle step registration, dependency management, and step completion for the puzzle system.
/// </summary>
public class PuzzleManager : MonoBehaviour
{
private static PuzzleManager _instance;
private static bool _isQuitting;
[SerializeField] private float proximityCheckInterval = 0.02f;
// Reference to player transform for proximity calculations
private Transform _playerTransform;
private Coroutine _proximityCheckCoroutine;
// Settings reference
private IInteractionSettings _interactionSettings;
// Current level puzzle data
private PuzzleLevelDataSO _currentLevelData;
private AsyncOperationHandle<PuzzleLevelDataSO> _levelDataLoadOperation;
private bool _isLoadingLevelData = false;
/// <summary>
/// Singleton instance of the PuzzleManager. No longer creates an instance if one doesn't exist.
/// </summary>
public static PuzzleManager Instance => _instance;
// Events to notify about step lifecycle
public event Action<PuzzleStepSO> OnStepCompleted;
public event Action<PuzzleStepSO> OnStepUnlocked;
public event Action<PuzzleLevelDataSO> OnLevelDataLoaded;
public event Action<PuzzleLevelDataSO> OnAllPuzzlesComplete;
private HashSet<PuzzleStepSO> _completedSteps = new HashSet<PuzzleStepSO>();
private HashSet<PuzzleStepSO> _unlockedSteps = new HashSet<PuzzleStepSO>();
// Registration for ObjectiveStepBehaviour
private Dictionary<PuzzleStepSO, ObjectiveStepBehaviour> _stepBehaviours = new Dictionary<PuzzleStepSO, ObjectiveStepBehaviour>();
void Awake()
{
_instance = this;
// Initialize settings reference
_interactionSettings = GameManager.GetSettingsObject<IInteractionSettings>();
// Register for post-boot initialization
BootCompletionService.RegisterInitAction(InitializePostBoot);
}
private void InitializePostBoot()
{
// Subscribe to SceneManagerService events after boot is complete
SceneManagerService.Instance.SceneLoadCompleted += OnSceneLoadCompleted;
// Find player transform
_playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
// Start proximity check coroutine
StartProximityChecks();
// Load puzzle data for the current scene if not already loading
if (_currentLevelData == null && !_isLoadingLevelData)
{
LoadPuzzleDataForCurrentScene();
}
Logging.Debug("[PuzzleManager] Subscribed to SceneManagerService events");
}
void OnDestroy()
{
StopProximityChecks();
// Unsubscribe from scene manager events
if (SceneManagerService.Instance != null)
{
SceneManagerService.Instance.SceneLoadCompleted -= OnSceneLoadCompleted;
}
// Release addressable handle if needed
if (_levelDataLoadOperation.IsValid())
{
Addressables.Release(_levelDataLoadOperation);
}
}
/// <summary>
/// Called when a scene is loaded
/// </summary>
public void OnSceneLoadCompleted(string sceneName)
{
// Skip for non-gameplay scenes
if (sceneName == "BootstrapScene" || string.IsNullOrEmpty(sceneName))
{
return;
}
Logging.Debug($"[Puzzles] Scene loaded: {sceneName}, loading puzzle data");
LoadPuzzleDataForCurrentScene(sceneName);
// Find player transform again in case it changed with scene load
_playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
// Restart proximity checks
StartProximityChecks();
}
/// <summary>
/// Load puzzle data for the current scene
/// </summary>
private void LoadPuzzleDataForCurrentScene(string sceneName = null)
{
string currentScene = sceneName ?? SceneManagerService.Instance.CurrentGameplayScene;
if (string.IsNullOrEmpty(currentScene))
{
Logging.Warning("[Puzzles] Cannot load puzzle data: Current scene name is empty");
return;
}
_isLoadingLevelData = true;
string addressablePath = $"Puzzles/{currentScene}";
Logging.Debug($"[Puzzles] Loading puzzle data from addressable: {addressablePath}");
// Release previous handle if needed
if (_levelDataLoadOperation.IsValid())
{
Addressables.Release(_levelDataLoadOperation);
}
if (!AppleHillsUtils.AddressableKeyExists(addressablePath))
{
Logging.Warning($"[Puzzles] Puzzle key does not exist in Addressables: {addressablePath}. Returning early!");
return;
}
// Load the level data asset
_levelDataLoadOperation = Addressables.LoadAssetAsync<PuzzleLevelDataSO>(addressablePath);
_levelDataLoadOperation.Completed += handle =>
{
_isLoadingLevelData = false;
if (handle.Status == AsyncOperationStatus.Succeeded)
{
_currentLevelData = handle.Result;
Logging.Debug($"[Puzzles] Loaded level data: {_currentLevelData.levelId} with {_currentLevelData.allSteps.Count} steps");
// Reset state
_completedSteps.Clear();
_unlockedSteps.Clear();
// Unlock initial steps
UnlockInitialSteps();
// Update existing ObjectiveStepBehaviours with the current state
UpdateRegisteredStepStates();
// Notify listeners
OnLevelDataLoaded?.Invoke(_currentLevelData);
}
else
{
Logging.Warning($"[Puzzles] Failed to load puzzle data for {currentScene}: {handle.OperationException?.Message}");
}
};
}
/// <summary>
/// Start the proximity check coroutine.
/// </summary>
private void StartProximityChecks()
{
StopProximityChecks();
_proximityCheckCoroutine = StartCoroutine(CheckProximityRoutine());
}
/// <summary>
/// Stop the proximity check coroutine.
/// </summary>
private void StopProximityChecks()
{
if (_proximityCheckCoroutine != null)
{
StopCoroutine(_proximityCheckCoroutine);
_proximityCheckCoroutine = null;
}
}
/// <summary>
/// Coroutine that periodically checks player proximity to all puzzle steps.
/// </summary>
private IEnumerator CheckProximityRoutine()
{
WaitForSeconds wait = new WaitForSeconds(proximityCheckInterval);
while (true)
{
if (_playerTransform != null)
{
// Get the proximity threshold from settings directly using our settings reference
float proximityThreshold = _interactionSettings?.DefaultPuzzlePromptRange ?? 3.0f;
// Check distance to each step behavior
foreach (var kvp in _stepBehaviours)
{
if (kvp.Value == null) continue;
if (IsPuzzleStepCompleted(kvp.Key.stepId)) continue;
float distance = Vector3.Distance(_playerTransform.position, kvp.Value.transform.position);
// Determine the proximity state - only Close or Far now
ObjectiveStepBehaviour.ProximityState state =
(distance <= proximityThreshold)
? ObjectiveStepBehaviour.ProximityState.Close
: ObjectiveStepBehaviour.ProximityState.Far;
// Update the step's proximity state
kvp.Value.UpdateProximityState(state);
}
}
yield return wait;
}
}
/// <summary>
/// Registers a step behaviour with the manager.
/// </summary>
/// <param name="behaviour">The step behaviour to register.</param>
public void RegisterStepBehaviour(ObjectiveStepBehaviour behaviour)
{
if (behaviour?.stepData == null) return;
if (!_stepBehaviours.ContainsKey(behaviour.stepData))
{
_stepBehaviours.Add(behaviour.stepData, behaviour);
Logging.Debug($"[Puzzles] Registered step: {behaviour.stepData.stepId} on {behaviour.gameObject.name}");
// Immediately set the correct state based on current puzzle state
UpdateStepState(behaviour);
}
}
/// <summary>
/// Updates a step's state based on the current puzzle state.
/// </summary>
private void UpdateStepState(ObjectiveStepBehaviour behaviour)
{
if (behaviour?.stepData == null) return;
// If step is already completed, ignore
if (_completedSteps.Contains(behaviour.stepData))
return;
// If step is already unlocked, update the behaviour
if (_unlockedSteps.Contains(behaviour.stepData))
{
behaviour.UnlockStep();
}
else
{
// Make sure it's locked
behaviour.LockStep();
}
}
/// <summary>
/// Updates the states of all registered step behaviours based on current puzzle state.
/// </summary>
private void UpdateRegisteredStepStates()
{
foreach (var kvp in _stepBehaviours)
{
UpdateStepState(kvp.Value);
}
}
/// <summary>
/// Unregisters a step behaviour from the manager.
/// </summary>
/// <param name="behaviour">The step behaviour to unregister.</param>
public void UnregisterStepBehaviour(ObjectiveStepBehaviour behaviour)
{
if (behaviour?.stepData == null) return;
_stepBehaviours.Remove(behaviour.stepData);
Logging.Debug($"[Puzzles] Unregistered step: {behaviour.stepData.stepId} on {behaviour.gameObject.name}");
}
/// <summary>
/// Unlocks all initial steps (those with no dependencies)
/// </summary>
private void UnlockInitialSteps()
{
if (_currentLevelData == null) return;
// Unlock initial steps
foreach (var step in _currentLevelData.initialSteps)
{
UnlockStep(step);
}
Logging.Debug($"[Puzzles] Unlocked {_unlockedSteps.Count} initial steps");
}
/// <summary>
/// Called when a step is completed. Unlocks dependent steps if their dependencies are met.
/// </summary>
/// <param name="step">The completed step.</param>
public void MarkPuzzleStepCompleted(PuzzleStepSO step)
{
if (_completedSteps.Contains(step)) return;
if (_currentLevelData == null) return;
_completedSteps.Add(step);
Logging.Debug($"[Puzzles] Step completed: {step.stepId}");
// Broadcast completion
OnStepCompleted?.Invoke(step);
// Unlock steps that are unlocked by this step
foreach (var unlockStep in _currentLevelData.GetUnlockedSteps(step))
{
if (AreStepDependenciesMet(unlockStep))
{
Logging.Debug($"[Puzzles] Unlocking step {unlockStep.stepId} after completing {step.stepId}");
UnlockStep(unlockStep);
}
else
{
Logging.Debug($"[Puzzles] Step {unlockStep.stepId} not unlocked yet, waiting for other dependencies");
}
}
// Check if all puzzle steps are now complete
CheckPuzzleCompletion();
}
/// <summary>
/// Checks if all dependencies for a step are met.
/// </summary>
/// <param name="step">The step to check.</param>
/// <returns>True if all dependencies are met, false otherwise.</returns>
private bool AreStepDependenciesMet(PuzzleStepSO step)
{
if (_currentLevelData == null || step == null) return false;
// If it's an initial step, it has no dependencies
if (_currentLevelData.IsInitialStep(step)) return true;
// Check if dependencies are met using pre-processed data
if (_currentLevelData.stepDependencies.TryGetValue(step.stepId, out string[] dependencies))
{
foreach (var depId in dependencies)
{
// Find the dependency step
bool dependencyMet = false;
foreach (var completedStep in _completedSteps)
{
if (completedStep.stepId == depId)
{
dependencyMet = true;
break;
}
}
if (!dependencyMet) return false;
}
}
return true;
}
/// <summary>
/// Unlocks a specific step and notifies its behaviour.
/// </summary>
/// <param name="step">The step to unlock.</param>
private void UnlockStep(PuzzleStepSO step)
{
if (_unlockedSteps.Contains(step)) return;
_unlockedSteps.Add(step);
if (_stepBehaviours.TryGetValue(step, out var behaviour))
{
behaviour.UnlockStep();
}
Logging.Debug($"[Puzzles] Step unlocked: {step.stepId}");
// Broadcast unlock
OnStepUnlocked?.Invoke(step);
}
/// <summary>
/// Checks if the puzzle is complete (all steps in level finished).
/// </summary>
private void CheckPuzzleCompletion()
{
if (_currentLevelData == null) return;
if (_currentLevelData.IsLevelComplete(_completedSteps))
{
Logging.Debug("[Puzzles] All puzzles complete! Level finished.");
// Fire level complete event
OnAllPuzzlesComplete?.Invoke(_currentLevelData);
}
}
/// <summary>
/// Returns whether a step is already unlocked.
/// </summary>
public bool IsStepUnlocked(PuzzleStepSO step)
{
return _unlockedSteps.Contains(step);
}
/// <summary>
/// Checks if a puzzle step with the specified ID has been completed
/// </summary>
/// <param name="stepId">The ID of the puzzle step to check</param>
/// <returns>True if the step has been completed, false otherwise</returns>
public bool IsPuzzleStepCompleted(string stepId)
{
return _completedSteps.Any(step => step.stepId == stepId);
}
/// <summary>
/// Get the current level puzzle data
/// </summary>
public PuzzleLevelDataSO GetCurrentLevelData()
{
return _currentLevelData;
}
void OnApplicationQuit()
{
_isQuitting = true;
}
}
}