Great timeline system (Age of AI WON)
This commit is contained in:
1 parent
2ce0391c16
commit
e312131725
182 files changed
+380070
-470221
No files matched your search
@@ -23,15 +23,5 @@ namespace Code.Game.Entities
|
||||
motor.SetPositionAndRotation(targetWorldPos, targetWorldRot);
|
||||
motor.BaseVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
public static EntitySnapshot GetSnapshot(this EntityProperties entityProperties)
|
||||
{
|
||||
return EntitySnapshot.GetSnapshot(entityProperties);
|
||||
}
|
||||
|
||||
public static void RestoreSnapshot(this EntityProperties entityProperties, EntitySnapshot snapshot)
|
||||
{
|
||||
EntitySnapshot.RestoreSnapshot(entityProperties, snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5ee879ec01aa444299cfdf84914718d3
|
||||
timeCreated: 1793383803
|
||||
guid: 5ee879ec01aa444299cfdf84914718d3
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Actions
|
||||
@@ -6,18 +7,20 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public int CurrentFrame;
|
||||
public int TransitionFrames;
|
||||
public Quaternion StartRotation;
|
||||
public HashSet<EntityId> HitEntities = new();
|
||||
|
||||
public override BattleActionData GetSnapshot()
|
||||
{
|
||||
var snapshot = new AttackBattleActionData()
|
||||
return new AttackBattleActionData
|
||||
{
|
||||
TotalFrames = TotalFrames,
|
||||
Finished = Finished,
|
||||
CurrentFrame = CurrentFrame,
|
||||
TransitionFrames = TransitionFrames,
|
||||
StartRotation = StartRotation,
|
||||
HitEntities = new HashSet<EntityId>(HitEntities)
|
||||
};
|
||||
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public override void RestoreSnapshot(BattleActionData snapshot)
|
||||
@@ -28,6 +31,8 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
Finished = neededSnapshot.Finished;
|
||||
CurrentFrame = neededSnapshot.CurrentFrame;
|
||||
TransitionFrames = neededSnapshot.TransitionFrames;
|
||||
StartRotation = neededSnapshot.StartRotation;
|
||||
HitEntities = new HashSet<EntityId>(neededSnapshot.HitEntities);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Linq;
|
||||
using Code.Game.Entities;
|
||||
using Code.Infrastructure.Particles;
|
||||
using Code.Infrastructure.Utils;
|
||||
using Code.OfficeGame.BattleMode.Actions.Deciders;
|
||||
using Code.OfficeGame.BattleMode.HitBoxes;
|
||||
@@ -11,21 +10,29 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
|
||||
{
|
||||
public class BattleActionPlayerAttackMMA : BattleAction
|
||||
{
|
||||
private AttackActionConfig _attackData;
|
||||
private IParticleService _particleService;
|
||||
public int EntryStateHash => Animator.StringToHash("WalkBlend");
|
||||
private readonly AttackActionConfig _attackData;
|
||||
private static readonly int EntryStateHash = Animator.StringToHash("WalkBlend");
|
||||
|
||||
public BattleActionPlayerAttackMMA(MultipleConfig<BattleActionParameters> attackData,
|
||||
IParticleService particleService)
|
||||
public BattleActionPlayerAttackMMA(MultipleConfig<BattleActionParameters> attackData)
|
||||
{
|
||||
_particleService = particleService;
|
||||
_attackData = (AttackActionConfig)
|
||||
attackData.Configs.SingleOrDefault(x => x.ActionType == ActionType);
|
||||
_attackData = (AttackActionConfig)attackData.Configs.SingleOrDefault(x => x.ActionType == ActionType);
|
||||
}
|
||||
|
||||
public override BattleActionType ActionType => BattleActionType.PlayerAttackMMA;
|
||||
public override DeciderType DeciderType => DeciderType.Rotation;
|
||||
|
||||
public override void Tick(float tickDelta,
|
||||
public override BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result)
|
||||
{
|
||||
return new AttackBattleActionData
|
||||
{
|
||||
TotalFrames = _attackData.TotalFrames,
|
||||
TransitionFrames = _attackData.TransitionFrames,
|
||||
StartRotation = entity.KinematicCharacterMotor.TransientRotation
|
||||
};
|
||||
}
|
||||
|
||||
public override void Tick(
|
||||
float tickDelta,
|
||||
EntityProperties entity,
|
||||
BattleActionDecisionResult battleActionDecisionResult,
|
||||
BattleActionData battleActionData)
|
||||
@@ -41,42 +48,50 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
|
||||
{
|
||||
actionData.TransitionFrames = _attackData.TransitionFrames;
|
||||
actionData.TotalFrames = _attackData.TotalFrames;
|
||||
|
||||
actionData.StartRotation = entity.KinematicCharacterMotor.TransientRotation;
|
||||
actionData.HitEntities.Clear();
|
||||
|
||||
entity.SyncRootMotionToMotor();
|
||||
|
||||
var entityAnimator = entity.animator;
|
||||
entityAnimator.applyRootMotion = true;
|
||||
|
||||
var transitionTime = actionData.TransitionFrames * BattleTimeline.TickDelta;
|
||||
entityAnimator.CrossFadeInFixedTime(_attackData.StateHash, transitionTime);
|
||||
entityAnimator.CrossFadeInFixedTime(_attackData.StateHash, actionData.TransitionFrames * BattleTimeline.TickDelta);
|
||||
}
|
||||
else if (actionData.CurrentFrame <= actionData.TransitionFrames
|
||||
&& actionData.TransitionFrames > 0)
|
||||
else if (actionData.CurrentFrame <= actionData.TransitionFrames && actionData.TransitionFrames > 0)
|
||||
{
|
||||
float t = (float)actionData.CurrentFrame / actionData.TransitionFrames;
|
||||
Quaternion transientRotation = Quaternion.Lerp(
|
||||
entity.KinematicCharacterMotor.TransientRotation,
|
||||
deciderResult.Rotation,
|
||||
t);
|
||||
|
||||
entity.KinematicCharacterMotor.SetRotation(transientRotation);
|
||||
Quaternion rot = Quaternion.Slerp(actionData.StartRotation, deciderResult.Rotation, t);
|
||||
entity.KinematicCharacterMotor.SetRotation(rot);
|
||||
}
|
||||
|
||||
actionData.CurrentFrame++;
|
||||
}
|
||||
|
||||
public override void PostPhysicsTick(
|
||||
EntityProperties entity,
|
||||
BattleActionDecisionResult battleActionDecisionResult,
|
||||
BattleActionData battleActionData)
|
||||
{
|
||||
if (battleActionData is not AttackBattleActionData actionData) return;
|
||||
|
||||
if (actionData.CurrentFrame >= _attackData.HitboxStartFrame
|
||||
&& actionData.CurrentFrame <= _attackData.HitboxEndFrame)
|
||||
{
|
||||
entity.EntityHitBoxes.CheckHitsForCurrentFrame(OnEnemyHit, _attackData.AttackingBodyPart);
|
||||
entity.EntityHitBoxes.CheckHitsForCurrentFrame(OnEnemyHit, HitBoxPartType.RAnkle);
|
||||
entity.EntityHitBoxes.CheckHitsForCurrentFrame(
|
||||
SimContext,
|
||||
(attackerCol, enemyCol, hitPart) => OnEnemyHit(actionData, attackerCol, enemyCol, hitPart),
|
||||
_attackData.AttackingBodyPart);
|
||||
|
||||
entity.EntityHitBoxes.CheckHitsForCurrentFrame(
|
||||
SimContext,
|
||||
(attackerCol, enemyCol, hitPart) => OnEnemyHit(actionData, attackerCol, enemyCol, hitPart),
|
||||
HitBoxPartType.RAnkle);
|
||||
}
|
||||
|
||||
if (actionData.CurrentFrame >= actionData.TotalFrames)
|
||||
{
|
||||
var entityAnimator = entity.animator;
|
||||
|
||||
entity.SyncRootMotionToMotor();
|
||||
|
||||
entityAnimator.applyRootMotion = false;
|
||||
entityAnimator.Play(EntryStateHash, 0, 0f);
|
||||
entityAnimator.Update(0f);
|
||||
|
||||
@@ -84,59 +99,55 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
|
||||
}
|
||||
}
|
||||
|
||||
public override DeciderType DeciderType => DeciderType.Rotation;
|
||||
|
||||
public override BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result)
|
||||
{
|
||||
return new AttackBattleActionData() { TotalFrames = _attackData.TotalFrames };
|
||||
}
|
||||
|
||||
public override void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result)
|
||||
{
|
||||
// var entityAnimator = entity.animator;
|
||||
//
|
||||
// entity.SyncRootMotionToMotor();
|
||||
//
|
||||
// entityAnimator.Play(EntryStateHash, 0, 0f);
|
||||
// entityAnimator.Update(0f);
|
||||
entity.animator.applyRootMotion = false;
|
||||
}
|
||||
|
||||
private void OnEnemyHit(Collider attacker, Collider enemyCollider)
|
||||
{
|
||||
var defenderId = enemyCollider.GetComponentInParent<EntityProperties>().GetEntityId();
|
||||
var attackerId = attacker.GetComponentInParent<EntityProperties>().GetEntityId();
|
||||
|
||||
Vector3 attackerDirection = attacker.transform.TransformDirection(_attackData.LocalKnockbackDirection);
|
||||
attackerDirection.y = 0f;
|
||||
attackerDirection.Normalize();
|
||||
|
||||
var actionData = new StuggerActionData
|
||||
private void OnEnemyHit(
|
||||
AttackBattleActionData attackData,
|
||||
Collider attacker,
|
||||
Collider enemyCollider,
|
||||
HitBoxPartType hitPart)
|
||||
{
|
||||
var defenderProps = enemyCollider.GetComponentInParent<EntityProperties>();
|
||||
var attackerProps = attacker.GetComponentInParent<EntityProperties>();
|
||||
if (defenderProps == null || attackerProps == null) return;
|
||||
|
||||
var defenderId = defenderProps.GetEntityId();
|
||||
var attackerId = attackerProps.GetEntityId();
|
||||
|
||||
// Защита от многокадрового урона по одной цели за один удар
|
||||
if (!attackData.HitEntities.Add(defenderId)) return;
|
||||
|
||||
Vector3 knockbackDir = attackerProps.KinematicCharacterMotor.Transform
|
||||
.TransformDirection(_attackData.LocalKnockbackDirection);
|
||||
knockbackDir.y = 0f;
|
||||
if (knockbackDir.sqrMagnitude > 0.0001f) knockbackDir.Normalize();
|
||||
|
||||
var forcedActionData = new StuggerActionData
|
||||
{
|
||||
TotalFrames = _attackData.StuggerFrames,
|
||||
CurrentFrame = 0,
|
||||
KnockbackDirection = attackerDirection,
|
||||
KnockbackDirection = knockbackDir,
|
||||
KnockbackSpeed = _attackData.KnockbackSpeed,
|
||||
KnockbackDistance = _attackData.KnockbackDistance
|
||||
};
|
||||
var decisionResult = new AsIsBattleActionDeciderResult { ActionType = BattleActionType.Stugger };
|
||||
|
||||
EntityAttackedData attackedData = new()
|
||||
var forcedDecision = new AsIsBattleActionDeciderResult
|
||||
{
|
||||
ForcedActionData = actionData,
|
||||
ForcedDecisionResult = decisionResult,
|
||||
ActionType = BattleActionType.Stugger,
|
||||
ResultCode = BattleActionDecisionResultCode.Decided
|
||||
};
|
||||
|
||||
var attackedData = new EntityAttackedData
|
||||
{
|
||||
ForcedActionData = forcedActionData,
|
||||
ForcedDecisionResult = forcedDecision,
|
||||
Damage = _attackData.Damage
|
||||
};
|
||||
|
||||
battleTimeline.AttackRequest(attackerId, defenderId, attackedData);
|
||||
|
||||
//battleTimeline.ForceDecideAction(originEntityId, actionData, decisionResult);
|
||||
|
||||
if(!BattleTimeline.IsSilentSimulation)
|
||||
_particleService.EmitOneShot(
|
||||
new ParticlePartitionIDPair(ParticlePartition.HitParticles, 0),
|
||||
15,
|
||||
enemyCollider.transform.position,
|
||||
Quaternion.identity);
|
||||
SimContext.SubmitAttack(attackerId, defenderId, hitPart, enemyCollider.transform.position, attackedData);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,21 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public abstract class BattleAction
|
||||
{
|
||||
public abstract void Tick(float tickDelta, EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult, BattleActionData battleActionData);
|
||||
public abstract BattleActionType ActionType { get; }
|
||||
public abstract DeciderType DeciderType { get; }
|
||||
public abstract BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result);
|
||||
public abstract void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result);
|
||||
|
||||
protected BattleTimeline battleTimeline;
|
||||
public void SetBattleTimeline(BattleTimeline battleTimeline) => this.battleTimeline = battleTimeline;
|
||||
protected IBattleSimulationContext SimContext { get; private set; }
|
||||
public void SetSimulationContext(IBattleSimulationContext context) => SimContext = context;
|
||||
|
||||
public abstract BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result);
|
||||
public abstract void Tick(float tickDelta, EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult, BattleActionData battleActionData);
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается ПОСЛЕ KCC.Simulate, Animator.Update и Physics.SyncTransforms.
|
||||
/// Здесь проверяются хитбоксы и достижение целевой позиции.
|
||||
/// </summary>
|
||||
public virtual void PostPhysicsTick(EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult, BattleActionData battleActionData) { }
|
||||
|
||||
public abstract void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result);
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,14 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
private const float StoppingDistance = 0.15f;
|
||||
private const float RotateDistance = 1f;
|
||||
private const float NavMeshSampleRadius = 1.5f;
|
||||
private const float TurnSpeedDegPerSec = 720f;
|
||||
private const float TurnSpeedDegPerSec = 720f;
|
||||
private const int StuckExtraFrames = 90;
|
||||
|
||||
private int MoveStateHash => Animator.StringToHash("WalkBlend");
|
||||
private static readonly int MoveStateHash = Animator.StringToHash("WalkBlend");
|
||||
|
||||
public override BattleActionType ActionType => BattleActionType.Move;
|
||||
public override DeciderType DeciderType => DeciderType.Position;
|
||||
|
||||
// Ультра супер мега конструкция для проверки и утверждения точной позиции. Но не работающая.
|
||||
public override BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result)
|
||||
{
|
||||
MovementBattleActionData data = new();
|
||||
@@ -29,21 +29,17 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
|
||||
Vector3 toTargetXZ = targetPos - startPos;
|
||||
toTargetXZ.y = 0f;
|
||||
|
||||
Debug.DrawLine(startPos, targetPos, Color.red, 5f);
|
||||
|
||||
float distanceXZ = toTargetXZ.magnitude;
|
||||
|
||||
if (distanceXZ <= StoppingDistance)
|
||||
if (toTargetXZ.magnitude <= StoppingDistance)
|
||||
{
|
||||
data.IsRotateOnly = true;
|
||||
data.Corners = null;
|
||||
|
||||
float angle = Quaternion.Angle(entity.KinematicCharacterMotor.TransientRotation, positionDecisionResult.Rotation);
|
||||
|
||||
if (angle < 1f)
|
||||
{
|
||||
data.TotalFrames = 0;
|
||||
data.Finished = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -60,6 +56,7 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
if (!hasStart || !hasTarget)
|
||||
{
|
||||
data.TotalFrames = 0;
|
||||
data.Finished = true;
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -71,13 +68,12 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
data.Corners = new[] { startPos, validTarget };
|
||||
data.CurrentCornerIndex = 1;
|
||||
data.TotalFrames = CalculatePathFrames(data.Corners, entity.MovementController);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
NavMeshPath path = new();
|
||||
if (NavMesh.CalculatePath(validStart, validTarget, NavMesh.AllAreas, path)
|
||||
&& path.status == NavMeshPathStatus.PathComplete
|
||||
if (NavMesh.CalculatePath(validStart, validTarget, NavMesh.AllAreas, path)
|
||||
&& path.status == NavMeshPathStatus.PathComplete
|
||||
&& path.corners.Length > 1)
|
||||
{
|
||||
path.corners[0] = startPos;
|
||||
@@ -90,43 +86,31 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
else
|
||||
{
|
||||
data.TotalFrames = 0;
|
||||
data.Finished = true;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public override void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result)
|
||||
{
|
||||
entity.KinematicCharacterMotor.BaseVelocity = Vector3.zero;
|
||||
|
||||
entity.MovementController.Freeze = true;
|
||||
entity.MovementController.InternalVelocityAdd = Vector3.zero;
|
||||
entity.MovementController.MoveInputVector = Vector3.zero;
|
||||
|
||||
Debug.Log($"{entity.GetEntityId()} is frozen");
|
||||
}
|
||||
|
||||
public override void Tick(
|
||||
float tickDelta,
|
||||
EntityProperties entity,
|
||||
BattleActionDecisionResult battleActionDecisionResult,
|
||||
float tickDelta,
|
||||
EntityProperties entity,
|
||||
BattleActionDecisionResult battleActionDecisionResult,
|
||||
BattleActionData battleActionData)
|
||||
{
|
||||
if (battleActionData is not MovementBattleActionData movementActionData
|
||||
|| battleActionDecisionResult is not PositionBattleActionDeciderResult positionDecisionResult)
|
||||
if (battleActionData is not MovementBattleActionData movementActionData
|
||||
|| battleActionDecisionResult is not PositionBattleActionDeciderResult positionDecisionResult)
|
||||
{
|
||||
battleActionData.Finished = true;
|
||||
return;
|
||||
}
|
||||
|
||||
var movementController = entity.MovementController;
|
||||
|
||||
movementController.Freeze = false;
|
||||
|
||||
movementActionData.CurrentFrame++;
|
||||
|
||||
if (movementActionData.IsRotateOnly)
|
||||
{
|
||||
movementActionData.CurrentFrame++;
|
||||
|
||||
float angle = Quaternion.Angle(movementController.Motor.TransientRotation, positionDecisionResult.Rotation);
|
||||
int framesLeft = Mathf.Max(1, movementActionData.TotalFrames - movementActionData.CurrentFrame + 1);
|
||||
float stepAngle = angle / framesLeft;
|
||||
@@ -134,11 +118,10 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
Quaternion nextRot = Quaternion.RotateTowards(
|
||||
movementController.Motor.TransientRotation,
|
||||
positionDecisionResult.Rotation,
|
||||
stepAngle
|
||||
);
|
||||
stepAngle);
|
||||
|
||||
entity.KinematicCharacterMotor.SetRotation(nextRot);
|
||||
StopMovementAndFinish(movementController);
|
||||
StopMovementInputs(movementController);
|
||||
|
||||
if (movementActionData.CurrentFrame >= movementActionData.TotalFrames || angle <= 0.5f)
|
||||
{
|
||||
@@ -152,7 +135,7 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
if (movementActionData.Corners == null || movementActionData.CurrentCornerIndex >= movementActionData.Corners.Length)
|
||||
{
|
||||
entity.KinematicCharacterMotor.SetRotation(positionDecisionResult.Rotation);
|
||||
StopMovementAndFinish(movementController);
|
||||
StopMovementInputs(movementController);
|
||||
battleActionData.Finished = true;
|
||||
return;
|
||||
}
|
||||
@@ -160,28 +143,17 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
if (!movementActionData.WasStarted)
|
||||
{
|
||||
movementActionData.WasStarted = true;
|
||||
float transitionDurationSeconds = 10 * BattleTimeline.TickDelta;
|
||||
entity.animator.CrossFadeInFixedTime(MoveStateHash, transitionDurationSeconds);
|
||||
entity.animator.applyRootMotion = false;
|
||||
entity.animator.CrossFadeInFixedTime(MoveStateHash, 10 * BattleTimeline.TickDelta);
|
||||
}
|
||||
|
||||
Vector3 currentPos = entity.KinematicCharacterMotor.TransientPosition;
|
||||
|
||||
while (movementActionData.CurrentCornerIndex < movementActionData.Corners.Length)
|
||||
{
|
||||
Vector3 toCorner = movementActionData.Corners[movementActionData.CurrentCornerIndex] - currentPos;
|
||||
toCorner.y = 0f;
|
||||
|
||||
if (toCorner.sqrMagnitude <= StoppingDistance * StoppingDistance)
|
||||
movementActionData.CurrentCornerIndex++;
|
||||
else
|
||||
break;
|
||||
}
|
||||
AdvanceCorners(movementActionData, currentPos);
|
||||
|
||||
if (movementActionData.CurrentCornerIndex >= movementActionData.Corners.Length)
|
||||
{
|
||||
entity.KinematicCharacterMotor.SetRotation(positionDecisionResult.Rotation);
|
||||
StopMovementAndFinish(movementController);
|
||||
|
||||
StopMovementInputs(movementController);
|
||||
battleActionData.Finished = true;
|
||||
return;
|
||||
}
|
||||
@@ -197,7 +169,6 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
bool preLastPoint = isLastCorner && distance < RotateDistance;
|
||||
|
||||
float maxStep = movementController.MaxStableMoveSpeed * tickDelta;
|
||||
|
||||
float inputMagnitude = (isLastCorner && distance < maxStep && maxStep > 0f)
|
||||
? distance / maxStep
|
||||
: 1f;
|
||||
@@ -213,22 +184,62 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
MoveVector = moveNormal * inputMagnitude,
|
||||
Look = lookRotation
|
||||
};
|
||||
|
||||
movementController.SetInputs(ref aiInputs);
|
||||
}
|
||||
|
||||
public override void PostPhysicsTick(
|
||||
EntityProperties entity,
|
||||
BattleActionDecisionResult battleActionDecisionResult,
|
||||
BattleActionData battleActionData)
|
||||
{
|
||||
if (battleActionData.Finished
|
||||
|| battleActionData is not MovementBattleActionData movementActionData
|
||||
|| battleActionDecisionResult is not PositionBattleActionDeciderResult positionDecisionResult
|
||||
|| movementActionData.IsRotateOnly
|
||||
|| movementActionData.Corners == null)
|
||||
return;
|
||||
|
||||
Vector3 postMovePos = entity.KinematicCharacterMotor.TransientPosition;
|
||||
AdvanceCorners(movementActionData, postMovePos);
|
||||
|
||||
Vector3 postMovePos = movementController.Motor.TransientPosition;
|
||||
Vector3 toFinal = movementActionData.Corners[^1] - postMovePos;
|
||||
toFinal.y = 0f;
|
||||
|
||||
if (isLastCorner && toFinal.sqrMagnitude <= StoppingDistance * StoppingDistance)
|
||||
bool arrived = movementActionData.CurrentCornerIndex >= movementActionData.Corners.Length
|
||||
|| toFinal.sqrMagnitude <= StoppingDistance * StoppingDistance;
|
||||
bool stuckTimeout = movementActionData.CurrentFrame > movementActionData.TotalFrames + StuckExtraFrames;
|
||||
|
||||
if (arrived || stuckTimeout)
|
||||
{
|
||||
entity.KinematicCharacterMotor.SetRotation(positionDecisionResult.Rotation);
|
||||
StopMovementAndFinish(movementController);
|
||||
StopMovementInputs(entity.MovementController);
|
||||
battleActionData.Finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void StopMovementAndFinish(MovementController movementController)
|
||||
public override void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result)
|
||||
{
|
||||
entity.KinematicCharacterMotor.BaseVelocity = Vector3.zero;
|
||||
entity.MovementController.Freeze = true;
|
||||
entity.MovementController.InternalVelocityAdd = Vector3.zero;
|
||||
entity.MovementController.MoveInputVector = Vector3.zero;
|
||||
}
|
||||
|
||||
private static void AdvanceCorners(MovementBattleActionData data, Vector3 pos)
|
||||
{
|
||||
while (data.CurrentCornerIndex < data.Corners.Length)
|
||||
{
|
||||
Vector3 toCorner = data.Corners[data.CurrentCornerIndex] - pos;
|
||||
toCorner.y = 0f;
|
||||
|
||||
if (toCorner.sqrMagnitude <= StoppingDistance * StoppingDistance)
|
||||
data.CurrentCornerIndex++;
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void StopMovementInputs(MovementController movementController)
|
||||
{
|
||||
var emptyInputs = new AICharacterInputs
|
||||
{
|
||||
@@ -239,13 +250,11 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
movementController.Motor.BaseVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
private int CalculatePathFrames(Vector3[] corners, MovementController movementController)
|
||||
private static int CalculatePathFrames(Vector3[] corners, MovementController movementController)
|
||||
{
|
||||
if (corners == null || corners.Length < 2)
|
||||
return 0;
|
||||
if (corners == null || corners.Length < 2) return 0;
|
||||
|
||||
float totalDistanceXZ = 0f;
|
||||
|
||||
for (int i = 1; i < corners.Length; i++)
|
||||
{
|
||||
Vector3 segment = corners[i] - corners[i - 1];
|
||||
@@ -256,10 +265,7 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
float effectiveDistance = Mathf.Max(0f, totalDistanceXZ - StoppingDistance);
|
||||
float stepPerFrame = movementController.MaxStableMoveSpeed * BattleTimeline.TickDelta;
|
||||
|
||||
if (stepPerFrame <= 0.0001f)
|
||||
return 0;
|
||||
|
||||
return Mathf.Max(1, Mathf.CeilToInt(effectiveDistance / stepPerFrame));
|
||||
return stepPerFrame <= 0.0001f ? 0 : Mathf.Max(1, Mathf.CeilToInt(effectiveDistance / stepPerFrame));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using Code.OfficeGame.BattleMode.Actions.Player;
|
||||
using Code.OfficeGame.BattleMode.Marker;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Actions.Deciders
|
||||
@@ -167,6 +168,10 @@ namespace Code.OfficeGame.BattleMode.Actions.Deciders
|
||||
|
||||
private void SelectPosition(InputAction.CallbackContext input)
|
||||
{
|
||||
// Эта херовина не позволит кликнуть, когда курсор на UI. Случай пока невозможный, но сделаем допущение
|
||||
if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject())
|
||||
return;
|
||||
|
||||
_targetPosition = _lastViewedPosition;
|
||||
|
||||
_playerLockedDecisionMarker.MoveMarker(_targetPosition);
|
||||
|
||||
@@ -6,6 +6,7 @@ using Code.OfficeGame.BattleMode.Actions.Player;
|
||||
using Code.OfficeGame.BattleMode.Marker;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Actions.Deciders
|
||||
@@ -151,6 +152,10 @@ namespace Code.OfficeGame.BattleMode.Actions.Deciders
|
||||
|
||||
private void SelectRotation(InputAction.CallbackContext input)
|
||||
{
|
||||
// Эта херовина не позволит кликнуть, когда курсор на UI. Случай пока невозможный, но сделаем допущение
|
||||
if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject())
|
||||
return;
|
||||
|
||||
_playerLockedDecisionMarker.MoveMarker(_entityPosition);
|
||||
_playerLockedDecisionMarker.transform.rotation = _targetRotation;
|
||||
_playerLockedDecisionMarker.Toggle(true);
|
||||
|
||||
@@ -5,178 +5,239 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public class EntityPreviewVisuals : MonoBehaviour
|
||||
{
|
||||
[Header("Материалы для MKToon")]
|
||||
[Tooltip("Полупрозрачный материал для статичного слепка в точке снапшота")]
|
||||
[SerializeField]
|
||||
private Material snapshotGhostMaterial;
|
||||
public const int MaxGhostStages = 5; // 0 = Commit + до 4 прерываний
|
||||
|
||||
[Tooltip(
|
||||
"Опционально: материал для самой движущейся модели во время превью (если null — меняется только Rim/Tint)")]
|
||||
[SerializeField]
|
||||
private Material activePreviewMaterial;
|
||||
[Header("Материалы MKToon")]
|
||||
[SerializeField] private Material snapshotGhostMaterial;
|
||||
[SerializeField] private Material activePreviewMaterial;
|
||||
|
||||
[Header("Настройки подсветки MKToon (если activePreviewMaterial не задан)")] [SerializeField]
|
||||
private Color previewAlbedoTint = new Color(0.6f, 0.85f, 1f, 1f);
|
||||
[Header("Цвета проекции по стадиям прерываний")]
|
||||
[SerializeField] private Color[] stageProjectionTints =
|
||||
{
|
||||
new(0.55f, 0.85f, 1.0f, 1f), // Stage 0: до первого прерывания (голубой)
|
||||
new(1.0f, 0.85f, 0.35f, 1f), // Stage 1: после 1-го прерывания (жёлтый)
|
||||
new(1.0f, 0.55f, 0.25f, 1f), // Stage 2: после 2-го прерывания (оранжевый)
|
||||
new(0.95f, 0.3f, 0.5f, 1f), // Stage 3+: 3+ прерываний (малиновый)
|
||||
};
|
||||
|
||||
[SerializeField, ColorUsage(true, true)]
|
||||
private Color previewRimColor = new Color(0f, 1.5f, 2f, 1f);
|
||||
[Header("Цвета статичных слепков")]
|
||||
[SerializeField] private Color defaultGhostTint = new(0.6f, 0.85f, 1f, 0.35f);
|
||||
[SerializeField] private Color completedActorGhostColor = new(0.2f, 1f, 0.45f, 0.65f);
|
||||
|
||||
private sealed class GhostSlot
|
||||
{
|
||||
public GameObject Root;
|
||||
public Mesh[] BakedMeshes;
|
||||
public MeshFilter[] Filters;
|
||||
public MeshRenderer[] Renderers;
|
||||
public int TriggerFrame = int.MaxValue;
|
||||
public bool IsActiveInBake;
|
||||
}
|
||||
|
||||
private SkinnedMeshRenderer[] _skinnedRenderers;
|
||||
private MeshRenderer[] _meshRenderers;
|
||||
|
||||
// Кэш оригинальных материалов
|
||||
private readonly Dictionary<Renderer, Material[]> _originalMaterials = new();
|
||||
|
||||
// Пул объектов для статичного слепка (чтобы не делать Instantiate и new Mesh каждый цикл превью)
|
||||
private GameObject _snapshotGhostRoot;
|
||||
private readonly List<Mesh> _bakedMeshes = new();
|
||||
private readonly List<MeshFilter> _ghostMeshFilters = new();
|
||||
private readonly List<MeshRenderer> _ghostMeshRenderers = new();
|
||||
private GhostSlot[] _ghostSlots;
|
||||
|
||||
private MaterialPropertyBlock _propBlock;
|
||||
private static readonly int AlbedoColorId = Shader.PropertyToID("_AlbedoColor");
|
||||
private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
|
||||
private static readonly int RimColorId = Shader.PropertyToID("_RimColor");
|
||||
|
||||
private bool _isPreviewLookApplied;
|
||||
private int _currentAppliedStage = -1;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_propBlock = new MaterialPropertyBlock();
|
||||
_skinnedRenderers = GetComponentsInChildren<SkinnedMeshRenderer>();
|
||||
_meshRenderers = GetComponentsInChildren<MeshRenderer>();
|
||||
|
||||
// Сохраняем родные материалы MKToon
|
||||
foreach (var sr in _skinnedRenderers)
|
||||
_originalMaterials[sr] = sr.sharedMaterials;
|
||||
|
||||
foreach (var mr in _meshRenderers)
|
||||
_originalMaterials[mr] = mr.sharedMaterials;
|
||||
foreach (var sr in _skinnedRenderers) _originalMaterials[sr] = sr.sharedMaterials;
|
||||
foreach (var mr in _meshRenderers) _originalMaterials[mr] = mr.sharedMaterials;
|
||||
|
||||
InitializeGhostPool();
|
||||
}
|
||||
|
||||
private void InitializeGhostPool()
|
||||
{
|
||||
_snapshotGhostRoot = new GameObject($"{gameObject.name}_SnapshotGhost");
|
||||
_snapshotGhostRoot.SetActive(false);
|
||||
_ghostSlots = new GhostSlot[MaxGhostStages];
|
||||
|
||||
for (int s = 0; s < MaxGhostStages; s++)
|
||||
{
|
||||
var root = new GameObject($"{gameObject.name}_GhostStage_{s}");
|
||||
root.SetActive(false);
|
||||
|
||||
int count = _skinnedRenderers.Length;
|
||||
var slot = new GhostSlot
|
||||
{
|
||||
Root = root,
|
||||
BakedMeshes = new Mesh[count],
|
||||
Filters = new MeshFilter[count],
|
||||
Renderers = new MeshRenderer[count]
|
||||
};
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var partGo = new GameObject($"Part_{i}");
|
||||
partGo.transform.SetParent(root.transform, false);
|
||||
|
||||
var mf = partGo.AddComponent<MeshFilter>();
|
||||
var mr = partGo.AddComponent<MeshRenderer>();
|
||||
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
|
||||
var mesh = new Mesh { name = $"BakedGhost_{s}_{i}" };
|
||||
mf.sharedMesh = mesh;
|
||||
|
||||
slot.BakedMeshes[i] = mesh;
|
||||
slot.Filters[i] = mf;
|
||||
slot.Renderers[i] = mr;
|
||||
}
|
||||
|
||||
_ghostSlots[s] = slot;
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearAllGhosts()
|
||||
{
|
||||
if (_ghostSlots == null) return;
|
||||
foreach (var slot in _ghostSlots)
|
||||
{
|
||||
slot.IsActiveInBake = false;
|
||||
slot.TriggerFrame = int.MaxValue;
|
||||
if (slot.Root != null) slot.Root.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Запекает статичный слепок во время BakeFrom (в точке Commit или в точке прерывания).
|
||||
/// </summary>
|
||||
public void BakeGhostAtStage(int stageIndex, int triggerFrame, bool isCompletingActor)
|
||||
{
|
||||
if (snapshotGhostMaterial == null || stageIndex < 0 || stageIndex >= MaxGhostStages)
|
||||
return;
|
||||
|
||||
var slot = _ghostSlots[stageIndex];
|
||||
slot.TriggerFrame = triggerFrame;
|
||||
slot.IsActiveInBake = true;
|
||||
slot.Root.transform.SetPositionAndRotation(transform.position, transform.rotation);
|
||||
|
||||
Color ghostColor = isCompletingActor
|
||||
? completedActorGhostColor
|
||||
: GetStageColor(stageIndex, alphaOverride: defaultGhostTint.a);
|
||||
|
||||
// Создаём легковесные меш-объекты под каждый SkinnedMeshRenderer персонажа
|
||||
for (int i = 0; i < _skinnedRenderers.Length; i++)
|
||||
{
|
||||
var partGo = new GameObject($"GhostPart_{i}");
|
||||
partGo.transform.SetParent(_snapshotGhostRoot.transform, false);
|
||||
var sr = _skinnedRenderers[i];
|
||||
sr.BakeMesh(slot.BakedMeshes[i]);
|
||||
|
||||
var mf = partGo.AddComponent<MeshFilter>();
|
||||
var mr = partGo.AddComponent<MeshRenderer>();
|
||||
var ghostTransform = slot.Filters[i].transform;
|
||||
ghostTransform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
|
||||
|
||||
// Отключаем тени у призрака для чистоты картинки и производительности
|
||||
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
int subMeshCount = Mathf.Max(1, slot.BakedMeshes[i].subMeshCount);
|
||||
var mats = new Material[subMeshCount];
|
||||
for (int m = 0; m < subMeshCount; m++) mats[m] = snapshotGhostMaterial;
|
||||
slot.Renderers[i].sharedMaterials = mats;
|
||||
|
||||
var bakedMesh = new Mesh { name = $"BakedGhostMesh_{i}" };
|
||||
mf.sharedMesh = bakedMesh;
|
||||
|
||||
_bakedMeshes.Add(bakedMesh);
|
||||
_ghostMeshFilters.Add(mf);
|
||||
_ghostMeshRenderers.Add(mr);
|
||||
slot.Renderers[i].GetPropertyBlock(_propBlock);
|
||||
_propBlock.SetColor(AlbedoColorId, ghostColor);
|
||||
_propBlock.SetColor(BaseColorId, ghostColor);
|
||||
slot.Renderers[i].SetPropertyBlock(_propBlock);
|
||||
}
|
||||
|
||||
slot.Root.SetActive(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается перед стартом цикла PreviewBattleLoopAsync (в момент снятия снапшота)
|
||||
/// Синхронизирует видимость слепков и цвет проекции для текущего кадра ползунка.
|
||||
/// Для прошлых кадров (viewFrame <= committedFrame) проекция автоматически выключается!
|
||||
/// </summary>
|
||||
public void ShowPreviewState(bool spawnStaticSnapshotGhost = true)
|
||||
public void UpdateForTimelineFrame(int viewFrame, int committedFrame, int interruptionStage, bool showPreviewVisuals)
|
||||
{
|
||||
// 1. Запекаем полупрозрачную статую в текущей точке снапшота
|
||||
if (spawnStaticSnapshotGhost && snapshotGhostMaterial != null)
|
||||
bool inFuture = showPreviewVisuals && viewFrame > committedFrame;
|
||||
|
||||
if (!inFuture)
|
||||
{
|
||||
_snapshotGhostRoot.transform.SetPositionAndRotation(transform.position, transform.rotation);
|
||||
|
||||
for (int i = 0; i < _skinnedRenderers.Length; i++)
|
||||
{
|
||||
var sr = _skinnedRenderers[i];
|
||||
sr.BakeMesh(_bakedMeshes[i]); // Мгновенный снимок позы скелета!
|
||||
|
||||
var ghostTransform = _ghostMeshFilters[i].transform;
|
||||
ghostTransform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
|
||||
// ghostTransform.localScale = sr.transform.lossyScale;
|
||||
|
||||
// Назначаем прозрачный материал на все саб-меши
|
||||
int subMeshCount = _bakedMeshes[i].subMeshCount;
|
||||
Material[] ghostMats = new Material[Mathf.Max(1, subMeshCount)];
|
||||
for (int m = 0; m < ghostMats.Length; m++)
|
||||
ghostMats[m] = snapshotGhostMaterial;
|
||||
|
||||
_ghostMeshRenderers[i].sharedMaterials = ghostMats;
|
||||
}
|
||||
|
||||
_snapshotGhostRoot.SetActive(true);
|
||||
HidePreviewLook();
|
||||
for (int s = 0; s < _ghostSlots.Length; s++)
|
||||
if (_ghostSlots[s].Root.activeSelf) _ghostSlots[s].Root.SetActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Меняем внешний вид самой модели, которая сейчас побежит в превью
|
||||
ApplyPreviewLookToMainModel();
|
||||
ApplyPreviewLook(interruptionStage);
|
||||
|
||||
for (int s = 0; s < _ghostSlots.Length; s++)
|
||||
{
|
||||
var slot = _ghostSlots[s];
|
||||
bool shouldShow = slot.IsActiveInBake && viewFrame > slot.TriggerFrame;
|
||||
if (slot.Root.activeSelf != shouldShow)
|
||||
slot.Root.SetActive(shouldShow);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается в блоке finally в PreviewBattleLoopAsync
|
||||
/// </summary>
|
||||
public void HidePreviewState()
|
||||
{
|
||||
if (_snapshotGhostRoot != null)
|
||||
_snapshotGhostRoot.SetActive(false);
|
||||
|
||||
RestoreMainModelLook();
|
||||
ClearAllGhosts();
|
||||
HidePreviewLook();
|
||||
}
|
||||
|
||||
private void ApplyPreviewLookToMainModel()
|
||||
private void ApplyPreviewLook(int stage)
|
||||
{
|
||||
if (_isPreviewLookApplied && _currentAppliedStage == stage) return;
|
||||
_isPreviewLookApplied = true;
|
||||
_currentAppliedStage = stage;
|
||||
|
||||
Color tint = GetStageColor(stage);
|
||||
|
||||
foreach (var (renderer, origMats) in _originalMaterials)
|
||||
{
|
||||
if (renderer == null) continue;
|
||||
|
||||
// Способ 1: Если задан отдельный материал для превью — подменяем sharedMaterials
|
||||
if (activePreviewMaterial != null)
|
||||
{
|
||||
Material[] previewMats = new Material[origMats.Length];
|
||||
for (int i = 0; i < previewMats.Length; i++)
|
||||
previewMats[i] = activePreviewMaterial;
|
||||
|
||||
var previewMats = new Material[origMats.Length];
|
||||
for (int i = 0; i < previewMats.Length; i++) previewMats[i] = activePreviewMaterial;
|
||||
renderer.sharedMaterials = previewMats;
|
||||
}
|
||||
// Способ 2: Иначе подкрашиваем родной MKToon через MaterialPropertyBlock (без аллокаций)
|
||||
else
|
||||
{
|
||||
renderer.GetPropertyBlock(_propBlock);
|
||||
_propBlock.SetColor(AlbedoColorId, previewAlbedoTint);
|
||||
_propBlock.SetColor(RimColorId, previewRimColor);
|
||||
renderer.SetPropertyBlock(_propBlock);
|
||||
}
|
||||
|
||||
renderer.GetPropertyBlock(_propBlock);
|
||||
_propBlock.SetColor(AlbedoColorId, tint);
|
||||
_propBlock.SetColor(RimColorId, tint * 1.5f);
|
||||
renderer.SetPropertyBlock(_propBlock);
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreMainModelLook()
|
||||
private void HidePreviewLook()
|
||||
{
|
||||
if (!_isPreviewLookApplied) return;
|
||||
_isPreviewLookApplied = false;
|
||||
_currentAppliedStage = -1;
|
||||
|
||||
foreach (var (renderer, origMats) in _originalMaterials)
|
||||
{
|
||||
if (renderer == null) continue;
|
||||
|
||||
if (activePreviewMaterial != null)
|
||||
{
|
||||
renderer.sharedMaterials = origMats;
|
||||
}
|
||||
else
|
||||
{
|
||||
renderer.SetPropertyBlock(null); // Сбрасывает все переопределения PropertyBlock
|
||||
}
|
||||
if (activePreviewMaterial != null) renderer.sharedMaterials = origMats;
|
||||
renderer.SetPropertyBlock(null);
|
||||
}
|
||||
}
|
||||
|
||||
private Color GetStageColor(int stage, float? alphaOverride = null)
|
||||
{
|
||||
Color c = stageProjectionTints[Mathf.Clamp(stage, 0, stageProjectionTints.Length - 1)];
|
||||
if (alphaOverride.HasValue) c.a = alphaOverride.Value;
|
||||
return c;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
foreach (var mesh in _bakedMeshes)
|
||||
if (_ghostSlots == null) return;
|
||||
foreach (var slot in _ghostSlots)
|
||||
{
|
||||
if (mesh != null) Destroy(mesh);
|
||||
if (slot == null) continue;
|
||||
foreach (var mesh in slot.BakedMeshes)
|
||||
if (mesh != null) Destroy(mesh);
|
||||
if (slot.Root != null) Destroy(slot.Root);
|
||||
}
|
||||
|
||||
if (_snapshotGhostRoot != null)
|
||||
Destroy(_snapshotGhostRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,66 @@
|
||||
using Code.OfficeGame.BattleMode.Health;
|
||||
using KinematicCharacterController;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
public struct BonePoseSnapshot
|
||||
{
|
||||
public Vector3[] LocalPositions;
|
||||
public Quaternion[] LocalRotations;
|
||||
|
||||
public static BonePoseSnapshot Capture(Transform[] bones)
|
||||
{
|
||||
if (bones == null || bones.Length == 0)
|
||||
return default;
|
||||
|
||||
int count = bones.Length;
|
||||
var pos = new Vector3[count];
|
||||
var rot = new Quaternion[count];
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
pos[i] = bones[i].localPosition;
|
||||
rot[i] = bones[i].localRotation;
|
||||
}
|
||||
|
||||
return new BonePoseSnapshot
|
||||
{
|
||||
LocalPositions = pos,
|
||||
LocalRotations = rot
|
||||
};
|
||||
}
|
||||
|
||||
public readonly void ApplyTo(Transform[] bones)
|
||||
{
|
||||
if (bones == null || LocalPositions == null) return;
|
||||
|
||||
int count = Mathf.Min(bones.Length, LocalPositions.Length);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
bones[i].localPosition = LocalPositions[i];
|
||||
bones[i].localRotation = LocalRotations[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct EntitySnapshot
|
||||
{
|
||||
// 1. KCC Motor
|
||||
// --- Уровень 1: Визуальный (для O(1) скраббинга ползунком) ---
|
||||
public Vector3 Position;
|
||||
public Quaternion Rotation;
|
||||
public Vector3 BaseVelocity;
|
||||
public BonePoseSnapshot BonePose;
|
||||
public HealthData CurrentHealth;
|
||||
|
||||
// 2. MovementController
|
||||
// --- Уровень 2: Полное состояние симуляции (для BakeFrom) ---
|
||||
public KinematicCharacterMotorState MotorState;
|
||||
public bool IsFrozen;
|
||||
public Vector3 MoveInputVector;
|
||||
public Vector3 LookInputVector;
|
||||
|
||||
// 3. Здоровье
|
||||
public HealthData CurrentHealth;
|
||||
|
||||
// 4. Аниматор
|
||||
public Vector3 InternalVelocityAdd;
|
||||
public AnimatorSnapshot AnimatorSnapshot;
|
||||
|
||||
public static EntitySnapshot GetSnapshot(EntityProperties entity)
|
||||
public static EntitySnapshot GetSnapshot(EntityProperties entity, Transform[] cachedBones)
|
||||
{
|
||||
var motor = entity.KinematicCharacterMotor;
|
||||
var moveCtrl = entity.MovementController;
|
||||
@@ -30,49 +69,52 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
{
|
||||
Position = motor.TransientPosition,
|
||||
Rotation = motor.TransientRotation,
|
||||
BaseVelocity = motor.BaseVelocity,
|
||||
BonePose = BonePoseSnapshot.Capture(cachedBones),
|
||||
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
|
||||
|
||||
MotorState = motor.GetState(),
|
||||
IsFrozen = moveCtrl.Freeze,
|
||||
// Сохраните текущие входы контроллера (добавьте публичные геттеры в MovementController, если они приватные)
|
||||
MoveInputVector = moveCtrl.MoveInputVector,
|
||||
LookInputVector = moveCtrl.LookInputVector,
|
||||
|
||||
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
|
||||
InternalVelocityAdd = moveCtrl.InternalVelocityAdd,
|
||||
AnimatorSnapshot = AnimatorSnapshot.GetSnapshot(entity.animator)
|
||||
};
|
||||
}
|
||||
|
||||
public static void RestoreSnapshot(EntityProperties entity, EntitySnapshot snapshot)
|
||||
/// <summary>
|
||||
/// Мгновенное O(1) восстановление визуала для ползунка и воспроизведения ленты.
|
||||
/// Не трогает Mecanim и не мутирует EntityHealth.
|
||||
/// </summary>
|
||||
public static void ApplyVisualOnly(EntityProperties entity, Transform[] cachedBones, in EntitySnapshot snapshot)
|
||||
{
|
||||
entity.KinematicCharacterMotor.SetPositionAndRotation(
|
||||
snapshot.Position,
|
||||
snapshot.Rotation,
|
||||
bypassInterpolation: true);
|
||||
|
||||
snapshot.BonePose.ApplyTo(cachedBones);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Полное детерминированное восстановление для старта/перезапекания физической симуляции.
|
||||
/// </summary>
|
||||
public static void RestoreForSimulation(EntityProperties entity, Transform[] cachedBones, in EntitySnapshot snapshot)
|
||||
{
|
||||
var motor = entity.KinematicCharacterMotor;
|
||||
var moveCtrl = entity.MovementController;
|
||||
|
||||
// 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);
|
||||
moveCtrl.MoveInputVector = snapshot.MoveInputVector;
|
||||
moveCtrl.LookInputVector = snapshot.LookInputVector;
|
||||
moveCtrl.InternalVelocityAdd = snapshot.InternalVelocityAdd;
|
||||
|
||||
// 2. Восстанавливаем капсулу KCC (bypassInterpolation = true сбрасывает внутренние буферы перемещения)
|
||||
motor.SetPositionAndRotation(snapshot.Position, snapshot.Rotation, bypassInterpolation: true);
|
||||
motor.BaseVelocity = snapshot.BaseVelocity;
|
||||
motor.ApplyState(snapshot.MotorState, bypassInterpolation: true);
|
||||
|
||||
// 3. Восстанавливаем здоровье (без вызова анимаций смерти)
|
||||
if (entity.EntityHealth != null)
|
||||
{
|
||||
entity.EntityHealth.SetHealthData(snapshot.CurrentHealth);
|
||||
}
|
||||
|
||||
// 4. Восстанавливаем точную позу и фазу перехода Animator
|
||||
snapshot.AnimatorSnapshot.RestoreTo(entity.animator);
|
||||
|
||||
// 5. Мгновенно синхронизируем коллайдеры костей в PhysX
|
||||
Physics.SyncTransforms();
|
||||
snapshot.BonePose.ApplyTo(cachedBones);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,8 +197,8 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
layerSnap.NextFullPathHash = nextInfo.fullPathHash;
|
||||
layerSnap.NextNormalizedTime = nextInfo.normalizedTime;
|
||||
layerSnap.NextStateLength = Mathf.Max(0.0001f, nextInfo.length);
|
||||
layerSnap.TotalTransitionDuration = totalTransSeconds;
|
||||
layerSnap.ElapsedTransitionTime = totalTransSeconds * transInfo.normalizedTime;
|
||||
layerSnap.TotalTransitionDuration = Mathf.Max(0.0001f, totalTransSeconds);
|
||||
layerSnap.ElapsedTransitionTime = layerSnap.TotalTransitionDuration * transInfo.normalizedTime;
|
||||
}
|
||||
|
||||
_layers[i] = layerSnap;
|
||||
@@ -182,7 +224,7 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
}
|
||||
}
|
||||
|
||||
public void RestoreTo(Animator targetAnimator)
|
||||
public readonly void RestoreTo(Animator targetAnimator)
|
||||
{
|
||||
if (targetAnimator == null || _layers == null) return;
|
||||
|
||||
@@ -217,29 +259,25 @@ namespace Code.OfficeGame.BattleMode.Actions
|
||||
|
||||
if (!layer.IsInTransition || layer.NextFullPathHash == 0)
|
||||
{
|
||||
// CrossFadeInFixedTime с длительностью 0f гарантированно убивает любой старый переход без Rebind()!
|
||||
float timeInSeconds = layer.NormalizedTime * layer.StateLength;
|
||||
float timeInSeconds = Mathf.Max(0f, 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;
|
||||
// Защита от отрицательного времени (фикс бага старого AnimatorSnapshot)
|
||||
float startSecondsA = Mathf.Max(0f, (layer.NormalizedTime * layer.StateLength) - layer.ElapsedTransitionTime);
|
||||
float startSecondsB = Mathf.Max(0f, (layer.NextNormalizedTime * layer.NextStateLength) - layer.ElapsedTransitionTime);
|
||||
|
||||
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, startSecondsA);
|
||||
targetAnimator.Update(0f);
|
||||
|
||||
// 2. Запускаем переход с оригинальной полной длительностью
|
||||
targetAnimator.CrossFadeInFixedTime(
|
||||
layer.NextFullPathHash,
|
||||
layer.TotalTransitionDuration,
|
||||
i,
|
||||
startSecondsB);
|
||||
|
||||
// 3. Прокручиваем аниматор ровно на ElapsedTransitionTime вперед (с выключенным RootMotion),
|
||||
// чтобы внутренний вес смешивания Mecanim встал ровно в ту же долю процента!
|
||||
targetAnimator.Update(layer.ElapsedTransitionTime);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,6 @@ namespace Code.OfficeGame.BattleMode.Effects
|
||||
{
|
||||
public override EffectType Type => EffectType.Attack;
|
||||
|
||||
public abstract void Apply(in int damage);
|
||||
public abstract void Apply(ref int damage);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,6 @@ namespace Code.OfficeGame.BattleMode.Effects
|
||||
{
|
||||
public override EffectType Type => EffectType.Defense;
|
||||
|
||||
public abstract void Apply(in int damage);
|
||||
public abstract void Apply(ref int damage);
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,11 @@ namespace Code.OfficeGame.BattleMode
|
||||
{
|
||||
public int Damage;
|
||||
public HitBoxPartType HitBoxPartType;
|
||||
|
||||
public Vector3 HitWorldPosition;
|
||||
|
||||
public EntityId AttackerId;
|
||||
public EntityId DefenderId;
|
||||
|
||||
|
||||
public EntityProperties Attacker;
|
||||
public EntityProperties Defender;
|
||||
|
||||
@@ -21,7 +22,9 @@ namespace Code.OfficeGame.BattleMode
|
||||
|
||||
public bool Equals(EntityAttackedData other)
|
||||
{
|
||||
return AttackerId == other.AttackerId && DefenderId == other.DefenderId && HitBoxPartType == other.HitBoxPartType;
|
||||
return AttackerId == other.AttackerId
|
||||
&& DefenderId == other.DefenderId
|
||||
&& HitBoxPartType == other.HitBoxPartType;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
|
||||
@@ -32,7 +32,8 @@ namespace Code.OfficeGame.BattleMode.Health
|
||||
return;
|
||||
}
|
||||
|
||||
var newCurrentHealth = _healthData.CurrentValue.CurrentHealth - damage * hitBoxPartModifier[hitBoxPart];
|
||||
int modifier = hitBoxPartModifier.GetValueOrDefault(hitBoxPart, 1);
|
||||
var newCurrentHealth = _healthData.CurrentValue.CurrentHealth - damage * modifier;
|
||||
|
||||
_healthData.Value = new HealthData()
|
||||
{
|
||||
|
||||
@@ -4,53 +4,59 @@ using Code.Infrastructure.Camera;
|
||||
using Code.Infrastructure.UI;
|
||||
using Code.OfficeGame.BattleMode.Actions;
|
||||
using Code.OfficeGame.BattleMode.Health.UI;
|
||||
using Code.OfficeGame.BattleMode.Timeline;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using R3;
|
||||
using Reflex.Attributes;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Health
|
||||
{
|
||||
public class HealthPanelsHolder : IDisposable
|
||||
{
|
||||
public List<EntityHealthPanel> PanelList;
|
||||
public List<EntityHealthPanel> PanelList { get; private set; } = new();
|
||||
private readonly List<(EntityHealthPanel Panel, EntityId EntityId)> _bindings = new();
|
||||
|
||||
[Inject]
|
||||
private void Construct(CameraStateMachine cameraStateMachine)
|
||||
{
|
||||
foreach (var panel in PanelList) panel.Construct(cameraStateMachine);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Список опрокинуть в контейнер
|
||||
/// </summary>
|
||||
/// <param name="factory"></param>
|
||||
/// <param name="entities"></param>
|
||||
/// <returns></returns>
|
||||
public async UniTask SpawnHealthBars(
|
||||
IUIFactory factory,
|
||||
List<EntityProperties> entities)
|
||||
|
||||
public async UniTask SpawnHealthBars(IUIFactory factory, List<EntityProperties> entities)
|
||||
{
|
||||
PanelList = new List<EntityHealthPanel>();
|
||||
_bindings.Clear();
|
||||
|
||||
foreach (var entity in entities)
|
||||
{
|
||||
var healthBarTarget = entity.GetComponentInChildren<HealthBarTarget>();
|
||||
|
||||
if(!healthBarTarget) continue;
|
||||
|
||||
var panel = (EntityHealthPanel) await factory.LoadPanel(UIPanelType.EntityHealthBar, false);
|
||||
if (!healthBarTarget) continue;
|
||||
|
||||
var panel = (EntityHealthPanel)await factory.LoadPanel(UIPanelType.EntityHealthBar, false);
|
||||
panel.SetTarget(healthBarTarget.transform);
|
||||
|
||||
panel.SubscribeHealthPanel(entity.EntityHealth);
|
||||
|
||||
|
||||
PanelList.Add(panel);
|
||||
_bindings.Add((panel, entity.GetEntityId()));
|
||||
}
|
||||
}
|
||||
|
||||
public IDisposable BindToTimeline(BattleTimeline timeline)
|
||||
{
|
||||
var bag = new DisposableBag();
|
||||
foreach (var (panel, entityId) in _bindings)
|
||||
{
|
||||
panel.BindToTimeline(timeline, entityId).AddTo(ref bag);
|
||||
}
|
||||
return bag;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var panel in PanelList)
|
||||
foreach (var panel in PanelList)
|
||||
panel.Dispose();
|
||||
PanelList.Clear();
|
||||
_bindings.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using Code.Infrastructure.Camera;
|
||||
using Code.Infrastructure.UI;
|
||||
@@ -21,11 +22,9 @@ namespace Code.OfficeGame.BattleMode.Health.UI
|
||||
[SerializeField] private Color fullColor;
|
||||
[SerializeField] private Color deadColor;
|
||||
|
||||
[SerializeField]
|
||||
[Range(0.1f,0.9f)]
|
||||
[SerializeField, Range(0.1f, 0.9f)]
|
||||
private float criticalPercent;
|
||||
|
||||
private DisposableBag _healthSubscriptions;
|
||||
|
||||
private Camera _camera;
|
||||
private Transform _target;
|
||||
|
||||
@@ -34,67 +33,70 @@ namespace Code.OfficeGame.BattleMode.Health.UI
|
||||
{
|
||||
_camera = cameraStateMachine.Camera;
|
||||
}
|
||||
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (!_target || !_camera) return;
|
||||
|
||||
Vector3 screenPos = _camera.WorldToScreenPoint(_target.position);
|
||||
|
||||
bool isVisible = screenPos.z > 0;
|
||||
|
||||
if (isVisible)
|
||||
if (screenPos.z > 0)
|
||||
transform.position = screenPos;
|
||||
}
|
||||
|
||||
public void SetTarget(Transform target)
|
||||
{
|
||||
_target = target;
|
||||
}
|
||||
|
||||
public void SubscribeHealthPanel(EntityHealth entityHealth)
|
||||
{
|
||||
entityHealth.HealthData
|
||||
.Subscribe(SetHealthStatus)
|
||||
.AddTo(ref _healthSubscriptions);
|
||||
public void SetTarget(Transform target) => _target = target;
|
||||
|
||||
_previousHealthData = entityHealth.HealthData.CurrentValue;
|
||||
}
|
||||
|
||||
private HealthData _previousHealthData;
|
||||
|
||||
private void SetHealthStatus(HealthData healthData)
|
||||
public IDisposable BindToTimeline(BattleTimeline timeline, EntityId entityId)
|
||||
{
|
||||
if (healthData.CurrentHealth <= 0)
|
||||
var bag = new DisposableBag();
|
||||
|
||||
void Refresh()
|
||||
{
|
||||
int slot = timeline.GetSlotIndex(entityId);
|
||||
if (slot < 0 || timeline.Track.FrameCount == 0) return;
|
||||
|
||||
var viewSnap = timeline.Track.GetFrame(timeline.DisplayFrame.CurrentValue);
|
||||
var endSnap = timeline.Track.GetFrame(timeline.Track.LastFrame);
|
||||
|
||||
var viewHp = viewSnap.Entities[slot].PhysicsAndVisuals.CurrentHealth;
|
||||
var endHp = endSnap.Entities[slot].PhysicsAndVisuals.CurrentHealth;
|
||||
|
||||
ApplyHealthStatus(viewHp, endHp);
|
||||
}
|
||||
|
||||
timeline.DisplayFrame.Subscribe(_ => Refresh()).AddTo(ref bag);
|
||||
timeline.OnTrackRebaked.Subscribe(_ => Refresh()).AddTo(ref bag);
|
||||
Refresh();
|
||||
|
||||
return bag;
|
||||
}
|
||||
|
||||
private void ApplyHealthStatus(HealthData viewHp, HealthData predictedEndHp)
|
||||
{
|
||||
float max = Mathf.Max(1, viewHp.MaxHealth);
|
||||
float viewPct = Mathf.Clamp01(viewHp.CurrentHealth / max);
|
||||
float endPct = Mathf.Clamp01(predictedEndHp.CurrentHealth / max);
|
||||
|
||||
if (viewHp.CurrentHealth <= 0)
|
||||
{
|
||||
healthText.color = deadColor;
|
||||
healthText.SetText("Dead");
|
||||
|
||||
if(BattleTimeline.IsSilentSimulation)
|
||||
silentHealthBar.fillAmount = 1;
|
||||
else healthBar.fillAmount = 1;
|
||||
|
||||
healthBar.fillAmount = 0f;
|
||||
silentHealthBar.fillAmount = 0f;
|
||||
return;
|
||||
}
|
||||
|
||||
float healthPercentage = (float)healthData.CurrentHealth / healthData.MaxHealth;
|
||||
|
||||
if(BattleTimeline.IsSilentSimulation)
|
||||
if(_previousHealthData.CurrentHealth != healthData.CurrentHealth) silentHealthBar.fillAmount = healthPercentage;
|
||||
else silentHealthBar.fillAmount = 0;
|
||||
else
|
||||
{
|
||||
healthBar.fillAmount = healthPercentage;
|
||||
_previousHealthData = healthData;
|
||||
}
|
||||
// SB
|
||||
// Основной бар — HP на текущем кадре ползунка;
|
||||
// silentHealthBar — подложка прогнозируемого остатка/урона в конце превью
|
||||
healthBar.fillAmount = viewPct;
|
||||
silentHealthBar.fillAmount = predictedEndHp.CurrentHealth < viewHp.CurrentHealth ? viewPct : 0f;
|
||||
|
||||
healthText.SetText($"{healthData.CurrentHealth}/{healthData.MaxHealth}");
|
||||
// Если хотите показывать именно остаток после урона на healthBar, а потерянный кусок на silentHealthBar:
|
||||
// healthBar.fillAmount = endPct;
|
||||
// silentHealthBar.fillAmount = viewPct;
|
||||
|
||||
if (healthPercentage <= criticalPercent)
|
||||
healthBar.color = criticalColor;
|
||||
else
|
||||
healthBar.color = fullColor;
|
||||
healthText.color = Color.white;
|
||||
healthText.SetText($"{viewHp.CurrentHealth}/{viewHp.MaxHealth}");
|
||||
healthBar.color = viewPct <= criticalPercent ? criticalColor : fullColor;
|
||||
}
|
||||
|
||||
public override UniTask Open(CancellationToken cts = default)
|
||||
@@ -108,10 +110,5 @@ namespace Code.OfficeGame.BattleMode.Health.UI
|
||||
gameObject.SetActive(false);
|
||||
return UniTask.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
_healthSubscriptions.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,31 +5,41 @@ using UnityEngine;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.HitBoxes
|
||||
{
|
||||
// TODO Добавить меотды отключения,чтобы не получать урон во время стаггера
|
||||
public class EntityHitBoxes : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private Dictionary<HitBoxPartType, BoxCollider> bodyParts;
|
||||
private LayerMask _hitBoxLayerMask;
|
||||
|
||||
private readonly Dictionary<Collider, HitBoxPartType> _colliderToPart = new();
|
||||
private readonly Collider[] _hitResults = new Collider[8];
|
||||
private LayerMask _hitBoxLayerMask;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
// foreach (var part in bodyParts.Values)
|
||||
// {
|
||||
// part.enabled = false;
|
||||
// }
|
||||
_hitBoxLayerMask = LayerMask.GetMask("HitBox");
|
||||
|
||||
if (bodyParts != null)
|
||||
{
|
||||
foreach (var (part, col) in bodyParts)
|
||||
{
|
||||
if (col != null) _colliderToPart[col] = part;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void CheckHitsForCurrentFrame(Action<Collider, Collider> onNewTargetHit, HitBoxPartType hitBoxPartType)
|
||||
public bool TryGetPartType(Collider col, out HitBoxPartType partType) =>
|
||||
_colliderToPart.TryGetValue(col, out partType);
|
||||
|
||||
public void CheckHitsForCurrentFrame(
|
||||
IBattleSimulationContext simContext,
|
||||
Action<Collider, Collider, HitBoxPartType> onTargetHit,
|
||||
HitBoxPartType attackingBodyPart)
|
||||
{
|
||||
BoxCollider box = bodyParts[hitBoxPartType];
|
||||
if (bodyParts == null || !bodyParts.TryGetValue(attackingBodyPart, out BoxCollider box) || box == null)
|
||||
return;
|
||||
|
||||
simContext?.RecordHitboxVisual(box, Color.red);
|
||||
|
||||
Transform boxTransform = box.transform;
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -44,10 +54,14 @@ namespace Code.OfficeGame.BattleMode.HitBoxes
|
||||
for (int i = 0; i < hitsCount; i++)
|
||||
{
|
||||
Collider hitCol = _hitResults[i];
|
||||
|
||||
if (hitCol.transform.root == transform.root) continue;
|
||||
|
||||
onNewTargetHit?.Invoke(box, hitCol);
|
||||
var defenderHitBoxes = hitCol.GetComponentInParent<EntityHitBoxes>();
|
||||
HitBoxPartType hitPart = HitBoxPartType.Chest;
|
||||
if (defenderHitBoxes != null)
|
||||
defenderHitBoxes.TryGetPartType(hitCol, out hitPart);
|
||||
|
||||
onTargetHit?.Invoke(box, hitCol, hitPart);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,18 @@ namespace Code.OfficeGame.BattleMode.HitBoxes
|
||||
|
||||
private static bool _initialized;
|
||||
|
||||
public static void DrawMatrix(Matrix4x4 matrix, Color color, float duration = 1.0f)
|
||||
{
|
||||
EnsureInitialized();
|
||||
if (_material == null) return;
|
||||
|
||||
_boxes.Add(new ActiveBox
|
||||
{
|
||||
Matrix = matrix,
|
||||
Color = color,
|
||||
ExpireTime = Time.unscaledTime + duration
|
||||
});
|
||||
}
|
||||
/// <summary>
|
||||
/// Отрисовка хитбокса напрямую по BoxCollider
|
||||
/// </summary>
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using Code.Game.Entities;
|
||||
using Code.OfficeGame.BattleMode.Actions;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.Snapshots
|
||||
{
|
||||
public class SnapshotUtilityNonStatic
|
||||
{
|
||||
Dictionary<EntityId, BattleActionData> actionDataSnapshots = new();
|
||||
Dictionary<EntityId, BattleActionDecisionResult> resultsSnapshots = new();
|
||||
Dictionary<EntityId, EntitySnapshot> entitySnapshots = new();
|
||||
|
||||
public void GetSnapshots(
|
||||
Dictionary<EntityId, EntityProperties> entities,
|
||||
Dictionary<EntityId, BattleActionDecisionResult> actionDecisionResults,
|
||||
Dictionary<EntityId, BattleActionData> battleActionDatas)
|
||||
{
|
||||
foreach (var (entityId, entity) in entities)
|
||||
{
|
||||
if (!actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult)
|
||||
|| !battleActionDatas.TryGetValue(entityId, out var battleActionData))
|
||||
{
|
||||
entity.EntityPreviewVisuals.ShowPreviewState(spawnStaticSnapshotGhost: false);
|
||||
continue;
|
||||
}
|
||||
|
||||
entity.EntityPreviewVisuals.ShowPreviewState(spawnStaticSnapshotGhost: true);
|
||||
|
||||
resultsSnapshots[entityId] = actionDecisionResult.GetSnapshot();
|
||||
actionDataSnapshots[entityId] = battleActionData.GetSnapshot();
|
||||
entitySnapshots[entityId] = entity.GetSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
public void RestoreFromSnapshots(
|
||||
Dictionary<EntityId, EntityProperties> entities,
|
||||
Dictionary<EntityId, BattleActionDecisionResult> actionDecisionResults,
|
||||
Dictionary<EntityId, BattleActionData> battleActionDatas)
|
||||
{
|
||||
foreach (var (entityId, entity) in entities)
|
||||
{
|
||||
if (!resultsSnapshots.TryGetValue(entityId, out var actionDecisionResult)
|
||||
|| !actionDataSnapshots.TryGetValue(entityId, out var battleActionData))
|
||||
continue;
|
||||
|
||||
if (actionDecisionResults.TryGetValue(entityId, out var currentDecisionResult) && battleActionDatas.TryGetValue(entityId, out var currentActionData))
|
||||
{
|
||||
Debug.Log(
|
||||
$"Restoring {actionDecisionResult.ActionType} of {currentDecisionResult.ActionType} for {entityId}");
|
||||
Debug.Log(
|
||||
$"Also {battleActionData} of {currentActionData} for {entityId}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log($"Something gone wrong for {entityId}, Restoring {actionDecisionResult.ActionType} Also {battleActionData}");
|
||||
}
|
||||
|
||||
actionDecisionResults[entityId] = actionDecisionResult.GetSnapshot();
|
||||
battleActionDatas[entityId] = battleActionData.GetSnapshot();
|
||||
|
||||
entity.RestoreSnapshot(entitySnapshots[entityId]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2bf8fe2677b947a781568c78e8dc7e99
|
||||
timeCreated: 1794237839
|
||||
@@ -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
|
||||
@@ -82,7 +82,7 @@ namespace Code.OfficeGame.BattleMode.UI
|
||||
|
||||
await _motionHandle.ToUniTask(cts);
|
||||
|
||||
gameObject.SetActive(true);
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Code.Infrastructure.UI;
|
||||
@@ -5,90 +6,193 @@ using Code.OfficeGame.BattleMode.Timeline;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using LitMotion;
|
||||
using LitMotion.Extensions;
|
||||
using R3;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace Code.OfficeGame.BattleMode.UI
|
||||
{
|
||||
public class BattleTimelinePanel : UIPanel
|
||||
{
|
||||
[SerializeField] private int maxFrames = 250;
|
||||
[SerializeField] private GameObject timelineKeyPrefab;
|
||||
[SerializeField] private float duration = 0.35f;
|
||||
[SerializeField] private RectTransform timelineItself;
|
||||
[SerializeField] private TMP_Text prevAction;
|
||||
|
||||
public void SetPreviousActionText(string text) => prevAction.text = text;
|
||||
[SerializeField] private TMP_Text frameCounterText;
|
||||
|
||||
// TODO Вырезать или пощадить
|
||||
private readonly Dictionary<EntityId, int> _entityEndFrames = new();
|
||||
private readonly Dictionary<EntityId, RectTransform> _entityKeys = new();
|
||||
[Header("Управление ползунком")]
|
||||
[SerializeField] private Slider timelineSlider;
|
||||
[SerializeField] private Button playPauseButton;
|
||||
[SerializeField] private Button stepBackButton;
|
||||
[SerializeField] private Button stepForwardButton;
|
||||
[SerializeField] private Button returnToCommitButton;
|
||||
|
||||
private int _lastKnownCurrentFrame;
|
||||
[Header("Маркеры и цветные полосы событий")]
|
||||
[SerializeField] private RectTransform markersContainer;
|
||||
[SerializeField] private Image markerStripePrefab;
|
||||
[SerializeField] private RectTransform commitMarkerLine;
|
||||
|
||||
[SerializeField] private Color[] stageInterruptionColors =
|
||||
{
|
||||
new(1.0f, 0.85f, 0.2f, 0.95f), // 1-е прерывание
|
||||
new(1.0f, 0.55f, 0.2f, 0.95f), // 2-е прерывание
|
||||
new(0.95f, 0.3f, 0.5f, 0.95f) // 3+ прерывание
|
||||
};
|
||||
[SerializeField] private Color hitEventColor = new(1f, 0.3f, 0.1f, 0.9f);
|
||||
[SerializeField] private Color deathEventColor = new(0.85f, 0.05f, 0.15f, 1f);
|
||||
|
||||
private readonly List<Image> _spawnedMarkers = new();
|
||||
private bool _suppressSliderCallback;
|
||||
private MotionHandle _motionHandle;
|
||||
|
||||
public void SetAction(TimelineBattleAction action)
|
||||
|
||||
public void SetPreviousActionText(string text)
|
||||
{
|
||||
_entityEndFrames[action.EntityId] = action.Frame;
|
||||
|
||||
if (!_entityKeys.TryGetValue(action.EntityId, out RectTransform keyRect))
|
||||
{
|
||||
keyRect = (RectTransform)Instantiate(timelineKeyPrefab, timelineItself).transform;
|
||||
_entityKeys[action.EntityId] = keyRect;
|
||||
}
|
||||
|
||||
UpdateKeyPosition(keyRect, action.Frame - _lastKnownCurrentFrame);
|
||||
if (prevAction != null) prevAction.text = text;
|
||||
}
|
||||
public void OnFrameTick(int currentFrame)
|
||||
{
|
||||
_lastKnownCurrentFrame = currentFrame;
|
||||
|
||||
foreach (var (entityId, endFrame) in _entityEndFrames)
|
||||
{
|
||||
if (_entityKeys.TryGetValue(entityId, out RectTransform keyRect))
|
||||
public IDisposable BindTimeline(BattleTimeline timeline)
|
||||
{
|
||||
var bag = new DisposableBag();
|
||||
|
||||
timelineSlider.wholeNumbers = true;
|
||||
|
||||
// 1. Границы ползунка растут до конца последнего действия
|
||||
timeline.MaxFrame
|
||||
.Subscribe(maxFrame =>
|
||||
{
|
||||
int remainingFrames = Mathf.Max(0, endFrame - currentFrame);
|
||||
UpdateKeyPosition(keyRect, remainingFrames);
|
||||
}
|
||||
timelineSlider.minValue = 0;
|
||||
timelineSlider.maxValue = Mathf.Max(1, maxFrame);
|
||||
UpdateFrameCounter(timeline.DisplayFrame.CurrentValue, maxFrame);
|
||||
})
|
||||
.AddTo(ref bag);
|
||||
|
||||
// 2. Текущий кадр двигает ползунок без рекурсии
|
||||
timeline.DisplayFrame
|
||||
.Subscribe(frame =>
|
||||
{
|
||||
_suppressSliderCallback = true;
|
||||
timelineSlider.SetValueWithoutNotify(frame);
|
||||
_suppressSliderCallback = false;
|
||||
UpdateFrameCounter(frame, timeline.MaxFrame.CurrentValue);
|
||||
})
|
||||
.AddTo(ref bag);
|
||||
|
||||
// 3. Ползунок заблокирован только во время реального исполнения
|
||||
timeline.Mode
|
||||
.Subscribe(mode => timelineSlider.interactable = mode != TimelineMode.BattlePlaying)
|
||||
.AddTo(ref bag);
|
||||
|
||||
// 4. Обновление цветных полос прерываний, ударов и смертей при перепекании
|
||||
timeline.OnTrackRebaked
|
||||
.Subscribe(track => RebuildMarkers(track, timeline.CommittedFrame.CurrentValue))
|
||||
.AddTo(ref bag);
|
||||
|
||||
timeline.CommittedFrame
|
||||
.Subscribe(commitFrame => UpdateCommitLine(commitFrame, timeline.MaxFrame.CurrentValue))
|
||||
.AddTo(ref bag);
|
||||
|
||||
// 5. Пользователь тянет ползунок -> скраббинг таймлайна
|
||||
timelineSlider.OnValueChangedAsObservable()
|
||||
.Subscribe(val =>
|
||||
{
|
||||
if (_suppressSliderCallback) return;
|
||||
timeline.ScrubToFrame((int)val);
|
||||
})
|
||||
.AddTo(ref bag);
|
||||
|
||||
if (playPauseButton != null)
|
||||
playPauseButton.OnClickAsObservable().Subscribe(_ => timeline.TogglePreviewPlayPause()).AddTo(ref bag);
|
||||
|
||||
if (stepBackButton != null)
|
||||
stepBackButton.OnClickAsObservable().Subscribe(_ => timeline.StepFrame(-1)).AddTo(ref bag);
|
||||
|
||||
if (stepForwardButton != null)
|
||||
stepForwardButton.OnClickAsObservable().Subscribe(_ => timeline.StepFrame(+1)).AddTo(ref bag);
|
||||
|
||||
if (returnToCommitButton != null)
|
||||
returnToCommitButton.OnClickAsObservable().Subscribe(_ => timeline.ReturnToCommittedFrame()).AddTo(ref bag);
|
||||
|
||||
return bag;
|
||||
}
|
||||
|
||||
private void RebuildMarkers(BattleTimelineTrack track, int committedFrame)
|
||||
{
|
||||
for (int i = 0; i < _spawnedMarkers.Count; i++)
|
||||
if (_spawnedMarkers[i] != null) Destroy(_spawnedMarkers[i].gameObject);
|
||||
_spawnedMarkers.Clear();
|
||||
|
||||
float maxFrame = Mathf.Max(1, track.LastFrame);
|
||||
UpdateCommitLine(committedFrame, track.LastFrame);
|
||||
|
||||
if (markerStripePrefab == null || markersContainer == null) return;
|
||||
|
||||
var events = track.AllEvents;
|
||||
for (int i = 0; i < events.Count; i++)
|
||||
{
|
||||
var ev = events[i];
|
||||
Color? color = ev.EventType switch
|
||||
{
|
||||
TimelineEventType.ActionCompleted => GetInterruptionColor(ev.InterruptionStage),
|
||||
TimelineEventType.HitLanded => hitEventColor,
|
||||
TimelineEventType.EntityDied => deathEventColor,
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (!color.HasValue) continue;
|
||||
|
||||
var stripe = Instantiate(markerStripePrefab, markersContainer);
|
||||
stripe.color = color.Value;
|
||||
PlaceNormalizedX((RectTransform)stripe.transform, ev.Frame / maxFrame);
|
||||
_spawnedMarkers.Add(stripe);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateKeyPosition(RectTransform keyRect, int relativeFrame)
|
||||
private Color GetInterruptionColor(int stage)
|
||||
{
|
||||
var rectWidth = timelineItself.rect.width;
|
||||
var frameSize = rectWidth / maxFrames;
|
||||
if (stageInterruptionColors == null || stageInterruptionColors.Length == 0)
|
||||
return Color.yellow;
|
||||
int idx = Mathf.Clamp(stage - 1, 0, stageInterruptionColors.Length - 1);
|
||||
return stageInterruptionColors[idx];
|
||||
}
|
||||
|
||||
keyRect.anchoredPosition = new Vector2(frameSize * relativeFrame - rectWidth / 2f, 0f);
|
||||
private void UpdateCommitLine(int committedFrame, int maxFrame)
|
||||
{
|
||||
if (commitMarkerLine == null) return;
|
||||
PlaceNormalizedX(commitMarkerLine, committedFrame / (float)Mathf.Max(1, maxFrame));
|
||||
}
|
||||
|
||||
private static void PlaceNormalizedX(RectTransform rect, float normalized01)
|
||||
{
|
||||
normalized01 = Mathf.Clamp01(normalized01);
|
||||
rect.anchorMin = new Vector2(normalized01, 0f);
|
||||
rect.anchorMax = new Vector2(normalized01, 1f);
|
||||
rect.anchoredPosition = Vector2.zero;
|
||||
}
|
||||
|
||||
private void UpdateFrameCounter(int current, int max)
|
||||
{
|
||||
if (frameCounterText != null)
|
||||
frameCounterText.SetText($"{current} / {max}");
|
||||
}
|
||||
|
||||
public override async UniTask Open(CancellationToken cts = default)
|
||||
{
|
||||
gameObject.SetActive(true);
|
||||
|
||||
float startY = -((RectTransform)transform).rect.height;
|
||||
float targetY = 0f;
|
||||
|
||||
_motionHandle = LMotion.Create(startY, targetY, duration)
|
||||
_motionHandle = LMotion.Create(startY, 0f, duration)
|
||||
.WithEase(Ease.OutCubic)
|
||||
.WithScheduler(MotionScheduler.UpdateIgnoreTimeScale)
|
||||
.BindToAnchoredPositionY((RectTransform)transform);
|
||||
|
||||
await _motionHandle.ToUniTask(cts);
|
||||
}
|
||||
|
||||
public override async UniTask Close(CancellationToken cts = default)
|
||||
{
|
||||
float startY = 0;
|
||||
float targetY = ((RectTransform)transform).rect.height;
|
||||
|
||||
_motionHandle = LMotion.Create(startY, targetY, duration)
|
||||
_motionHandle = LMotion.Create(0f, targetY, duration)
|
||||
.WithEase(Ease.InBack)
|
||||
.WithScheduler(MotionScheduler.UpdateIgnoreTimeScale)
|
||||
.BindToAnchoredPositionY((RectTransform)transform);
|
||||
|
||||
await _motionHandle.ToUniTask(cts);
|
||||
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user