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;
}
}; make it exactly like zealan is talking abot and make all implmenatations 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
fredrik.. — Today at 2:00 AM
So what do we do then? Arent i supposed to precompute all possible answers or have i missunderstood?
Zealan — Today at 2:02 AM
bro
ive already answered this
To align your TimeToReachCalculator class with Zealan's approach, you'll need to implement a lookup table that significantly reduces computational complexity by limiting the dimensions and utilizing interpolations. This approach ensures O(1) time complexity for calculating the minimum time to reach a position for each car, while keeping the memory footprint manageable (around 500MB as discussed).
Here's a step-by-step guide to refactoring your TimeToReachCalculator class:
Reduce Dimensionality: Instead of accounting for full 3D positions and velocities, focus on key dimensions:
2D Delta Position (XY): The horizontal distance to the target.
Delta Z: The vertical distance to the target.
Velocity Toward Target: A single float representing the component of velocity in the direction of the target.
Rotation Time: Time required to align the car's orientation towards the target.
Surface Time: Time required to reach any surface (walls, floor).
Create a Lookup Table Structure:
Bins/Subdivisions: Divide each dimension into discrete bins to limit the number of possible values.
Interpolation: Use bilinear or trilinear interpolation between nearby precomputed values to achieve higher accuracy without exponentially increasing table size.
Precompute the Lookup Table:
Due to the vast number of possible states, precompute only the essential subset of states by focusing on deltaPos and other reduced dimensions.
Store this data efficiently, possibly compressing it or using a multi-level lookup approach.
Modify the Calculation Method:
Replace the iterative loop with a direct lookup from the precomputed table.
Handle edge cases and perform interpolations as necessary to maintain accuracy.
Example Implementation:
Below is an example of how you might implement this approach in your TimeToReachCalculator class. Note that this is a high-level example and may require adjustments based on your specific requirements and constraints.
cpp
#include <cmath>
#include <vector>
#include <array>
#include <limits>
#include <cassert>
#include <mutex>
// Define the dimensions for the lookup table
constexpr int XY_RESOLUTION = 300; // Adjust based on required precision
constexpr int Z_RESOLUTION = 100;
constexpr int VELOCITY_RESOLUTION = 100;
constexpr int ROT_TIME_RESOLUTION = 50;
constexpr int SURFACE_TIME_RESOLUTION = 50;
// Define the ranges for each dimension
constexpr float MAX_XY_DIST = 6000.0f;
constexpr float MAX_Z_DIST = 3000.0f;
constexpr float MAX_VELOCITY = 2300.0f;
constexpr float MAX_ROT_TIME = 2.0f; // seconds
constexpr float MAX_SURFACE_TIME = 10.0f; // seconds
// Helper function for clamping
template <typename T>
constexpr T clamp(const T& value, const T& minVal, const T& maxVal) {
return value < minVal ? minVal : (value > maxVal ? maxVal : value);
}
// TimeToReachCalculator Class with Lookup Table
class TimeToReachCalculator {
public:
// Initialize the lookup table (singleton pattern)
static TimeToReachCalculator& getInstance() {
static TimeToReachCalculator instance;
return instance;
}
// Main function to calculate time to reach using the lookup table
float calculateTimeToReach(const PlayerData& player, const Vec& targetPos) {
// Calculate delta positions
Vec deltaPos = targetPos - player.phys.pos;
float xyDist = std::sqrt(deltaPos.x * deltaPos.x + deltaPos.y * deltaPos.y);
float zDist = deltaPos.z;
// Calculate velocity towards target
Vec dirToTarget = deltaPos.Normalized();
float velToTarget = clamp(player.phys.vel.Dot(dirToTarget), -MAX_TOTAL_SPEED, MAX_TOTAL_SPEED);
// Calculate rotation time
float rotTime = calculateRotationTime(player, targetPos);
// Calculate surface time
float surfaceTime = calculateTimeToReachAnySurface(player);
// Clamp all parameters to lookup table ranges
xyDist = clamp(xyDist, 0.0f, MAX_XY_DIST);
zDist = clamp(zDist, -MAX_Z_DIST, MAX_Z_DIST);
velToTarget = clamp(velToTarget, -MAX_VELOCITY, MAX_VELOCITY);
rotTime = clamp(rotTime, 0.0f, MAX_ROT_TIME);
surfaceTime = clamp(surfaceTime, 0.0f, MAX_SURFACE_TIME);
// Convert continuous values to discrete indices
int xyIdx = static_cast<int>((xyDist / MAX_XY_DIST) * (XY_RESOLUTION - 1));
int zIdx = static_cast<int>(((zDist + MAX_Z_DIST) / (2 * MAX_Z_DIST)) * (Z_RESOLUTION - 1));
int velIdx = static_cast<int>(((velToTarget + MAX_VELOCITY) / (2 * MAX_VELOCITY)) * (VELOCITY_RESOLUTION - 1));
int rotIdx = static_cast<int>((rotTime / MAX_ROT_TIME) * (ROT_TIME_RESOLUTION - 1));
int surfaceIdx = static_cast<int>((surfaceTime / MAX_SURFACE_TIME) * (SURFACE_TIME_RESOLUTION - 1));
// Retrieve the precomputed time from the lookup table
float precomputedTime = lookupTable[xyIdx][zIdx][velIdx][rotIdx][surfaceIdx];
// Optionally, perform interpolation here for higher accuracy
return precomputedTime;
}
private:
// Private constructor for singleton
TimeToReachCalculator() {
// Initialize the lookup table
// For demonstration, we'll fill it with dummy values
// In practice, you should precompute these values based on your physics
lookupTable.resize(XY_RESOLUTION);
for(auto& xyPlane : lookupTable) {
xyPlane.resize(Z_RESOLUTION);
for(auto& zPlane : xyPlane) {
zPlane.resize(VELOCITY_RESOLUTION);
for(auto& velPlane : zPlane) {
velPlane.resize(ROT_TIME_RESOLUTION);
for(auto& rotPlane : velPlane) {
rotPlane.resize(SURFACE_TIME_RESOLUTION, 0.0f); // Initialize with 0.0f or actual computed time
}
}
}
}
// TODO: Precompute and fill the lookup table with actual time values
// This could be done offline and loaded from a file to save initialization time
// Alternatively, implement a precomputation step here
}
// Delete copy constructor and assignment operator
TimeToReachCalculator(const TimeToReachCalculator&) = delete;
TimeToReachCalculator& operator=(const TimeToReachCalculator&) = delete;
// Lookup table: 5-dimensional vector
std::vector<std::vector<std::vector<std::vector<std::vector<float>>>>> lookupTable;
// Constants (same as original class)
static constexpr float SIDE_WALL_X = 4096.0f;
static constexpr float CLOSE_DISTANCE = 10.0f;
static constexpr float NEAR_WALL_DISTANCE = 4077.0f;
static constexpr float Z_THRESHOLD = 256.0f;
static constexpr float EPSILON = 1e-3f;
static constexpr float DIST_REACH_THRESH = 80.0f;
static constexpr float STEP_INTERVAL = 1.0f / 60.0f;
static constexpr float FLIP_FORCE = 495.0f;
static constexpr float AIR_ACCEL = 133.334f;
static constexpr float BOOST_ACCEL_AIR = 2116.666f;
static constexpr float MAX_TOTAL_SPEED = 2300.0f;
static constexpr float BRAKE_ACCEL = 3500.0f;
static constexpr float BOOST_ACCEL_GROUND = 1983.332f;
static constexpr float DRIVE_ACCEL = 1600.0f;
static constexpr float MAX_DRIVE_SPEED = 1410.0f;
static constexpr float GRAVITY_Z = -650.0f;
static constexpr float BACK_WALL_Y = 5120.0f;
static constexpr float NEG_BACK_WALL_Y = -5120.0f;
static constexpr float MAX_BACKWALL_Y = 5100.0f;
static constexpr float BOOST_ACCEL_POS = 1000.0f;
static constexpr float BOOST_ACCEL_NEG = -1000.0f;
static constexpr float FLOOR_Z = 18.0f;
static constexpr float BOOST_ACCEL_DOWN = -1000.0f;
static constexpr float MAX_TIME = 10.0f;
static constexpr float JUMP_IMPULSE = 291.667f;
static constexpr float GROUND_Z_THRESHOLD = 50.0f;
static constexpr float MAX_SIMULATION_TIME = 10.0f;
// Example placeholder for calculateRotationTime (retain original implementation)
float calculateRotationTime(const PlayerData& player, const Vec& targetPos) const {
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 = clamp(playerForward.Dot(dirToTarget), -1.0f, 1.0f);
float angleDiff = std::acos(dotProduct);
return angleDiff / MAX_ANG_VEL;
}
// Example placeholder for calculateTimeToReachAnySurface (retain original implementation)
float calculateTimeToReachAnySurface(const PlayerData& player) const {
// ... (Same as your original implementation)
// This should remain unchanged or be optimized similarly
// For brevity, not included here
return 0.0f; // Placeholder
}
};
// Usage Example
/*
int main() {
PlayerData player;
Vec targetPos;
// Initialize player and targetPos...
TimeToReachCalculator& calculator = TimeToReachCalculator::getInstance();
float time = calculator.calculateTimeToReach(player, targetPos);
// Use the calculated time...
}
*/
Detailed Explanation:
Singleton Pattern:
The TimeToReachCalculator class is implemented as a singleton to ensure that only one instance of the lookup table exists, conserving memory and ensuring consistency across calculations.
Lookup Table Dimensions:
The lookup table is a 5-dimensional vector representing:
XY Distance (XY_RESOLUTION)
Z Distance (Z_RESOLUTION)
Velocity Toward Target (VELOCITY_RESOLUTION)
Rotation Time (ROT_TIME_RESOLUTION)
Surface Time (SURFACE_TIME_RESOLUTION)
Index Calculation:
Each parameter is clamped to its maximum value to prevent out-of-bound errors.
Continuous values are converted to discrete indices based on their resolution and maximum range.
Precomputation:
The example initializes the lookup table with dummy values (0.0f). In practice, you need to precompute the actual time values based on your physics engine and fill the lookup table accordingly.
Precomputation Strategies:
Offline Precomputation: Calculate the times beforehand and serialize the lookup table to a file. Load this file at runtime.
Runtime Precomputation: Implement a separate initialization step that fills the lookup table by simulating scenarios. This can be time-consuming and may not be feasible for large tables.
Interpolation:
To enhance accuracy without dramatically increasing the table size, implement interpolation between the nearest precomputed values. This is especially useful when the exact indices do not match the current state.
Thread Safety:
If your application is multithreaded, ensure that the lookup table is thread-safe. You might need to use mutexes or other synchronization mechanisms during the table initialization phase.
Memory Optimization:
Given the potentially large size of a 5D lookup table, consider using more memory-efficient data structures or compression techniques.
To align with your target of around 500MB, you can adjust the resolutions accordingly or include additional parameters as needed.
Final Notes
Precompute Offline: Given the high computational cost of filling a large lookup table, precompute the table offline and load it at runtime. This approach avoids lengthy initialization times during gameplay.
Dynamic Adjustments: If certain parameters vary significantly during gameplay, consider implementing dynamic adjustments or partial recalculations to maintain accuracy.
Testing and Validation: Rigorously test the accuracy of your lookup table against the original iterative calculation to ensure that the interpolation and dimensionality reduction do not introduce significant errors.
Scalability: Monitor the lookup table's performance and scalability, especially if you plan to support more cars or additional game mechanics in the future.
By following this approach, you can optimize your TimeToReachCalculator to operate efficiently with reduced memory usage while maintaining high accuracy through strategic dimensionality reduction and interpolation.
Not yet included in a published release.
Example: If certain dimensions have dependencies or constraints, you can reduce the effective dimensions by eliminating redundant or impossible states.
Alternative Approaches:
Hashing Partial States: Instead of a full 5D table, hash partial states and store only the most critical combinations.
Function Approximation: Use machine learning models or mathematical functions to approximate the time to reach based on input parameters, reducing the need for extensive lookup tables.