Great timeline system (Age of AI WON)

This commit is contained in:
ThomasCharester committed 2026-11-20 01:36:01 +03:00
1 parent 2ce0391c16
commit e312131725
182 files changed
+380070 -470221

No files matched your search

@@ -0,0 +1,443 @@
using System;
using System.Collections.Generic;
using Code.Game.Entities;
using Code.OfficeGame.BattleMode.Actions;
using Code.OfficeGame.BattleMode.Effects;
using Code.OfficeGame.BattleMode.HitBoxes;
using KinematicCharacterController;
using UnityEngine;
namespace Code.OfficeGame.BattleMode.Timeline
{
public interface IBattleSimulationContext
{
float TickDelta { get; }
int CurrentSimFrame { get; }
int GetSlotIndex(EntityId entityId);
void SubmitAttack(
EntityId attackerId,
EntityId defenderId,
HitBoxPartType hitPart,
Vector3 hitWorldPosition,
EntityAttackedData attackedData);
void RecordHitboxVisual(BoxCollider box, Color color);
}
public sealed class BattleSimulator : IBattleSimulationContext
{
public const int TicksPerSecond = 60;
public const float FixedTickDelta = 1f / TicksPerSecond;
public const int MaxBakeFramesPerStep = 360; // 6 секунд предохранитель
private static readonly int VelocityForwardHash = Animator.StringToHash("VelocityForward");
private static readonly int VelocityRightHash = Animator.StringToHash("VelocityRight");
public float TickDelta => FixedTickDelta;
public int CurrentSimFrame { get; private set; }
public bool IsBaking { get; private set; }
private readonly Dictionary<BattleActionType, BattleAction> _actions;
private readonly List<EntityAttackedData> _pendingAttacks = new(8);
private readonly List<TimelineEvent> _frameEvents = new(8);
private readonly List<FrameHitboxVisual> _frameHitboxes = new(8);
private EntityProperties[] _entities;
private Transform[][] _entityBones;
private Dictionary<EntityId, int> _idToSlot;
private EntityActionSlotSnapshot[] _workingSlots;
public BattleSimulator(Dictionary<BattleActionType, BattleAction> actions)
{
_actions = actions;
}
public void BindEntities(EntityProperties[] entities)
{
_entities = entities;
_entityBones = new Transform[entities.Length][];
_idToSlot = new Dictionary<EntityId, int>(entities.Length);
_workingSlots = new EntityActionSlotSnapshot[entities.Length];
for (int i = 0; i < entities.Length; i++)
{
_idToSlot[entities[i].GetEntityId()] = i;
_entityBones[i] = CollectSkeletonTransforms(entities[i]);
}
}
private static Transform[] CollectSkeletonTransforms(EntityProperties properties)
{
if (properties.animator == null) return Array.Empty<Transform>();
var unique = new HashSet<Transform>();
var list = new List<Transform>(64);
foreach (var t in properties.animator.transform.GetComponentsInChildren<Transform>(includeInactive: true))
{
if (unique.Add(t)) list.Add(t);
}
return list.ToArray();
}
public int GetSlotIndex(EntityId entityId) =>
_idToSlot != null && _idToSlot.TryGetValue(entityId, out int slot) ? slot : -1;
public void SubmitAttack(
EntityId attackerId,
EntityId defenderId,
HitBoxPartType hitPart,
Vector3 hitWorldPosition,
EntityAttackedData attackedData)
{
int attackerSlot = GetSlotIndex(attackerId);
int defenderSlot = GetSlotIndex(defenderId);
if (attackerSlot < 0 || defenderSlot < 0) return;
// Заполняем ключи ДО проверки дубликатов
attackedData.AttackerId = attackerId;
attackedData.DefenderId = defenderId;
attackedData.HitBoxPartType = hitPart;
attackedData.HitWorldPosition = hitWorldPosition;
attackedData.Attacker = _entities[attackerSlot];
attackedData.Defender = _entities[defenderSlot];
for (int i = 0; i < _pendingAttacks.Count; i++)
{
if (_pendingAttacks[i].Equals(attackedData))
return;
}
_pendingAttacks.Add(attackedData);
}
public void RecordHitboxVisual(BoxCollider box, Color color)
{
if (box == null) return;
Transform t = box.transform;
Vector3 worldCenter = t.TransformPoint(box.center);
Vector3 worldSize = Vector3.Scale(box.size, t.lossyScale);
_frameHitboxes.Add(new FrameHitboxVisual
{
Matrix = Matrix4x4.TRS(worldCenter, t.rotation, worldSize),
Color = color
});
}
public BattleFrameSnapshot CaptureCurrentFrame(
int frame,
int interruptionStage,
EntityActionSlotSnapshot[] slots,
ulong readySlotsMask,
TimelineEvent[] events,
FrameHitboxVisual[] hitboxVisuals)
{
var entitySnaps = new EntityFrameSnapshot[_entities.Length];
for (int i = 0; i < _entities.Length; i++)
{
entitySnaps[i] = new EntityFrameSnapshot
{
EntityId = _entities[i].GetEntityId(),
PhysicsAndVisuals = EntitySnapshot.GetSnapshot(_entities[i], _entityBones[i]),
ActionSlot = slots[i].Clone()
};
}
return new BattleFrameSnapshot
{
Frame = frame,
InterruptionStage = interruptionStage,
Entities = entitySnaps,
ReadySlotsMask = readySlotsMask,
Events = events,
HitboxVisuals = hitboxVisuals
};
}
/// <summary>
/// Быстрое O(1) применение позы и позиции (для ползунка и воспроизведения).
/// </summary>
public void ApplyVisualFrameToWorld(BattleFrameSnapshot snapshot)
{
for (int i = 0; i < _entities.Length; i++)
{
EntitySnapshot.ApplyVisualOnly(_entities[i], _entityBones[i], snapshot.Entities[i].PhysicsAndVisuals);
}
Physics.SyncTransforms();
}
/// <summary>
/// Полное восстановление KCC + Mecanim + HP (для начала симуляции и перед Decider).
/// </summary>
public void RestoreSimulationToWorld(BattleFrameSnapshot snapshot)
{
for (int i = 0; i < _entities.Length; i++)
{
EntitySnapshot.RestoreForSimulation(_entities[i], _entityBones[i], snapshot.Entities[i].PhysicsAndVisuals);
}
Physics.SyncTransforms();
}
/// <summary>
/// Запекает будущее начиная со startFrame до завершения ВСЕХ активных действий.
/// При recordGhosts == true запекает слепки на старте (Stage 0) и на каждом кадре прерывания.
/// </summary>
public void BakeFrom(
BattleTimelineTrack track,
int startFrame,
bool recordGhosts,
int overrideSlot = -1,
EntityActionSlotSnapshot? overrideAction = null)
{
IsBaking = true;
try
{
track.TruncateAfter(startFrame);
var baseSnapshot = track.GetFrame(startFrame);
RestoreSimulationToWorld(baseSnapshot);
for (int i = 0; i < _entities.Length; i++)
{
_workingSlots[i] = (i == overrideSlot && overrideAction.HasValue)
? overrideAction.Value.Clone()
: baseSnapshot.Entities[i].ActionSlot.Clone();
_entities[i].EntityPreviewVisuals?.ClearAllGhosts();
}
// Stage 0: статичный слепок исходной точки (CommittedFrame)
if (recordGhosts)
{
for (int i = 0; i < _entities.Length; i++)
_entities[i].EntityPreviewVisuals?.BakeGhostAtStage(0, startFrame, isCompletingActor: false);
}
int currentStage = 0;
int steps = 0;
while (HasAnyActiveAction() && steps < MaxBakeFramesPerStep)
{
steps++;
CurrentSimFrame = startFrame + steps;
var nextFrameSnap = StepSingleFrame(CurrentSimFrame, ref currentStage, recordGhosts);
track.AppendFrame(nextFrameSnap);
}
}
finally
{
IsBaking = false;
RestoreSimulationToWorld(track.GetFrame(startFrame));
}
}
private bool HasAnyActiveAction()
{
for (int i = 0; i < _entities.Length; i++)
{
if (_entities[i].EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType != BattleActionType.None && slot.ActionData != null && !slot.ActionData.Finished)
return true;
}
return false;
}
private BattleFrameSnapshot StepSingleFrame(int frame, ref int currentStage, bool recordGhosts)
{
_pendingAttacks.Clear();
_frameEvents.Clear();
_frameHitboxes.Clear();
// ФАЗА 1: Логика тика действий (установка входов KCC, CrossFade, повороты)
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
if (entity.EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType == BattleActionType.None) continue;
_actions[slot.ActionType].Tick(FixedTickDelta, entity, slot.DecisionResult, slot.ActionData);
}
// ФАЗА 2: Единый шаг KCC для всех моторов одновременно
KinematicCharacterSystem.Simulate(
FixedTickDelta,
KinematicCharacterSystem.CharacterMotors,
KinematicCharacterSystem.PhysicsMovers);
// ФАЗА 3: Параметры BlendTree ходьбы + шаг аниматоров + RootMotion синхронизация каждый тик
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
UpdateAnimatorLocomotionParams(entity);
entity.animator.Update(FixedTickDelta);
if (entity.animator.applyRootMotion)
entity.SyncRootMotionToMotor();
}
// ФАЗА 4: Единый шаг PhysX и синхронизация костей/хитбоксов ДО проверок
Physics.Simulate(FixedTickDelta);
Physics.SyncTransforms();
// ФАЗА 5: Пост-проверка (хитбоксы и достижение точки уже по актуальным позициям!)
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
if (entity.EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType == BattleActionType.None) continue;
_actions[slot.ActionType].PostPhysicsTick(entity, slot.DecisionResult, slot.ActionData);
}
// ФАЗА 6: Одновременное разрешение всех попаданий кадра (честный Clash)
ResolvePendingAttacks(frame, currentStage);
// ФАЗА 7: Завершение окончившихся действий, смена стадии прерываний и запекание слепков
ulong readyMask = 0UL;
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
if (entity.EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType != BattleActionType.None && slot.ActionData.Finished)
{
BattleActionType completedType = slot.ActionType;
_actions[completedType].Finish(entity, slot.ActionData, slot.DecisionResult);
_workingSlots[i] = EntityActionSlotSnapshot.CreateNone(frame, completedType);
readyMask |= 1UL << i;
}
}
if (readyMask != 0UL)
{
currentStage++;
for (int i = 0; i < _entities.Length; i++)
{
bool isCompleting = (readyMask & (1UL << i)) != 0UL;
if (isCompleting)
{
_frameEvents.Add(new TimelineEvent(
frame,
i,
_entities[i].GetEntityId(),
TimelineEventType.ActionCompleted,
currentStage,
_entities[i].KinematicCharacterMotor.TransientPosition));
}
// Запекаем слепки ВСЕХ сущностей на кадре прерывания (завершивший — отдельным цветом)
if (recordGhosts && currentStage < EntityPreviewVisuals.MaxGhostStages)
{
_entities[i].EntityPreviewVisuals?.BakeGhostAtStage(
currentStage,
frame,
isCompleting);
}
}
}
return CaptureCurrentFrame(
frame,
currentStage,
_workingSlots,
readyMask,
_frameEvents.Count > 0 ? _frameEvents.ToArray() : Array.Empty<TimelineEvent>(),
_frameHitboxes.Count > 0 ? _frameHitboxes.ToArray() : Array.Empty<FrameHitboxVisual>());
}
private static void UpdateAnimatorLocomotionParams(EntityProperties entity)
{
if (entity.animator == null || entity.KinematicCharacterMotor == null) return;
var vel = entity.KinematicCharacterMotor.Velocity;
var t = entity.KinematicCharacterMotor.Transform;
entity.animator.SetFloat(VelocityForwardHash, Vector3.Project(vel, t.right).magnitude);
entity.animator.SetFloat(VelocityRightHash, Vector3.Project(vel, t.forward).magnitude);
}
private void ResolvePendingAttacks(int frame, int currentStage)
{
if (_pendingAttacks.Count == 0) return;
for (int i = 0; i < _pendingAttacks.Count; i++)
{
var request = _pendingAttacks[i];
int defenderSlot = GetSlotIndex(request.DefenderId);
if (defenderSlot < 0) continue;
var attacker = request.Attacker;
var defender = request.Defender;
if (defender.EntityHealth.IsDead) continue;
int damage = request.Damage;
foreach (var effect in attacker.Effects)
if (effect is AttackEffect atk) atk.Apply(ref damage);
foreach (var effect in defender.Effects)
if (effect is DefenseEffect def) def.Apply(ref damage);
defender.EntityHealth.GetDamage(damage, request.HitBoxPartType);
_frameEvents.Add(new TimelineEvent(
frame,
defenderSlot,
request.DefenderId,
TimelineEventType.HitLanded,
currentStage,
request.HitWorldPosition,
request.HitBoxPartType,
damage));
var oldSlot = _workingSlots[defenderSlot];
if (oldSlot.ActionType != BattleActionType.None)
{
_actions[oldSlot.ActionType].Finish(defender, oldSlot.ActionData, oldSlot.DecisionResult);
}
if (defender.EntityHealth.IsDead)
{
_workingSlots[defenderSlot] = EntityActionSlotSnapshot.CreateNone(frame, oldSlot.LastCompletedActionType);
_frameEvents.Add(new TimelineEvent(
frame,
defenderSlot,
request.DefenderId,
TimelineEventType.EntityDied,
currentStage,
defender.KinematicCharacterMotor.TransientPosition));
}
else
{
_workingSlots[defenderSlot] = new EntityActionSlotSnapshot
{
ActionType = request.ForcedDecisionResult.ActionType,
DecisionResult = request.ForcedDecisionResult,
ActionData = request.ForcedActionData,
LastCompletedActionType = oldSlot.LastCompletedActionType,
ActionStartFrame = frame,
EstimatedEndFrame = frame + request.ForcedActionData.TotalFrames
};
_frameEvents.Add(new TimelineEvent(
frame,
defenderSlot,
request.DefenderId,
TimelineEventType.Staggered,
currentStage,
defender.KinematicCharacterMotor.TransientPosition));
}
}
_pendingAttacks.Clear();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d8ff8646a8b04f07bbd2f317f843f482
timeCreated: 1795124527
@@ -2,15 +2,15 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Code.Game.Entities;
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.Effects;
using Code.OfficeGame.BattleMode.Snapshots;
using Code.OfficeGame.BattleMode.Health;
using Code.OfficeGame.BattleMode.HitBoxes;
using Code.OfficeGame.BattleMode.UI;
using Cysharp.Threading.Tasks;
using R3;
@@ -18,40 +18,44 @@ using UnityEngine;
namespace Code.OfficeGame.BattleMode.Timeline
{
public class BattleTimeline
public sealed class BattleTimeline : IDisposable
{
public const int TicksPerSecond = 60;
public const float TickDelta = 1f / TicksPerSecond;
public static bool IsSilentSimulation { get; private set; }
public const int TicksPerSecond = BattleSimulator.TicksPerSecond;
public const float TickDelta = BattleSimulator.FixedTickDelta;
public static float PlaybackSpeed { get; set; } = 1f;
private readonly ReactiveProperty<int> _currentBattleFrame = new(0);
public ReadOnlyReactiveProperty<int> CurrentBattleFrame => _currentBattleFrame;
// Реактивное состояние для UI (ползунок, маркеры, HP-бары)
private readonly ReactiveProperty<int> _displayFrame = new(0);
private readonly ReactiveProperty<int> _committedFrame = new(0);
private readonly ReactiveProperty<int> _maxFrame = new(0);
private readonly ReactiveProperty<TimelineMode> _mode = new(TimelineMode.Idle);
private readonly Subject<BattleTimelineTrack> _onTrackRebaked = new();
private readonly Subject<TimelineEvent> _onRealEvent = new();
public ReadOnlyReactiveProperty<int> DisplayFrame => _displayFrame;
public ReadOnlyReactiveProperty<int> CommittedFrame => _committedFrame;
public ReadOnlyReactiveProperty<int> MaxFrame => _maxFrame;
public ReadOnlyReactiveProperty<TimelineMode> Mode => _mode;
public Observable<BattleTimelineTrack> OnTrackRebaked => _onTrackRebaked;
public Observable<TimelineEvent> OnRealEvent => _onRealEvent;
public BattleTimelineTrack Track { get; } = new();
private readonly BattleTimelinePanel _timelinePanel;
private DisposableBag _battleSubscriptions;
private readonly BattleActionDecisionPanel _decisionPanel;
private readonly HealthPanelsHolder _healthPanelsHolder;
private readonly CameraStateMachine _cameraStateMachine;
private readonly IParticleService _particleService;
private Dictionary<BattleActionType, BattleAction> _battleActions;
private Dictionary<DeciderType, BattleActionDecider> _battleActionDeciders;
private Dictionary<EnemyDeciderTypes, EnemyDecider> _enemyDeciders;
private Dictionary<EntityId, EntityProperties> _entities;
private Dictionary<EntityId, BattleActionData> _battleActionDatas = new();
private Dictionary<EntityId, BattleActionDecisionResult> _actionDecisionResults = new();
private SnapshotUtilityNonStatic _snapshotUtility = new();
private BattleActionDecisionPanel _battleActionDecisionPanel;
private CameraStateMachine _cameraStateMachine;
private SemaphoreSlim _preview = new(1,1);
// Entity, damage
private List<EntityAttackedData> _attackRequests = new();
private List<EntityAttackedData> _predictedAttackRequests = new();
private readonly Dictionary<BattleActionType, BattleAction> _battleActions;
private readonly Dictionary<DeciderType, BattleActionDecider> _battleActionDeciders;
private readonly Dictionary<EnemyDeciderTypes, EnemyDecider> _enemyDeciders;
private readonly BattleSimulator _simulator;
private EntityProperties[] _entities;
private CancellationTokenSource _previewLoopCts;
private bool _previewVisualsEnabled;
public BattleTimeline(
BattleTimelinePanel timelinePanel,
@@ -59,558 +63,436 @@ namespace Code.OfficeGame.BattleMode.Timeline
IEnumerable<BattleActionDecider> battleActionDeciders,
IEnumerable<EnemyDecider> enemyDeciders,
BattleActionDecisionPanel battleActionDecisionPanel,
CameraStateMachine cameraStateMachine)
HealthPanelsHolder healthPanelsHolder,
CameraStateMachine cameraStateMachine,
IParticleService particleService)
{
_cameraStateMachine = cameraStateMachine;
_battleActionDecisionPanel = battleActionDecisionPanel;
_timelinePanel = timelinePanel;
_decisionPanel = battleActionDecisionPanel;
_healthPanelsHolder = healthPanelsHolder;
_cameraStateMachine = cameraStateMachine;
_particleService = particleService;
_battleActions = new();
foreach (var battleAction in battleActions)
{
battleAction.SetBattleTimeline(this);
_battleActions.Add(battleAction.ActionType, battleAction);
}
_battleActions = battleActions.ToDictionary(x => x.ActionType);
_battleActionDeciders = battleActionDeciders.ToDictionary(x => x.DeciderType);
_enemyDeciders = enemyDeciders.ToDictionary(x=>x.EnemyDeciderType);
_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;
public async UniTask RunBattleLoopAsync(List<EntityProperties> entities, CancellationToken ctx)
{
_entities = entities.ToDictionary(x => x.GetEntityId());
_battleLoopCt = ctx;
_entities = entities.ToArray();
_simulator.BindEntities(_entities);
foreach (var (id, entity) in _entities)
{
_battleActionDatas[id] = new NoneBattleActionData() { Finished = true };
_actionDecisionResults[id] = new AsIsBattleActionDeciderResult()
{ ActionType = BattleActionType.None, ResultCode = BattleActionDecisionResultCode.Decided };
}
_currentBattleFrame.Value = 0;
var initialSlots = new EntityActionSlotSnapshot[_entities.Length];
for (int i = 0; i < _entities.Length; i++)
initialSlots[i] = EntityActionSlotSnapshot.CreateNone(0);
_battleSubscriptions = new DisposableBag();
var frameZero = _simulator.CaptureCurrentFrame(
frame: 0,
interruptionStage: 0,
slots: initialSlots,
readySlotsMask: 0UL,
events: Array.Empty<TimelineEvent>(),
hitboxVisuals: Array.Empty<FrameHitboxVisual>());
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
{
_currentBattleFrame
.Subscribe(_timelinePanel.OnFrameTick)
.AddTo(ref _battleSubscriptions);
await DecideActions(_entities.Keys.ToArray(), ctx);
while (!ctx.IsCancellationRequested)
{
EntityId[] entitiesNeedOrders = await PlayTimelineUntilPause(ctx);
var readySlots = Track.GetReadySlotsAt(_committedFrame.Value);
if (readySlots.Count == 0) break;
await DecideActions(entitiesNeedOrders, ctx);
// 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
{
_battleSubscriptions.Dispose();
StopPreviewLoop();
HideAllPreviewVisuals();
HitboxDrawer.Clear();
_mode.Value = TimelineMode.Idle;
}
}
private async UniTask<EntityId[]> PlayTimelineUntilPause(CancellationToken ctx)
private async UniTask PlayBakedRangeAsync(int startFrame, int endFrame, CancellationToken ctx)
{
float accumulator = 0f;
StopPreviewLoop();
_previewVisualsEnabled = false;
HideAllPreviewVisuals();
_mode.Value = TimelineMode.BattlePlaying;
while (!ctx.IsCancellationRequested)
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)
while (accumulator >= TickDelta && frame <= endFrame && !ctx.IsCancellationRequested)
{
accumulator -= TickDelta;
_currentBattleFrame.Value++;
var readyEntities = SimulateSingleFrame(_entities);
if (readyEntities.Length > 0)
{
foreach (var entityId in readyEntities)
{
Debug.Log($"Entity {entityId} is real ready");
_battleActions[_actionDecisionResults[entityId].ActionType]
.Finish(
_entities[entityId],
_battleActionDatas[entityId],
_actionDecisionResults[entityId]);
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
}
return readyEntities;
}
_committedFrame.Value = frame;
ApplyFrame(frame, playOneShotVfx: true);
frame++;
}
}
return null;
}
// TODO ЗАПУСКАТЬ ДВА ЦИКЛА ПОЛНЫЙ И ДО ПРЕРЫВАНИЯ
private async UniTask PreviewBattleLoopAsync(int frameCount,
Dictionary<EntityId, EntityProperties> entities,
CancellationToken ctx)
{
if (frameCount <= 0)
{
_preview.Release(1);
throw new Exception("FrameCount must be > 0");
}
_snapshotUtility.GetSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
try
{
while (!ctx.IsCancellationRequested)
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
await PlayTimelineForCertainFrames(frameCount, ctx).AttachExternalCancellation(ctx);
}
}
finally
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
foreach (var (_, entity) in entities)
{
entity.EntityPreviewVisuals.HidePreviewState();
}
_preview.Release(1);
}
}
private async UniTask PreviewBattleLoopAsync(EntityId entityId,
Dictionary<EntityId, EntityProperties> entities,
CancellationToken ctx)
private async UniTask DecideActionsForSlots(List<int> readySlots, CancellationToken ctx)
{
_snapshotUtility.GetSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
_mode.Value = TimelineMode.Deciding;
try
// Сначала решения принимают ИИ — игрок сразу увидит их запечённый план на таймлайне
var orderedSlots = readySlots
.OrderBy(slot => _entities[slot].TeamData.Team == EntityTeam.Good ? 1 : 0)
.ToList();
foreach (int slotIndex in orderedSlots)
{
while (!ctx.IsCancellationRequested)
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
_simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value));
ApplyFrame(_committedFrame.Value, playOneShotVfx: false);
await PlayTimelineUntilThatSpecific(entityId, ctx).AttachExternalCancellation(ctx);
}
}
finally
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
foreach (var (_, entity) in entities)
{
entity.EntityPreviewVisuals.HidePreviewState();
}
EntityActionSlotSnapshot chosenSlot = await DecideForSingleSlot(slotIndex, ctx);
_preview.Release(1);
Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot = chosenSlot;
RebakeFromCommitted(recordGhosts: false);
}
}
private async UniTask PlayTimelineForCertainFrames(int frameCount, CancellationToken ctx)
private async UniTask<EntityActionSlotSnapshot> DecideForSingleSlot(int slotIndex, CancellationToken ctx)
{
float accumulator = 0f;
int counter = frameCount;
while (counter > 0 && !ctx.IsCancellationRequested)
var entity = _entities[slotIndex];
if (entity.TeamData.Team == EntityTeam.ChaoticEvil)
{
bool isCanceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
if (isCanceled) break;
var (enemyRes, enemyData) = await _enemyDeciders[entity.TeamData.DeciderType]
.DecideEnemy(ctx, entity, _battleActions);
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
while (accumulator >= TickDelta && counter > 0 && !ctx.IsCancellationRequested)
return new EntityActionSlotSnapshot
{
// Debug.Log($"Simulating {counter}/{frameCount}");
accumulator -= TickDelta;
counter--;
var readyEntities = SimulateSingleFrame(_entities);
if (readyEntities.Length > 0)
{
foreach (var entityId in readyEntities)
{
var battleActionType = _actionDecisionResults[entityId].ActionType;
Debug.Log($"Entity {entityId} is preview ready {battleActionType}");
_battleActions[battleActionType]
.Finish(
_entities[entityId],
_battleActionDatas[entityId],
_actionDecisionResults[entityId]);
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
}
// return;
}
}
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 PlayTimelineUntilThatSpecific(EntityId specificEntityId, CancellationToken ctx)
private async UniTask<EntityActionSlotSnapshot> DecideForPlayerSlot(int slotIndex, CancellationToken ctx)
{
float accumulator = 0f;
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)
{
bool isCanceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
if (isCanceled) break;
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);
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();
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;
var readyEntities = SimulateSingleFrame(_entities);
current++;
if (current > endFrame) current = startFrame;
if (readyEntities.Length > 0)
{
foreach (var entityId in readyEntities)
{
var battleActionType = _actionDecisionResults[entityId].ActionType;
Debug.Log($"Entity {entityId} is preview ready {battleActionType}");
_battleActions[_actionDecisionResults[entityId].ActionType]
.Finish(
_entities[entityId],
_battleActionDatas[entityId],
_actionDecisionResults[entityId]);
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
}
if(readyEntities.Contains(specificEntityId)) return;
}
ApplyFrame(current, playOneShotVfx: false);
}
}
}
public List<EntityAttackedData> PredictSilently(int lookaheadFrames)
private void StopPreviewLoop()
{
// var snapshot = TakeFullBattleSnapshot();
_snapshotUtility.GetSnapshots(
_entities,
_actionDecisionResults,
_battleActionDatas);
_predictedAttackRequests.Clear();
IsSilentSimulation = true;
try
{
for (int i = 0; i < lookaheadFrames; i++)
{
var readyEntities = SimulateSingleFrame(_entities);
if (readyEntities.Length > 0) break; // Останавливаемся, если чей-то ход закончился
}
}
finally
{
IsSilentSimulation = false;
_snapshotUtility.RestoreFromSnapshots(
_entities,
_actionDecisionResults,
_battleActionDatas);
// RestoreFullBattleSnapshot(snapshot);
}
return _predictedAttackRequests;
if (_previewLoopCts == null) return;
_previewLoopCts.Cancel();
_previewLoopCts.Dispose();
_previewLoopCts = null;
}
private EntityId[] SimulateSingleFrame(Dictionary<EntityId, EntityProperties> inEntities)
/// <summary>
/// Единая точка отображения любого кадра (бой, превью и скраббинг ползунком).
/// </summary>
private void ApplyFrame(int frame, bool playOneShotVfx)
{
foreach (var (entityId, entity) in inEntities)
var snapshot = Track.GetFrame(frame);
_simulator.ApplyVisualFrameToWorld(snapshot);
_displayFrame.Value = snapshot.Frame;
// Обновляем многоступенчатые слепки и цвет проекции ТОЛЬКО для кадров будущего (> CommittedFrame)
for (int i = 0; i < _entities.Length; i++)
{
if (!_actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult)
|| !_battleActionDatas.TryGetValue(entityId, out var battleActionData))
continue;
_battleActions[actionDecisionResult.ActionType]
.Tick(
TickDelta,
entity,
actionDecisionResult,
battleActionData);
entity.animator.Update(TickDelta);
_entities[i].EntityPreviewVisuals?.UpdateForTimelineFrame(
viewFrame: snapshot.Frame,
committedFrame: _committedFrame.Value,
interruptionStage: snapshot.InterruptionStage,
showPreviewVisuals: _previewVisualsEnabled);
}
KinematicCharacterController.KinematicCharacterSystem.Simulate(
TickDelta,
KinematicCharacterController.KinematicCharacterSystem.CharacterMotors,
KinematicCharacterController.KinematicCharacterSystem.PhysicsMovers
);
Physics.Simulate(TickDelta);
Physics.SyncTransforms();
ProcessAttackRequests();
var readyEntities = _battleActionDatas
.Where(x => x.Value.Finished)
.Where(x=> !inEntities[x.Key].EntityHealth.IsDead)
.Select(x => x.Key)
.ToArray();
return readyEntities;
}
private async UniTask DecideActions(EntityId[] entities, CancellationToken ctx)
{
foreach (var entityId in entities)
// Хитбоксы текущего кадра не исчезают, даже если ползунок остановлен!
HitboxDrawer.Clear();
var hitboxes = snapshot.HitboxVisuals;
if (hitboxes != null)
{
var (decisionResult, battleActionData) = await DecideAction(ctx, _entities[entityId]);
for (int i = 0; i < hitboxes.Length; i++)
HitboxDrawer.DrawMatrix(hitboxes[i].Matrix, hitboxes[i].Color, duration: 999f);
}
_actionDecisionResults[entityId] = decisionResult;
_battleActionDatas[entityId] = battleActionData;
// События VFX стреляют только в реальном воспроизведении
if (playOneShotVfx && snapshot.Events is { Length: > 0 })
{
for (int i = 0; i < snapshot.Events.Length; i++)
_onRealEvent.OnNext(snapshot.Events[i]);
}
}
private async UniTask<(BattleActionDecisionResult, BattleActionData)> DecideAction(CancellationToken ctx,
EntityProperties entity)
private void HandleRealEvent(TimelineEvent ev)
{
if(entity.TeamData.Team == EntityTeam.Good)
if (ev.EventType == TimelineEventType.HitLanded)
{
var (decisionResult, actionData) = await DecideForPlayer(ctx, entity);
if (decisionResult == null || actionData == null)
throw new ArgumentNullException(nameof(decisionResult));
return (decisionResult, actionData);
_particleService.EmitOneShot(
new ParticlePartitionIDPair(ParticlePartition.HitParticles, 0),
15,
ev.WorldPosition,
Quaternion.identity);
}
if (entity.TeamData.Team == EntityTeam.ChaoticEvil)
{
var (enemyDecisionResult, enemyActionData) =
await _enemyDeciders[entity.TeamData.DeciderType].DecideEnemy(ctx, entity, _battleActions);
if (enemyDecisionResult == null || enemyActionData == null)
throw new ArgumentNullException(nameof(enemyDecisionResult));
return (enemyDecisionResult, enemyActionData);
}
return (new AsIsBattleActionDeciderResult(), new NoneBattleActionData());
}
private async UniTask<(BattleActionDecisionResult decisionResult, BattleActionData actionData)> DecideForPlayer(CancellationToken ctx, EntityProperties entity)
private void HideAllPreviewVisuals()
{
_battleActionDecisionPanel.SetEntityInfo(entity.battleActionTypes);
BattleActionType decidedActionType = BattleActionType.None;
BattleActionDecisionResult decisionResult = null;
BattleActionData actionData = null;
var entityId = entity.GetEntityId();
BattleActionData entityActionDataSnapshot = null;
BattleActionDecisionResult entityResultSnapshot = null;
if (_battleActionDatas.TryGetValue(entityId, out var battleActionData))
entityActionDataSnapshot = battleActionData.GetSnapshot();
if (_actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult))
{
entityResultSnapshot = actionDecisionResult.GetSnapshot();
_timelinePanel.SetPreviousActionText(entityResultSnapshot.ActionType.ToString());
}
while (decidedActionType == BattleActionType.None || ctx.IsCancellationRequested)
{
Cursor.lockState = CursorLockMode.Confined;
((CameraBattleModeState)_cameraStateMachine.CurrentBaseState).battleDeciding = true;
await _battleActionDecisionPanel.Open(ctx);
decidedActionType = await _battleActionDecisionPanel.GetDecision(ctx);
if (decidedActionType == BattleActionType.None) continue;
var deciderType = _battleActions[decidedActionType].DeciderType;
_battleActionDeciders[deciderType].MountDecider(entity);
CancellationTokenSource previewCancellationToken = new();
while (!ctx.IsCancellationRequested)
{
Cursor.lockState = CursorLockMode.Locked;
((CameraBattleModeState)_cameraStateMachine.CurrentBaseState).battleDeciding = false;
await _battleActionDecisionPanel.Close(ctx);
decisionResult = await _battleActionDeciders[deciderType].GetDecision();
decisionResult.ActionType = decidedActionType;
previewCancellationToken.Cancel();
previewCancellationToken.Dispose();
await _preview.WaitAsync(ctx);
_preview.Release();
actionData = _battleActions[decidedActionType].MountAndGetFrames(entity, decisionResult);
if (decisionResult.ResultCode == BattleActionDecisionResultCode.Deciding)
{
_actionDecisionResults[entityId] = decisionResult;
_battleActionDatas[entityId] = actionData;
previewCancellationToken = new();
await _preview.WaitAsync(previewCancellationToken.Token);
PredictSilently(actionData.TotalFrames);
PreviewBattleLoopAsync(entityId, _entities, previewCancellationToken.Token)
.Forget();
}
else if (decisionResult.ResultCode == BattleActionDecisionResultCode.CancelDecision)
{
decidedActionType = BattleActionType.None;
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
break;
}
else break;
}
_battleActionDeciders[deciderType].UnmountDecider();
}
_battleActionDatas[entityId] = entityActionDataSnapshot;
_actionDecisionResults[entityId] = entityResultSnapshot;
return (decisionResult, actionData);
if (_entities == null) return;
for (int i = 0; i < _entities.Length; i++)
_entities[i].EntityPreviewVisuals?.HidePreviewState();
}
// public void ForceDecideAction(
// EntityId entityId,
// BattleActionData forcedBattleActionData,
// BattleActionDecisionResult forcedBattleActionDataResult)
// {
// if(_battleActionDatas.TryGetValue(entityId, out var battleActionData)
// && _actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult))
// _battleActions[_actionDecisionResults[entityId].ActionType]
// .Finish(
// _entities[entityId],
// battleActionData,
// actionDecisionResult);
//
// _battleActionDatas[entityId] = forcedBattleActionData;
// _actionDecisionResults[entityId] = forcedBattleActionDataResult;
//
// Debug.Log($"Задано действие {forcedBattleActionDataResult.ActionType} для {entityId} with {forcedBattleActionData.GetType()}");
// }
private void ProcessAttackRequests()
public void Dispose()
{
foreach (var request in _attackRequests)
{
var attacker = request.Attacker;
var defender = request.Defender;
var attackEffects = attacker.Effects.Where(x => x.Type == EffectType.Attack)
.Select(x => (AttackEffect)x);
var damage = request.Damage;
foreach (var effect in attackEffects)
{
effect.Apply(damage);
}
var defendEffects = defender.Effects.Where(x => x.Type == EffectType.Defense)
.Select(x => (DefenseEffect)x);
foreach (var effect in defendEffects)
{
effect.Apply(damage);
}
defender.EntityHealth.GetDamage(damage, request.HitBoxPartType);
var defenderId = request.DefenderId;
if (_battleActionDatas.TryGetValue(defenderId, out var battleActionData)
&& _actionDecisionResults.TryGetValue(defenderId, out var actionDecisionResult))
_battleActions[_actionDecisionResults[defenderId].ActionType]
.Finish(
_entities[defenderId],
battleActionData,
actionDecisionResult);
Debug.Log($"{defender} got {damage} and {defender.EntityHealth.IsDead}");
if (defender.EntityHealth.IsDead)
{
var forcedDeathData = new NoneBattleActionData();
var forcedDeathDecision = new AsIsBattleActionDeciderResult();
_battleActionDatas[defenderId] = forcedDeathData;
_actionDecisionResults[defenderId] = forcedDeathDecision;
}
else
{
_battleActionDatas[defenderId] = request.ForcedActionData;
_actionDecisionResults[defenderId] = request.ForcedDecisionResult;
}
}
_attackRequests.Clear();
}
public void AttackRequest(EntityId attacker, EntityId defender, EntityAttackedData attackedData)
{
if (_attackRequests.Contains(attackedData)) return;
attackedData.AttackerId = attacker;
attackedData.DefenderId = defender;
attackedData.Attacker = _entities[attacker];
attackedData.Defender = _entities[defender];
_attackRequests.Add(attackedData);
}
public void KillEntity(EntityId entityId)
{
StopPreviewLoop();
HitboxDrawer.Clear();
_displayFrame.Dispose();
_committedFrame.Dispose();
_maxFrame.Dispose();
_mode.Dispose();
_onTrackRebaked.Dispose();
_onRealEvent.Dispose();
}
}
}
@@ -0,0 +1,131 @@
using Code.OfficeGame.BattleMode.Actions;
using Code.OfficeGame.BattleMode.HitBoxes;
using UnityEngine;
namespace Code.OfficeGame.BattleMode.Timeline
{
public enum TimelineMode
{
Idle,
Deciding,
PreviewPlaying,
Scrubbing,
BattlePlaying
}
public enum TimelineEventType
{
ActionCompleted, // Прерывание на выбор действия
HitLanded, // Реальное попадание (уже после эффектов и проверки смерти)
Staggered, // Наложен стаггер
EntityDied // Смерть сущности
}
public readonly struct TimelineEvent
{
public readonly int Frame;
public readonly int SlotIndex;
public readonly EntityId EntityId;
public readonly TimelineEventType EventType;
public readonly int InterruptionStage;
public readonly Vector3 WorldPosition;
public readonly HitBoxPartType HitPart;
public readonly int Value; // Например, итоговый урон
public TimelineEvent(
int frame,
int slotIndex,
EntityId entityId,
TimelineEventType eventType,
int interruptionStage,
Vector3 worldPosition = default,
HitBoxPartType hitPart = default,
int value = 0)
{
Frame = frame;
SlotIndex = slotIndex;
EntityId = entityId;
EventType = eventType;
InterruptionStage = interruptionStage;
WorldPosition = worldPosition;
HitPart = hitPart;
Value = value;
}
}
public struct EntityActionSlotSnapshot
{
public BattleActionType ActionType;
public BattleActionDecisionResult DecisionResult;
public BattleActionData ActionData;
public BattleActionType LastCompletedActionType;
public int ActionStartFrame;
public int EstimatedEndFrame;
public readonly EntityActionSlotSnapshot Clone()
{
return new EntityActionSlotSnapshot
{
ActionType = ActionType,
DecisionResult = DecisionResult?.GetSnapshot(),
ActionData = ActionData?.GetSnapshot(),
LastCompletedActionType = LastCompletedActionType,
ActionStartFrame = ActionStartFrame,
EstimatedEndFrame = EstimatedEndFrame
};
}
public static EntityActionSlotSnapshot CreateNone(
int frame,
BattleActionType lastCompleted = BattleActionType.None)
{
return new EntityActionSlotSnapshot
{
ActionType = BattleActionType.None,
DecisionResult = new AsIsBattleActionDeciderResult
{
ActionType = BattleActionType.None,
ResultCode = BattleActionDecisionResultCode.Decided
},
ActionData = new NoneBattleActionData { TotalFrames = 0, Finished = true },
LastCompletedActionType = lastCompleted,
ActionStartFrame = frame,
EstimatedEndFrame = frame
};
}
}
public struct EntityFrameSnapshot
{
public EntityId EntityId;
public EntitySnapshot PhysicsAndVisuals;
public EntityActionSlotSnapshot ActionSlot;
}
public struct FrameHitboxVisual
{
public Matrix4x4 Matrix;
public Color Color;
}
public sealed class BattleFrameSnapshot
{
public int Frame;
/// <summary>
/// Сколько прерываний уже прошло к этому кадру в текущем прогнозе (0 = до первого прерывания).
/// Используется для смены цвета проекции.
/// </summary>
public int InterruptionStage;
public EntityFrameSnapshot[] Entities;
/// <summary>
/// Битовая маска слотов (0..63), чьё действие ЗАВЕРШИЛОСЬ именно на этом кадре.
/// </summary>
public ulong ReadySlotsMask;
public TimelineEvent[] Events;
public FrameHitboxVisual[] HitboxVisuals;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 26f0790ef3ff47fda533540652b9d50d
timeCreated: 1795124345
@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using Code.OfficeGame.BattleMode.Actions;
namespace Code.OfficeGame.BattleMode.Timeline
{
public sealed class BattleTimelineTrack
{
private readonly List<BattleFrameSnapshot> _frames = new(512);
private readonly List<TimelineEvent> _allEvents = new(64);
public int FrameCount => _frames.Count;
public int LastFrame => _frames.Count > 0 ? _frames.Count - 1 : 0;
public IReadOnlyList<TimelineEvent> AllEvents => _allEvents;
public void Initialize(BattleFrameSnapshot frameZero)
{
_frames.Clear();
_allEvents.Clear();
AppendFrame(frameZero);
}
public BattleFrameSnapshot GetFrame(int frame)
{
if (_frames.Count == 0)
throw new InvalidOperationException("Timeline track is empty.");
int clamped = Math.Clamp(frame, 0, _frames.Count - 1);
return _frames[clamped];
}
public void TruncateAfter(int keepUpToFrame)
{
int removeStart = keepUpToFrame + 1;
if (removeStart < _frames.Count)
_frames.RemoveRange(removeStart, _frames.Count - removeStart);
for (int i = _allEvents.Count - 1; i >= 0; i--)
{
if (_allEvents[i].Frame > keepUpToFrame)
_allEvents.RemoveAt(i);
}
}
public void AppendFrame(BattleFrameSnapshot snapshot)
{
_frames.Add(snapshot);
if (snapshot.Events is { Length: > 0 })
_allEvents.AddRange(snapshot.Events);
}
/// <summary>
/// Первый кадр строго после fromFrame, на котором хотя бы один живой боец завершил действие.
/// </summary>
public int FindNextPauseFrame(int fromFrame)
{
for (int f = fromFrame + 1; f < _frames.Count; f++)
{
if (_frames[f].ReadySlotsMask != 0UL)
return f;
}
return LastFrame;
}
/// <summary>
/// Кадр завершения действия конкретного слота (учитывая прерывания).
/// </summary>
public int FindActionEndFrameForSlot(int fromFrame, int slotIndex)
{
ulong mask = 1UL << slotIndex;
for (int f = fromFrame + 1; f < _frames.Count; f++)
{
if ((_frames[f].ReadySlotsMask & mask) != 0UL)
return f;
}
return LastFrame;
}
/// <summary>
/// Возвращает индексы всех живых слотов, которым нужен новый приказ на кадре frame.
/// </summary>
public List<int> GetReadySlotsAt(int frame)
{
var result = new List<int>();
var snap = GetFrame(frame);
for (int i = 0; i < snap.Entities.Length; i++)
{
var e = snap.Entities[i];
bool isDead = e.PhysicsAndVisuals.CurrentHealth.CurrentHealth <= 0;
if (isDead) continue;
bool markedReady = (snap.ReadySlotsMask & (1UL << i)) != 0UL;
bool isIdleNone = e.ActionSlot.ActionType == BattleActionType.None;
if (markedReady || isIdleNone)
result.Add(i);
}
return result;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d8b32783a1b1403a9a34e805e905e13e
timeCreated: 1795124497