using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Code.Game.OfficeGame.BattleMode; using Code.Game.OfficeGame.Entities; using Code.Infrastructure.Camera; using Code.Infrastructure.Particles; using Code.OfficeGame.BattleMode.Actions; using Code.OfficeGame.BattleMode.Actions.AI; using Code.OfficeGame.BattleMode.Actions.Deciders; using Code.OfficeGame.BattleMode.CursorControl; using Code.OfficeGame.BattleMode.Health; using Code.OfficeGame.BattleMode.HitBoxes; using Code.OfficeGame.BattleMode.UI; using Cysharp.Threading.Tasks; using R3; using UnityEngine; namespace Code.OfficeGame.BattleMode.Timeline { public sealed class BattleTimeline : IDisposable { public const int TicksPerSecond = BattleSimulator.TicksPerSecond; public const float TickDelta = BattleSimulator.FixedTickDelta; public static float PlaybackSpeed { get; set; } = 1f; // Реактивное состояние для UI (ползунок, маркеры, HP-бары) private readonly ReactiveProperty _displayFrame = new(0); private readonly ReactiveProperty _committedFrame = new(0); private readonly ReactiveProperty _maxFrame = new(0); private readonly ReactiveProperty _mode = new(TimelineMode.Idle); private readonly Subject _onTrackRebaked = new(); private readonly Subject _onRealEvent = new(); public ReadOnlyReactiveProperty DisplayFrame => _displayFrame; public ReadOnlyReactiveProperty CommittedFrame => _committedFrame; public ReadOnlyReactiveProperty MaxFrame => _maxFrame; public ReadOnlyReactiveProperty Mode => _mode; public Observable OnTrackRebaked => _onTrackRebaked; public Observable OnRealEvent => _onRealEvent; public BattleTimelineTrack Track { get; } = new(); private readonly BattleTimelinePanel _timelinePanel; private readonly BattleActionDecisionPanel _decisionPanel; private readonly HealthPanelsHolder _healthPanelsHolder; private readonly CameraStateMachine _cameraStateMachine; private readonly IParticleService _particleService; private readonly Dictionary _battleActions; private readonly Dictionary _battleActionDeciders; private readonly Dictionary _enemyDeciders; private readonly BattleSimulator _simulator; private EntityProperties[] _entities; private CancellationTokenSource _previewLoopCts; private bool _previewVisualsEnabled; public BattleTimeline( BattleTimelinePanel timelinePanel, IEnumerable battleActions, IEnumerable battleActionDeciders, IEnumerable enemyDeciders, BattleActionDecisionPanel battleActionDecisionPanel, HealthPanelsHolder healthPanelsHolder, CameraStateMachine cameraStateMachine, IParticleService particleService, BattleModeCursorController cursorController) { _cursorController = cursorController; _timelinePanel = timelinePanel; _decisionPanel = battleActionDecisionPanel; _healthPanelsHolder = healthPanelsHolder; _cameraStateMachine = cameraStateMachine; _particleService = particleService; _battleActions = battleActions.ToDictionary(x => x.ActionType); _battleActionDeciders = battleActionDeciders.ToDictionary(x => x.DeciderType); _enemyDeciders = enemyDeciders.ToDictionary(x => x.EnemyDeciderType); _simulator = new BattleSimulator(_battleActions); foreach (var action in _battleActions.Values) action.SetSimulationContext(_simulator); } public int GetSlotIndex(EntityId id) => _simulator.GetSlotIndex(id); // =================== УПРАВЛЕНИЕ ПОЛЗУНКОМ И ПЛЕЕРОМ =================== public void ScrubToFrame(int targetFrame) { if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0) return; StopPreviewLoop(); _mode.Value = TimelineMode.Scrubbing; int clamped = Mathf.Clamp(targetFrame, 0, Track.LastFrame); ApplyFrame(clamped, playOneShotVfx: false); } public void StepFrame(int delta) { if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0) return; ScrubToFrame(_displayFrame.Value + delta); } public void TogglePreviewPlayPause() { if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0) return; if (_mode.Value == TimelineMode.PreviewPlaying) { StopPreviewLoop(); _mode.Value = TimelineMode.Scrubbing; } else if (Track.LastFrame > _committedFrame.Value) { StartPreviewLoop(_committedFrame.Value, Track.LastFrame, _battleLoopCt); } } public void ReturnToCommittedFrame() { if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0) return; StopPreviewLoop(); ApplyFrame(_committedFrame.Value, playOneShotVfx: false); _mode.Value = TimelineMode.Deciding; } // =================== ОСНОВНОЙ ЦИКЛ БОЯ =================== private CancellationToken _battleLoopCt; private BattleModeCursorController _cursorController; public async UniTask RunBattleLoopAsync(List entities, CancellationToken ctx) { _battleLoopCt = ctx; _entities = entities.ToArray(); _simulator.BindEntities(_entities); var initialSlots = new EntityActionSlotSnapshot[_entities.Length]; for (int i = 0; i < _entities.Length; i++) initialSlots[i] = EntityActionSlotSnapshot.CreateNone(0); var frameZero = _simulator.CaptureCurrentFrame( frame: 0, interruptionStage: 0, slots: initialSlots, readySlotsMask: 0UL, events: Array.Empty(), hitboxVisuals: Array.Empty()); Track.Initialize(frameZero); _committedFrame.Value = 0; _displayFrame.Value = 0; _maxFrame.Value = 0; using var uiBinding = _timelinePanel.BindTimeline(this); using var hpBinding = _healthPanelsHolder.BindToTimeline(this); using var vfxSub = _onRealEvent.Subscribe(HandleRealEvent); try { while (!ctx.IsCancellationRequested) { var readySlots = Track.GetReadySlotsAt(_committedFrame.Value); if (readySlots.Count == 0) break; // 1. Собираем приказы для всех освободившихся бойцов await DecideActionsForSlots(readySlots, ctx); // 2. Финально запекаем будущее со всеми утверждёнными приказами (без слепков) _previewVisualsEnabled = false; HideAllPreviewVisuals(); RebakeFromCommitted(recordGhosts: false); int nextPauseFrame = Track.FindNextPauseFrame(_committedFrame.Value); if (nextPauseFrame <= _committedFrame.Value) { await UniTask.Yield(PlayerLoopTiming.Update, ctx); continue; } // 3. Плавно проигрываем готовые кадры до ближайшего прерывания await PlayBakedRangeAsync(_committedFrame.Value + 1, nextPauseFrame, ctx); // Синхронизируем физику и HP строго на новом CommittedFrame _simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value)); } } finally { StopPreviewLoop(); HideAllPreviewVisuals(); HitboxDrawer.Clear(); _mode.Value = TimelineMode.Idle; } } private async UniTask PlayBakedRangeAsync(int startFrame, int endFrame, CancellationToken ctx) { StopPreviewLoop(); _previewVisualsEnabled = false; HideAllPreviewVisuals(); _mode.Value = TimelineMode.BattlePlaying; float accumulator = 0f; int frame = startFrame; while (frame <= endFrame && !ctx.IsCancellationRequested) { await UniTask.Yield(PlayerLoopTiming.Update, ctx); accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed; while (accumulator >= TickDelta && frame <= endFrame && !ctx.IsCancellationRequested) { accumulator -= TickDelta; _committedFrame.Value = frame; ApplyFrame(frame, playOneShotVfx: true); frame++; } } } private async UniTask DecideActionsForSlots(List readySlots, CancellationToken ctx) { _mode.Value = TimelineMode.Deciding; // Сначала решения принимают ИИ — игрок сразу увидит их запечённый план на таймлайне var orderedSlots = readySlots .OrderBy(slot => _entities[slot].TeamData.Team == EntityTeam.Good ? 1 : 0) .ToList(); foreach (int slotIndex in orderedSlots) { _simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value)); ApplyFrame(_committedFrame.Value, playOneShotVfx: false); EntityActionSlotSnapshot chosenSlot = await DecideForSingleSlot(slotIndex, ctx); Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot = chosenSlot; RebakeFromCommitted(recordGhosts: false); } } private async UniTask DecideForSingleSlot(int slotIndex, CancellationToken ctx) { var entity = _entities[slotIndex]; if (entity.TeamData.Team == EntityTeam.ChaoticEvil) { var (enemyRes, enemyData) = _enemyDeciders[entity.TeamData.DeciderType] .DecideEnemy(entity, _battleActions); return new EntityActionSlotSnapshot { ActionType = enemyRes.ActionType, DecisionResult = enemyRes, ActionData = enemyData, LastCompletedActionType = Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot.LastCompletedActionType, ActionStartFrame = _committedFrame.Value, EstimatedEndFrame = _committedFrame.Value + enemyData.TotalFrames }; } if (entity.TeamData.Team == EntityTeam.Good) return await DecideForPlayerSlot(slotIndex, ctx); return EntityActionSlotSnapshot.CreateNone(_committedFrame.Value); } private async UniTask DecideForPlayerSlot(int slotIndex, CancellationToken ctx) { var entity = _entities[slotIndex]; var lastCompleted = Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot.LastCompletedActionType; _decisionPanel.SetEntityInfo(entity.battleActionTypes); _timelinePanel.SetPreviousActionText(lastCompleted.ToString()); // Сразу запекаем прогноз с текущими действиями врагов — ползунок доступен уже в меню выбора! _previewVisualsEnabled = true; RebakeFromCommitted(recordGhosts: true); ApplyFrame(_committedFrame.Value, playOneShotVfx: false); var cameraBattleState = _cameraStateMachine.CurrentBaseState as CameraBattleModeState; while (!ctx.IsCancellationRequested) { // Cursor.lockState = CursorLockMode.Confined; if (cameraBattleState != null) cameraBattleState.battleDeciding = true; await _decisionPanel.Open(ctx); BattleActionType decidedType = await _decisionPanel.GetDecision(ctx); if (decidedType == BattleActionType.None) continue; var deciderType = _battleActions[decidedType].DeciderType; var decider = _battleActionDeciders[deciderType]; StopPreviewLoop(); _simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value)); ApplyFrame(_committedFrame.Value, playOneShotVfx: false); await decider.MountDecider(entity); bool waitingForFirstTarget = true; try { while (!ctx.IsCancellationRequested) { // Пока цель ещё не выбрана — курсор залочен под прицеливание камеры. // Как только цель выбрана (идёт превью) — курсор свободен (Confined), // чтобы игрок мог двигать ползунок таймлайна (а вращать камеру через ПКМ). // Cursor.lockState = waitingForFirstTarget ? CursorLockMode.Locked : CursorLockMode.Confined; if (cameraBattleState != null) cameraBattleState.battleDeciding = !waitingForFirstTarget; await _decisionPanel.Close(ctx); var decisionResult = await decider.GetDecision(); decisionResult.ActionType = decidedType; StopPreviewLoop(); _simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value)); if (decisionResult.ResultCode == BattleActionDecisionResultCode.CancelDecision) { RebakeFromCommitted(recordGhosts: true); ApplyFrame(_committedFrame.Value, playOneShotVfx: false); break; } var actionData = _battleActions[decidedType].MountAndGetFrames(entity, decisionResult); var candidateSlot = new EntityActionSlotSnapshot { ActionType = decidedType, DecisionResult = decisionResult, ActionData = actionData, LastCompletedActionType = lastCompleted, ActionStartFrame = _committedFrame.Value, EstimatedEndFrame = _committedFrame.Value + actionData.TotalFrames }; if (decisionResult.ResultCode == BattleActionDecisionResultCode.Deciding) { waitingForFirstTarget = false; _previewVisualsEnabled = true; RebakeFromCommitted( recordGhosts: true, overrideSlot: slotIndex, overrideAction: candidateSlot); StartPreviewLoop(_committedFrame.Value, Track.LastFrame, ctx); } else // BattleActionDecisionResultCode.Decided { _previewVisualsEnabled = false; HideAllPreviewVisuals(); return candidateSlot; } } } finally { StopPreviewLoop(); await decider.UnmountDecider(); } } return EntityActionSlotSnapshot.CreateNone(_committedFrame.Value, lastCompleted); } // =================== ЗАПЕКАНИЕ И ПРИМЕНЕНИЕ КАДРОВ =================== private void RebakeFromCommitted( bool recordGhosts, int overrideSlot = -1, EntityActionSlotSnapshot? overrideAction = null) { _simulator.BakeFrom(Track, _committedFrame.Value, recordGhosts, overrideSlot, overrideAction); _maxFrame.Value = Track.LastFrame; _onTrackRebaked.OnNext(Track); } private void StartPreviewLoop(int startFrame, int endFrame, CancellationToken battleCtx) { StopPreviewLoop(); if (endFrame <= startFrame) return; _mode.Value = TimelineMode.PreviewPlaying; _previewLoopCts = CancellationTokenSource.CreateLinkedTokenSource(battleCtx); RunPreviewPlaybackAsync(startFrame, endFrame, _previewLoopCts.Token).Forget(); } private async UniTaskVoid RunPreviewPlaybackAsync(int startFrame, int endFrame, CancellationToken ctx) { float accumulator = 0f; int current = startFrame; while (!ctx.IsCancellationRequested) { bool canceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow(); if (canceled) break; accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed; while (accumulator >= TickDelta && !ctx.IsCancellationRequested) { accumulator -= TickDelta; current++; if (current > endFrame) current = startFrame; ApplyFrame(current, playOneShotVfx: false); } } } private void StopPreviewLoop() { if (_previewLoopCts == null) return; _previewLoopCts.Cancel(); _previewLoopCts.Dispose(); _previewLoopCts = null; } /// /// Единая точка отображения любого кадра (бой, превью и скраббинг ползунком). /// private void ApplyFrame(int frame, bool playOneShotVfx) { var snapshot = Track.GetFrame(frame); _simulator.ApplyVisualFrameToWorld(snapshot); _displayFrame.Value = snapshot.Frame; // Обновляем многоступенчатые слепки и цвет проекции ТОЛЬКО для кадров будущего (> CommittedFrame) for (int i = 0; i < _entities.Length; i++) { _entities[i].EntityPreviewVisuals?.UpdateForTimelineFrame( viewFrame: snapshot.Frame, committedFrame: _committedFrame.Value, interruptionStage: snapshot.InterruptionStage, showPreviewVisuals: _previewVisualsEnabled); } // Хитбоксы текущего кадра не исчезают, даже если ползунок остановлен! HitboxDrawer.Clear(); var hitboxes = snapshot.HitboxVisuals; if (hitboxes != null) { for (int i = 0; i < hitboxes.Length; i++) HitboxDrawer.DrawMatrix(hitboxes[i].Matrix, hitboxes[i].Color, duration: 999f); } // События VFX стреляют только в реальном воспроизведении if (playOneShotVfx && snapshot.Events is { Length: > 0 }) { for (int i = 0; i < snapshot.Events.Length; i++) _onRealEvent.OnNext(snapshot.Events[i]); } } private void HandleRealEvent(TimelineEvent ev) { if (ev.EventType == TimelineEventType.HitLanded) { _particleService.EmitOneShot( new ParticlePartitionIDPair(ParticlePartition.HitParticles, 0), 15, ev.WorldPosition, Quaternion.identity); } } private void HideAllPreviewVisuals() { if (_entities == null) return; for (int i = 0; i < _entities.Length; i++) _entities[i].EntityPreviewVisuals?.HidePreviewState(); } public void Dispose() { StopPreviewLoop(); HitboxDrawer.Clear(); _displayFrame.Dispose(); _committedFrame.Dispose(); _maxFrame.Dispose(); _mode.Dispose(); _onTrackRebaked.Dispose(); _onRealEvent.Dispose(); } } }