int team_size = 1;
//static int counter = 0;
//int team_size = (rand() % 100 < 50) ? 1 : ((rand() % 100 < 90) ? 2 : 3);
std::cout << "Team Size: " << team_size << std::endl;
// { PZSUM(new Reward(), 1.0f, 0.75f), 1.0f},
// { new Reward(), 1.0f},
// Define PZSUM as a local variable
const auto PZSUM = [](RewardFunction* rewardFunc, float teamSpirit = 1.0f, float opponentScale = 1.0f) {
return new ZeroSumReward(rewardFunc, teamSpirit, opponentScale);
};
auto rewards = new LogCombinedReward(
std::vector<std::pair<RewardFunction*, float>>{
{ new sBP1(arena), 1.0f },
}
);
{
static std::once_flag onceFlag;
std::call_once(onceFlag,
[&] {
for (int i = 0; i < rewards->rewardFuncs.size(); i++)
g_RewardNames.push_back(rewards->GetRewardFuncName(i));
}
);
}
std::vector<TerminalCondition*> terminalConditions = {
new NoTouchCondition(NO_TOUCH_TIMEOUT_SECS * 120 / TICK_SKIP),
new GoalScoreCondition()
//new BallTouchGroundCondition()
};
auto obs = new DefaultOBS();
auto actionParser = new DiscreteAction();
auto stateSetter = new WeightedSampleSetter(
{
{new RandomState(true, true, false), 0.9f},
{new KickoffState(), 0.1f},
{new AirDribbleSetup(), 0.0f},
{new ReplaySetter(team_size), 0.0f},
}
);
Match* match = new Match(
rewards,
terminalConditions,
obs,
actionParser,
stateSetter,
team_size, // Team size
true // Spawn opponents
);
Gym* gym = new Gym(match, TICK_SKIP);
return { match, gym };
}
int main(int argc, char* argv[]) {
// Initialize RocketSim with collision meshes
RocketSim::Init("./collision_meshes");
code
// Make configuration for the learner
LearnerConfig cfg = {};
cfg.renderMode = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--render") == 0) {
cfg.renderMode = true;
cfg.renderTimeScale = 1.0f;
cfg.deterministic = true;
}
}
// Play around with these to see what the optimal is for your machine, more isn't always better
cfg.numThreads = 16;
cfg.numGamesPerThread = 20;
// We want a large itr/batch size
// You'll want to increase this as your bot improves, up to an extent
int tsPerItr = 100 * 1000;
cfg.timestepsPerIteration = tsPerItr;
cfg.ppo.batchSize = 100000;
cfg.ppo.miniBatchSize = 25000; // Lower this if too much VRAM is being allocated
cfg.expBufferSize = tsPerItr * 2;
// This is just set to 1 to match rlgym-ppo example
// I've found the best value is somewhere between 2 and 4
// Increasing this will lower SPS, but increase step efficiency
cfg.ppo.epochs = 3;
// Reasonable starting entropy
cfg.ppo.entCoef = 0.01f;
cfg.skillTrackerConfig.enabled = true;
cfg.timestepsPerSave = 2'000'000;
cfg.checkpointsToKeep = 30;
cfg.skillTrackerConfig.numEnvs = 16;
cfg.skillTrackerConfig.numThreads = 16;
cfg.skillTrackerConfig.perModeRatings = true;
cfg.metricsRunName = "RUN6";
cfg.metricsProjectName = "MAIN2";
cfg.metricsGroupName = "RUN";
// Good learning rate to start, may start to be too high around 100m steps
cfg.ppo.policyLR = 1e-4; // 1e-4 -> 8e-5 -> 4e-5 -> 2e-5 ->1e-5
cfg.ppo.criticLR = 1e-4;
// Default model size
cfg.ppo.policyLayerSizes = { 512, 512, 512, 512 };
cfg.ppo.criticLayerSizes = { 512, 512, 512, 512 }; // tomorrow 1548, 1024, 512, 512, 256
//cfg.ppo.policyLayerSizes = { 1024, 1024, 1024, 1024, 1024 };
//cfg.ppo.criticLayerSizes = { 1024, 1024, 1024, 1024, 1024 };
cfg.sendMetrics = true; // Send metrics
// Make the learner with the environment creation function and the config we just made
Learner learner = Learner(EnvCreateFunc, cfg);
// Set up our callbacks
learner.stepCallback = [](GameInst* gameInst, const RLGSC::Gym::StepResult& stepResult, Report& gameMetrics) {
// Original OnStep logic
OnStep(gameInst, stepResult, gameMetrics);
// Update GlobalBallPred
BallPred::Update(gameInst->gym->arena);
};
learner.iterationCallback = OnIteration;
// Start learning!
learner.Learn();
return 0;
} give the reward the correct arena #pragma once
#include "../../BaseInc.h"
#include "../Car/Car.h"
#include "../Ball/Ball.h"
#include "../BoostPad/BoostPad.h"
#include "../CollisionMasks.h"
// The container for all game simulation
// Stores cars, the ball, all arena collisions, and manages the overall game state
class Arena {
public:
code
GameMode gameMode;
uint32_t _lastCarID = 0;
std::unordered_set<Car*> _cars;
bool ownsCars = true; // If true, deleting this arena instance deletes all cars
std::unordered_map<uint32_t, Car*> _carIDMap;
Ball* ball;
bool ownsBall = true; // If true, deleting this arena instance deletes the ball
std::vector<BoostPad*> _boostPads;
bool ownsBoostPads = true; // If true, deleing this arena instance deletes all boost pads
BoostPadGrid _boostPadGrid;
SuspensionCollisionGrid _suspColGrid;
MutatorConfig _mutatorConfig;
const MutatorConfig& GetMutatorConfig() { return _mutatorConfig; }
RSAPI void SetMutatorConfig(const MutatorConfig& mutatorConfig);
// Time in seconds each tick (1/tickrate)
float tickTime;
// Returns (1 / tickTime)
float GetTickRate() const {
return 1 / tickTime;
}
// Total ticks this arena instance has been simulated for, never resets
uint64_t tickCount = 0;
const std::unordered_set<Car*>& GetCars() { return _cars; }
const std::vector<BoostPad*>& GetBoostPads() { return _boostPads; }
// Returns true if added, false if car was already added
bool _AddCarFromPtr(Car* car);
RSAPI Car* AddCar(Team team, const CarConfig& config = CAR_CONFIG_OCTANE);
// Returns false if the car ID was not found in the cars list
RSAPI bool RemoveCar(uint32_t id);
// Returns false if the car was not found in the cars list
// NOTE: If the car was removed, the car will be freed and the pointer will be made invalid
bool RemoveCar(Car* car) {
return RemoveCar(car->id);
}
RSAPI Car* GetCar(uint32_t id);
btDiscreteDynamicsWorld _bulletWorld;
struct {
btDefaultCollisionConfiguration collisionConfig;
btCollisionDispatcher collisionDispatcher;
btOverlappingPairCache* overlappingPairCache;
btBroadphaseInterface* broadphase;
btSequentialImpulseConstraintSolver constraintSolver;
} _bulletWorldParams;
btRigidBody* _worldCollisionRBs = NULL;
size_t _worldCollisionRBAmount = 0;
btBvhTriangleMeshShape* _worldCollisionBvhShapes = NULL;
btStaticPlaneShape* _worldCollisionPlaneShapes = NULL;
struct {
GoalScoreEventFn func = NULL;
void* userInfo = NULL;
} _goalScoreCallback;
RSAPI void SetGoalScoreCallback(GoalScoreEventFn callbackFn, void* userInfo = NULL);
struct {
CarBumpEventFn func = NULL;
void* userInfo = NULL;
} _carBumpCallback;
RSAPI void SetCarBumpCallback(CarBumpEventFn callbackFn, void* userInfo = NULL);
// NOTE: Arena should be destroyed after use
RSAPI static Arena* Create(GameMode gameMode, const ArenaConfig& arenaConfig = {}, float tickRate = 120);
// Serialize entire arena state including cars, ball, and boostpads
RSAPI void Serialize(DataStreamOut& out) const;
// Load new arena from serialized data
RSAPI static Arena* DeserializeNew(DataStreamIn& in);
Arena(const Arena& other) = delete; // No copy constructor, use Arena::Clone() instead
Arena& operator =(const Arena& other) = delete; // No copy operator, use Arena::Clone() instead
Arena(Arena&& other) = delete; // No move constructor
Arena& operator =(Arena&& other) = delete; // No move operator
// Get a deep copy of the arena
RSAPI Arena* Clone(bool copyCallbacks);
// NOTE: Car ID will not be restored
RSAPI Car* DeserializeNewCar(DataStreamIn& in, Team team);
// Simulate everything in the arena for a given number of ticks
RSAPI void Step(int ticksToSimulate = 1);
RSAPI void ResetToRandomKickoff(int seed = -1);
// Returns true if the ball is probably going in, does not account for wall or ceiling bounces
// NOTE: Purposefully overestimates, just like the real RL's shot prediction
// To check which goal it will score in, use the ball's velocity
// Margin can be manually adjusted with extraMargin (negative to prevent overestimating)
RSAPI bool IsBallProbablyGoingIn(float maxTime = 2.f, float extraMargin = 0, Team* goalTeamOut = NULL) const;
// Returns true if the ball is in the net
// Works for all gamemodes (and does nothing in THE_VOID)
RSAPI bool IsBallScored() const;
// Free all associated memory
RSAPI ~Arena();
// NOTE: Passed shape pointer will be freed when arena is deconstructed
template <class T>
btRigidBody* _AddStaticCollisionShape(
size_t rbIndex, size_t meshListIndex, T* shape, T* meshList, btVector3 posBT = btVector3(0, 0, 0),
bool isHoopsNet = false) {
static_assert(std::is_base_of<btCollisionShape, T>::value);
meshList[meshListIndex] = *shape;
assert(rbIndex < _worldCollisionRBAmount);
btRigidBody& shapeRB = _worldCollisionRBs[rbIndex];
shapeRB = btRigidBody(0, NULL, &meshList[meshListIndex]);
shapeRB.setWorldTransform(btTransform(btMatrix3x3::getIdentity(), posBT));
shapeRB.setUserPointer(this);
if (isHoopsNet) {
_bulletWorld.addRigidBody(&shapeRB, CollisionMasks::HOOPS_NET, CollisionMasks::HOOPS_NET);
} else {
_bulletWorld.addRigidBody(&shapeRB);
}
return &shapeRB;
}
void _SetupArenaCollisionShapes();
// Static function called by Bullet internally when adding a collision point
static bool _BulletContactAddedCallback(
btManifoldPoint& cp,
const btCollisionObjectWrapper* colObjA, int partID_A, int indexA,
const btCollisionObjectWrapper* colObjB, int partID_B, int indexB
);
void _BtCallback_OnCarBallCollision(Car* car, Ball* ball, btManifoldPoint& manifoldPoint, bool ballIsBodyA);
void _BtCallback_OnCarCarCollision(Car* car1, Car* car2, btManifoldPoint& manifoldPoint);
void _BtCallback_OnCarWorldCollision(Car* car, btCollisionObject* worldObject, btManifoldPoint& manifoldPoint);
const ArenaConfig& GetArenaConfig() const {
return _config;
}
// Backwards compatability
ArenaMemWeightMode GetMemWeightMode() {
return _config.memWeightMode;
}
private:
code
// Constructor for use by Arena::Create()
Arena(GameMode gameMode, const ArenaConfig& config, float tickRate = 120);
// Making this private because horrible memory overflows can happen if you changed it
ArenaConfig _config;
};
RS_NS_END
To ensure that your reward functions receive the correct Arena instance, you need to adjust the order in which you create and initialize your objects within the EnvCreateFunc. Currently, it appears that you’re attempting to create reward functions that depend on the Arena before the Arena itself has been instantiated. This can lead to undefined behavior or runtime errors since the arena variable is not yet available when you initialize your rewards.
Here’s a step-by-step guide to modify your EnvCreateFunc to properly initialize the Arena and pass it to your reward functions:
1. Instantiate the Arena First
Before you create your reward functions, you should first instantiate the Arena. This ensures that you have a valid Arena pointer/reference that can be passed to your reward functions.
2. Pass the Arena to Reward Functions
Once the Arena is instantiated, you can pass it to your reward function constructors. This may require modifying the constructors of your reward classes (e.g., sBP1) to accept an Arena pointer.
3. Modify the Environment Creation Function
Here's how you can adjust your EnvCreateFunc to follow these steps:
cpp
EnvCreateResult EnvCreateFunc() {
constexpr int TICK_SKIP = 12;
constexpr float NO_TOUCH_TIMEOUT_SECS = 16.f;
int team_size = 1;
// static int counter = 0;
// int team_size = (rand() % 100 < 50) ? 1 : ((rand() % 100 < 90) ? 2 : 3);
std::cout << "Team Size: " << team_size << std::endl;
// Initialize Arena first
ArenaConfig arenaConfig; // Initialize with desired configurations
GameMode gameMode = /* Set your game mode */;
Arena* arena = Arena::Create(gameMode, arenaConfig, 120.0f); // Example tick rate
// Define PZSUM as a local variable
const auto PZSUM = [](RewardFunction* rewardFunc, float teamSpirit = 1.0f, float opponentScale = 1.0f) {
return new ZeroSumReward(rewardFunc, teamSpirit, opponentScale);
};
// Now that the Arena is created, you can safely pass it to your reward functions
auto rewards = new LogCombinedReward(
std::vector<std::pair<RewardFunction*, float>>{
{ new sBP1(arena), 1.0f },
// Add other reward functions as needed
}
);
{
static std::once_flag onceFlag;
std::call_once(onceFlag, [&] {
for (int i = 0; i < rewards->rewardFuncs.size(); i++)
g_RewardNames.push_back(rewards->GetRewardFuncName(i));
});
}
std::vector<TerminalCondition*> terminalConditions = {
new NoTouchCondition(NO_TOUCH_TIMEOUT_SECS * 120 / TICK_SKIP),
new GoalScoreCondition()
// new BallTouchGroundCondition()
};
auto obs = new DefaultOBS();
auto actionParser = new DiscreteAction();
auto stateSetter = new WeightedSampleSetter(
{
{new RandomState(true, true, false), 0.9f},
{new KickoffState(), 0.1f},
{new AirDribbleSetup(), 0.0f},
{new ReplaySetter(team_size), 0.0f},
}
);
// Now that rewards and arena are initialized, create the Match
Match* match = new Match(
rewards,
terminalConditions,
obs,
actionParser,
stateSetter,
team_size, // Team size
true // Spawn opponents
);
// Optionally, you might need to associate the arena with the match or vice versa
// match->SetArena(arena); // If such a method exists
Gym* gym = new Gym(match, TICK_SKIP);
return { match, gym };
}
4. Ensure Reward Functions Accept Arena
Make sure that your reward function classes (e.g., sBP1) have constructors that accept an Arena*. For example:
cpp
// sBP1.h
#pragma once
#include "RewardFunction.h"
#include "Arena.h"
class sBP1 : public RewardFunction {
public:
sBP1(Arena* arena) : _arena(arena) {
// Initialize as needed
}
virtual float CalculateReward(/* parameters */) override {
// Use _arena to calculate the reward
}
private:
Arena* _arena;
};
5. Handle Arena Ownership
Be mindful of object ownership to prevent memory leaks or dangling pointers:
Ownership: Decide whether Match or Gym should own the Arena. Typically, the Match would manage the Arena, and thus, it should handle its destruction.
Smart Pointers: Consider using smart pointers (std::shared_ptr or std::unique_ptr) to manage the lifetime of dynamically allocated objects like Arena, Match, and Gym. This helps in automatically managing memory and preventing leaks.
6. Update Callback Functions If Needed
If your callback functions require access to the Arena, ensure they have a way to reference it, either through the GameInst, Match, or Gym objects.
Example with Smart Pointers
Here’s how you can modify the EnvCreateFunc using smart pointers for better memory management:
cpp
#include <memory>
EnvCreateResult EnvCreateFunc() {
// ... [initial setup code]
// Initialize Arena with smart pointer
std::shared_ptr<Arena> arena = std::make_shared<Arena>(GameMode::YourMode, arenaConfig, 120.0f);
// Define rewards with the Arena pointer
auto rewards = std::make_unique<LogCombinedReward>(
std::vector<std::pair<RewardFunction*, float>>{
{ new sBP1(arena.get()), 1.0f },
// Add other reward functions as needed
}
);
// ... [rest of the setup code]
// Create Match with smart pointers
std::shared_ptr<Match> match = std::make_shared<Match>(
rewards.get(),
terminalConditions,
obs,
actionParser,
stateSetter,
team_size,
true
);
// Create Gym
std::shared_ptr<Gym> gym = std::make_shared<Gym>(match.get(), TICK_SKIP);
return { match.get(), gym.get() };
}
Note: You need to ensure that the lifetime of Arena, Match, and Gym objects are properly managed, especially if you’re going to pass raw pointers around. Using smart pointers helps manage these lifetimes automatically.
7. Final Considerations
Initialization Order: Always ensure that dependencies are initialized before they are used. In your case, the Arena must be initialized before any reward functions that depend on it.
Thread Safety: If your environment creation function is called from multiple threads, ensure that shared resources are protected appropriately.
Error Handling: Add error handling to manage cases where object creation might fail. This can prevent your program from crashing unexpectedly.
By restructuring your EnvCreateFunc to instantiate the Arena before creating the reward functions and ensuring that all dependencies are correctly passed, you can provide the correct Arena instance to your rewards and avoid potential issues related to undefined or incorrect references.