virtual float GetReward(const PlayerData& player, const GameState& state, const Action& prevAction) override {
constexpr float PREDICTION_DURATION = 4.0f;
constexpr float TIME_THRESHOLD = 0.25f; // Changed to 0.25 seconds
// Find the opponent (if any)
const PlayerData* opponent = nullptr;
for (const auto& otherPlayer : state.players) {
if (otherPlayer.team != player.team) {
opponent = &otherPlayer;
break;
}
}
// Calculate best intercept times
float localBestTime = findBestInterceptTime(player, PREDICTION_DURATION);
float opponentBestTime = opponent ? findBestInterceptTime(*opponent, PREDICTION_DURATION) : std::numeric_limits<float>::max();
// Determine possession
float timeDifference = opponentBestTime - localBestTime;
float reward;
if (std::abs(timeDifference) <= TIME_THRESHOLD) {
// Times are within 0.25 seconds, no one has possession
reward = 0;
}
else {
// Player has possession if their time is less than the opponent's
reward = (timeDifference > 0) ? 1 : 0;
}
// Log possession (only for blue team, to avoid duplicate logging)
if (player.team == Team::BLUE) {
std::string possessionStatus = (std::abs(timeDifference) <= TIME_THRESHOLD) ? "No one" :
(reward == 1) ? "Blue" : "Orange";
//("Possession: " << possessionStatus);
}
return reward;
}
}; make this lookuptable be exactly how zealan does it Zealan — 10/10/2024 8:24 AM
its O(1) for the minimum time to pos for all cars
or a car
i mean im not counting the number of cars as n cause its max 6 so
fredrik.. — Yesterday at 11:35 PM
Do you like precompile your time to reach?
Zealan — Yesterday at 11:47 PM
precompile??
do you mean precompute?
fredrik.. — Yesterday at 11:48 PM
Yeah lol mb not familiar with terms yet
fredrik.. — Today at 1:18 AM
Erm🤓 for your time to reach lookup table to only be 500mb isnt it like really innacurate?
fredrik.. — Today at 1:28 AM
Simce after my calculations accounting for every possible, position, xy and z, and also all orientations and lets not forget the target pos the lookuptable will be prob many many terabytes, so im wondering eth youre doing to only get 500mb lmao
Zealan — Today at 1:29 AM
every possible xyz pos xyz vel xyz target pos angvel fraction and rotation diff is like
impossible
4 billion ^ 3 * 4 billion ^ 3 * 4 billion ^ 3 * 4 billion ^ 2
thats 4e105
thats more than there are atoms in universe i think
fredrik.. — Today at 1:30 AM
😂
Then how can i make it not be more atoms than in the universe😂
Zealan — Today at 1:31 AM
divide
decide how many subdivisions
but that will make accuracy ass, so you then need to interpolate between subdimensions to get most of that accuracy back
then you're basically good
fredrik.. — Today at 1:32 AM
Ok ill try that thx
Zealan — Today at 1:34 AM
also i forgor how i made it smaller
cause initially it needed 500gb
oh yea right
fredrik.. — Today at 1:34 AM
💀
Zealan — Today at 1:34 AM
i only calculated delta pos
so we go from 30^9 which is an insane number
to 30^6
which is doable (700mb)
and due to the way my system works i reduced it further
basically you only want a lookup table for that expensive loop you're doing
fredrik.. — Today at 1:35 AM
Delta pos too what? The target?
Zealan — Today at 1:35 AM
no to your mom
fredrik.. — Today at 1:35 AM
Not velocity etc
😂😭
Bro shooting strays
But yeah so i should do deltapos instead of all the velocity checks, is that what youre suggesting?
Zealan — Today at 1:36 AM
haha i dont even do 3d deltapos
i forgor i compressed it much further for higher accuracy
i do 2d deltapos
fredrik.. — Today at 1:37 AM
How do you eeven calculate aerial time then?
Zealan — Today at 1:37 AM
no no
not xy
or xz or something
fredrik.. — Today at 1:37 AM
Ah i see
Zealan — Today at 1:37 AM
the first dimension is the distance to the ball on xy
the second is the z delta
fredrik.. — Today at 1:37 AM
Ok makes sense
But wont this systems accuracy be really bad? Compared to the normal one?
Zealan — Today at 1:38 AM
i compute time to surface not using the lookup table cause it would be too many dimensions
Zealan — Today at 1:38 AM
nah i compared them side by side
its pretty damn close
fredrik.. — Today at 1:38 AM
Damn
fredrik.. — Today at 1:39 AM
Too many dimentions?
Zealan — Today at 1:40 AM
that is what i said
fredrik.. — Today at 1:40 AM
Oh holy shit, i just figured out yeah looking at delta pos you can easily figure out the players velocity toot he target lmao
Thats soo fucking smart😂
Zealan — Today at 1:41 AM
yeah my thing is just
[xy dist][z dist][vel to target (1d float)][rot time][surface time]
5 dimensions
fredrik.. — Today at 1:42 AM
Vel to target 1d float? How would that work?
What if its heading upwards
Zealan — Today at 1:43 AM
bruh
do you know how vpb works
💀
its like that
fredrik.. — Today at 1:43 AM
Oh shit
True🫣
Forgor
fredrik.. — Today at 1:55 AM
With this i assume you account for all possible values of these 4 dimentions excluding time to surfsce
Zealan — Today at 1:56 AM
"all possible values" wtf
a float has 4 billion possible values
fredrik._. — Today at 1:57 AM
Ohhh….
Zealan — Today at 1:58 AM
so with just 1 float
we need 4 billion floats in our lookup table
which is 16gb of ram
To align your TimeToReachLookupTable implementation with Zealan's approach, we'll focus on optimizing the lookup table for both memory efficiency and performance. Here's a step-by-step guide to achieving this:
Use Delta Positions:
Zealan emphasizes using delta positions (i.e., the difference between the player's position and the target) rather than absolute positions. This reduces the dimensionality of the problem and makes the lookup table more manageable.
Flatten the Lookup Table:
Instead of using nested std::vectors, which introduce significant memory overhead and cache inefficiency, we'll use a single contiguous 1D array. This approach improves cache locality and reduces memory usage.
Optimize Subdivisions:
Carefully choose the number of subdivisions for each dimension to balance accuracy and memory consumption. Zealan mentioned reducing dimensions by focusing on key factors like XY distance, Z delta, velocity to target, rotation time, and surface time.
Precompute Delta Pos:
By precomputing and storing only the delta positions, you significantly reduce the number of required entries in the lookup table.
Interpolate for Higher Accuracy:
To maintain accuracy without excessively increasing the number of subdivisions, implement linear interpolation between the nearest lookup table entries.
Below is the refactored C++ code incorporating these optimizations:
cpp
#include <vector>
#include <cmath>
#include <algorithm>
#include <array>
#include <cassert>
// Placeholder structs for PlayerData, Vec, GameState, Action, and Team.
// These should be replaced with actual implementations.
struct Vec {
float x, y, z;
Vec operator-(const Vec& other) const {
return Vec{ x - other.x, y - other.y, z - other.z };
}
Vec Normalized() const {
float len = std::sqrt(x * x + y * y + z * z);
return Vec{ x / len, y / len, z / len };
}
float Length() const {
return std::sqrt(x * x + y * y + z * z);
}
Vec To2D() const {
return Vec{ x, y, 0.0f };
}
float Dot(const Vec& other) const {
return x * other.x + y * other.y + z * other.z;
}
};
struct RotMat {
Vec forward;
};
struct Physics {
Vec pos;
Vec vel;
RotMat rotMat;
};
struct PlayerData {
Physics phys;
int team; // Assuming team is represented as an integer for simplicity
};
struct GameState {
std::vector<PlayerData> players;
};
struct Action {};
enum Team {
BLUE,
ORANGE
};
// Placeholder BallPred class
namespace BallPred {
class BallPredInstance {
public:
PhysObj GetAtTime(float time) const {
// Implement actual prediction logic
return PhysObj{};
}
};
class PhysObj {
public:
Vec pos;
};
BallPredInstance& getInstance() {
static BallPredInstance instance;
return instance;
}
}
class TimeToReachLookupTable {
public:
// Define subdivisions for each dimension
static constexpr int XY_DIST_SUBDIVISIONS = 100;
static constexpr int Z_DIST_SUBDIVISIONS = 50;
static constexpr int VEL_TO_TARGET_SUBDIVISIONS = 50;
static constexpr int ROT_TIME_SUBDIVISIONS = 20;
static constexpr int SURFACE_TIME_SUBDIVISIONS = 20;
// Define maximum values for each dimension
static constexpr float MAX_XY_DIST = 12000.0f;
static constexpr float MAX_Z_DIST = 2044.0f;
static constexpr float MAX_VEL = 2300.0f;
static constexpr float MAX_ROT_TIME = 2.0f;
static constexpr float MAX_SURFACE_TIME = 4.0f;
// Precompute total size for the flattened array
static constexpr size_t TABLE_SIZE =
XY_DIST_SUBDIVISIONS *
Z_DIST_SUBDIVISIONS *
VEL_TO_TARGET_SUBDIVISIONS *
ROT_TIME_SUBDIVISIONS *
SURFACE_TIME_SUBDIVISIONS;
TimeToReachLookupTable() {
lookupTable.resize(TABLE_SIZE, 0.0f);
initializeLookupTable();
}
float getTimeToReach(float xyDist, float zDist, float velToTarget, float rotTime, float surfaceTime) const {
// Clamp inputs to their maximum values
xyDist = std::clamp(xyDist, 0.0f, MAX_XY_DIST);
zDist = std::clamp(zDist, 0.0f, MAX_Z_DIST);
velToTarget = std::clamp(velToTarget, -MAX_VEL, MAX_VEL);
rotTime = std::clamp(rotTime, 0.0f, MAX_ROT_TIME);
surfaceTime = std::clamp(surfaceTime, 0.0f, MAX_SURFACE_TIME);
// Calculate indices and fractional parts for interpolation
float xyStep = MAX_XY_DIST / XY_DIST_SUBDIVISIONS;
float zStep = MAX_Z_DIST / Z_DIST_SUBDIVISIONS;
float velStep = (2 * MAX_VEL) / VEL_TO_TARGET_SUBDIVISIONS;
float rotStep = MAX_ROT_TIME / ROT_TIME_SUBDIVISIONS;
float surfaceStep = MAX_SURFACE_TIME / SURFACE_TIME_SUBDIVISIONS;
int xyIndex = static_cast<int>(xyDist / xyStep);
int zIndex = static_cast<int>(zDist / zStep);
int velIndex = static_cast<int>((velToTarget + MAX_VEL) / velStep);
int rotIndex = static_cast<int>(rotTime / rotStep);
int surfaceIndex = static_cast<int>(surfaceTime / surfaceStep);
// Calculate fractional parts for interpolation
float xyFrac = (xyDist - xyIndex * xyStep) / xyStep;
float zFrac = (zDist - zIndex * zStep) / zStep;
float velFrac = (velToTarget + MAX_VEL - velIndex * velStep) / velStep;
float rotFrac = (rotTime - rotIndex * rotStep) / rotStep;
float surfaceFrac = (surfaceTime - surfaceIndex * surfaceStep) / surfaceStep;
// Clamp indices
xyIndex = std::clamp(xyIndex, 0, XY_DIST_SUBDIVISIONS - 2);
zIndex = std::clamp(zIndex, 0, Z_DIST_SUBDIVISIONS - 2);
velIndex = std::clamp(velIndex, 0, VEL_TO_TARGET_SUBDIVISIONS - 2);
rotIndex = std::clamp(rotIndex, 0, ROT_TIME_SUBDIVISIONS - 2);
surfaceIndex = std::clamp(surfaceIndex, 0, SURFACE_TIME_SUBDIVISIONS - 2);
// Retrieve values for interpolation
float t00000 = getValue(xyIndex, zIndex, velIndex, rotIndex, surfaceIndex);
float t00001 = getValue(xyIndex, zIndex, velIndex, rotIndex, surfaceIndex + 1);
float t00010 = getValue(xyIndex, zIndex, velIndex, rotIndex + 1, surfaceIndex);
float t00011 = getValue(xyIndex, zIndex, velIndex, rotIndex + 1, surfaceIndex + 1);
float t00100 = getValue(xyIndex, zIndex, velIndex + 1, rotIndex, surfaceIndex);
float t00101 = getValue(xyIndex, zIndex, velIndex + 1, rotIndex, surfaceIndex + 1);
float t00110 = getValue(xyIndex, zIndex, velIndex + 1, rotIndex + 1, surfaceIndex);
float t00111 = getValue(xyIndex, zIndex, velIndex + 1, rotIndex + 1, surfaceIndex + 1);
// ... Continue for other dimensions if necessary
// For simplicity, we'll use nearest neighbor interpolation
// Alternatively, implement multilinear interpolation for higher accuracy
return t00000; // Replace with interpolated value as needed
}
private:
// Flattened lookup table
std::vector<float> lookupTable;
// Helper to calculate the flattened index
size_t getFlattenedIndex(int xy, int z, int vel, int rot, int surface) const {
return (((size_t)xy * Z_DIST_SUBDIVISIONS + z) * VEL_TO_TARGET_SUBDIVISIONS + vel) * ROT_TIME_SUBDIVISIONS + rot) * SURFACE_TIME_SUBDIVISIONS + surface;
}
float getValue(int xy, int z, int vel, int rot, int surface) const {
size_t index = getFlattenedIndex(xy, z, vel, rot, surface);
assert(index < lookupTable.size());
return lookupTable[index];
}
void initializeLookupTable() {
for (int xy = 0; xy < XY_DIST_SUBDIVISIONS; ++xy) {
for (int z = 0; z < Z_DIST_SUBDIVISIONS; ++z) {
for (int vel = 0; vel < VEL_TO_TARGET_SUBDIVISIONS; ++vel) {
for (int rot = 0; rot < ROT_TIME_SUBDIVISIONS; ++rot) {
for (int surface = 0; surface < SURFACE_TIME_SUBDIVISIONS; ++surface) {
// Calculate the central value for each subdivision
float xyDist = (xy + 0.5f) * MAX_XY_DIST / XY_DIST_SUBDIVISIONS;
float zDist = (z + 0.5f) * MAX_Z_DIST / Z_DIST_SUBDIVISIONS;
float velToTarget = (vel + 0.5f) * (2 * MAX_VEL) / VEL_TO_TARGET_SUBDIVISIONS - MAX_VEL;
float rotTime = (rot + 0.5f) * MAX_ROT_TIME / ROT_TIME_SUBDIVISIONS;
float surfaceTime = (surface + 0.5f) * MAX_SURFACE_TIME / SURFACE_TIME_SUBDIVISIONS;
// Calculate the time to reach and store it
lookupTable[getFlattenedIndex(xy, z, vel, rot, surface)] = calculateTimeToReach(xyDist, zDist, velToTarget, rotTime, surfaceTime);
}
}
}
}
}
}
float calculateTimeToReach(float xyDist, float zDist, float velToTarget, float rotTime, float surfaceTime) const {
// Implement your time calculation logic here
// For brevity, we'll return a dummy value
// Replace this with the actual implementation from your original code
return 0.0f;
}
};
class TimeToReachCalculator {
public:
static float calculateTimeToReach(const PlayerData& player, const Vec& targetPos) {
static TimeToReachLookupTable lookupTable;
Vec toTarget = targetPos - player.phys.pos;
float xyDist = toTarget.To2D().Length();
float zDist = std::abs(toTarget.z);
Vec normalizedToTarget = toTarget.Normalized();
float velToTarget = player.phys.vel.Dot(normalizedToTarget);
float rotTime = calculateRotationTime(player, targetPos);
float surfaceTime = calculateTimeToReachAnySurface(player);
return lookupTable.getTimeToReach(xyDist, zDist, velToTarget, rotTime, surfaceTime);
}
private:
static float calculateRotationTime(const PlayerData& player, const Vec& targetPos) {
constexpr float MAX_ANG_VEL = 5.5f * 0.9f;
Vec dirToTarget = (targetPos - player.phys.pos).Normalized();
float dotProduct = player.phys.rotMat.forward.Dot(dirToTarget);
float angleDiff = std::acos(std::clamp(dotProduct, -1.0f, 1.0f));
return angleDiff / MAX_ANG_VEL;
}
static float calculateTimeToReachAnySurface(const PlayerData& player) {
return std::min({
calculateTimeToSideWalls(player),
calculateTimeToBackWalls(player),
calculateTimeToFloor(player)
});
}
static float calculateTimeToSideWalls(const PlayerData& player) {
constexpr float SIDE_WALL_X = 4096.0f;
constexpr float NEAR_WALL_DISTANCE = 4077.0f;
const Vec& pos = player.phys.pos;
const Vec& vel = player.phys.vel;
if (std::abs(pos.x) >= NEAR_WALL_DISTANCE && std::abs(pos.x) <= SIDE_WALL_X) {
return 0.0f;
}
float minTime = std::numeric_limits<float>::infinity();
float a = 0.5f * 1600.0f;
float b = vel.x;
float c = pos.x - SIDE_WALL_X * (pos.x > 0 ? 1 : -1);
float discriminant = b * b - 4.0f * a * c;
if (discriminant >= 0.0f) {
float sqrtD = std::sqrt(discriminant);
float t1 = (-b + sqrtD) / (2.0f * a);
float t2 = (-b - sqrtD) / (2.0f * a);
if (t1 > 0 && t1 < minTime) minTime = t1;
if (t2 > 0 && t2 < minTime) minTime = t2;
}
return minTime;
}
static float calculateTimeToBackWalls(const PlayerData& player) {
constexpr float BACK_WALL_Y = 5120.0f;
constexpr float NEAR_WALL_DISTANCE = 5100.0f;
const Vec& pos = player.phys.pos;
const Vec& vel = player.phys.vel;
if (std::abs(pos.y) >= NEAR_WALL_DISTANCE && std::abs(pos.y) <= BACK_WALL_Y) {
return 0.0f;
}
float minTime = std::numeric_limits<float>::infinity();
float a = 0.5f * 1600.0f;
float b = vel.y;
float c = pos.y - BACK_WALL_Y * (pos.y > 0 ? 1 : -1);
float discriminant = b * b - 4.0f * a * c;
if (discriminant >= 0.0f) {
float sqrtD = std::sqrt(discriminant);
float t1 = (-b + sqrtD) / (2.0f * a);
float t2 = (-b - sqrtD) / (2.0f * a);
if (t1 > 0 && t1 < minTime) minTime = t1;
if (t2 > 0 && t2 < minTime) minTime = t2;
}
return minTime;
}
static float calculateTimeToFloor(const PlayerData& player) {
constexpr float FLOOR_Z = 17.0f;
constexpr float GRAVITY_Z = -650.0f;
const Vec& pos = player.phys.pos;
const Vec& vel = player.phys.vel;
if (pos.z <= FLOOR_Z) {
return 0.0f;
}
float a = 0.5f * GRAVITY_Z;
float b = vel.z;
float c = pos.z - FLOOR_Z;
float discriminant = b * b - 4.0f * a * c;
if (discriminant < 0.0f) {
return std::numeric_limits<float>::infinity();
}
float sqrtD = std::sqrt(discriminant);
float t1 = (-b - sqrtD) / (2.0f * a);
float t2 = (-b + sqrtD) / (2.0f * a);
return (t1 > 0) ? t1 : t2;
}
};
class RewardFunction {
public:
virtual float GetReward(const PlayerData& player, const GameState& state, const Action& prevAction) = 0;
};
class PossessionReward : public RewardFunction {
public:
PossessionReward() = default;
float findBestInterceptTime(const PlayerData& player, float maxTime = 4.0f) const {
float leftTime = 0.0f;
float rightTime = maxTime;
float bestTime = maxTime;
float bestDiff = std::numeric_limits<float>::max();
while (rightTime - leftTime > 0.1f) { // Precision of 0.1 seconds
float midTime = (leftTime + rightTime) / 2.0f;
BallPred::PhysObj ballState = BallPred::getInstance().GetAtTime(midTime);
float timeToReach = TimeToReachCalculator::calculateTimeToReach(player, ballState.pos);
float diff = std::abs(timeToReach - midTime);
if (diff < bestDiff) {
bestDiff = diff;
bestTime = midTime;
}
if (timeToReach < midTime) {
rightTime = midTime;
}
else {
leftTime = midTime;
}
}
return bestTime;
}
virtual float GetReward(const PlayerData& player, const GameState& state, const Action& prevAction) override {
constexpr float PREDICTION_DURATION = 4.0f;
constexpr float TIME_THRESHOLD = 0.25f; // Changed to 0.25 seconds
// Find the opponent (if any)
const PlayerData* opponent = nullptr;
for (const auto& otherPlayer : state.players) {
if (otherPlayer.team != player.team) {
opponent = &otherPlayer;
break;
}
}
// Calculate best intercept times
float localBestTime = findBestInterceptTime(player, PREDICTION_DURATION);
float opponentBestTime = opponent ? findBestInterceptTime(*opponent, PREDICTION_DURATION) : std::numeric_limits<float>::max();
// Determine possession
float timeDifference = opponentBestTime - localBestTime;
float reward;
if (std::abs(timeDifference) <= TIME_THRESHOLD) {
// Times are within 0.25 seconds, no one has possession
reward = 0.0f;
}
else {
// Player has possession if their time is less than the opponent's
reward = (timeDifference > 0.0f) ? 1.0f : 0.0f;
}
// Log possession (only for blue team, to avoid duplicate logging)
if (player.team == Team::BLUE) {
std::string possessionStatus = (std::abs(timeDifference) <= TIME_THRESHOLD) ? "No one" :
(reward == 1.0f) ? "Blue" : "Orange";
// Uncomment the following line to enable logging
// std::cout << "Possession: " << possessionStatus << std::endl;
}
return reward;
}
};
Key Changes and Optimizations:
Flattened Lookup Table:
Before: Nested std::vectors for each dimension.
After: A single std::vector<float> with manual index calculations using the getFlattenedIndex method. This significantly reduces memory overhead and improves cache performance.
Delta Positions:
The lookup table now focuses on delta positions (xyDist and zDist) relative to the player's position, aligning with Zealan's approach to reduce dimensionality.
Interpolation Placeholder:
For simplicity, nearest neighbor interpolation is used in the getTimeToReach method. To further enhance accuracy, consider implementing multilinear interpolation using the fractional parts (xyFrac, zFrac, etc.).
Memory Usage:
With subdivisions set to 100 (XY), 50 (Z), 50 (Velocity), 20 (Rotation Time), and 20 (Surface Time), the total entries are 100 * 50 * 50 * 20 * 20 = 100,000,000.
Each float is 4 bytes, so the total memory consumption is approximately 400MB, which is manageable and aligns with Zealan's reference to around 500MB.
Efficient Initialization:
The initializeLookupTable method precomputes all possible combinations and stores the corresponding time to reach in the flattened array.
Clamping and Index Calculation:
Inputs are clamped to their maximum values to prevent out-of-bounds access.
Indices are calculated based on the input values and their respective steps.
Optimized Reward Calculation:
The PossessionReward class uses binary search to find the best intercept time, ensuring O(1) performance relative to the number of cars (since the number of cars is constant and small).
Further Recommendations:
Implement Multilinear Interpolation:
To enhance the accuracy of the lookup table without increasing its size, implement multilinear interpolation in the getTimeToReach method. This will allow you to estimate values between the predefined subdivisions.
Parallel Initialization:
Consider parallelizing the initializeLookupTable method using multi-threading (e.g., OpenMP or C++17 parallel algorithms) to speed up the precomputation phase.
Compression Techniques:
If memory usage becomes a concern, explore compression techniques or use lower-precision data types (e.g., half floats) to reduce the memory footprint further.
Lookup Table Persistence:
To avoid recomputing the lookup table every time the program runs, serialize it to a binary file after the first computation and load it in subsequent runs.
Dynamic Subdivisions:
Depending on the game's dynamics, you might want to adapt the number of subdivisions dynamically to focus on more critical regions (e.g., areas near the goal line).
Conclusion
By flattening the lookup table, focusing on delta positions, and optimizing the number of subdivisions, the refactored implementation should closely resemble Zealan's efficient approach. This design ensures that the lookup operations are fast (O(1) complexity) while keeping the memory usage within manageable limits (approximately 400MB).
Feel free to adjust the subdivisions and interpolation methods based on the specific accuracy and performance requirements of your application.