To scale the velocity component of your reward function based on the distance to the ground and the nearest walls, you'll need to incorporate these distances into your reward calculation. Below is a modified version of your TouchReward class that accomplishes this. I've added comments to explain each step.
#include <algorithm>
#include <cmath>
// Assuming Vec, RewardFunction, GameState, PlayerData, Action, etc., are defined elsewhere
class TouchReward : public RewardFunction {
public:
Vec prevVel;
// Constructor initializes previous velocity to zero
TouchReward() : prevVel(Vec(0, 0, 0)) {}
// Reset function resets the previous velocity
virtual void Reset(const GameState& initialState) override {
prevVel = Vec(0, 0, 0);
}
// Function to calculate the distance to the closest wall
static float DistToClosestWall(float x, float y) {
float dist_side_wall = std::abs(4096.0f - std::abs(x));
float dist_back_wall = std::abs(5120.0f - std::abs(y));
// Corner calculation
float x1 = 4096.0f - 1152.0f;
float y1 = 5120.0f;
float x2 = 4096.0f;
float y2 = 5120.0f - 1152.0f;
float A = std::abs(x) - x1;
float B = std::abs(y) - y1;
float C = x2 - x1;
float D = y2 - y1;
float dot = A * C + B * D;
float len_sq = C * C + D * D;
float param = (len_sq != 0) ? dot / len_sq : -1;
float xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
float dx = std::abs(x) - xx;
float dy = std::abs(y) - yy;
float dist_corner_wall = std::sqrt(dx * dx + dy * dy);
return std::min({ dist_side_wall, dist_back_wall, dist_corner_wall });
}
// Constants for scaling conditions
static constexpr float MAX_EXTRAP_Z = CommonValues::GOAL_HEIGHT + 230.f;
static constexpr float MIN_SCORE_TIME = 0.9f;
// Function to calculate scaling factor based on distances
float CalculateScalingFactor(const GameState& state) const {
// Calculate distance to the ground (assuming ground is at z = 0)
float distToGround = std::abs(state.ball.pos.z);
// Calculate distance to the closest wall
float distToWall = DistToClosestWall(state.ball.pos.x, state.ball.pos.y);
// Normalize distances to [0, 1] range for scaling
// You may need to adjust the denominators based on your game field dimensions
float normDistToGround = std::min(distToGround / 3000.0f, 1.0f); // Assuming 3000 units max height
float normDistToWall = std::min(distToWall / 5120.0f, 1.0f); // Assuming 5120 units max distance
// Combine the normalized distances. You can choose a different strategy if needed
// For example, using a weighted sum or a product
float scalingFactor = (normDistToGround + normDistToWall) / 2.0f;
// Ensure the scaling factor is within [0, 1]
scalingFactor = std::clamp(scalingFactor, 0.0f, 1.0f);
return scalingFactor;
}
// Modified GetReward function with scaling
virtual float GetReward(const PlayerData& player, const GameState& state, const Action& prevAction) override {
float reward = 0.0f;
// Only calculate reward if the ball was touched in this step
if (player.ballTouchedStep) {
// Calculate velocity difference
float velDiff = (prevVel - state.ball.vel).Length();
// Base velocity reward
float baseReward = (velDiff + state.ball.vel.Length()) / (3000.0f * 2.0f);
// Calculate scaling factor based on distances
float scalingFactor = CalculateScalingFactor(state);
// Apply scaling to the base reward
reward = baseReward * scalingFactor;
/*
// Debugging prints (uncomment if needed)
std::cout << "Vel diff: " << velDiff << std::endl;
std::cout << "Curr Vel: " << state.ball.vel.Length() << std::endl;
std::cout << "Base Reward: " << baseReward << std::endl;
std::cout << "Scaling Factor: " << scalingFactor << std::endl;
std::cout << "Scaled Reward: " << reward << std::endl;
std::cout << "Ball Vel: " << state.ball.vel << std::endl;
std::cout << "Previous Vel: " << prevVel << std::endl;
*/
}
// Update previous velocity for the next step
prevVel = state.ball.vel;
// Additional reward logic based on extrapolated position
float goalY = RLConst::SOCCAR_GOAL_SCORE_BASE_THRESHOLD_Y * (player.team == Team::BLUE ? 1 : -1);
float distToGoalY = std::abs(state.ball.pos.y - goalY);
float extrapScoreTime = distToGoalY / std::max(std::abs(state.ball.vel.y), 0.01f);
Vec extrapScorePos = state.ball.pos + state.ball.vel * extrapScoreTime;
extrapScorePos.z += CommonValues::GRAVITY_Z * (extrapScoreTime * extrapScoreTime) / 2;
if (extrapScoreTime <= MIN_SCORE_TIME || extrapScorePos.z >= MAX_EXTRAP_Z) {
reward = 0.0f; // Disable reward if the ball is about to score or go too high
}
return reward;
}
};
Explanation of Changes
-
Distance Calculations:
- Distance to Ground: Calculated as the absolute value of the ball's z-position (
state.ball.pos.z), assuming the ground is at z = 0.
- Distance to Wall: Utilizes the existing
DistToClosestWall function to calculate the nearest distance from the ball's position to any wall.
-
Scaling Factor Calculation:
- Normalization: Both distances are normalized to a [0, 1] range. You might need to adjust the normalization denominators (
3000.0f for ground distance and 5120.0f for wall distance) based on your game's field dimensions to ensure appropriate scaling.
- Combining Distances: The normalized distances are averaged to create a single scaling factor. This factor determines how much the velocity-based reward should be scaled. A higher distance results in a higher scaling factor, thus increasing the reward.
- Clamping: The scaling factor is clamped between 0 and 1 to prevent it from exceeding expected bounds.
-
Applying the Scaling Factor:
- The base velocity reward (
baseReward) is multiplied by the scalingFactor. This ensures that the velocity component of the reward is influenced by how far the ball is from the ground and walls.
-
Integration with Existing Logic:
- The existing logic that potentially zeroes out the reward based on extrapolated position remains unchanged and is executed after scaling the velocity-based reward.
- The
prevVel is updated at the end of the GetReward function to maintain state for the next reward calculation.
Additional Considerations
-
Parameter Tuning: The normalization constants (3000.0f and 5120.0f) are placeholders. You should adjust these based on the actual dimensions and dynamics of your game environment to ensure the scaling behaves as intended.
-
Scaling Strategy: Currently, the scaling factor is a simple average of the normalized distances. Depending on your specific requirements, you might want to use a different method to combine these distances, such as a weighted sum, product, or a more complex function.
-
Performance Optimization: If CalculateScalingFactor is computationally expensive and the reward function is called frequently, consider caching results or optimizing the function further.
-
Testing and Debugging: Uncomment the debugging std::cout statements to monitor the values of velocity differences, scaling factors, and rewards to ensure that the scaling behaves as expected during development.
By integrating the distance-based scaling into your reward function, the agent will be incentivized not only based on the velocity of the ball but also considering its proximity to the ground and walls, potentially leading to more context-aware and effective behavior.