void RLBotBot::RenderTimeToReachBall(const RLGSC::GameState& gs) { if…
- User
void RLBotBot::RenderTimeToReachBall(const RLGSC::GameState& gs) { if (!renderTimeToReachBallEnabled || !ballPredTracker) return; rlbot::ScopedRenderer renderer("time_to_reach_renderer");
auto calculateMinAirTime = [](const Vec& playerPos, const Vec& playerVel, bool hasFlip) { constexpr float GRAVITY = 650.0f; float timeToGround = RS_MAX(0.0f, (-playerVel.z + std::sqrt(playerVel.z * playerVel.z + 2 * GRAVITY * playerPos.z)) / GRAVITY); float timeToSideWall = (playerVel.x != 0.0f) ? RS_MIN( std::abs((CommonValues::SIDE_WALL_X - playerPos.x) / playerVel.x), std::abs((-CommonValues::SIDE_WALL_X - playerPos.x) / playerVel.x) ) : std::numeric_limits<float>::infinity(); float timeToBackWall = (playerVel.y != 0.0f) ? RS_MIN( std::abs((CommonValues::BACK_WALL_Y - playerPos.y) / playerVel.y), std::abs((-CommonValues::BACK_WALL_Y - playerPos.y) / playerVel.y) ) : std::numeric_limits<float>::infinity(); float timeToCeiling = (playerVel.z > 0.0f) ? (CommonValues::CEILING_Z - playerPos.z) / playerVel.z : std::numeric_limits<float>::infinity(); return RS_MIN(RS_MIN(timeToGround, timeToSideWall), RS_MIN(timeToBackWall, timeToCeiling)); }; auto getTimeToReachBall = [&calculateMinAirTime](const PlayerData& player, const Vec& ballPos) { constexpr float MAX_ROTATION_SPEED = 5.5f; constexpr float DIST_REACH_THRESH = 10.0f; constexpr float STEP_INTERVAL = 1.0f / 60.0f; constexpr float FLIP_FORCE = 500.0f; constexpr float AIR_ACCEL = 66.66667f; constexpr float BOOST_ACCEL_AIR = 1058.33333f; constexpr float MAX_TOTAL_SPEED = 2300.0f; constexpr float BRAKE_ACCEL = 3500.0f; constexpr float BOOST_ACCEL_GROUND = 991.66667f; constexpr float DRIVE_ACCEL = 1600.0f; constexpr float MAX_DRIVE_SPEED = 1410.0f; const Vec& playerPos = player.phys.pos; const Vec& playerForward = player.phys.rotMat.forward; const Vec& playerVel = player.phys.vel; bool hasFlip = player.carState.HasFlipOrJump(); float dist = (ballPos - playerPos).Length(); Vec dirToBall = ballPos - playerPos; Vec normalizedDirToBall = dirToBall.Normalized(); float curVel = playerVel.Dot(normalizedDirToBall); float angleDiff = std::acos(RS_CLAMP(playerForward.Dot(normalizedDirToBall), -1.0f, 1.0f)); float rotTime = angleDiff / MAX_ROTATION_SPEED; float t = 0.0f; float curDist = dist; float minAirTime = calculateMinAirTime(playerPos, playerVel, hasFlip); while (t < minAirTime && curDist > DIST_REACH_THRESH) { bool hasRotated = t >= rotTime; if (hasFlip && t == 0.0f) { curVel += FLIP_FORCE; } float airAccel = AIR_ACCEL + (BOOST_ACCEL_AIR * hasRotated); curVel += airAccel * STEP_INTERVAL; curVel = RS_MIN(curVel, MAX_TOTAL_SPEED); curDist -= curVel * STEP_INTERVAL; t += STEP_INTERVAL; } while (curDist > DIST_REACH_THRESH) { bool hasRotated = t >= rotTime; if (curVel < 0.0f) { curVel += (BRAKE_ACCEL + BOOST_ACCEL_GROUND * hasRotated) * STEP_INTERVAL; } else if (curVel < MAX_DRIVE_SPEED) { curVel += (DRIVE_ACCEL + BOOST_ACCEL_GROUND * hasRotated) * STEP_INTERVAL; } else if (curVel < MAX_TOTAL_SPEED) { curVel += BOOST_ACCEL_GROUND * hasRotated * STEP_INTERVAL; } else { float remainingTime = curDist / curVel; return t + remainingTime; } curVel = RS_MIN(curVel, MAX_TOTAL_SPEED); curDist -= curVel * STEP_INTERVAL; t += STEP_INTERVAL; } return t; }; constexpr float PREDICTION_DURATION = 6.0f; // Predict 6 seconds into the future // Update ball prediction RocketSim::BallState currentBallState; currentBallState.pos = RocketSim::Vec(gs.ball.pos.x, gs.ball.pos.y, gs.ball.pos.z); currentBallState.vel = RocketSim::Vec(gs.ball.vel.x, gs.ball.vel.y, gs.ball.vel.z); currentBallState.angVel = RocketSim::Vec(gs.ball.angVel.x, gs.ball.angVel.y, gs.ball.angVel.z); currentBallState.rotMat = RocketSim::RotMat(gs.ball.rotMat.forward, gs.ball.rotMat.right, gs.ball.rotMat.up); int numTicks = static_cast<int>(PREDICTION_DURATION * 120); // Assuming 120 ticks per second ballPredTracker->UpdatePredManual(currentBallState, numTicks); const auto& ballPredData = ballPredTracker->predData; size_t numPoints = RS_MIN(static_cast<size_t>(numTicks), ballPredData.size()); // Find the opponent const PlayerData* opponent = nullptr; for (const auto& player : gs.players) { if (player.team != gs.players[index].team) { opponent = &player; break; } } if (!opponent) { // No opponent found, return early return; } std::vector<float> localTimeToReach(numPoints); std::vector<float> opponentTimeToReach(numPoints); float localPossession = 0.0f; float opponentPossession = 0.0f; for (size_t j = 0; j < numPoints; ++j) { Vec ballPos(ballPredData[j].pos.x, ballPredData[j].pos.y, ballPredData[j].pos.z); localTimeToReach[j] = getTimeToReachBall(gs.players[index], ballPos); opponentTimeToReach[j] = getTimeToReachBall(*opponent, ballPos); if (localTimeToReach[j] < opponentTimeToReach[j]) { localPossession += 1.0f; } else { opponentPossession += 1.0f; } } float totalPossession = localPossession + opponentPossession; localPossession /= totalPossession; opponentPossession /= totalPossession; // Render possession information std::stringstream localSS, opponentSS; localSS << "Local player possession: " << std::fixed << std::setprecision(2) << localPossession * 100 << "%"; opponentSS << "Opponent possession: " << std::fixed << std::setprecision(2) << opponentPossession * 100 << "%"; renderer.DrawString2D(localSS.str(), rlbot::Color::blue, rlbot::flat::Vector3{ 10, 10, 0 }, 2.0f, 2.0f); renderer.DrawString2D(opponentSS.str(), rlbot::Color::white, rlbot::flat::Vector3{ 10, 40, 0 }, 2.0f, 2.0f); // Render the path and time to reach for both players std::vector<rlbot::flat::Vector3> points; std::vector<const rlbot::flat::Vector3*> pointPointers; for (size_t j = 0; j < numPoints; j += 5) { points.push_back({ static_cast<float>(ballPredData[j].pos.x), static_cast<float>(ballPredData[j].pos.y), static_cast<float>(ballPredData[j].pos.z) }); pointPointers.push_back(&points.back()); std::stringstream localSS, opponentSS; localSS << std::fixed << std::setprecision(2) << localTimeToReach[j] << "s"; opponentSS << std::fixed << std::setprecision(2) << opponentTimeToReach[j] << "s"; rlbot::flat::Vector3 localTextPos = { static_cast<float>(ballPredData[j].pos.x), static_cast<float>(ballPredData[j].pos.y), static_cast<float>(ballPredData[j].pos.z + 50.0f) }; rlbot::flat::Vector3 opponentTextPos = { static_cast<float>(ballPredData[j].pos.x), static_cast<float>(ballPredData[j].pos.y), static_cast<float>(ballPredData[j].pos.z - 50.0f) }; renderer.DrawString3D(localSS.str(), rlbot::Color::blue, localTextPos, 1.0f, 1.0f); renderer.DrawString3D(opponentSS.str(), rlbot::Color::white, opponentTextPos, 1.0f, 1.0f); } renderer.DrawPolyLine3D(rlbot::Color::yellow, pointPointers); // Render overall possession summary std::stringstream summaryStream; summaryStream << "Team Possession - " << (gs.players[index].team == Team::BLUE ? "Blue: " : "Orange: ") << std::fixed << std::setprecision(2) << localPossession * 100 << "% | " << (gs.players[index].team == Team::BLUE ? "Orange: " : "Blue: ") << opponentPossession * 100 << "%"; renderer.DrawString2D(summaryStream.str(), rlbot::Color::white, rlbot::flat::Vector3{ 10, 70, 0 }, 2.0f, 2.0f);} is the logic and calculations for this totally logic?
- Assistant
Your
RenderTimeToReachBallfunction employs a reasonable approach to estimate and visualize the time it takes for both the local player and an opponent to reach the ball in a Rocket League match. However, there are several areas where the logic and calculations can be refined to ensure accuracy and efficiency. Here's a detailed analysis of your implementation:1. Min Air Time Calculation (
calculateMinAirTime)Current Implementation:
float timeToGround = RS_MAX(0.0f, (-playerVel.z + std::sqrt(playerVel.z * playerVel.z + 2 * GRAVITY * playerPos.z)) / GRAVITY);Issue Identified: The quadratic equation used to calculate
timeToGroundmay have an incorrect sign. In the standard physics formula for projectile motion under gravity:[ z(t) = z_0 + v_z t - \frac{1}{2} g t^2 ]
Solving for
z(t) = 0gives:[ t = \frac{v_z + \sqrt{v_z^2 + 2 g z_0}}{g} ]
However, your implementation uses:
[ t = \frac{-v_z + \sqrt{v_z^2 + 2 g z_0}}{g} ]
Recommendation: Ensure that the correct root is selected to represent the positive and physically meaningful time. Typically, the positive root (i.e., using
+v_zinstead of-v_z) is appropriate unless there's a specific reason to choose otherwise based on your coordinate system.Revised Calculation:
float timeToGround = (playerVel.z + std::sqrt(playerVel.z * playerVel.z + 2 * GRAVITY * playerPos.z)) / GRAVITY; timeToGround = RS_MAX(0.0f, timeToGround);2. Opponent Selection
Current Implementation:
const PlayerData* opponent = nullptr; for (const auto& player : gs.players) { if (player.team != gs.players[index].team) { opponent = &player; break; } }Issue Identified: The function selects only the first opponent found, which might not accurately represent the actual competition for ball possession, especially in matches with multiple opponents.
Recommendation: Consider iterating through all opponents to determine which one has the quickest time to reach each predicted ball position. This ensures a more accurate assessment of possession chances.
Revised Approach:
std::vector<const PlayerData*> opponents; for (const auto& player : gs.players) { if (player.team != gs.players[index].team) { opponents.push_back(&player); } } // Later in possession calculation: for (size_t j = 0; j < numPoints; ++j) { Vec ballPos(ballPredData[j].pos.x, ballPredData[j].pos.y, ballPredData[j].pos.z); localTimeToReach[j] = getTimeToReachBall(gs.players[index], ballPos); float minOpponentTime = std::numeric_limits<float>::infinity(); for (const auto& opp : opponents) { float oppTime = getTimeToReachBall(*opp, ballPos); if (oppTime < minOpponentTime) { minOpponentTime = oppTime; } } opponentTimeToReach[j] = minOpponentTime; if (localTimeToReach[j] < opponentTimeToReach[j]) { localPossession += 1.0f; } else { opponentPossession += 1.0f; } }3. Time Step and Prediction Points
Current Implementation:
constexpr float STEP_INTERVAL = 1.0f / 60.0f; int numTicks = static_cast<int>(PREDICTION_DURATION * 120); // Assuming 120 ticks per second size_t numPoints = RS_MIN(static_cast<size_t>(numTicks), ballPredData.size());Issue Identified: The function uses a high number of prediction points (e.g., 720 points for a 6-second prediction at 120 ticks per second), which can be computationally intensive, especially when considering multiple opponents.
Recommendation: Optimize by reducing the number of prediction points or increasing the
STEP_INTERVALto lessen computational load without significantly compromising accuracy. Additionally, ensure that the prediction frequency aligns with the game's update rate.Revised Approach:
constexpr float STEP_INTERVAL = 1.0f / 60.0f; // Adjust as needed based on game performance int numTicks = static_cast<int>(PREDICTION_DURATION / STEP_INTERVAL); size_t numPoints = RS_MIN(static_cast<size_t>(numTicks), ballPredData.size());4. Movement and Acceleration Modeling (
getTimeToReachBall)Current Implementation: The function
getTimeToReachBallsimulates the player's movement towards the ball using simplified physics, considering factors like flipping, acceleration, and maximum speeds.Issue Identified: Rocket League's physics are complex, and the current model may oversimplify certain aspects, potentially leading to inaccurate time estimations.
Recommendation: Enhance the movement model by incorporating more detailed physics, such as boosting mechanics, drag, and precise handling of jumps and flips. Alternatively, validate the current model against in-game data to ensure its accuracy and make adjustments as necessary.
5. Rendering Considerations
Current Implementation: The function renders detailed information, including per-point reach times and possession percentages, which can be cluttered visually.
Recommendation: Streamline the rendering by selectively displaying key information, such as overall possession percentages and highlighting critical prediction points where possession changes. This approach improves readability without overwhelming the user with excessive data.
6. Code Optimization and Maintenance
Recommendations:
- Modularize the Code: Break down large functions into smaller, more manageable pieces with clear responsibilities.
- Documentation: Add comments and documentation to explain complex calculations and logic, facilitating easier maintenance and updates.
- Performance Profiling: Regularly profile the code to identify and address performance bottlenecks, especially if the function impacts game performance.
Conclusion
While the foundational logic of your
RenderTimeToReachBallfunction is sound, addressing the highlighted areas will enhance its accuracy, efficiency, and maintainability. By refining the time calculations, opponent selection process, and movement modeling, you can achieve a more precise and reliable estimation of ball possession dynamics within your Rocket League bot.Feel free to reach out if you need further assistance or specific code examples for any of the recommended changes!