Files
OldThink/Content.Shared/Movement/Components/SharedPlayerInputMoverComponent.cs

271 lines
10 KiB
C#
Raw Normal View History

using System;
using Content.Shared.CCVar;
using Robust.Shared.Configuration;
2020-06-24 02:21:20 +02:00
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
2020-06-24 02:21:20 +02:00
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Players;
2020-06-24 02:21:20 +02:00
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
2021-06-09 22:19:39 +02:00
namespace Content.Shared.Movement.Components
2020-06-24 02:21:20 +02:00
{
Physics (#3485) * Content side new physics structure * BroadPhase outline done * But we need to fix WorldAABB * Fix static pvs AABB * Fix import * Rando fixes * B is for balloon * Change human mob hitbox to circle * Decent movement * Start adding friction to player controller I think it's the best way to go about it to keep other objects somewhat consistent for physics. * This baby can fit so many physics bugs in it. * Slight mob mover optimisations. * Player mover kinda works okay. * Beginnings of testbed * More testbed * Circlestack bed * Namespaces * BB fixes * Pull WorldAABB * Joint pulling * Semi-decent movement I guess. * Pulling better * Bullet controller + old movement * im too dumb for this shit * Use kinematic mob controller again It's probably for the best TBH * Stashed shitcode * Remove SlipController * In which movement code is entirely refactored * Singularity fix * Fix ApplyLinearImpulse * MoveRelay fix * Fix door collisions * Disable subfloor collisions Saves on broadphase a fair bit * Re-implement ClimbController * Zumzum's pressure * Laggy item throwing * Minor atmos change * Some caching * Optimise controllers * Optimise CollideWith to hell and back * Re-do throwing and tile friction * Landing too * Optimise controllers * Move CCVars and other stuff swept is beautiful * Cleanup a bunch of controllers * Fix shooting and high pressure movement controller * Flashing improvements * Stuff and things * Combat collisions * Combat mode collisions * Pulling distance joint again * Cleanup physics interfaces * More like scuffedularity * Shit's fucked * Haha tests go green * Bigmoneycrab * Fix dupe pulling * Zumzum's based fix * Don't run tile friction for non-predicted bodies * Experimental pulling improvement * Everything's a poly now * Optimise AI region debugging a bit Could still be better but should improve default performance a LOT * Mover no updater * Crazy kinematic body idea * Good collisions * KinematicController * Fix aghost * Throwing refactor * Pushing cleanup * Fix throwing and footstep sounds * Frametime in ICollideBehavior * Fix stuff * Actually fix weightlessness * Optimise collision behaviors a lot * Make open lockers still collide with walls * powwweeerrrrr * Merge master proper * AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA * AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA * AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA * Ch ch ch changesss * SHIP IT * Fix #if DEBUG * Fix vaulting and item locker collision * Fix throwing * Editing yaml by hand what can go wrong * on * Last yaml fixes * Okay now it's fixed * Linter Co-authored-by: Metal Gear Sloth <metalgearsloth@gmail.com> Co-authored-by: Vera Aguilera Puerto <zddm@outlook.es>
2021-03-08 04:09:59 +11:00
[RegisterComponent]
[ComponentReference(typeof(IMoverComponent))]
[NetworkedComponent()]
public sealed class SharedPlayerInputMoverComponent : Component, IMoverComponent
2020-06-24 02:21:20 +02:00
{
// This class has to be able to handle server TPS being lower than client FPS.
// While still having perfectly responsive movement client side.
// We do this by keeping track of the exact sub-tick values that inputs are pressed on the client,
// and then building a total movement vector based on those sub-tick steps.
//
// We keep track of the last sub-tick a movement input came in,
// Then when a new input comes in, we calculate the fraction of the tick the LAST input was active for
// (new sub-tick - last sub-tick)
// and then add to the total-this-tick movement vector
// by multiplying that fraction by the movement direction for the last input.
// This allows us to incrementally build the movement vector for the current tick,
// without having to keep track of some kind of list of inputs and calculating it later.
//
// We have to keep track of a separate movement vector for walking and sprinting,
// since we don't actually know our current movement speed while processing inputs.
// We change which vector we write into based on whether we were sprinting after the previous input.
// (well maybe we do but the code is designed such that MoverSystem applies movement speed)
// (and I'm not changing that)
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
2022-01-15 03:26:37 +01:00
[Dependency] private readonly IEntityManager _entityManager = default!;
2020-06-24 02:21:20 +02:00
private GameTick _lastInputTick;
private ushort _lastInputSubTick;
private Vector2 _curTickWalkMovement;
private Vector2 _curTickSprintMovement;
private MoveButtons _heldMoveButtons = MoveButtons.None;
[ViewVariables]
public Angle LastGridAngle { get; set; } = new(0);
2022-01-15 03:26:37 +01:00
public float CurrentWalkSpeed =>
_entityManager.TryGetComponent<MovementSpeedModifierComponent>(Owner,
out var movementSpeedModifierComponent)
? movementSpeedModifierComponent.CurrentWalkSpeed
: MovementSpeedModifierComponent.DefaultBaseWalkSpeed;
2020-06-24 02:21:20 +02:00
2022-01-15 03:26:37 +01:00
public float CurrentSprintSpeed =>
_entityManager.TryGetComponent<MovementSpeedModifierComponent>(Owner,
out var movementSpeedModifierComponent)
? movementSpeedModifierComponent.CurrentSprintSpeed
: MovementSpeedModifierComponent.DefaultBaseSprintSpeed;
2020-06-24 02:21:20 +02:00
public bool Sprinting => !HasFlag(_heldMoveButtons, MoveButtons.Walk);
2020-06-24 02:21:20 +02:00
/// <summary>
/// Calculated linear velocity direction of the entity.
/// </summary>
[ViewVariables]
public (Vector2 walking, Vector2 sprinting) VelocityDir
{
get
{
if (!_gameTiming.InSimulation)
{
// Outside of simulation we'll be running client predicted movement per-frame.
// So return a full-length vector as if it's a full tick.
// Physics system will have the correct time step anyways.
var immediateDir = DirVecForButtons(_heldMoveButtons);
return Sprinting ? (Vector2.Zero, immediateDir) : (immediateDir, Vector2.Zero);
}
Vector2 walk;
Vector2 sprint;
float remainingFraction;
if (_gameTiming.CurTick > _lastInputTick)
{
walk = Vector2.Zero;
sprint = Vector2.Zero;
remainingFraction = 1;
}
else
{
walk = _curTickWalkMovement;
sprint = _curTickSprintMovement;
remainingFraction = (ushort.MaxValue - _lastInputSubTick) / (float) ushort.MaxValue;
}
var curDir = DirVecForButtons(_heldMoveButtons) * remainingFraction;
if (Sprinting)
{
sprint += curDir;
}
else
{
walk += curDir;
}
// Logger.Info($"{curDir}{walk}{sprint}");
return (walk, sprint);
}
}
/// <summary>
/// Whether or not the player can move diagonally.
/// </summary>
[ViewVariables]
public bool DiagonalMovementEnabled => _configurationManager.GetCVar<bool>(CCVars.GameDiagonalMovement);
2020-06-24 02:21:20 +02:00
Physics (#3452) * Content side new physics structure * BroadPhase outline done * But we need to fix WorldAABB * Fix static pvs AABB * Fix import * Rando fixes * B is for balloon * Change human mob hitbox to circle * Decent movement * Start adding friction to player controller I think it's the best way to go about it to keep other objects somewhat consistent for physics. * This baby can fit so many physics bugs in it. * Slight mob mover optimisations. * Player mover kinda works okay. * Beginnings of testbed * More testbed * Circlestack bed * Namespaces * BB fixes * Pull WorldAABB * Joint pulling * Semi-decent movement I guess. * Pulling better * Bullet controller + old movement * im too dumb for this shit * Use kinematic mob controller again It's probably for the best TBH * Stashed shitcode * Remove SlipController * In which movement code is entirely refactored * Singularity fix * Fix ApplyLinearImpulse * MoveRelay fix * Fix door collisions * Disable subfloor collisions Saves on broadphase a fair bit * Re-implement ClimbController * Zumzum's pressure * Laggy item throwing * Minor atmos change * Some caching * Optimise controllers * Optimise CollideWith to hell and back * Re-do throwing and tile friction * Landing too * Optimise controllers * Move CCVars and other stuff swept is beautiful * Cleanup a bunch of controllers * Fix shooting and high pressure movement controller * Flashing improvements * Stuff and things * Combat collisions * Combat mode collisions * Pulling distance joint again * Cleanup physics interfaces * More like scuffedularity * Shit's fucked * Haha tests go green * Bigmoneycrab Co-authored-by: Metal Gear Sloth <metalgearsloth@gmail.com>
2021-03-01 03:11:29 +11:00
/// <inheritdoc />
protected override void Initialize()
Physics (#3452) * Content side new physics structure * BroadPhase outline done * But we need to fix WorldAABB * Fix static pvs AABB * Fix import * Rando fixes * B is for balloon * Change human mob hitbox to circle * Decent movement * Start adding friction to player controller I think it's the best way to go about it to keep other objects somewhat consistent for physics. * This baby can fit so many physics bugs in it. * Slight mob mover optimisations. * Player mover kinda works okay. * Beginnings of testbed * More testbed * Circlestack bed * Namespaces * BB fixes * Pull WorldAABB * Joint pulling * Semi-decent movement I guess. * Pulling better * Bullet controller + old movement * im too dumb for this shit * Use kinematic mob controller again It's probably for the best TBH * Stashed shitcode * Remove SlipController * In which movement code is entirely refactored * Singularity fix * Fix ApplyLinearImpulse * MoveRelay fix * Fix door collisions * Disable subfloor collisions Saves on broadphase a fair bit * Re-implement ClimbController * Zumzum's pressure * Laggy item throwing * Minor atmos change * Some caching * Optimise controllers * Optimise CollideWith to hell and back * Re-do throwing and tile friction * Landing too * Optimise controllers * Move CCVars and other stuff swept is beautiful * Cleanup a bunch of controllers * Fix shooting and high pressure movement controller * Flashing improvements * Stuff and things * Combat collisions * Combat mode collisions * Pulling distance joint again * Cleanup physics interfaces * More like scuffedularity * Shit's fucked * Haha tests go green * Bigmoneycrab Co-authored-by: Metal Gear Sloth <metalgearsloth@gmail.com>
2021-03-01 03:11:29 +11:00
{
Physics (#3485) * Content side new physics structure * BroadPhase outline done * But we need to fix WorldAABB * Fix static pvs AABB * Fix import * Rando fixes * B is for balloon * Change human mob hitbox to circle * Decent movement * Start adding friction to player controller I think it's the best way to go about it to keep other objects somewhat consistent for physics. * This baby can fit so many physics bugs in it. * Slight mob mover optimisations. * Player mover kinda works okay. * Beginnings of testbed * More testbed * Circlestack bed * Namespaces * BB fixes * Pull WorldAABB * Joint pulling * Semi-decent movement I guess. * Pulling better * Bullet controller + old movement * im too dumb for this shit * Use kinematic mob controller again It's probably for the best TBH * Stashed shitcode * Remove SlipController * In which movement code is entirely refactored * Singularity fix * Fix ApplyLinearImpulse * MoveRelay fix * Fix door collisions * Disable subfloor collisions Saves on broadphase a fair bit * Re-implement ClimbController * Zumzum's pressure * Laggy item throwing * Minor atmos change * Some caching * Optimise controllers * Optimise CollideWith to hell and back * Re-do throwing and tile friction * Landing too * Optimise controllers * Move CCVars and other stuff swept is beautiful * Cleanup a bunch of controllers * Fix shooting and high pressure movement controller * Flashing improvements * Stuff and things * Combat collisions * Combat mode collisions * Pulling distance joint again * Cleanup physics interfaces * More like scuffedularity * Shit's fucked * Haha tests go green * Bigmoneycrab * Fix dupe pulling * Zumzum's based fix * Don't run tile friction for non-predicted bodies * Experimental pulling improvement * Everything's a poly now * Optimise AI region debugging a bit Could still be better but should improve default performance a LOT * Mover no updater * Crazy kinematic body idea * Good collisions * KinematicController * Fix aghost * Throwing refactor * Pushing cleanup * Fix throwing and footstep sounds * Frametime in ICollideBehavior * Fix stuff * Actually fix weightlessness * Optimise collision behaviors a lot * Make open lockers still collide with walls * powwweeerrrrr * Merge master proper * AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA * AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA * AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA * Ch ch ch changesss * SHIP IT * Fix #if DEBUG * Fix vaulting and item locker collision * Fix throwing * Editing yaml by hand what can go wrong * on * Last yaml fixes * Okay now it's fixed * Linter Co-authored-by: Metal Gear Sloth <metalgearsloth@gmail.com> Co-authored-by: Vera Aguilera Puerto <zddm@outlook.es>
2021-03-08 04:09:59 +11:00
base.Initialize();
Owner.EnsureComponentWarn<PhysicsComponent>();
2021-12-03 15:53:09 +01:00
LastGridAngle = IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(Owner).Parent?.WorldRotation ?? new Angle(0);
Physics (#3452) * Content side new physics structure * BroadPhase outline done * But we need to fix WorldAABB * Fix static pvs AABB * Fix import * Rando fixes * B is for balloon * Change human mob hitbox to circle * Decent movement * Start adding friction to player controller I think it's the best way to go about it to keep other objects somewhat consistent for physics. * This baby can fit so many physics bugs in it. * Slight mob mover optimisations. * Player mover kinda works okay. * Beginnings of testbed * More testbed * Circlestack bed * Namespaces * BB fixes * Pull WorldAABB * Joint pulling * Semi-decent movement I guess. * Pulling better * Bullet controller + old movement * im too dumb for this shit * Use kinematic mob controller again It's probably for the best TBH * Stashed shitcode * Remove SlipController * In which movement code is entirely refactored * Singularity fix * Fix ApplyLinearImpulse * MoveRelay fix * Fix door collisions * Disable subfloor collisions Saves on broadphase a fair bit * Re-implement ClimbController * Zumzum's pressure * Laggy item throwing * Minor atmos change * Some caching * Optimise controllers * Optimise CollideWith to hell and back * Re-do throwing and tile friction * Landing too * Optimise controllers * Move CCVars and other stuff swept is beautiful * Cleanup a bunch of controllers * Fix shooting and high pressure movement controller * Flashing improvements * Stuff and things * Combat collisions * Combat mode collisions * Pulling distance joint again * Cleanup physics interfaces * More like scuffedularity * Shit's fucked * Haha tests go green * Bigmoneycrab Co-authored-by: Metal Gear Sloth <metalgearsloth@gmail.com>
2021-03-01 03:11:29 +11:00
}
2020-06-24 02:21:20 +02:00
/// <summary>
/// Toggles one of the four cardinal directions. Each of the four directions are
/// composed into a single direction vector, <see cref="VelocityDir"/>. Enabling
/// opposite directions will cancel each other out, resulting in no direction.
/// </summary>
/// <param name="direction">Direction to toggle.</param>
/// <param name="subTick"></param>
/// <param name="enabled">If the direction is active.</param>
public void SetVelocityDirection(Direction direction, ushort subTick, bool enabled)
{
// Logger.Info($"[{_gameTiming.CurTick}/{subTick}] {direction}: {enabled}");
var bit = direction switch
{
Direction.East => MoveButtons.Right,
Direction.North => MoveButtons.Up,
Direction.West => MoveButtons.Left,
Direction.South => MoveButtons.Down,
_ => throw new ArgumentException(nameof(direction))
};
SetMoveInput(subTick, enabled, bit);
}
private void SetMoveInput(ushort subTick, bool enabled, MoveButtons bit)
{
// Modifies held state of a movement button at a certain sub tick and updates current tick movement vectors.
if (_gameTiming.CurTick > _lastInputTick)
{
_curTickWalkMovement = Vector2.Zero;
_curTickSprintMovement = Vector2.Zero;
_lastInputTick = _gameTiming.CurTick;
_lastInputSubTick = 0;
}
2020-07-08 02:59:07 +02:00
if (subTick >= _lastInputSubTick)
2020-07-08 01:28:49 +02:00
{
var fraction = (subTick - _lastInputSubTick) / (float) ushort.MaxValue;
ref var lastMoveAmount = ref Sprinting ? ref _curTickSprintMovement : ref _curTickWalkMovement;
2020-06-24 02:21:20 +02:00
2020-07-08 01:28:49 +02:00
lastMoveAmount += DirVecForButtons(_heldMoveButtons) * fraction;
2020-06-24 02:21:20 +02:00
2020-07-08 01:28:49 +02:00
_lastInputSubTick = subTick;
}
2020-06-24 02:21:20 +02:00
if (enabled)
{
_heldMoveButtons |= bit;
}
else
{
_heldMoveButtons &= ~bit;
}
Dirty();
}
public void SetSprinting(ushort subTick, bool walking)
2020-06-24 02:21:20 +02:00
{
// Logger.Info($"[{_gameTiming.CurTick}/{subTick}] Sprint: {enabled}");
SetMoveInput(subTick, walking, MoveButtons.Walk);
2020-06-24 02:21:20 +02:00
}
public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
{
if (curState is MoverComponentState state)
{
_heldMoveButtons = state.Buttons;
_lastInputTick = GameTick.Zero;
_lastInputSubTick = 0;
}
}
public override ComponentState GetComponentState()
2020-06-24 02:21:20 +02:00
{
return new MoverComponentState(_heldMoveButtons);
}
/// <summary>
/// Retrieves the normalized direction vector for a specified combination of movement keys.
/// </summary>
private Vector2 DirVecForButtons(MoveButtons buttons)
{
// key directions are in screen coordinates
// _moveDir is in world coordinates
// if the camera is moved, this needs to be changed
var x = 0;
x -= HasFlag(buttons, MoveButtons.Left) ? 1 : 0;
x += HasFlag(buttons, MoveButtons.Right) ? 1 : 0;
2020-06-24 02:21:20 +02:00
var y = 0;
if (DiagonalMovementEnabled || x == 0)
{
y -= HasFlag(buttons, MoveButtons.Down) ? 1 : 0;
y += HasFlag(buttons, MoveButtons.Up) ? 1 : 0;
2020-06-24 02:21:20 +02:00
}
var vec = new Vector2(x, y);
// can't normalize zero length vector
if (vec.LengthSquared > 1.0e-6)
{
// Normalize so that diagonals aren't faster or something.
vec = vec.Normalized;
}
return vec;
}
[Serializable, NetSerializable]
private sealed class MoverComponentState : ComponentState
{
public MoveButtons Buttons { get; }
public MoverComponentState(MoveButtons buttons)
2020-06-24 02:21:20 +02:00
{
Buttons = buttons;
}
}
[Flags]
private enum MoveButtons : byte
{
None = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8,
Walk = 16,
2020-06-24 02:21:20 +02:00
}
private static bool HasFlag(MoveButtons buttons, MoveButtons flag)
{
return (buttons & flag) == flag;
}
2020-06-24 02:21:20 +02:00
}
}