void RLBotBot::RenderGlobalBallPred(const RLGSC::GameState& gs) {
if (!renderBallPredictionsEnabled) return;
code
rlbot::ScopedRenderer renderer("global_ballpred_renderer");
const Arena* arena = predictionArena;
if (!arena) return;
BallPred& ballPred = BallPred::getInstance();
ballPred.Update(arena); // Update prediction for the current arena
// Time intervals and precision settings for refinement
constexpr float INITIAL_INTERVAL = 0.5f; // Start with 0.5s interval
constexpr float MIN_INTERVAL = 0.01f; // Minimum interval (1ms)
constexpr int MAX_STEPS = 6; // Max refinement steps (0.5s -> 0.25s -> 0.125s, etc.)
constexpr float MAX_PRED_TIME = 2.0f; // Total prediction time (2 seconds)
std::vector<rlbot::flat::Vector3> points;
float currentTime = 0.0f;
// Start with the initial interval
for (float interval = INITIAL_INTERVAL; interval >= MIN_INTERVAL; interval /= 2.0f) {
// Refine the time intervals with each step
for (int step = 0; step <= MAX_STEPS; step++) {
if (currentTime > MAX_PRED_TIME) break;
PhysObj ballState = ballPred.GetAtTime(currentTime); // Get ball state at current time
points.push_back(rlbot::flat::Vector3{
static_cast<float>(ballState.pos.x),
static_cast<float>(ballState.pos.y),
static_cast<float>(ballState.pos.z)
});
currentTime += interval; // Move to the next refined time
}
}
// Render lines between consecutive points
for (size_t i = 0; i < points.size() - 1; i++) {
renderer.DrawLine3D(rlbot::Color::yellow, points[i], points[i + 1]);
}
// Draw a green dot at the last predicted point
if (!points.empty()) {
renderer.DrawRect3D(
rlbot::Color::green,
points.back(),
10,
10,
true,
true
);
}
static float calculateTimeToReachAir(const PlayerData& player, const Vec& targetPos) {
Vec carPos = player.phys.pos;
Vec carVel = player.phys.vel;
Vec dirToTarget = (targetPos - carPos).Normalized();
float dist = (targetPos - carPos).Length() - CommonValues::BALL_RADIUS;
float vel = carVel.Dot(dirToTarget);
float rotTime = calculateRotationTime(player, targetPos);
float t = 0;
for (float curDist = dist, curVel = vel; curDist > DIST_REACH_THRESH; t += STEP_INTERVAL, curDist -= curVel * STEP_INTERVAL) {
bool hasRotated = t >= rotTime;
if (curVel < MAX_TOTAL_SPEED && t == 0) {
// Initial jump/dodge impulse
curVel += JUMP_IMPULSE;
}
// Apply air acceleration and boost
float accel = AIR_ACCEL + (hasRotated ? BOOST_ACCEL_AIR : 0);
curVel += accel * STEP_INTERVAL;
// Apply gravity (project it onto the direction to target)
float gravityComponent = GRAVITY_Z * dirToTarget.z;
curVel += gravityComponent * STEP_INTERVAL;
if (curVel >= MAX_TOTAL_SPEED) {
return t + (curDist / curVel);
}
}
return t;
}
static float calculateTimeToSideWalls(const PlayerData& player) {
const Vec& pos = player.phys.pos;
const Vec& vel = player.phys.vel;
float minTime = std::numeric_limits<float>::infinity();
if (std::abs(pos.x) >= NEAR_WALL_DISTANCE && std::abs(pos.x) <= SIDE_WALL_X) {
return 0.0f;
}
if (vel.x > EPSILON) {
float a = 0.5f * DRIVE_ACCEL;
float b = vel.x;
float c = pos.x - SIDE_WALL_X;
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 > EPSILON && t1 < minTime) {
minTime = t1;
}
if (t2 > EPSILON && t2 < minTime) {
minTime = t2;
}
}
}
if (vel.x < -EPSILON) {
float a = 0.5f * (-DRIVE_ACCEL);
float b = vel.x;
float c = pos.x + SIDE_WALL_X;
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 > EPSILON && t1 < minTime) {
minTime = t1;
}
if (t2 > EPSILON && t2 < minTime) {
minTime = t2;
}
}
}
return minTime;
}
static float calculateTimeToBackWalls(const PlayerData& player) {
const Vec& pos = player.phys.pos;
const Vec& vel = player.phys.vel;
float minTime = std::numeric_limits<float>::infinity();
if (pos.y >= MAX_BACKWALL_Y || pos.y <= -MAX_BACKWALL_Y) {
return 0.0f;
}
if (pos.y >= BACK_WALL_Y || pos.y <= NEG_BACK_WALL_Y) {
return 0.0f;
}
if (vel.y > EPSILON) {
float a = 0.5f * BOOST_ACCEL_POS;
float b = vel.y;
float c = pos.y - BACK_WALL_Y;
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 > EPSILON && t1 < minTime) {
minTime = t1;
}
if (t2 > EPSILON && t2 < minTime) {
minTime = t2;
}
}
}
if (vel.y < -EPSILON) {
float a = 0.5f * BOOST_ACCEL_NEG;
float b = vel.y;
float c = pos.y - NEG_BACK_WALL_Y;
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 > EPSILON && t1 < minTime) {
minTime = t1;
}
if (t2 > EPSILON && t2 < minTime) {
minTime = t2;
}
}
}
return minTime;
}
static float calculateTimeToFloor(const PlayerData& player) {
const Vec& pos = player.phys.pos;
const Vec& vel = player.phys.vel;
if (pos.z <= FLOOR_Z) {
return 0.0f;
}
float totalAccel = GRAVITY_Z + BOOST_ACCEL_DOWN;
float a = 0.5f * totalAccel;
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);
float timeToFloor = std::numeric_limits<float>::infinity();
if (t1 > 0.0f) {
timeToFloor = t1;
}
if (t2 > 0.0f && t2 < timeToFloor) {
timeToFloor = t2;
}
return timeToFloor;
}
static float calculateTimeToReachAnySurface(const PlayerData& player) {
// Calculate individual times to each surface
float timeToSideWalls = calculateTimeToSideWalls(player);
// RG_LOG(timeToSideWalls); // Uncomment if logging is needed
float timeToBackWalls = calculateTimeToBackWalls(player);
//RG_LOG(timeToBackWalls); // Uncomment if logging is needed
float timeToFloor = calculateTimeToFloor(player);
// RG_LOG(timeToFloor); // Uncomment if logging is needed
// Assign identifier variables for clarity
float minTimeBetweenBackWallsAndFloor = RS_MIN(timeToBackWalls, timeToFloor);
// Now find the minimum time among side walls and the previously computed minimum
float minTime = RS_MIN(timeToSideWalls, minTimeBetweenBackWallsAndFloor);
return minTime;
}
static float calculateRotationTime(const PlayerData& player, const Vec& targetPos) {
constexpr float MAX_ANG_VEL = 5.5f * 0.9f;
Vec playerPos = player.phys.pos;
Vec playerForward = player.phys.rotMat.forward;
Vec dirToTarget = (targetPos - playerPos).Normalized();
float dotProduct = RS_CLAMP(playerForward.Dot(dirToTarget), -1.0f, 1.0f);
float angleDiff = std::acos(dotProduct);
return angleDiff / MAX_ANG_VEL;
}
};you should specify the interval
not the amount of prediction points
you should find the closest reach margin with like 0.5s interval
then check neighboring times at 0.25s
then at 0.125s
etc
until you find the best tick
like a trinary search
It seems like you want to enhance your ball prediction rendering by dynamically refining the prediction intervals using a trinary search approach. Instead of uniformly sampling prediction points with fixed intervals, this method will allow you to hone in on the optimal prediction times more efficiently. Below, I'll guide you through implementing this approach in your RenderGlobalBallPred function and integrating it with your TimeToReachCalculatorv2 class.
Overview
Objective: Implement a trinary search-like refinement process to dynamically determine prediction intervals, focusing on the closest reach margin.
Approach:
Start with a broad interval (e.g., 0.5 seconds).
Refine the interval iteratively (e.g., 0.25s, 0.125s, etc.) to narrow down the optimal prediction time.
Use the TimeToReachCalculatorv2 to assess how close the player can reach the ball at each interval.
Step-by-Step Implementation
1. Modify RenderGlobalBallPred to Implement Trinary Search
We'll adjust the RenderGlobalBallPred function to perform a trinary search for the optimal prediction time. This involves:
Defining Search Parameters: Initial interval, minimum interval, maximum prediction time, and maximum refinement levels.
Performing Trinary Search: Iteratively narrowing down the best time to predict the ball's position.
Rendering the Predicted Path: Drawing lines between the predicted points for visualization.
Here's the updated code:
cpp
void RLBotBot::RenderGlobalBallPred(const RLGSC::GameState& gs) {
if (!renderBallPredictionsEnabled) return;
rlbot::ScopedRenderer renderer("global_ballpred_renderer");
const Arena* arena = predictionArena;
if (!arena) return;
BallPred& ballPred = BallPred::getInstance();
ballPred.Update(arena); // Update prediction for the current arena
// Define search parameters
constexpr float INITIAL_INTERVAL = 0.5f; // Start with 0.5s interval
constexpr float MIN_INTERVAL = 0.001f; // Minimum interval (1ms)
constexpr int MAX_REFINEMENT_LEVELS = 6; // Number of refinement iterations
constexpr float MAX_PRED_TIME = 2.0f; // Total prediction time (2 seconds)
// Initialize search bounds
float low = 0.0f;
float high = MAX_PRED_TIME;
float bestTime = 0.0f;
float bestMargin = std::numeric_limits<float>::max();
// Perform trinary search over refinement levels
for (int level = 0; level < MAX_REFINEMENT_LEVELS; ++level) {
float interval = high - low;
if (interval < MIN_INTERVAL) break; // Stop if interval is sufficiently small
// Calculate two midpoints for trinary division
float third = interval / 3.0f;
float mid1 = low + third;
float mid2 = high - third;
// Calculate reach margins at both midpoints
float margin1 = CalculateReachMargin(mid1);
float margin2 = CalculateReachMargin(mid2);
// Determine which segment to keep based on margin comparison
if (margin1 < margin2) {
high = mid2;
if (margin1 < bestMargin) {
bestMargin = margin1;
bestTime = mid1;
}
} else {
low = mid1;
if (margin2 < bestMargin) {
bestMargin = margin2;
bestTime = mid2;
}
}
}
// Collect prediction points around the best time with finer intervals
std::vector<rlbot::flat::Vector3> points;
constexpr float POINT_INTERVAL = 0.01f; // Finer interval for rendering
float startTime = std::max(bestTime - INITIAL_INTERVAL, 0.0f);
float endTime = std::min(bestTime + INITIAL_INTERVAL, MAX_PRED_TIME);
for (float t = startTime; t <= endTime; t += POINT_INTERVAL) {
PhysObj ballState = ballPred.GetAtTime(t); // Get ball state at time t
points.emplace_back(rlbot::flat::Vector3{
static_cast<float>(ballState.pos.x),
static_cast<float>(ballState.pos.y),
static_cast<float>(ballState.pos.z)
});
}
// Render lines between consecutive points
for (size_t i = 0; i < points.size() - 1; i++) {
renderer.DrawLine3D(rlbot::Color::yellow, points[i], points[i + 1]);
}
// Draw a green dot at the best predicted point
if (!points.empty()) {
rlbot::flat::Vector3 bestPoint = points[std::distance(points.begin(), std::find(points.begin(), points.end(), rlbot::flat::Vector3{
static_cast<float>(ballPred.GetAtTime(bestTime).pos.x),
static_cast<float>(ballPred.GetAtTime(bestTime).pos.y),
static_cast<float>(ballPred.GetAtTime(bestTime).pos.z)
}))];
renderer.DrawRect3D(
rlbot::Color::green,
bestPoint,
10.0f, // Width
10.0f, // Height
true, // Fill
true // Depth test
);
}
}
2. Implement CalculateReachMargin
This function calculates how close the player can reach the ball at a given time. It leverages your existing TimeToReachCalculatorv2 class to determine the time the player needs to reach the ball's position and computes the margin between the predicted time and the required time.
cpp
float RLBotBot::CalculateReachMargin(float predictionTime) const {
// Retrieve player data (implement GetPlayerData accordingly)
PlayerData player = GetPlayerData(); // You need to define this method
// Get the ball's position at the prediction time
PhysObj ballState = BallPred::getInstance().GetAtTime(predictionTime);
Vec targetPos = ballState.pos;
// Calculate the time required for the player to reach the target position
float timeToReach = TimeToReachCalculatorv2::calculateTimeToReach(player, targetPos);
// Compute the absolute difference between prediction and reach time
return std::abs(timeToReach - predictionTime);
}
Notes:
GetPlayerData Method: You need to implement this method to retrieve the current player's data (PlayerData). This typically involves accessing the player's current position, velocity, and other relevant physics data.
Error Handling: Ensure that your TimeToReachCalculatorv2 returns valid times. Handle cases where the player cannot reach the target within the prediction time.
3. Integrate with TimeToReachCalculatorv2
Ensure that your TimeToReachCalculatorv2 class is correctly integrated and accessible within the RLBotBot class. Here's a brief overview of how to utilize it:
cpp
// Example usage within RLBotBot
PlayerData RLBotBot::GetPlayerData() const {
// Implement this method to return the current player's data
// This might involve accessing game state or player objects
}
float RLBotBot::CalculateReachMargin(float predictionTime) const {
PlayerData player = GetPlayerData();
PhysObj ballState = BallPred::getInstance().GetAtTime(predictionTime);
Vec targetPos = ballState.pos;
float timeToReach = TimeToReachCalculatorv2::calculateTimeToReach(player, targetPos);
// Handle cases where timeToReach is not possible
if (timeToReach < 0.0f) {
// Assign a large penalty if unreachable
return std::numeric_limits<float>::max();
}
return std::abs(timeToReach - predictionTime);
}
Considerations:
Precision: The minimum interval (MIN_INTERVAL) and point interval (POINT_INTERVAL) can be adjusted based on the desired precision and performance constraints.
Performance: Trinary search reduces the number of evaluations needed compared to uniform sampling, but ensure that calculateTimeToReach is optimized for real-time performance, especially if called frequently.
Visualization: Adjust the rendering parameters (colors, sizes) as needed for better visualization in the game.
4. Testing and Validation
After implementing the above changes:
Test Different Scenarios: Verify the prediction rendering across various game states, player positions, and ball trajectories.
Performance Monitoring: Ensure that the trinary search and reach margin calculations do not introduce significant lag.
Visual Verification: Check that the rendered lines and dots accurately represent the predicted ball path and the optimal reach point.
5. Additional Enhancements
Adaptive Refinement Levels: Instead of a fixed number of refinement levels, you can make the process adaptive based on the change in margins.
Caching Results: If certain predictions are reused, consider caching results to avoid redundant calculations.
Parallel Processing: For further optimization, especially in complex scenarios, explore parallelizing reach margin calculations.
Conclusion
By implementing a trinary search approach in your RenderGlobalBallPred function, you can dynamically and efficiently determine the optimal prediction intervals. This method focuses computational resources on the most promising prediction times, enhancing both performance and accuracy. Integrating this with your TimeToReachCalculatorv2 ensures that the predictions are grounded in realistic player movement capabilities.
If you encounter specific issues during implementation or need further assistance with particular parts of the code, feel free to ask!