Skip to content

Commit

Permalink
Support for new flatbuffers spec
Browse files Browse the repository at this point in the history
Small rewrite to `FlatBufferSession.cs` for safety & more async
  • Loading branch information
VirxEC committed Jul 10, 2024
1 parent d5aacaa commit 4fa1499
Show file tree
Hide file tree
Showing 16 changed files with 250 additions and 169 deletions.
13 changes: 12 additions & 1 deletion RLBotCS/Conversion/FlatToCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ private static string MapMaxScore(MaxScore maxScore) =>
_ => throw new ArgumentOutOfRangeException(nameof(maxScore), maxScore, null)
};

private static string MapMultiBall(MultiBall multiBall) =>
multiBall switch
{
MultiBall.One => "",
MultiBall.Two => "TwoBalls",
MultiBall.Four => "FourBalls",
MultiBall.Six => "SixBalls",
_ => throw new ArgumentOutOfRangeException(nameof(multiBall), multiBall, null)
};

private static string MapOvertime(OvertimeOption option) =>
option switch
{
Expand Down Expand Up @@ -186,7 +196,7 @@ private static string MapRespawnTime(RespawnTimeOption option) =>
{
RespawnTimeOption.Three_Seconds => "",
RespawnTimeOption.Two_Seconds => "TwoSecondsRespawn",
RespawnTimeOption.One_Seconds => "OneSecondsRespawn",
RespawnTimeOption.One_Second => "OneSecondsRespawn",
RespawnTimeOption.Disable_Goal_Reset => "DisableGoalDelay",
_ => throw new ArgumentOutOfRangeException(nameof(option), option, null)
};
Expand Down Expand Up @@ -233,6 +243,7 @@ public static string MakeOpenCommand(MatchSettingsT matchSettings)
// Parse mutator settings
command += GetOption(MapMatchLength(mutatorSettings.MatchLength));
command += GetOption(MapMaxScore(mutatorSettings.MaxScore));
command += GetOption(MapMultiBall(mutatorSettings.MultiBall));
command += GetOption(MapOvertime(mutatorSettings.OvertimeOption));
command += GetOption(MapSeriesLength(mutatorSettings.SeriesLengthOption));
command += GetOption(MapGameSpeed(mutatorSettings.GameSpeedOption));
Expand Down
8 changes: 6 additions & 2 deletions RLBotCS/Conversion/FlatToModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ GameState gameState
Local = ToVectorFromT(local)
}
),
rlbot.flat.BallAnchorT { Local: var local }
=> new RelativeAnchor() { ActorId = gameState.Ball.ActorId, Local = ToVectorFromT(local) },
rlbot.flat.BallAnchorT { Index: var index, Local: var local }
=> new RelativeAnchor()
{
ActorId = gameState.GetBallActorIdFromIndex(index),
Local = ToVectorFromT(local)
},
_ => new RelativeAnchor(),
};

Expand Down
183 changes: 105 additions & 78 deletions RLBotCS/Conversion/GameStateToFlat.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Bridge.Models.Message;
using Bridge.Packet;
using Bridge.State;
using Google.FlatBuffers;
using rlbot.flat;
Expand Down Expand Up @@ -26,57 +27,74 @@ private static RotatorT ToRotatorT(this Bridge.Models.Phys.Rotator vec) =>
Roll = vec.Roll
};

public static TypedPayload ToFlatBuffers(this GameState gameState, FlatBufferBuilder builder)
internal static ushort GetBallActorIdFromIndex(this GameState gameState, uint index)
{
// Create the ball info
PhysicsT ballPhysics =
new()
{
Location = gameState.Ball.Physics.Location.ToVector3T(),
Rotation = gameState.Ball.Physics.Rotation.ToRotatorT(),
Velocity = gameState.Ball.Physics.Velocity.ToVector3T(),
AngularVelocity = gameState.Ball.Physics.AngularVelocity.ToVector3T()
};

TouchT lastTouch =
new()
{
PlayerName = gameState.Ball.LatestTouch.PlayerName,
PlayerIndex = gameState.Ball.LatestTouch.PlayerIndex,
Team = gameState.Ball.LatestTouch.Team,
GameSeconds = gameState.Ball.LatestTouch.TimeSeconds,
Location = gameState.Ball.LatestTouch.HitLocation.ToVector3T(),
Normal = gameState.Ball.LatestTouch.HitNormal.ToVector3T()
};
try
{
return gameState.Balls.ElementAt((int)index).Key;
}
catch (ArgumentOutOfRangeException)
{
return 0;
}
}

CollisionShapeUnion collisionShape = gameState.Ball.Shape switch
public static TypedPayload ToFlatBuffers(this GameState gameState, FlatBufferBuilder builder)
{
List<BallInfoT> balls = new(gameState.Balls.Count);
foreach (var ball in gameState.Balls.Values)
{
ICollisionShape.Box boxShape
=> CollisionShapeUnion.FromBoxShape(
new()
{
Length = boxShape.Length,
Width = boxShape.Width,
Height = boxShape.Height
}
),
ICollisionShape.Sphere sphereShape
=> CollisionShapeUnion.FromSphereShape(new() { Diameter = sphereShape.Diameter }),
ICollisionShape.Cylinder cylinderShape
=> CollisionShapeUnion.FromCylinderShape(
new() { Diameter = cylinderShape.Diameter, Height = cylinderShape.Height }
),
_ => CollisionShapeUnion.FromSphereShape(new SphereShapeT { Diameter = 91.25f * 2 })
};
// Create the ball info
PhysicsT ballPhysics =
new()
{
Location = ball.Physics.Location.ToVector3T(),
Rotation = ball.Physics.Rotation.ToRotatorT(),
Velocity = ball.Physics.Velocity.ToVector3T(),
AngularVelocity = ball.Physics.AngularVelocity.ToVector3T()
};

BallInfoT ballInfo =
new()
TouchT lastTouch =
new()
{
PlayerName = ball.LatestTouch.PlayerName,
PlayerIndex = ball.LatestTouch.PlayerIndex,
Team = ball.LatestTouch.Team,
GameSeconds = ball.LatestTouch.TimeSeconds,
Location = ball.LatestTouch.HitLocation.ToVector3T(),
Normal = ball.LatestTouch.HitNormal.ToVector3T()
};

CollisionShapeUnion collisionShape = ball.Shape switch
{
Physics = ballPhysics,
LatestTouch = lastTouch,
Shape = collisionShape
ICollisionShape.Box boxShape
=> CollisionShapeUnion.FromBoxShape(
new()
{
Length = boxShape.Length,
Width = boxShape.Width,
Height = boxShape.Height
}
),
ICollisionShape.Sphere sphereShape
=> CollisionShapeUnion.FromSphereShape(new() { Diameter = sphereShape.Diameter }),
ICollisionShape.Cylinder cylinderShape
=> CollisionShapeUnion.FromCylinderShape(
new() { Diameter = cylinderShape.Diameter, Height = cylinderShape.Height }
),
_ => CollisionShapeUnion.FromSphereShape(new SphereShapeT { Diameter = 91.25f * 2 })
};

balls.Add(
new()
{
Physics = ballPhysics,
LatestTouch = lastTouch,
Shape = collisionShape
}
);
}

rlbot.flat.GameStateType gameStateType = gameState.GameStateType switch
{
GameStateType.Inactive => rlbot.flat.GameStateType.Inactive,
Expand Down Expand Up @@ -110,19 +128,15 @@ ICollisionShape.Cylinder cylinderShape
];

List<BoostPadStateT> boostStates = gameState
.GameBoosts.Select(boost => new BoostPadStateT { IsActive = boost.IsActive, Timer = boost.Timer })
.BoostPads.Values.Select(
boost => new BoostPadStateT { IsActive = boost.IsActive, Timer = boost.Timer }
)
.ToList();

List<PlayerInfoT> players = [];
for (uint i = 0; i < (uint)gameState.GameCars.Count; i++)
List<PlayerInfoT> players = new(gameState.GameCars.Count);
foreach (var car in gameState.GameCars.Values)
{
if (!gameState.GameCars.ContainsKey(i))
// Often, at the start of a match,
// not all the car data will be present.
// Just skip appending players for now.
break;

var airState = gameState.GameCars[i].CarState switch
var airState = car.CarState switch
{
CarState.OnGround => AirState.OnGround,
CarState.Jumping => AirState.Jumping,
Expand All @@ -137,44 +151,57 @@ ICollisionShape.Cylinder cylinderShape
{
Physics = new()
{
Location = gameState.GameCars[i].Physics.Location.ToVector3T(),
Rotation = gameState.GameCars[i].Physics.Rotation.ToRotatorT(),
Velocity = gameState.GameCars[i].Physics.Velocity.ToVector3T(),
AngularVelocity = gameState.GameCars[i].Physics.AngularVelocity.ToVector3T()
Location = car.Physics.Location.ToVector3T(),
Rotation = car.Physics.Rotation.ToRotatorT(),
Velocity = car.Physics.Velocity.ToVector3T(),
AngularVelocity = car.Physics.AngularVelocity.ToVector3T()
},
AirState = airState,
DodgeTimeout = gameState.GameCars[i].DodgeTimeout,
DemolishedTimeout = gameState.GameCars[i].DemolishedTimeout,
IsSupersonic = gameState.GameCars[i].IsSuperSonic,
IsBot = gameState.GameCars[i].IsBot,
Name = gameState.GameCars[i].Name,
Team = gameState.GameCars[i].Team,
Boost = (uint)Math.Floor(gameState.GameCars[i].Boost),
SpawnId = gameState.GameCars[i].SpawnId,
DodgeTimeout = car.DodgeTimeout,
DemolishedTimeout = car.DemolishedTimeout,
IsSupersonic = car.IsSuperSonic,
IsBot = car.IsBot,
Name = car.Name,
Team = car.Team,
Boost = (uint)Math.Floor(car.Boost),
SpawnId = car.SpawnId,
ScoreInfo = new()
{
Score = gameState.GameCars[i].ScoreInfo.Score,
Goals = gameState.GameCars[i].ScoreInfo.Goals,
OwnGoals = gameState.GameCars[i].ScoreInfo.OwnGoals,
Assists = gameState.GameCars[i].ScoreInfo.Assists,
Saves = gameState.GameCars[i].ScoreInfo.Saves,
Shots = gameState.GameCars[i].ScoreInfo.Shots,
Demolitions = gameState.GameCars[i].ScoreInfo.Demolitions
Score = car.ScoreInfo.Score,
Goals = car.ScoreInfo.Goals,
OwnGoals = car.ScoreInfo.OwnGoals,
Assists = car.ScoreInfo.Assists,
Saves = car.ScoreInfo.Saves,
Shots = car.ScoreInfo.Shots,
Demolitions = car.ScoreInfo.Demolitions
},
Hitbox = new()
{
Length = gameState.GameCars[i].Hitbox.Length,
Width = gameState.GameCars[i].Hitbox.Width,
Height = gameState.GameCars[i].Hitbox.Height
Length = car.Hitbox.Length,
Width = car.Hitbox.Width,
Height = car.Hitbox.Height
},
HitboxOffset = car.HitboxOffset.ToVector3T(),
Accolades = car.Accolades,
LastInput = new()
{
Throttle = car.LastInput.Throttle,
Steer = car.LastInput.Steer,
Pitch = car.LastInput.Pitch,
Yaw = car.LastInput.Yaw,
Roll = car.LastInput.Roll,
Jump = car.LastInput.Jump,
Boost = car.LastInput.Boost,
Handbrake = car.LastInput.Handbrake
},
HitboxOffset = gameState.GameCars[i].HitboxOffset.ToVector3T()
LastSpectated = car.LastSpectated,
}
);
}

var gameTickPacket = new GameTickPacketT
{
Ball = ballInfo,
Balls = balls,
GameInfo = gameInfo,
Teams = teams,
BoostPadStates = boostStates,
Expand Down
2 changes: 1 addition & 1 deletion RLBotCS/ManagerTools/BallPredictor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public static BallPredictionT Generate(PredictionMode mode, float currentTime, B
AngularVelocity = ToVec3(currentBall.Physics.AngularVelocity)
};

const ushort numSeconds = 8;
const ushort numSeconds = 6;
const ushort numSlices = numSeconds * 120;

BallPredictionT ballPrediction = new() { Slices = new List<PredictionSliceT>(numSlices) };
Expand Down
15 changes: 11 additions & 4 deletions RLBotCS/ManagerTools/MatchStarter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,15 @@ public void StartMatch(MatchSettingsT matchSettings)

public void MapSpawned()
{
if (_needsSpawnBots && _matchSettings != null)
if (_matchSettings != null)
{
SpawnCars(_matchSettings);
_needsSpawnBots = false;
bridge.TryWrite(new SetMutators(_matchSettings.MutatorSettings));

if (_needsSpawnBots)
{
SpawnCars(_matchSettings);
_needsSpawnBots = false;
}
}
}

Expand Down Expand Up @@ -144,11 +149,13 @@ private bool IsDifferentFromLast(MatchSettingsT matchSettings)
var lastMutators = lastMatchSettings.MutatorSettings;
var mutators = matchSettings.MutatorSettings;

return lastMatchSettings.GameMode != matchSettings.GameMode
return lastMatchSettings.Freeplay != matchSettings.Freeplay
|| lastMatchSettings.GameMode != matchSettings.GameMode
|| lastMatchSettings.GameMapUpk != matchSettings.GameMapUpk
|| lastMatchSettings.InstantStart != matchSettings.InstantStart
|| lastMutators.MatchLength != mutators.MatchLength
|| lastMutators.MaxScore != mutators.MaxScore
|| lastMutators.MultiBall != mutators.MultiBall
|| lastMutators.OvertimeOption != mutators.OvertimeOption
|| lastMutators.SeriesLengthOption != mutators.SeriesLengthOption
|| lastMutators.BallMaxSpeedOption != mutators.BallMaxSpeedOption
Expand Down
1 change: 1 addition & 0 deletions RLBotCS/ManagerTools/Parsing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ public static MatchSettingsT GetMatchSettings(string path)
{
MatchLength = ParseEnum(mutatorTable, "match_length", MatchLength.Five_Minutes),
MaxScore = ParseEnum(mutatorTable, "max_score", MaxScore.Default),
MultiBall = ParseEnum(mutatorTable, "multi_ball", MultiBall.One),
OvertimeOption = ParseEnum(mutatorTable, "overtime", OvertimeOption.Unlimited),
GameSpeedOption = ParseEnum(mutatorTable, "game_speed", GameSpeedOption.Default),
BallMaxSpeedOption = ParseEnum(mutatorTable, "ball_max_speed", BallMaxSpeedOption.Default),
Expand Down
3 changes: 1 addition & 2 deletions RLBotCS/Server/BridgeHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ private async Task HandleServer()
}

_context.GameState = MessageHandler.CreateUpdatedState(messageClump, _context.GameState);
_context.Writer.TryWrite(new DistributeGameState(_context.GameState));

var matchStarted = MessageHandler.ReceivedMatchInfo(messageClump);
if (matchStarted)
Expand All @@ -61,8 +62,6 @@ _context is

_context.MatchCommandSender.Send();
}

_context.Writer.TryWrite(new DistributeGameState(_context.GameState));
}
}
}
Expand Down
Loading

0 comments on commit 4fa1499

Please sign in to comment.