Remove CannyFastMath.

This commit is contained in:
Pieter-Jan Briers
2020-08-12 21:09:56 +02:00
parent 3ca3b5e684
commit f182ff5613
15 changed files with 64 additions and 81 deletions

View File

@@ -141,7 +141,7 @@ namespace Content.Client.GameObjects.Components.Weapons
const float xOffset = 0.0f; const float xOffset = 0.0f;
// Overkill but easy to adjust if you want to mess around with the design // Overkill but easy to adjust if you want to mess around with the design
var result = (float) Math.Clamp(slope * (float) Math.Pow(ratio - xOffset, exponent) + yOffset, 0.0, 1.0); var result = (float) FloatMath.Clamp(slope * (float) Math.Pow(ratio - xOffset, exponent) + yOffset, 0.0, 1.0);
DebugTools.Assert(!float.IsNaN(result)); DebugTools.Assert(!float.IsNaN(result));
return result; return result;
} }

View File

@@ -12,9 +12,6 @@ using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.PixelFormats;
using Color = Robust.Shared.Maths.Color; using Color = Robust.Shared.Maths.Color;
using CannyFastMath;
using Math = CannyFastMath.Math;
using MathF = CannyFastMath.MathF;
namespace Content.Client.Parallax namespace Content.Client.Parallax
{ {
@@ -81,7 +78,7 @@ namespace Content.Client.Parallax
private readonly NoiseGenerator.NoiseType NoiseType = NoiseGenerator.NoiseType.Fbm; private readonly NoiseGenerator.NoiseType NoiseType = NoiseGenerator.NoiseType.Fbm;
private readonly uint Seed = 1234; private readonly uint Seed = 1234;
private readonly float Persistence = 0.5f; private readonly float Persistence = 0.5f;
private readonly float Lacunarity = (float) (Math.TAU / 3); private readonly float Lacunarity = (float) (Math.PI / 3);
private readonly float Frequency = 1; private readonly float Frequency = 1;
private readonly uint Octaves = 3; private readonly uint Octaves = 3;
private readonly float Threshold; private readonly float Threshold;

View File

@@ -20,9 +20,6 @@ using Robust.Shared.Localization;
using Robust.Shared.Prototypes; using Robust.Shared.Prototypes;
using Robust.Shared.Timing; using Robust.Shared.Timing;
using Robust.Shared.ViewVariables; using Robust.Shared.ViewVariables;
using CannyFastMath;
using Math = CannyFastMath.Math;
using MathF = CannyFastMath.MathF;
namespace Content.Client.State namespace Content.Client.State
{ {

View File

@@ -6,9 +6,6 @@ using System;
using Robust.Client.Graphics.Shaders; using Robust.Client.Graphics.Shaders;
using Robust.Shared.IoC; using Robust.Shared.IoC;
using Robust.Shared.Prototypes; using Robust.Shared.Prototypes;
using CannyFastMath;
using Math = CannyFastMath.Math;
using MathF = CannyFastMath.MathF;
namespace Robust.Client.UserInterface.Controls namespace Robust.Client.UserInterface.Controls
{ {
@@ -45,7 +42,7 @@ namespace Robust.Client.UserInterface.Controls
} }
else else
{ {
var alpha = MathF.Clamp(0.5f * lerp, 0f, 0.5f); var alpha = FloatMath.Clamp(0.5f * lerp, 0f, 0.5f);
color = new Color(1f, 1f, 1f, alpha); color = new Color(1f, 1f, 1f, alpha);
} }

View File

@@ -2,6 +2,7 @@ using System;
using Content.Server.AI.WorldState; using Content.Server.AI.WorldState;
using Content.Server.AI.WorldState.States.Utility; using Content.Server.AI.WorldState.States.Utility;
using JetBrains.Annotations; using JetBrains.Annotations;
using Robust.Shared.Maths;
namespace Content.Server.AI.Utility.Considerations namespace Content.Server.AI.Utility.Considerations
{ {
@@ -16,7 +17,7 @@ namespace Content.Server.AI.Utility.Considerations
var modificationFactor = 1.0f - 1.0f / considerationsCount; var modificationFactor = 1.0f - 1.0f / considerationsCount;
var makeUpValue = (1.0f - score) * modificationFactor; var makeUpValue = (1.0f - score) * modificationFactor;
var adjustedScore = score + makeUpValue * score; var adjustedScore = score + makeUpValue * score;
return Math.Clamp(adjustedScore, 0.0f, 1.0f); return FloatMath.Clamp(adjustedScore, 0.0f, 1.0f);
} }
[Pure] [Pure]
@@ -43,7 +44,7 @@ namespace Content.Server.AI.Utility.Considerations
// ReSharper disable once CompareOfFloatsByEqualityOperator // ReSharper disable once CompareOfFloatsByEqualityOperator
return x == 1.0f ? 0.0f : 1.0f; return x == 1.0f ? 0.0f : 1.0f;
} }
public Func<float> InverseBoolCurve(Blackboard context) public Func<float> InverseBoolCurve(Blackboard context)
{ {
float Result() float Result()
@@ -58,7 +59,7 @@ namespace Content.Server.AI.Utility.Considerations
[Pure] [Pure]
private static float LogisticCurve(float x, float slope, float exponent, float yOffset, float xOffset) private static float LogisticCurve(float x, float slope, float exponent, float yOffset, float xOffset)
{ {
return Math.Clamp( return FloatMath.Clamp(
exponent * (1 / (1 + (float) Math.Pow(Math.Log(1000) * slope, -1 * x + xOffset))) + yOffset, 0.0f, 1.0f); exponent * (1 / (1 + (float) Math.Pow(Math.Log(1000) * slope, -1 * x + xOffset))) + yOffset, 0.0f, 1.0f);
} }
@@ -76,7 +77,7 @@ namespace Content.Server.AI.Utility.Considerations
[Pure] [Pure]
private static float QuadraticCurve(float x, float slope, float exponent, float yOffset, float xOffset) private static float QuadraticCurve(float x, float slope, float exponent, float yOffset, float xOffset)
{ {
return Math.Clamp(slope * (float) Math.Pow(x - xOffset, exponent) + yOffset, 0.0f, 1.0f); return FloatMath.Clamp(slope * (float) Math.Pow(x - xOffset, exponent) + yOffset, 0.0f, 1.0f);
} }
public Func<float> QuadraticCurve(Blackboard context, float slope, float exponent, float yOffset, float xOffset) public Func<float> QuadraticCurve(Blackboard context, float slope, float exponent, float yOffset, float xOffset)
@@ -102,7 +103,7 @@ namespace Content.Server.AI.Utility.Considerations
float Result() float Result()
{ {
var adjustedScore = GetAdjustedScore(context); var adjustedScore = GetAdjustedScore(context);
switch (preset) switch (preset)
{ {
case Considerations.PresetCurve.Distance: case Considerations.PresetCurve.Distance:

View File

@@ -51,13 +51,13 @@ namespace Content.Server.Atmos
if (maxForce > ThrowForce && throwTarget != GridCoordinates.InvalidGrid) if (maxForce > ThrowForce && throwTarget != GridCoordinates.InvalidGrid)
{ {
var moveForce = MathF.Min(maxForce * Math.Clamp(moveProb, 0, 100) / 100f, 50f); var moveForce = MathF.Min(maxForce * FloatMath.Clamp(moveProb, 0, 100) / 100f, 50f);
var pos = throwTarget.Position - transform.GridPosition.Position; var pos = throwTarget.Position - transform.GridPosition.Position;
LinearVelocity = pos * moveForce; LinearVelocity = pos * moveForce;
} }
else else
{ {
var moveForce = MathF.Min(maxForce * Math.Clamp(moveProb, 0, 100) / 100f, 25f); var moveForce = MathF.Min(maxForce * FloatMath.Clamp(moveProb, 0, 100) / 100f, 25f);
LinearVelocity = direction.ToVec() * moveForce; LinearVelocity = direction.ToVec() * moveForce;
} }

View File

@@ -138,7 +138,7 @@ namespace Content.Server.Atmos
{ {
if(_soundCooldown == 0) if(_soundCooldown == 0)
EntitySystem.Get<AudioSystem>().PlayAtCoords("/Audio/Effects/space_wind.ogg", EntitySystem.Get<AudioSystem>().PlayAtCoords("/Audio/Effects/space_wind.ogg",
GridIndices.ToGridCoordinates(_mapManager, GridIndex), AudioHelpers.WithVariation(0.125f).WithVolume(Math.Clamp(PressureDifference / 10, 10, 100))); GridIndices.ToGridCoordinates(_mapManager, GridIndex), AudioHelpers.WithVariation(0.125f).WithVolume(FloatMath.Clamp(PressureDifference / 10, 10, 100)));
} }
@@ -810,7 +810,7 @@ namespace Content.Server.Atmos
private void HandleDecompressionFloorRip(float sum) private void HandleDecompressionFloorRip(float sum)
{ {
if (sum > 20 && _robustRandom.Prob(Math.Clamp(sum / 100, 0.005f, 0.5f))) if (sum > 20 && _robustRandom.Prob(FloatMath.Clamp(sum / 100, 0.005f, 0.5f)))
_gridAtmosphereComponent.PryTile(GridIndices); _gridAtmosphereComponent.PryTile(GridIndices);
} }

View File

@@ -4,9 +4,6 @@ using Content.Server.GameObjects.Components.Chemistry;
using Content.Shared.Interfaces; using Content.Shared.Interfaces;
using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Serialization; using Robust.Shared.Serialization;
using CannyFastMath;
using Math = CannyFastMath.Math;
using MathF = CannyFastMath.MathF;
namespace Content.Server.Chemistry.ReactionEffects namespace Content.Server.Chemistry.ReactionEffects
{ {

View File

@@ -1,6 +1,6 @@
using Content.Shared.GameObjects.Components.Inventory; using System;
using Content.Shared.GameObjects.Components.Inventory;
using Robust.Shared.GameObjects; using Robust.Shared.GameObjects;
using Math = CannyFastMath.Math;
namespace Content.Server.GameObjects namespace Content.Server.GameObjects
{ {

View File

@@ -15,10 +15,7 @@ using Robust.Shared.IoC;
using Robust.Shared.Maths; using Robust.Shared.Maths;
using Robust.Shared.Serialization; using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables; using Robust.Shared.ViewVariables;
using CannyFastMath;
using Content.Shared.Interfaces.GameObjects.Components; using Content.Shared.Interfaces.GameObjects.Components;
using Math = CannyFastMath.Math;
using MathF = CannyFastMath.MathF;
namespace Content.Server.GameObjects.Components.Weapon.Melee namespace Content.Server.GameObjects.Components.Weapon.Melee
{ {

View File

@@ -180,7 +180,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels
{ {
var currentTime = _gameTiming.CurTime; var currentTime = _gameTiming.CurTime;
var timeSinceLastFire = (currentTime - _lastFire).TotalSeconds; var timeSinceLastFire = (currentTime - _lastFire).TotalSeconds;
var newTheta = Math.Clamp(_currentAngle.Theta + _angleIncrease - _angleDecay * timeSinceLastFire, _minAngle.Theta, _maxAngle.Theta); var newTheta = FloatMath.Clamp(_currentAngle.Theta + _angleIncrease - _angleDecay * timeSinceLastFire, _minAngle.Theta, _maxAngle.Theta);
_currentAngle = new Angle(newTheta); _currentAngle = new Angle(newTheta);
var random = (_robustRandom.NextDouble() - 0.5) * 2; var random = (_robustRandom.NextDouble() - 0.5) * 2;

View File

@@ -27,7 +27,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
public sealed class AiSteeringSystem : EntitySystem public sealed class AiSteeringSystem : EntitySystem
{ {
// http://www.red3d.com/cwr/papers/1999/gdc99steer.html for a steering overview // http://www.red3d.com/cwr/papers/1999/gdc99steer.html for a steering overview
#pragma warning disable 649 #pragma warning disable 649
[Dependency] private IMapManager _mapManager; [Dependency] private IMapManager _mapManager;
[Dependency] private IEntityManager _entityManager; [Dependency] private IEntityManager _entityManager;
@@ -45,9 +45,9 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
/// How close we need to get to the center of each tile /// How close we need to get to the center of each tile
/// </summary> /// </summary>
private const float TileTolerance = 0.8f; private const float TileTolerance = 0.8f;
private Dictionary<IEntity, IAiSteeringRequest> RunningAgents => _agentLists[_listIndex]; private Dictionary<IEntity, IAiSteeringRequest> RunningAgents => _agentLists[_listIndex];
// We'll cycle the running list every tick as all we're doing is getting a vector2 for the // We'll cycle the running list every tick as all we're doing is getting a vector2 for the
// agent's steering. Should help a lot given this is the most expensive operator by far. // agent's steering. Should help a lot given this is the most expensive operator by far.
// The AI will keep moving, it's just it'll keep moving in its existing direction. // The AI will keep moving, it's just it'll keep moving in its existing direction.
@@ -55,31 +55,31 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
private readonly List<Dictionary<IEntity, IAiSteeringRequest>> _agentLists = new List<Dictionary<IEntity, IAiSteeringRequest>>(AgentListCount); private readonly List<Dictionary<IEntity, IAiSteeringRequest>> _agentLists = new List<Dictionary<IEntity, IAiSteeringRequest>>(AgentListCount);
private const int AgentListCount = 2; private const int AgentListCount = 2;
private int _listIndex; private int _listIndex;
// Cache nextGrid // Cache nextGrid
private readonly Dictionary<IEntity, GridCoordinates> _nextGrid = new Dictionary<IEntity, GridCoordinates>(); private readonly Dictionary<IEntity, GridCoordinates> _nextGrid = new Dictionary<IEntity, GridCoordinates>();
/// <summary> /// <summary>
/// Current live paths for AI /// Current live paths for AI
/// </summary> /// </summary>
private readonly Dictionary<IEntity, Queue<TileRef>> _paths = new Dictionary<IEntity, Queue<TileRef>>(); private readonly Dictionary<IEntity, Queue<TileRef>> _paths = new Dictionary<IEntity, Queue<TileRef>>();
/// <summary> /// <summary>
/// Pathfinding request jobs we're waiting on /// Pathfinding request jobs we're waiting on
/// </summary> /// </summary>
private readonly Dictionary<IEntity, (CancellationTokenSource CancelToken, Job<Queue<TileRef>> Job)> _pathfindingRequests = private readonly Dictionary<IEntity, (CancellationTokenSource CancelToken, Job<Queue<TileRef>> Job)> _pathfindingRequests =
new Dictionary<IEntity, (CancellationTokenSource, Job<Queue<TileRef>>)>(); new Dictionary<IEntity, (CancellationTokenSource, Job<Queue<TileRef>>)>();
/// <summary> /// <summary>
/// Keep track of how long we've been in 1 position and re-path if it's been too long /// Keep track of how long we've been in 1 position and re-path if it's been too long
/// </summary> /// </summary>
private readonly Dictionary<IEntity, int> _stuckCounter = new Dictionary<IEntity, int>(); private readonly Dictionary<IEntity, int> _stuckCounter = new Dictionary<IEntity, int>();
/// <summary> /// <summary>
/// Get a fixed position for the target entity; if they move then re-path /// Get a fixed position for the target entity; if they move then re-path
/// </summary> /// </summary>
private readonly Dictionary<IEntity, GridCoordinates> _entityTargetPosition = new Dictionary<IEntity, GridCoordinates>(); private readonly Dictionary<IEntity, GridCoordinates> _entityTargetPosition = new Dictionary<IEntity, GridCoordinates>();
// Anti-Stuck // Anti-Stuck
// Given the collision avoidance can lead to twitching need to store a reference position and check if we've been near this too long // Given the collision avoidance can lead to twitching need to store a reference position and check if we've been near this too long
private readonly Dictionary<IEntity, GridCoordinates> _stuckPositions = new Dictionary<IEntity, GridCoordinates>(); private readonly Dictionary<IEntity, GridCoordinates> _stuckPositions = new Dictionary<IEntity, GridCoordinates>();
@@ -88,7 +88,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
base.Initialize(); base.Initialize();
_pathfindingSystem = Get<PathfindingSystem>(); _pathfindingSystem = Get<PathfindingSystem>();
for (var i = 0; i < AgentListCount; i++) for (var i = 0; i < AgentListCount; i++)
{ {
_agentLists.Add(new Dictionary<IEntity, IAiSteeringRequest>()); _agentLists.Add(new Dictionary<IEntity, IAiSteeringRequest>());
@@ -111,14 +111,14 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
var agentList = _agentLists[i]; var agentList = _agentLists[i];
// Register shouldn't be called twice; if it is then someone dun fucked up // Register shouldn't be called twice; if it is then someone dun fucked up
DebugTools.Assert(!agentList.ContainsKey(entity)); DebugTools.Assert(!agentList.ContainsKey(entity));
if (agentList.Count < lowestListCount) if (agentList.Count < lowestListCount)
{ {
lowestListCount = agentList.Count; lowestListCount = agentList.Count;
lowestListIndex = i; lowestListIndex = i;
} }
} }
_agentLists[lowestListIndex].Add(entity, steeringRequest); _agentLists[lowestListIndex].Add(entity, steeringRequest);
} }
@@ -133,7 +133,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
} }
if (_pathfindingRequests.TryGetValue(entity, out var request)) if (_pathfindingRequests.TryGetValue(entity, out var request))
{ {
switch (request.Job.Status) switch (request.Job.Status)
@@ -157,7 +157,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
} }
_pathfindingRequests.Remove(entity); _pathfindingRequests.Remove(entity);
} }
if (_paths.ContainsKey(entity)) if (_paths.ContainsKey(entity))
{ {
_paths.Remove(entity); _paths.Remove(entity);
@@ -177,7 +177,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
_entityTargetPosition.Remove(entity); _entityTargetPosition.Remove(entity);
} }
foreach (var agentList in _agentLists) foreach (var agentList in _agentLists)
{ {
if (agentList.ContainsKey(entity)) if (agentList.ContainsKey(entity))
@@ -214,7 +214,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
var result = Steer(agent, steering); var result = Steer(agent, steering);
steering.Status = result; steering.Status = result;
switch (result) switch (result)
{ {
case SteeringStatus.Pending: case SteeringStatus.Pending:
@@ -255,7 +255,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.Pending; return SteeringStatus.Pending;
} }
// Validation // Validation
// Check if we can even arrive -> Currently only samegrid movement supported // Check if we can even arrive -> Currently only samegrid movement supported
if (entity.Transform.GridID != steeringRequest.TargetGrid.GridID) if (entity.Transform.GridID != steeringRequest.TargetGrid.GridID)
@@ -263,7 +263,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath; return SteeringStatus.NoPath;
} }
// Check if we have arrived // Check if we have arrived
var targetDistance = (entity.Transform.MapPosition.Position - steeringRequest.TargetMap.Position).Length; var targetDistance = (entity.Transform.MapPosition.Position - steeringRequest.TargetMap.Position).Length;
if (targetDistance <= steeringRequest.ArrivalDistance) if (targetDistance <= steeringRequest.ArrivalDistance)
@@ -274,7 +274,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.Arrived; return SteeringStatus.Arrived;
} }
// Handle pathfinding job // Handle pathfinding job
// If we still have an existing path then keep following that until the new path arrives // If we still have an existing path then keep following that until the new path arrives
if (_pathfindingRequests.TryGetValue(entity, out var pathRequest) && pathRequest.Job.Status == JobStatus.Finished) if (_pathfindingRequests.TryGetValue(entity, out var pathRequest) && pathRequest.Job.Status == JobStatus.Finished)
@@ -297,7 +297,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath; return SteeringStatus.NoPath;
} }
// If we're closer to next tile then we don't want to walk backwards to our tile's center // If we're closer to next tile then we don't want to walk backwards to our tile's center
UpdatePath(entity, path); UpdatePath(entity, path);
@@ -319,7 +319,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
RequestPath(entity, steeringRequest); RequestPath(entity, steeringRequest);
return SteeringStatus.Pending; return SteeringStatus.Pending;
} }
var ignoredCollision = new List<IEntity>(); var ignoredCollision = new List<IEntity>();
// Check if the target entity has moved - If so then re-path // Check if the target entity has moved - If so then re-path
// TODO: Patch the path from the target's position back towards us, stopping if it ever intersects the current path // TODO: Patch the path from the target's position back towards us, stopping if it ever intersects the current path
@@ -331,19 +331,19 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath; return SteeringStatus.NoPath;
} }
// Check if target's moved too far // Check if target's moved too far
if (_entityTargetPosition.TryGetValue(entity, out var targetGrid) && (entitySteer.TargetGrid.Position - targetGrid.Position).Length >= entitySteer.TargetMaxMove) if (_entityTargetPosition.TryGetValue(entity, out var targetGrid) && (entitySteer.TargetGrid.Position - targetGrid.Position).Length >= entitySteer.TargetMaxMove)
{ {
// We'll just repath and keep following the existing one until we get a new one // We'll just repath and keep following the existing one until we get a new one
RequestPath(entity, steeringRequest); RequestPath(entity, steeringRequest);
} }
ignoredCollision.Add(entitySteer.Target); ignoredCollision.Add(entitySteer.Target);
} }
HandleStuck(entity); HandleStuck(entity);
// TODO: Probably need a dedicated queuing solver (doorway congestion FML) // TODO: Probably need a dedicated queuing solver (doorway congestion FML)
// Get the target grid (either next tile or target itself) and pass it in to the steering behaviors // Get the target grid (either next tile or target itself) and pass it in to the steering behaviors
// If there's nowhere to go then just stop and wait // If there's nowhere to go then just stop and wait
@@ -353,14 +353,14 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath; return SteeringStatus.NoPath;
} }
// Validate that we can even get to the next grid (could probably just check if we can use nextTile if we're not near the target grid) // Validate that we can even get to the next grid (could probably just check if we can use nextTile if we're not near the target grid)
if (!_pathfindingSystem.CanTraverse(entity, nextGrid.Value)) if (!_pathfindingSystem.CanTraverse(entity, nextGrid.Value))
{ {
controller.VelocityDir = Vector2.Zero; controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath; return SteeringStatus.NoPath;
} }
// Now we can /finally/ move // Now we can /finally/ move
var movementVector = Vector2.Zero; var movementVector = Vector2.Zero;
@@ -370,10 +370,10 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
movementVector += Seek(entity, nextGrid.Value); movementVector += Seek(entity, nextGrid.Value);
if (CollisionAvoidanceEnabled) if (CollisionAvoidanceEnabled)
{ {
movementVector += CollisionAvoidance(entity, movementVector, ignoredCollision); movementVector += CollisionAvoidance(entity, movementVector, ignoredCollision);
} }
// Group behaviors would also go here e.g. separation, cohesion, alignment // Group behaviors would also go here e.g. separation, cohesion, alignment
// Move towards it // Move towards it
DebugTools.Assert(movementVector != new Vector2(float.NaN, float.NaN)); DebugTools.Assert(movementVector != new Vector2(float.NaN, float.NaN));
controller.VelocityDir = movementVector.Normalized; controller.VelocityDir = movementVector.Normalized;
@@ -391,7 +391,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
return; return;
} }
var cancelToken = new CancellationTokenSource(); var cancelToken = new CancellationTokenSource();
var gridManager = _mapManager.GetGrid(entity.Transform.GridID); var gridManager = _mapManager.GetGrid(entity.Transform.GridID);
var startTile = gridManager.GetTileRef(entity.Transform.GridPosition); var startTile = gridManager.GetTileRef(entity.Transform.GridPosition);
@@ -403,7 +403,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
} }
var access = AccessReader.FindAccessTags(entity); var access = AccessReader.FindAccessTags(entity);
var job = _pathfindingSystem.RequestPath(new PathfindingArgs( var job = _pathfindingSystem.RequestPath(new PathfindingArgs(
entity.Uid, entity.Uid,
access, access,
@@ -423,11 +423,11 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
private void UpdatePath(IEntity entity, Queue<TileRef> path) private void UpdatePath(IEntity entity, Queue<TileRef> path)
{ {
_pathfindingRequests.Remove(entity); _pathfindingRequests.Remove(entity);
var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.GridPosition); var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.GridPosition);
var tile = path.Dequeue(); var tile = path.Dequeue();
var closestDistance = PathfindingHelpers.OctileDistance(entityTile, tile); var closestDistance = PathfindingHelpers.OctileDistance(entityTile, tile);
for (var i = 0; i < path.Count; i++) for (var i = 0; i < path.Count; i++)
{ {
tile = path.Peek(); tile = path.Peek();
@@ -441,7 +441,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
break; break;
} }
} }
_paths[entity] = path; _paths[entity] = path;
} }
@@ -458,20 +458,20 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
_nextGrid.Remove(entity); _nextGrid.Remove(entity);
} }
// If no tiles left just move towards the target (if we're close) // If no tiles left just move towards the target (if we're close)
if (!_paths.ContainsKey(entity) || _paths[entity].Count == 0) if (!_paths.ContainsKey(entity) || _paths[entity].Count == 0)
{ {
if ((steeringRequest.TargetGrid.Position - entity.Transform.GridPosition.Position).Length <= 2.0f) if ((steeringRequest.TargetGrid.Position - entity.Transform.GridPosition.Position).Length <= 2.0f)
{ {
return steeringRequest.TargetGrid; return steeringRequest.TargetGrid;
} }
// Too far so we need a re-path // Too far so we need a re-path
return null; return null;
} }
if (!_nextGrid.TryGetValue(entity, out var nextGrid) || if (!_nextGrid.TryGetValue(entity, out var nextGrid) ||
(nextGrid.Position - entity.Transform.GridPosition.Position).Length <= TileTolerance) (nextGrid.Position - entity.Transform.GridPosition.Position).Length <= TileTolerance)
{ {
UpdateGridCache(entity); UpdateGridCache(entity);
@@ -526,7 +526,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
return; return;
} }
// Okay now we're stuck // Okay now we're stuck
_paths.Remove(entity); _paths.Remove(entity);
_stuckCounter[entity] = 0; _stuckCounter[entity] = 0;
@@ -580,7 +580,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
return Vector2.Zero; return Vector2.Zero;
} }
if (target.TryGetComponent(out IPhysicsComponent physicsComponent)) if (target.TryGetComponent(out IPhysicsComponent physicsComponent))
{ {
var targetDistance = (targetPos.Position - entityPos.Position); var targetDistance = (targetPos.Position - entityPos.Position);
@@ -603,7 +603,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{ {
return Vector2.Zero; return Vector2.Zero;
} }
// We'll check tile-by-tile // We'll check tile-by-tile
// Rewriting this frequently so not many comments as they'll go stale // Rewriting this frequently so not many comments as they'll go stale
// I realise this is bad so please rewrite it ;-; // I realise this is bad so please rewrite it ;-;
@@ -636,7 +636,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
//Pathfinding updates are deferred so this may not be done yet. //Pathfinding updates are deferred so this may not be done yet.
if (physicsEntity.Deleted) continue; if (physicsEntity.Deleted) continue;
// if we're moving in the same direction then ignore // if we're moving in the same direction then ignore
// So if 2 entities are moving towards each other and both detect a collision they'll both move in the same direction // So if 2 entities are moving towards each other and both detect a collision they'll both move in the same direction
// i.e. towards the right // i.e. towards the right
@@ -650,7 +650,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering
var additionalVector = (centerGrid.Position - entityGridCoords.Position); var additionalVector = (centerGrid.Position - entityGridCoords.Position);
var distance = additionalVector.Length; var distance = additionalVector.Length;
// If we're too far no point, if we're close then cap it at the normalized vector // If we're too far no point, if we're close then cap it at the normalized vector
distance = Math.Clamp(2.5f - distance, 0.0f, 1.0f); distance = FloatMath.Clamp(2.5f - distance, 0.0f, 1.0f);
additionalVector = new Angle(90 * distance).RotateVec(additionalVector); additionalVector = new Angle(90 * distance).RotateVec(additionalVector);
avoidanceVector += additionalVector; avoidanceVector += additionalVector;
// if we do need to avoid that means we'll have to lookahead for the next tile // if we do need to avoid that means we'll have to lookahead for the next tile

View File

@@ -12,9 +12,6 @@ using Robust.Shared.IoC;
using Robust.Shared.Maths; using Robust.Shared.Maths;
using System; using System;
using System.Linq; using System.Linq;
using CannyFastMath;
using Math = CannyFastMath.Math;
using MathF = CannyFastMath.MathF;
namespace Content.Server.Interfaces.GameObjects.Components.Interaction namespace Content.Server.Interfaces.GameObjects.Components.Interaction
{ {
@@ -80,7 +77,7 @@ namespace Content.Server.Interfaces.GameObjects.Components.Interaction
{ {
EntityQuery = new TypeEntityQuery(typeof(SolarPanelComponent)); EntityQuery = new TypeEntityQuery(typeof(SolarPanelComponent));
// Initialize the sun to something random // Initialize the sun to something random
TowardsSun = Math.TAU * _robustRandom.NextDouble(); TowardsSun = MathHelper.TwoPi * _robustRandom.NextDouble();
SunAngularVelocity = Angle.FromDegrees(0.1 + ((_robustRandom.NextDouble() - 0.5) * 0.05)); SunAngularVelocity = Angle.FromDegrees(0.1 + ((_robustRandom.NextDouble() - 0.5) * 0.05));
} }

View File

@@ -16,7 +16,7 @@ using System.Linq;
using Robust.Shared.Log; using Robust.Shared.Log;
using System.Threading.Tasks; using System.Threading.Tasks;
using Content.Shared.Preferences; using Content.Shared.Preferences;
using Robust.Shared.Maths;
namespace Content.Server.GameTicking.GamePresets namespace Content.Server.GameTicking.GamePresets
@@ -60,7 +60,7 @@ namespace Content.Server.GameTicking.GamePresets
} }
} }
var numTraitors = Math.Clamp(readyPlayers.Count % PlayersPerTraitor, var numTraitors = FloatMath.Clamp(readyPlayers.Count % PlayersPerTraitor,
MinTraitors, readyPlayers.Count); MinTraitors, readyPlayers.Count);
for (var i = 0; i < numTraitors; i++) for (var i = 0; i < numTraitors; i++)

View File

@@ -1,4 +1,5 @@
using Content.Server.GameObjects.Components; using System;
using Content.Server.GameObjects.Components;
using Content.Shared.GameObjects.EntitySystems; using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.Physics; using Content.Shared.Physics;
using Robust.Shared.GameObjects.Components; using Robust.Shared.GameObjects.Components;
@@ -12,7 +13,6 @@ using Robust.Shared.Maths;
using Robust.Shared.Physics; using Robust.Shared.Physics;
using Robust.Shared.Random; using Robust.Shared.Random;
using Robust.Shared.Interfaces.Physics; using Robust.Shared.Interfaces.Physics;
using MathF = CannyFastMath.MathF;
namespace Content.Server.Throw namespace Content.Server.Throw
{ {