using System; using System.Collections.Generic; using Code.Game.Entities; using Code.Game.OfficeGame.Entities; using Code.OfficeGame.BattleMode.Actions; using Code.OfficeGame.BattleMode.Actions.AI; 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 _actions; private readonly List _pendingAttacks = new(8); private readonly List _frameEvents = new(8); private readonly List _frameHitboxes = new(8); private EntityProperties[] _entities; private Transform[][] _entityBones; private Dictionary _idToSlot; private EntityActionSlotSnapshot[] _workingSlots; private readonly IBattleAiResolver _aiResolver; public BattleSimulator( Dictionary actions, IBattleAiResolver aiResolver) { _actions = actions; _aiResolver = aiResolver; } public void BindEntities(EntityProperties[] entities) { _entities = entities; _entityBones = new Transform[entities.Length][]; _idToSlot = new Dictionary(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(); var unique = new HashSet(); var list = new List(64); foreach (var t in properties.animator.transform.GetComponentsInChildren(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 }; } /// /// Быстрое O(1) применение позы и позиции (для ползунка и воспроизведения). /// 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(); } /// /// Полное восстановление KCC + Mecanim + HP (для начала симуляции и перед Decider). /// 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(); } /// /// Запекает будущее начиная со startFrame до завершения ВСЕХ активных действий. /// При recordGhosts == true запекает слепки на старте (Stage 0) и на каждом кадре прерывания. /// 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: Параметры ходьбы + шаг аниматоров + чистый дельта-перенос RootMotion for (int i = 0; i < _entities.Length; i++) { var entity = _entities[i]; UpdateAnimatorLocomotionParams(entity); if (entity.animator.applyRootMotion) { Transform animT = entity.animator.transform; Vector3 savedLocalPos = animT.localPosition; Quaternion savedLocalRot = animT.localRotation; Vector3 worldPosBefore = animT.position; Quaternion worldRotBefore = animT.rotation; entity.animator.Update(FixedTickDelta); Vector3 worldDeltaPos = animT.position - worldPosBefore; Quaternion worldDeltaRot = animT.rotation * Quaternion.Inverse(worldRotBefore); // Возвращаем модель на её родной локальный оффсет animT.localPosition = savedLocalPos; animT.localRotation = savedLocalRot; var motor = entity.KinematicCharacterMotor; motor.SetPositionAndRotation( motor.TransientPosition + worldDeltaPos, worldDeltaRot * motor.TransientRotation, bypassInterpolation: true); motor.BaseVelocity = Vector3.zero; } else { entity.animator.Update(FixedTickDelta); } } // ФАЗА 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); } } } // Авто-цепочка ходов ИИ: если игрок НЕ освободился в этом кадре, но всё ещё занят действием, // освободившиеся враги сразу выбирают следующее действие прямо внутри запекания. if (_aiResolver != null && readyMask != 0UL) { bool anyPlayerReadyThisFrame = false; bool anyPlayerStillBusy = false; for (int i = 0; i < _entities.Length; i++) { if (_entities[i].EntityHealth.IsDead) continue; if (_entities[i].TeamData.Team != EntityTeam.Good) continue; if ((readyMask & (1UL << i)) != 0UL) anyPlayerReadyThisFrame = true; else if (_workingSlots[i].ActionType != BattleActionType.None && !_workingSlots[i].ActionData.Finished) anyPlayerStillBusy = true; } if (!anyPlayerReadyThisFrame && anyPlayerStillBusy) { for (int i = 0; i < _entities.Length; i++) { if ((readyMask & (1UL << i)) == 0UL) continue; var entity = _entities[i]; if (entity.TeamData.Team != EntityTeam.ChaoticEvil) continue; if (_aiResolver.TryResolveNextAction(entity, _actions, out var nextDecision, out var nextData)) { _workingSlots[i] = new EntityActionSlotSnapshot { ActionType = nextDecision.ActionType, DecisionResult = nextDecision, ActionData = nextData, LastCompletedActionType = _workingSlots[i].LastCompletedActionType, ActionStartFrame = frame, EstimatedEndFrame = frame + nextData.TotalFrames }; } } } } return CaptureCurrentFrame( frame, currentStage, _workingSlots, readyMask, _frameEvents.Count > 0 ? _frameEvents.ToArray() : Array.Empty(), _frameHitboxes.Count > 0 ? _frameHitboxes.ToArray() : Array.Empty()); } 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(); } } }