blob: 7aaefacf1b71f2b67e81563b7cab88629395ba35 [file] [log] [blame]
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -08001#include "y2020/control_loops/superstructure/turret/aiming.h"
2
James Kuszmaulb83d6e12020-02-22 20:44:48 -08003#include "y2020/constants.h"
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -08004#include "y2020/control_loops/drivetrain/drivetrain_base.h"
5
6namespace y2020 {
7namespace control_loops {
8namespace superstructure {
9namespace turret {
10
11using frc971::control_loops::Pose;
12
James Kuszmaul3b393d72020-02-26 19:43:51 -080013// Shooting-on-the-fly concept:
14// The current way that we manage shooting-on-the fly endeavors to be reasonably
15// simple, until we get a chance to see how the actual dynamics play out.
16// Essentially, we assume that the robot's velocity will represent a constant
17// offset to the ball's velocity over the entire trajectory to the goal and
18// then offset the target that we are pointing at based on that.
19// Let us assume that, if the robot shoots while not moving, regardless of shot
20// distance, the ball's average speed-over-ground to the target will be a
21// constant s_shot (this implies that if the robot is driving straight towards
22// the target, the actual ball speed-over-ground will be greater than s_shot).
23// We will define things in the robot's coordinate frame. We will be shooting
24// at a target that is at position (target_x, target_y) in the robot frame. The
25// robot is travelling at (v_robot_x, v_robot_y). In order to shoot the ball,
26// we need to generate some virtual target (virtual_x, virtual_y) that we will
27// shoot at as if we were standing still. The total time-of-flight to that
28// target will be t_shot = norm2(virtual_x, virtual_y) / s_shot.
29// we will have virtual_x + v_robot_x * t_shot = target_x, and the same
30// for y. This gives us three equations and three unknowns (virtual_x,
31// virtual_y, and t_shot), and given appropriate assumptions, can be solved
32// analytically. However, doing so is obnoxious and given appropriate functions
33// for t_shot may not be feasible. As such, instead of actually solving the
34// equation analytically, we will use an iterative solution where we maintain
35// a current virtual target estimate. We start with this estimate as if the
36// robot is stationary. We then use this estimate to calculate t_shot, and
37// calculate the next value for the virtual target.
38
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -080039namespace {
James Kuszmaula53c3ac2020-02-22 19:36:01 -080040// The overall length and width of the field, in meters.
41constexpr double kFieldLength = 15.983;
42constexpr double kFieldWidth = 8.212;
43// Height of the center of the port(s) above the ground, in meters.
44constexpr double kPortHeight = 2.494;
45
46// Maximum shot angle at which we will attempt to make the shot into the inner
47// port, in radians. Zero would imply that we could only shoot if we were
48// exactly perpendicular to the target. Larger numbers allow us to aim at the
49// inner port more aggressively, at the risk of being more likely to miss the
50// outer port entirely.
51constexpr double kMaxInnerPortAngle = 20.0 * M_PI / 180.0;
52
53// Distance (in meters) from the edge of the field to the port.
54constexpr double kEdgeOfFieldToPort = 2.404;
55
56// The amount (in meters) that the inner port is set back from the outer port.
57constexpr double kInnerPortBackset = 0.743;
58
James Kuszmaul3b393d72020-02-26 19:43:51 -080059// Average speed-over-ground of the ball on its way to the target. Our current
60// model assumes constant ball velocity regardless of shot distance.
61// TODO(james): Is this an appropriate model? For the outer port it should be
62// good enough that it doesn't really matter, but for the inner port it may be
63// more appropriate to do something more dynamic--however, it is not yet clear
64// how we would best estimate speed-over-ground given a hood angle + shooter
65// speed. Assuming a constant average speed over the course of the trajectory
66// should be reasonable, since all we are trying to do here is calculate an
67// overall time-of-flight (we don't actually care about the ball speed itself).
68constexpr double kBallSpeedOverGround = 15.0; // m/s
James Kuszmaulb83d6e12020-02-22 20:44:48 -080069
James Kuszmaula53c3ac2020-02-22 19:36:01 -080070// Minimum distance that we must be from the inner port in order to attempt the
71// shot--this is to account for the fact that if we are too close to the target,
72// then we won't have a clear shot on the inner port.
73constexpr double kMinimumInnerPortShotDistance = 4.0;
74
James Kuszmaulb83d6e12020-02-22 20:44:48 -080075// Amount of buffer, in radians, to leave to help avoid wrapping. I.e., any time
76// that we are in kAvoidEdges mode, we will keep ourselves at least
77// kAntiWrapBuffer radians away from the hardstops.
78constexpr double kAntiWrapBuffer = 0.2;
79
80constexpr double kTurretRange = constants::Values::kTurretRange().range();
81static_assert((kTurretRange - 2.0 * kAntiWrapBuffer) > 2.0 * M_PI,
82 "kAntiWrap buffer should be small enough that we still have 360 "
83 "degrees of range.");
84
James Kuszmaula53c3ac2020-02-22 19:36:01 -080085Pose ReverseSideOfField(Pose target) {
86 *target.mutable_pos() *= -1;
87 target.set_theta(aos::math::NormalizeAngle(target.rel_theta() + M_PI));
88 return target;
89}
90
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -080091flatbuffers::DetachedBuffer MakePrefilledGoal() {
92 flatbuffers::FlatBufferBuilder fbb;
93 fbb.ForceDefaults(true);
94 Aimer::Goal::Builder builder(fbb);
95 builder.add_unsafe_goal(0);
96 builder.add_goal_velocity(0);
97 builder.add_ignore_profile(true);
98 fbb.Finish(builder.Finish());
99 return fbb.Release();
100}
James Kuszmaul3b393d72020-02-26 19:43:51 -0800101
102// This implements the iteration in the described shooting-on-the-fly algorithm.
103// robot_pose: Current robot pose.
104// robot_velocity: Current robot velocity, in the absolute field frame.
105// target_pose: Absolute goal Pose.
106// current_virtual_pose: Current estimate of where we want to shoot at.
107Pose IterateVirtualGoal(const Pose &robot_pose,
108 const Eigen::Vector3d &robot_velocity,
109 const Pose &target_pose,
110 const Pose &current_virtual_pose) {
111 const double air_time =
112 current_virtual_pose.Rebase(&robot_pose).xy_norm() / kBallSpeedOverGround;
113 const Eigen::Vector3d virtual_target =
114 target_pose.abs_pos() - air_time * robot_velocity;
115 return Pose(virtual_target, target_pose.abs_theta());
116}
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800117} // namespace
118
James Kuszmaula53c3ac2020-02-22 19:36:01 -0800119Pose InnerPortPose(aos::Alliance alliance) {
120 const Pose target({kFieldLength / 2 + kInnerPortBackset,
121 -kFieldWidth / 2.0 + kEdgeOfFieldToPort, kPortHeight},
122 0.0);
123 if (alliance == aos::Alliance::kRed) {
124 return ReverseSideOfField(target);
125 }
126 return target;
127}
128
129Pose OuterPortPose(aos::Alliance alliance) {
130 Pose target(
131 {kFieldLength / 2, -kFieldWidth / 2.0 + kEdgeOfFieldToPort, kPortHeight},
132 0.0);
133 if (alliance == aos::Alliance::kRed) {
134 return ReverseSideOfField(target);
135 }
136 return target;
137}
138
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800139Aimer::Aimer() : goal_(MakePrefilledGoal()) {}
140
James Kuszmaul3b393d72020-02-26 19:43:51 -0800141void Aimer::Update(const Status *status, aos::Alliance alliance,
142 WrapMode wrap_mode, ShotMode shot_mode) {
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800143 const Pose robot_pose({status->x(), status->y(), 0}, status->theta());
James Kuszmaula53c3ac2020-02-22 19:36:01 -0800144 const Pose inner_port = InnerPortPose(alliance);
145 const Pose outer_port = OuterPortPose(alliance);
146 const Pose robot_pose_from_inner_port = robot_pose.Rebase(&inner_port);
James Kuszmaul3b393d72020-02-26 19:43:51 -0800147
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800148 // TODO(james): This code should probably just be in the localizer and have
149 // xdot/ydot get populated in the status message directly... that way we don't
150 // keep duplicating this math.
151 // Also, this doesn't currently take into account the lateral velocity of the
152 // robot. All of this would be helped by just doing this work in the Localizer
153 // itself.
154 const Eigen::Vector2d linear_angular =
155 drivetrain::GetDrivetrainConfig().Tlr_to_la() *
156 Eigen::Vector2d(status->localizer()->left_velocity(),
157 status->localizer()->right_velocity());
James Kuszmaul3b393d72020-02-26 19:43:51 -0800158 const double xdot = linear_angular(0) * std::cos(status->theta());
159 const double ydot = linear_angular(0) * std::sin(status->theta());
160
161 const double inner_port_angle = robot_pose_from_inner_port.heading();
162 const double inner_port_distance = robot_pose_from_inner_port.xy_norm();
163 aiming_for_inner_port_ =
164 (std::abs(inner_port_angle) < kMaxInnerPortAngle) &&
165 (inner_port_distance > kMinimumInnerPortShotDistance);
166
167 // This code manages compensating the goal turret heading for the robot's
168 // current velocity, to allow for shooting on-the-fly.
169 // This works by solving for the correct turret angle numerically, since while
170 // we technically could do it analytically, doing so would both make it hard
171 // to make small changes (since it would force us to redo the math) and be
172 // error-prone since it'd be easy to make typos or other minor math errors.
173 Pose virtual_goal;
174 {
175 const Pose goal = aiming_for_inner_port_ ? inner_port : outer_port;
176 virtual_goal = goal;
177 if (shot_mode == ShotMode::kShootOnTheFly) {
178 for (int ii = 0; ii < 3; ++ii) {
179 virtual_goal =
180 IterateVirtualGoal(robot_pose, {xdot, ydot, 0}, goal, virtual_goal);
181 }
182 VLOG(1) << "Shooting-on-the-fly target position: "
183 << virtual_goal.abs_pos().transpose();
184 }
185 virtual_goal = virtual_goal.Rebase(&robot_pose);
186 }
187
188 const double heading_to_goal = virtual_goal.heading();
189 CHECK(status->has_localizer());
190 distance_ = virtual_goal.xy_norm();
191
192 // The following code all works to calculate what the rate of turn of the
193 // turret should be. The code only accounts for the rate of turn if we are
194 // aiming at a static target, which should be close enough to correct that it
195 // doesn't matter that it fails to account for the
196 // shooting-on-the-fly compensation.
197 const double rel_x = virtual_goal.rel_pos().x();
198 const double rel_y = virtual_goal.rel_pos().y();
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800199 const double squared_norm = rel_x * rel_x + rel_y * rel_y;
James Kuszmaul3b393d72020-02-26 19:43:51 -0800200
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800201 // If squared_norm gets to be too close to zero, just zero out the relevant
202 // term to prevent NaNs. Note that this doesn't address the chattering that
203 // would likely occur if we were to get excessively close to the target.
James Kuszmaul3b393d72020-02-26 19:43:51 -0800204 // Note that x and y terms are swapped relative to what you would normally see
205 // in the derivative of atan because xdot and ydot are the derivatives of
206 // robot_pos and we are working with the atan of (target_pos - robot_pos).
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800207 const double atan_diff = (squared_norm < 1e-3)
208 ? 0.0
James Kuszmaul3b393d72020-02-26 19:43:51 -0800209 : (rel_y * xdot - rel_x * ydot) / squared_norm;
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800210 // heading = atan2(relative_y, relative_x) - robot_theta
211 // dheading / dt = (rel_x * rel_y' - rel_y * rel_x') / (rel_x^2 + rel_y^2) - dtheta / dt
212 const double dheading_dt = atan_diff - linear_angular(1);
213
James Kuszmaulb83d6e12020-02-22 20:44:48 -0800214 double range = kTurretRange;
James Kuszmaul3b393d72020-02-26 19:43:51 -0800215 if (wrap_mode == WrapMode::kAvoidEdges) {
James Kuszmaulb83d6e12020-02-22 20:44:48 -0800216 range -= 2.0 * kAntiWrapBuffer;
217 }
218 // Calculate a goal turret heading such that it is within +/- pi of the
219 // current position (i.e., a goal that would minimize the amount the turret
220 // would have to travel).
221 // We then check if this goal would bring us out of range of the valid angles,
222 // and if it would, we reset to be within +/- pi of zero.
223 double turret_heading = goal_.message().unsafe_goal() +
224 aos::math::NormalizeAngle(
225 heading_to_goal - goal_.message().unsafe_goal());
226 if (std::abs(turret_heading - constants::Values::kTurretRange().middle()) >
227 range / 2.0) {
228 turret_heading = aos::math::NormalizeAngle(turret_heading);
229 }
230
231 goal_.mutable_message()->mutate_unsafe_goal(turret_heading);
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800232 goal_.mutable_message()->mutate_goal_velocity(dheading_dt);
233}
234
235flatbuffers::Offset<AimerStatus> Aimer::PopulateStatus(
236 flatbuffers::FlatBufferBuilder *fbb) const {
237 AimerStatus::Builder builder(*fbb);
238 builder.add_turret_position(goal_.message().unsafe_goal());
239 builder.add_turret_velocity(goal_.message().goal_velocity());
James Kuszmaula53c3ac2020-02-22 19:36:01 -0800240 builder.add_aiming_for_inner_port(aiming_for_inner_port_);
James Kuszmaulb1b2d8e2020-02-21 21:11:46 -0800241 return builder.Finish();
242}
243
244} // namespace turret
245} // namespace superstructure
246} // namespace control_loops
247} // namespace y2020