You do some, you lose some
This commit is contained in:
1 parent
1d107924bf
commit
2ce0391c16
42 files changed
+331912
-5358
No files matched your search
@@ -2,6 +2,11 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public class NoneBattleActionData : BattleActionData
|
||||
{
|
||||
public NoneBattleActionData()
|
||||
{
|
||||
Finished = true;
|
||||
TotalFrames = 0;
|
||||
}
|
||||
public override BattleActionData GetSnapshot()
|
||||
{
|
||||
return new NoneBattleActionData()
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
|
||||
{
|
||||
actionData.TransitionFrames = _attackData.TransitionFrames;
|
||||
actionData.TotalFrames = _attackData.TotalFrames;
|
||||
|
||||
|
||||
entity.SyncRootMotionToMotor();
|
||||
|
||||
var entityAnimator = entity.animator;
|
||||
@@ -131,7 +131,8 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
|
||||
|
||||
//battleTimeline.ForceDecideAction(originEntityId, actionData, decisionResult);
|
||||
|
||||
_particleService.EmitOneShot(
|
||||
if(!BattleTimeline.IsSilentSimulation)
|
||||
_particleService.EmitOneShot(
|
||||
new ParticlePartitionIDPair(ParticlePartition.HitParticles, 0),
|
||||
15,
|
||||
enemyCollider.transform.position,
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
public override void Tick(float tickDelta, EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult,
|
||||
BattleActionData battleActionData)
|
||||
{
|
||||
// battleActionData.Finished = true;
|
||||
battleActionData.Finished = true;
|
||||
}
|
||||
|
||||
public override BattleActionType ActionType => BattleActionType.None;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using Code.Game.Gameplay.Player;
|
||||
using Code.OfficeGame.BattleMode.Health;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -6,41 +5,73 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public struct EntitySnapshot
|
||||
{
|
||||
public Vector3 BaseVelocity;
|
||||
// 1. KCC Motor
|
||||
public Vector3 Position;
|
||||
public Quaternion Rotation;
|
||||
|
||||
public AnimatorSnapshot AnimatorSnapshot;
|
||||
public MovementControllerSnapshot ControllerSnapshot;
|
||||
public EntityHealthSnapshot HealthSnapshot;
|
||||
public Vector3 BaseVelocity;
|
||||
|
||||
public static EntitySnapshot GetSnapshot(EntityProperties entityProperties)
|
||||
// 2. MovementController
|
||||
public bool IsFrozen;
|
||||
public Vector3 MoveInputVector;
|
||||
public Vector3 LookInputVector;
|
||||
|
||||
// 3. Здоровье
|
||||
public HealthData CurrentHealth;
|
||||
|
||||
// 4. Аниматор
|
||||
public AnimatorSnapshot AnimatorSnapshot;
|
||||
|
||||
public static EntitySnapshot GetSnapshot(EntityProperties entity)
|
||||
{
|
||||
var motor = entity.KinematicCharacterMotor;
|
||||
var moveCtrl = entity.MovementController;
|
||||
|
||||
return new EntitySnapshot
|
||||
{
|
||||
BaseVelocity = entityProperties.KinematicCharacterMotor.BaseVelocity,
|
||||
Position = entityProperties.KinematicCharacterMotor.TransientPosition,
|
||||
Rotation = entityProperties.KinematicCharacterMotor.TransientRotation,
|
||||
AnimatorSnapshot = AnimatorSnapshot.GetSnapshot(entityProperties.animator),
|
||||
ControllerSnapshot = MovementControllerSnapshot.GetSnapshot(entityProperties.MovementController),
|
||||
HealthSnapshot = EntityHealthSnapshot.GetSnapshot(entityProperties.EntityHealth)
|
||||
Position = motor.TransientPosition,
|
||||
Rotation = motor.TransientRotation,
|
||||
BaseVelocity = motor.BaseVelocity,
|
||||
|
||||
IsFrozen = moveCtrl.Freeze,
|
||||
// Сохраните текущие входы контроллера (добавьте публичные геттеры в MovementController, если они приватные)
|
||||
MoveInputVector = moveCtrl.MoveInputVector,
|
||||
LookInputVector = moveCtrl.LookInputVector,
|
||||
|
||||
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
|
||||
AnimatorSnapshot = AnimatorSnapshot.GetSnapshot(entity.animator)
|
||||
};
|
||||
}
|
||||
|
||||
public static void RestoreSnapshot(EntityProperties entityProperties, EntitySnapshot snapshot)
|
||||
public static void RestoreSnapshot(EntityProperties entity, EntitySnapshot snapshot)
|
||||
{
|
||||
snapshot.HealthSnapshot.RestoreSnapshot(entityProperties.EntityHealth);
|
||||
|
||||
// 1. Возвращаем капсулу KCC
|
||||
entityProperties.KinematicCharacterMotor.SetPositionAndRotation(snapshot.Position, snapshot.Rotation);
|
||||
entityProperties.KinematicCharacterMotor.BaseVelocity = snapshot.BaseVelocity;
|
||||
|
||||
snapshot.ControllerSnapshot.RestoreSnapshot(entityProperties.MovementController);
|
||||
|
||||
// 2. Возвращаем позу и локальное смещение меша
|
||||
snapshot.AnimatorSnapshot.RestoreTo(entityProperties.animator);
|
||||
var motor = entity.KinematicCharacterMotor;
|
||||
var moveCtrl = entity.MovementController;
|
||||
|
||||
// 3. Синхронизируем физику
|
||||
// 1. Восстанавливаем MovementController ДО шага KCC
|
||||
moveCtrl.Freeze = snapshot.IsFrozen;
|
||||
var restoredInputs = new Code.Game.Gameplay.Player.AICharacterInputs
|
||||
{
|
||||
MoveVector = snapshot.MoveInputVector,
|
||||
Look = snapshot.LookInputVector.sqrMagnitude > 0.0001f
|
||||
? Quaternion.LookRotation(snapshot.LookInputVector, motor.CharacterUp)
|
||||
: snapshot.Rotation
|
||||
};
|
||||
moveCtrl.SetInputs(ref restoredInputs);
|
||||
|
||||
// 2. Восстанавливаем капсулу KCC (bypassInterpolation = true сбрасывает внутренние буферы перемещения)
|
||||
motor.SetPositionAndRotation(snapshot.Position, snapshot.Rotation, bypassInterpolation: true);
|
||||
motor.BaseVelocity = snapshot.BaseVelocity;
|
||||
|
||||
// 3. Восстанавливаем здоровье (без вызова анимаций смерти)
|
||||
if (entity.EntityHealth != null)
|
||||
{
|
||||
entity.EntityHealth.SetHealthData(snapshot.CurrentHealth);
|
||||
}
|
||||
|
||||
// 4. Восстанавливаем точную позу и фазу перехода Animator
|
||||
snapshot.AnimatorSnapshot.RestoreTo(entity.animator);
|
||||
|
||||
// 5. Мгновенно синхронизируем коллайдеры костей в PhysX
|
||||
Physics.SyncTransforms();
|
||||
}
|
||||
}
|
||||
@@ -51,15 +82,17 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public int FullPathHash;
|
||||
public float NormalizedTime;
|
||||
public float StateLength;
|
||||
public float LayerWeight;
|
||||
|
||||
// Данные на случай, если снапшот сделан посреди CrossFade-перехода:
|
||||
|
||||
public bool IsInTransition;
|
||||
public int NextFullPathHash;
|
||||
public float NextNormalizedTime;
|
||||
public float RemainingTransitionDuration; // в секундах
|
||||
public float NextStateLength;
|
||||
public float TotalTransitionDuration;
|
||||
public float ElapsedTransitionTime;
|
||||
}
|
||||
|
||||
|
||||
public struct ParameterSnapshot
|
||||
{
|
||||
public int NameHash;
|
||||
@@ -68,122 +101,106 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
public int IntValue;
|
||||
public bool BoolValue;
|
||||
}
|
||||
|
||||
|
||||
private LayerStateSnapshot[] _layers;
|
||||
private ParameterSnapshot[] _parameters;
|
||||
|
||||
private Vector3 _localPosition;
|
||||
private Quaternion _localRotation;
|
||||
private float _speed;
|
||||
|
||||
private bool _applyRootMotion;
|
||||
|
||||
public static AnimatorSnapshot GetSnapshot(Animator animator)
|
||||
{
|
||||
var snapshot = new AnimatorSnapshot();
|
||||
snapshot.CaptureFrom(animator);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
|
||||
public void CaptureFrom(Animator animator)
|
||||
{
|
||||
if (animator == null) return;
|
||||
|
||||
|
||||
Transform animTransform = animator.transform;
|
||||
_localPosition = animTransform.localPosition;
|
||||
_localRotation = animTransform.localRotation;
|
||||
_speed = animator.speed;
|
||||
|
||||
_applyRootMotion = animator.applyRootMotion;
|
||||
|
||||
int layerCount = animator.layerCount;
|
||||
if (_layers == null || _layers.Length != layerCount)
|
||||
_layers = new LayerStateSnapshot[layerCount];
|
||||
|
||||
_layers = new LayerStateSnapshot[layerCount];
|
||||
|
||||
for (int i = 0; i < layerCount; i++)
|
||||
{
|
||||
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(i);
|
||||
bool inTransition = animator.IsInTransition(i);
|
||||
|
||||
|
||||
var layerSnap = new LayerStateSnapshot
|
||||
{
|
||||
FullPathHash = stateInfo.fullPathHash,
|
||||
NormalizedTime = stateInfo.normalizedTime,
|
||||
StateLength = Mathf.Max(0.0001f, stateInfo.length),
|
||||
LayerWeight = animator.GetLayerWeight(i),
|
||||
IsInTransition = inTransition
|
||||
};
|
||||
|
||||
|
||||
if (inTransition)
|
||||
{
|
||||
AnimatorStateInfo nextInfo = animator.GetNextAnimatorStateInfo(i);
|
||||
AnimatorTransitionInfo transInfo = animator.GetAnimatorTransitionInfo(i);
|
||||
|
||||
layerSnap.NextFullPathHash = nextInfo.fullPathHash;
|
||||
layerSnap.NextNormalizedTime = nextInfo.normalizedTime;
|
||||
|
||||
// Вычисляем оставшееся время перехода в секундах:
|
||||
|
||||
float totalTransSeconds = transInfo.durationUnit == DurationUnit.Fixed
|
||||
? transInfo.duration
|
||||
: transInfo.duration * stateInfo.length;
|
||||
|
||||
layerSnap.RemainingTransitionDuration = Mathf.Max(0f, totalTransSeconds * (1f - transInfo.normalizedTime));
|
||||
|
||||
layerSnap.NextFullPathHash = nextInfo.fullPathHash;
|
||||
layerSnap.NextNormalizedTime = nextInfo.normalizedTime;
|
||||
layerSnap.NextStateLength = Mathf.Max(0.0001f, nextInfo.length);
|
||||
layerSnap.TotalTransitionDuration = totalTransSeconds;
|
||||
layerSnap.ElapsedTransitionTime = totalTransSeconds * transInfo.normalizedTime;
|
||||
}
|
||||
|
||||
|
||||
_layers[i] = layerSnap;
|
||||
}
|
||||
|
||||
|
||||
int paramCount = animator.parameterCount;
|
||||
if (_parameters == null || _parameters.Length != paramCount)
|
||||
_parameters = new ParameterSnapshot[paramCount];
|
||||
|
||||
_parameters = new ParameterSnapshot[paramCount];
|
||||
|
||||
for (int i = 0; i < paramCount; i++)
|
||||
{
|
||||
AnimatorControllerParameter param = animator.GetParameter(i);
|
||||
int hash = param.nameHash;
|
||||
var paramSnapshot = new ParameterSnapshot { NameHash = hash, Type = param.type };
|
||||
|
||||
var pSnap = new ParameterSnapshot { NameHash = hash, Type = param.type };
|
||||
|
||||
switch (param.type)
|
||||
{
|
||||
case AnimatorControllerParameterType.Float:
|
||||
paramSnapshot.FloatValue = animator.GetFloat(hash);
|
||||
break;
|
||||
case AnimatorControllerParameterType.Int:
|
||||
paramSnapshot.IntValue = animator.GetInteger(hash);
|
||||
break;
|
||||
case AnimatorControllerParameterType.Float: pSnap.FloatValue = animator.GetFloat(hash); break;
|
||||
case AnimatorControllerParameterType.Int: pSnap.IntValue = animator.GetInteger(hash); break;
|
||||
case AnimatorControllerParameterType.Bool:
|
||||
case AnimatorControllerParameterType.Trigger:
|
||||
paramSnapshot.BoolValue = animator.GetBool(hash);
|
||||
break;
|
||||
case AnimatorControllerParameterType.Trigger: pSnap.BoolValue = animator.GetBool(hash); break;
|
||||
}
|
||||
_parameters[i] = paramSnapshot;
|
||||
_parameters[i] = pSnap;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void RestoreTo(Animator targetAnimator)
|
||||
{
|
||||
if (targetAnimator == null || _layers == null) return;
|
||||
|
||||
targetAnimator.Rebind();
|
||||
|
||||
bool prevRootMotion = targetAnimator.applyRootMotion;
|
||||
|
||||
targetAnimator.applyRootMotion = false;
|
||||
targetAnimator.speed = _speed;
|
||||
|
||||
|
||||
if (_parameters != null)
|
||||
{
|
||||
for (int i = 0; i < _parameters.Length; i++)
|
||||
{
|
||||
var p = _parameters[i];
|
||||
if (targetAnimator.IsParameterControlledByCurve(p.NameHash))
|
||||
continue;
|
||||
|
||||
if (targetAnimator.IsParameterControlledByCurve(p.NameHash)) continue;
|
||||
|
||||
switch (p.Type)
|
||||
{
|
||||
case AnimatorControllerParameterType.Float:
|
||||
targetAnimator.SetFloat(p.NameHash, p.FloatValue);
|
||||
break;
|
||||
case AnimatorControllerParameterType.Int:
|
||||
targetAnimator.SetInteger(p.NameHash, p.IntValue);
|
||||
break;
|
||||
case AnimatorControllerParameterType.Bool:
|
||||
targetAnimator.SetBool(p.NameHash, p.BoolValue);
|
||||
break;
|
||||
case AnimatorControllerParameterType.Float: targetAnimator.SetFloat(p.NameHash, p.FloatValue); break;
|
||||
case AnimatorControllerParameterType.Int: targetAnimator.SetInteger(p.NameHash, p.IntValue); break;
|
||||
case AnimatorControllerParameterType.Bool: targetAnimator.SetBool(p.NameHash, p.BoolValue); break;
|
||||
case AnimatorControllerParameterType.Trigger:
|
||||
if (p.BoolValue) targetAnimator.SetTrigger(p.NameHash);
|
||||
else targetAnimator.ResetTrigger(p.NameHash);
|
||||
@@ -191,77 +208,46 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int layerCount = Mathf.Min(_layers.Length, targetAnimator.layerCount);
|
||||
for (int i = 0; i < layerCount; i++)
|
||||
{
|
||||
var layer = _layers[i];
|
||||
targetAnimator.SetLayerWeight(i, layer.LayerWeight);
|
||||
|
||||
// 1. Ставим исходный стейт
|
||||
targetAnimator.Play(layer.FullPathHash, i, layer.NormalizedTime);
|
||||
targetAnimator.Update(0f);
|
||||
|
||||
// 2. Если в момент снапшота шёл переход (например, в атаку) —
|
||||
// запускаем CrossFade в целевой стейт с того места, где он остановился!
|
||||
if (layer.IsInTransition && layer.NextFullPathHash != 0)
|
||||
|
||||
if (!layer.IsInTransition || layer.NextFullPathHash == 0)
|
||||
{
|
||||
targetAnimator.CrossFade(
|
||||
// CrossFadeInFixedTime с длительностью 0f гарантированно убивает любой старый переход без Rebind()!
|
||||
float timeInSeconds = layer.NormalizedTime * layer.StateLength;
|
||||
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, timeInSeconds);
|
||||
targetAnimator.Update(0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 1. Отматываем оба стейта к моменту начала перехода (минус ElapsedTransitionTime)
|
||||
float startSecondsA = (layer.NormalizedTime * layer.StateLength) - layer.ElapsedTransitionTime;
|
||||
float startSecondsB = (layer.NextNormalizedTime * layer.NextStateLength) - layer.ElapsedTransitionTime;
|
||||
|
||||
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, startSecondsA);
|
||||
targetAnimator.Update(0f);
|
||||
|
||||
// 2. Запускаем переход с оригинальной полной длительностью
|
||||
targetAnimator.CrossFadeInFixedTime(
|
||||
layer.NextFullPathHash,
|
||||
layer.RemainingTransitionDuration, // у CrossFadeInFixedTime offset в секундах, а у CrossFade с фиксированным временем проще через CrossFadeInFixedTime:
|
||||
layer.TotalTransitionDuration,
|
||||
i,
|
||||
layer.NextNormalizedTime);
|
||||
startSecondsB);
|
||||
|
||||
// 3. Прокручиваем аниматор ровно на ElapsedTransitionTime вперед (с выключенным RootMotion),
|
||||
// чтобы внутренний вес смешивания Mecanim встал ровно в ту же долю процента!
|
||||
targetAnimator.Update(layer.ElapsedTransitionTime);
|
||||
}
|
||||
}
|
||||
|
||||
targetAnimator.Update(0f);
|
||||
|
||||
|
||||
Transform targetTransform = targetAnimator.transform;
|
||||
targetTransform.localPosition = _localPosition;
|
||||
targetTransform.localRotation = _localRotation;
|
||||
|
||||
targetAnimator.applyRootMotion = prevRootMotion;
|
||||
}
|
||||
}
|
||||
|
||||
public struct MovementControllerSnapshot
|
||||
{
|
||||
public Vector3 Velocity;
|
||||
public Vector3 LookInput;
|
||||
public Vector3 MoveInput;
|
||||
|
||||
public static MovementControllerSnapshot GetSnapshot(MovementController movementController)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Velocity = movementController.InternalVelocityAdd,
|
||||
MoveInput = movementController.MoveInputVector,
|
||||
LookInput = movementController.LookInputVector
|
||||
};
|
||||
}
|
||||
public void RestoreSnapshot(MovementController movementController)
|
||||
{
|
||||
movementController.InternalVelocityAdd = Velocity;
|
||||
movementController.MoveInputVector = MoveInput;
|
||||
movementController.LookInputVector = LookInput;
|
||||
}
|
||||
}
|
||||
|
||||
public struct EntityHealthSnapshot
|
||||
{
|
||||
public HealthData HealthData;
|
||||
|
||||
public static EntityHealthSnapshot GetSnapshot(EntityHealth entityHealth)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
HealthData = entityHealth.HealthData.CurrentValue
|
||||
};
|
||||
}
|
||||
|
||||
public void RestoreSnapshot(EntityHealth entityHealth)
|
||||
{
|
||||
entityHealth.SetHealthData(HealthData);
|
||||
targetAnimator.applyRootMotion = _applyRootMotion;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Threading;
|
||||
using Code.Infrastructure.Camera;
|
||||
using Code.Infrastructure.UI;
|
||||
using Code.OfficeGame.BattleMode.Timeline;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using R3;
|
||||
using Reflex.Attributes;
|
||||
@@ -14,6 +15,7 @@ namespace Code.OfficeGame.BattleMode.Health.UI
|
||||
{
|
||||
[SerializeField] private TMP_Text healthText;
|
||||
[SerializeField] private Image healthBar;
|
||||
[SerializeField] private Image silentHealthBar;
|
||||
|
||||
[SerializeField] private Color criticalColor;
|
||||
[SerializeField] private Color fullColor;
|
||||
@@ -55,23 +57,36 @@ namespace Code.OfficeGame.BattleMode.Health.UI
|
||||
entityHealth.HealthData
|
||||
.Subscribe(SetHealthStatus)
|
||||
.AddTo(ref _healthSubscriptions);
|
||||
|
||||
_previousHealthData = entityHealth.HealthData.CurrentValue;
|
||||
}
|
||||
|
||||
private HealthData _previousHealthData;
|
||||
|
||||
private void SetHealthStatus(HealthData healthData)
|
||||
{
|
||||
if (healthData.CurrentHealth <= 0)
|
||||
{
|
||||
healthText.color = deadColor;
|
||||
healthText.SetText("Dead");
|
||||
healthBar.fillAmount = 1;
|
||||
|
||||
if(BattleTimeline.IsSilentSimulation)
|
||||
silentHealthBar.fillAmount = 1;
|
||||
else healthBar.fillAmount = 1;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
float healthPercentage = (float)healthData.CurrentHealth / healthData.MaxHealth;
|
||||
|
||||
healthBar.fillAmount = healthPercentage;
|
||||
|
||||
|
||||
if(BattleTimeline.IsSilentSimulation)
|
||||
if(_previousHealthData.CurrentHealth != healthData.CurrentHealth) silentHealthBar.fillAmount = healthPercentage;
|
||||
else silentHealthBar.fillAmount = 0;
|
||||
else
|
||||
{
|
||||
healthBar.fillAmount = healthPercentage;
|
||||
_previousHealthData = healthData;
|
||||
}
|
||||
// SB
|
||||
|
||||
healthText.SetText($"{healthData.CurrentHealth}/{healthData.MaxHealth}");
|
||||
|
||||
@@ -27,7 +27,8 @@ namespace Code.OfficeGame.BattleMode.HitBoxes
|
||||
BoxCollider box = bodyParts[hitBoxPartType];
|
||||
Transform boxTransform = box.transform;
|
||||
|
||||
HitboxDrawer.DrawBox(box, Color.red, BattleTimeline.TickDelta);
|
||||
// TODO А ещё можно нарисовать все эти коллайдеры во время тихих рассчётов разной прозрачностью и по мере продвижения таймлайна увеличивать альфу для ближайшего коллайдера
|
||||
if(!BattleTimeline.IsSilentSimulation) HitboxDrawer.DrawBox(box, Color.red, BattleTimeline.TickDelta / Mathf.Max(0.01f, BattleTimeline.PlaybackSpeed));
|
||||
|
||||
Vector3 worldCenter = boxTransform.TransformPoint(box.center);
|
||||
Vector3 worldHalfExtents = Vector3.Scale(box.size * 0.5f, boxTransform.lossyScale);
|
||||
|
||||
@@ -22,6 +22,9 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
{
|
||||
public const int TicksPerSecond = 60;
|
||||
public const float TickDelta = 1f / TicksPerSecond;
|
||||
public static bool IsSilentSimulation { get; private set; }
|
||||
|
||||
public static float PlaybackSpeed { get; set; } = 1f;
|
||||
|
||||
private readonly ReactiveProperty<int> _currentBattleFrame = new(0);
|
||||
public ReadOnlyReactiveProperty<int> CurrentBattleFrame => _currentBattleFrame;
|
||||
@@ -38,15 +41,18 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
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();
|
||||
|
||||
|
||||
public BattleTimeline(
|
||||
BattleTimelinePanel timelinePanel,
|
||||
IEnumerable<BattleAction> battleActions,
|
||||
@@ -73,6 +79,14 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
public async UniTask RunBattleLoopAsync(List<EntityProperties> entities, CancellationToken ctx)
|
||||
{
|
||||
_entities = entities.ToDictionary(x => x.GetEntityId());
|
||||
|
||||
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;
|
||||
|
||||
_battleSubscriptions = new DisposableBag();
|
||||
@@ -106,7 +120,7 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
{
|
||||
await UniTask.Yield(PlayerLoopTiming.Update, ctx);
|
||||
|
||||
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f);
|
||||
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
|
||||
|
||||
while (accumulator >= TickDelta)
|
||||
{
|
||||
@@ -141,6 +155,7 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
}
|
||||
|
||||
// TODO ЗАПУСКАТЬ ДВА ЦИКЛА ПОЛНЫЙ И ДО ПРЕРЫВАНИЯ
|
||||
|
||||
private async UniTask PreviewBattleLoopAsync(int frameCount,
|
||||
Dictionary<EntityId, EntityProperties> entities,
|
||||
CancellationToken ctx)
|
||||
@@ -183,6 +198,7 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
_preview.Release(1);
|
||||
}
|
||||
}
|
||||
|
||||
private async UniTask PreviewBattleLoopAsync(EntityId entityId,
|
||||
Dictionary<EntityId, EntityProperties> entities,
|
||||
CancellationToken ctx)
|
||||
@@ -230,7 +246,7 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
bool isCanceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
|
||||
if (isCanceled) break;
|
||||
|
||||
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f);
|
||||
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
|
||||
|
||||
while (accumulator >= TickDelta && counter > 0 && !ctx.IsCancellationRequested)
|
||||
{
|
||||
@@ -261,6 +277,7 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async UniTask PlayTimelineUntilThatSpecific(EntityId specificEntityId, CancellationToken ctx)
|
||||
{
|
||||
float accumulator = 0f;
|
||||
@@ -270,7 +287,7 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
bool isCanceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
|
||||
if (isCanceled) break;
|
||||
|
||||
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f);
|
||||
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
|
||||
|
||||
while (accumulator >= TickDelta && !ctx.IsCancellationRequested)
|
||||
{
|
||||
@@ -300,6 +317,39 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
}
|
||||
}
|
||||
|
||||
public List<EntityAttackedData> PredictSilently(int lookaheadFrames)
|
||||
{
|
||||
// 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;
|
||||
}
|
||||
|
||||
private EntityId[] SimulateSingleFrame(Dictionary<EntityId, EntityProperties> inEntities)
|
||||
{
|
||||
foreach (var (entityId, entity) in inEntities)
|
||||
@@ -446,6 +496,8 @@ namespace Code.OfficeGame.BattleMode.Timeline
|
||||
|
||||
await _preview.WaitAsync(previewCancellationToken.Token);
|
||||
|
||||
PredictSilently(actionData.TotalFrames);
|
||||
|
||||
PreviewBattleLoopAsync(entityId, _entities, previewCancellationToken.Token)
|
||||
.Forget();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user