Rise
The Vieneo Province
Loading...
Searching...
No Matches
RouteGuidance.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cmath>
5#include <cstddef>
6#include <limits>
7#include <string>
8#include <utility>
9#include <vector>
10
11// The first node is the road entry point. Each later node carries the ID/name
12// of the incoming edge, matching Server.NET's TurnByTurn packet contract.
14{
15public:
16 struct Point { float x, y; };
17 struct Node { Point position; int edgeId; std::string street; };
18 enum CueType { Approaching = 0, Execute = 1, Continue = 2, Recalculating = 4, Completed = 5 };
19 struct Cue
20 {
22 bool continuesStreet = false;
23 // TurnByTurn f_z: integer direction 0..5, plus 0.5 when staying on the
24 // same street. Older servers still read the correct integer direction.
25 float WireDirection() const { return static_cast<float>(direction) + (continuesStreet ? 0.5f : 0.0f); }
26 };
27
28 void Reset(std::vector<Node> nodes = {}, bool preserveRecalculationCooldown = false)
29 {
30 nodes_ = std::move(nodes);
32 cumulativeMeters_.assign(nodes_.size(), 0.0f);
33 for (std::size_t i = 1; i < nodes_.size(); ++i)
34 cumulativeMeters_[i] = cumulativeMeters_[i - 1] + DistanceMeters(nodes_[i - 1].position, nodes_[i].position);
35 next_ = 0;
37 initialized_ = completed_ = false;
39 reroutePending_ = false;
41 if (!preserveRecalculationCooldown) recalculationCooldownSeconds_ = 0.0f;
42 bestProgressMeters_ = -(std::numeric_limits<float>::max)();
43 }
44 std::size_t NextNodeIndex() const { return next_; }
45 bool IsComplete() const { return completed_; }
46 static float DistanceMeters(Point a, Point b)
47 {
48 return std::hypot(a.x - b.x, a.y - b.y) * 2000.0f;
49 }
50 static float Heading(Point a, Point b)
51 {
52 return std::fmod(std::atan2(b.x - a.x, a.y - b.y) * 180.0f / 3.14159265358979323846f + 360.0f, 360.0f);
53 }
54 static float HeadingChange(float to, float from)
55 {
56 return std::fmod(to - from + 540.0f, 360.0f) - 180.0f;
57 }
58 static int Direction(float bearing)
59 {
60 if (bearing <= -130.0f || bearing >= 130.0f) return 5;
61 if (bearing <= -60.0f) return 2;
62 if (bearing <= -30.0f) return 1;
63 if (bearing >= 60.0f) return 4;
64 if (bearing >= 30.0f) return 3;
65 return 0;
66 }
67 static float WarningDistanceMeters(float speedKph)
68 {
69 // Eight seconds to prepare after allowing four seconds for delivery/queue
70 // latency and four for the spoken warning. Distance is along the route.
71 return (std::max)(120.0f, (std::min)(1000.0f, TravelMeters(speedKph, 16.0f)));
72 }
73 static float ExecuteDistanceMeters(float speedKph)
74 {
75 // The old fixed 15 m was less than one second at 60 km/h: the audio
76 // could arrive after the corner. Allow three seconds for the final cue.
77 return (std::max)(15.0f, (std::min)(100.0f, TravelMeters(speedKph, 3.0f)));
78 }
79
80 std::vector<Cue> Update(Point position, float speedKph, float elapsedSeconds = 0.0f)
81 {
82 std::vector<Cue> cues;
83 if (nodes_.empty() || completed_ || !std::isfinite(position.x) || !std::isfinite(position.y)) return cues;
84 // A stalled frame must not supply the entire deviation confirmation time.
85 const float seconds = std::isfinite(elapsedSeconds) ?
86 (std::max)(0.0f, (std::min)(1.0f, elapsedSeconds)) : 0.0f;
89 {
90 // Stop old turn cues while waiting for replacement geometry. Requests are
91 // reliable, but retry slowly if the server could not return a route.
92 rerouteWaitSeconds_ += seconds;
93 if (rerouteWaitSeconds_ >= 15.0f)
94 {
97 cues.push_back({ Recalculating, -1, 0.0f, 0 });
98 }
99 return cues;
100 }
101 if (!initialized_)
102 {
103 // A route can arrive after the vehicle has already passed its entry node.
104 // Acquire the nearest segment, so the connector does not point behind us.
105 float best = 20.0f;
106 for (std::size_t i = 1; i < nodes_.size(); ++i)
107 {
108 float t;
109 const float distance = SegmentDistance(position, nodes_[i - 1].position, nodes_[i].position, t);
110 if (t >= 0.0f && t <= 1.0f && distance < best)
111 {
112 best = distance;
113 next_ = i;
114 }
115 }
116 initialized_ = true;
117 previousPosition_ = position;
118 }
119 const Point movementStart = previousPosition_;
120 RecoverPassedNodes(position);
121 previousPosition_ = position;
122 if (ReachedRouteEnd(position)) next_ = nodes_.size();
123
124 // Advance against geometry, not distance samples belonging to a previous index.
125 // One update may pass several short intersection edges.
126 while (next_ < nodes_.size() && Reached(position, next_))
127 {
128 if (IsManeuver(next_))
129 {
130 if (executed_ != next_ && DistanceMeters(position, nodes_[next_].position) <= 30.0f &&
132 cues.push_back(ManeuverCue(Execute, next_, 0.0f));
135 }
136 ++next_;
137 }
138 if (next_ == nodes_.size())
139 {
140 completed_ = true;
141 cues.push_back({ Completed, 0, 0.0f, 0 });
142 return cues;
143 }
144 float deviationMeters;
145 if (ShouldRecalculate(position, seconds, deviationMeters) && recalculationCooldownSeconds_ <= 0.0f)
146 {
147 reroutePending_ = true;
148 rerouteWaitSeconds_ = 0.0f;
149 // Give the returned route and its spoken U-turn/entry instruction time
150 // to be followed instead of asking for the same route every few seconds.
152 cues.clear();
153 cues.push_back({ Recalculating, -1, deviationMeters, 0 });
154 return cues;
155 }
156
157 std::size_t maneuver = next_;
158 while (maneuver < nodes_.size() && !IsManeuver(maneuver)) ++maneuver;
159 const std::size_t end = maneuver < nodes_.size() ? maneuver : nodes_.size() - 1;
160 float remaining = DistanceMeters(position, nodes_[next_].position);
161 for (std::size_t i = next_ + 1; i <= end; ++i)
162 remaining += DistanceMeters(nodes_[i - 1].position, nodes_[i].position);
163
164 if (maneuver < nodes_.size() && executed_ != maneuver)
165 {
166 const float warningMeters = WarningDistanceMeters(speedKph);
167 if (remaining <= ExecuteDistanceMeters(speedKph))
168 {
169 if (ShouldSpeakExecution(maneuver))
170 cues.push_back(ManeuverCue(Execute, maneuver, remaining));
171 executed_ = maneuver;
172 }
173 else if (remaining <= warningMeters && warned_ != maneuver)
174 {
175 cues.push_back(ManeuverCue(Approaching, maneuver, remaining));
176 warned_ = maneuver;
177 }
178 }
179 // Joining the first road is not a maneuver, but needs the same distance
180 // reassurance. Confirm forward travel on that road before announcing it.
181 // An imminent maneuver takes priority and consumes this initial prompt.
182 if (!cues.empty()) initialContinuePending_ = false;
183 const bool joinedFirstRoad = initialContinuePending_ && IsFollowingCurrentEdge(movementStart, position);
184 const bool passedTurn = reassure_ != None && next_ > ManeuverExit(reassure_) &&
185 DistanceMeters(position, nodes_[reassure_].position) >= 15.0f;
186 const bool nextTurnAnnounced = maneuver < nodes_.size() && (warned_ == maneuver || executed_ == maneuver);
187 // With earlier warnings, the next turn may be announced before the prior
188 // turn's reassurance. Do not queue that stale reassurance afterward.
189 if (cues.empty() && !nextTurnAnnounced && (joinedFirstRoad || passedTurn) && remaining >= 50.0f)
190 {
191 cues.push_back({ Continue, nodes_[next_].edgeId, remaining, 0 });
192 reassure_ = None;
194 }
195 return cues;
196 }
197
198private:
199 static float TravelMeters(float speedKph, float seconds)
200 {
201 return std::isfinite(speedKph) ? (std::max)(0.0f, speedKph) / 3.6f * seconds : 0.0f;
202 }
203 static constexpr std::size_t None = (std::numeric_limits<std::size_t>::max)();
204 std::vector<Node> nodes_;
205 std::vector<float> cumulativeMeters_;
206 std::vector<std::size_t> maneuverExits_;
207 std::size_t next_ = 0, warned_ = None, executed_ = None, reassure_ = None;
208 bool initialized_ = false, completed_ = false;
211 bool reroutePending_ = false;
214 float bestProgressMeters_ = -(std::numeric_limits<float>::max)();
215
216 bool ShouldRecalculate(Point position, float seconds, float& deviationMeters)
217 {
218 float progress = -DistanceMeters(position, nodes_[0].position);
219 float offRoute = 0.0f;
220 if (next_ > 0)
221 {
222 float t;
223 offRoute = SegmentDistance(position, nodes_[next_ - 1].position, nodes_[next_].position, t);
224 progress = cumulativeMeters_[next_ - 1] + (std::min)(1.0f, t) *
225 DistanceMeters(nodes_[next_ - 1].position, nodes_[next_].position);
226 }
227 // Before joining, progress means getting closer to the entry. Once on the
228 // route, it means distance along the expected edge, so wrong-way travel is
229 // detected even when the vehicle remains directly on that road.
230 bestProgressMeters_ = (std::max)(bestProgressMeters_, progress);
231 deviationMeters = (std::max)(offRoute, bestProgressMeters_ - progress);
232 // Use the expected local edge after corner recovery, not the nearest edge
233 // anywhere on the route: a nearby return leg must not hide a missed turn.
234 if (deviationMeters > 50.0f) deviationSeconds_ += seconds;
235 else deviationSeconds_ = 0.0f;
236 return deviationSeconds_ >= 3.0f;
237 }
238
239 bool IsFollowingCurrentEdge(Point previous, Point position) const
240 {
241 if (next_ == 0 || DistanceMeters(previous, position) < 0.05f) return false;
242 const auto a = nodes_[next_ - 1].position;
243 const auto b = nodes_[next_].position;
244 float t;
245 if (SegmentDistance(position, a, b, t) > 20.0f || t <= 0.0f || t > 1.0f) return false;
246 const float dx = position.x - previous.x, dy = position.y - previous.y;
247 const float ex = b.x - a.x, ey = b.y - a.y;
248 const float forward = dx * ex + dy * ey;
249 // Within 45 degrees of the road: crossing it or driving the opposite way
250 // must not generate a "continue" instruction.
251 return forward > 0.0f && forward * forward >= 0.5f * (dx * dx + dy * dy) * (ex * ex + ey * ey);
252 }
253
255 {
256 // A driver can round an intersection without touching its tiny lane-link
257 // edges. Rejoin a nearby outgoing segment instead of waiting at that corner.
258 // Keep the search local and require forward motion: a later parallel road
259 // or the return leg of a hairpin must not consume the intervening route.
260 const float moved = DistanceMeters(previousPosition_, position);
261 if (moved < 0.05f) return;
262 float currentT;
263 const float currentDistance = next_ == 0 ? DistanceMeters(position, nodes_[0].position) :
264 SegmentDistance(position, nodes_[next_ - 1].position, nodes_[next_].position, currentT);
265 float best = (std::min)(20.0f, currentDistance - 2.0f);
266 const float lookAhead = (std::min)(250.0f, (std::max)(50.0f, moved * 1.5f));
267 float skippedMeters = 0.0f;
268 std::size_t recovered = next_;
269 for (std::size_t i = next_ + 1; i < nodes_.size() && skippedMeters <= lookAhead; ++i)
270 {
271 const auto a = nodes_[i - 1].position;
272 const auto b = nodes_[i].position;
273 float t;
274 const float distance = SegmentDistance(position, a, b, t);
275 const float forward = (position.x - previousPosition_.x) * (b.x - a.x) +
276 (position.y - previousPosition_.y) * (b.y - a.y);
277 if (t > 0.0f && t <= 1.0f && forward > 0.0f && distance < best)
278 {
279 best = distance;
280 recovered = i;
281 }
282 skippedMeters += DistanceMeters(a, b);
283 }
284 if (recovered > next_)
285 {
286 for (std::size_t i = next_; i < recovered; ++i)
287 if (IsManeuver(i)) reassure_ = recovered - 1;
288 next_ = recovered;
289 // These turns are behind the vehicle; resume on the current road without
290 // announcing the missed corners as new instructions.
291 executed_ = recovered - 1;
292 warned_ = None;
293 }
294 }
295
296 static float SegmentDistance(Point p, Point a, Point b, float& t)
297 {
298 const float dx = b.x - a.x, dy = b.y - a.y;
299 const float lengthSquared = dx * dx + dy * dy;
300 t = lengthSquared > 0.0f ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared : 0.0f;
301 const float clamped = (std::max)(0.0f, (std::min)(1.0f, t));
302 return DistanceMeters(p, { a.x + clamped * dx, a.y + clamped * dy });
303 }
304 bool ReachedRouteEnd(Point position) const
305 {
306 // Arrival is at the road access point, which may stop short of the waypoint.
307 // Allow the last 50 m, including tiny lane links, but not a nearby endpoint
308 // across a loop that the driver has yet to follow.
309 const float arrivalMeters = 50.0f;
310 if (DistanceMeters(position, nodes_.back().position) > arrivalMeters) return false;
311 float remaining = DistanceMeters(position, nodes_[next_].position);
312 for (std::size_t i = next_ + 1; i < nodes_.size() && remaining <= arrivalMeters; ++i)
313 remaining += DistanceMeters(nodes_[i - 1].position, nodes_[i].position);
314 if (remaining > arrivalMeters) return false;
315 if (DistanceMeters(position, nodes_.back().position) <= 20.0f) return true;
316 if (next_ == 0) return false;
317 float t;
318 return SegmentDistance(position, nodes_[next_ - 1].position, nodes_[next_].position, t) <= 20.0f;
319 }
320 bool Reached(Point p, std::size_t i) const
321 {
322 const float distance = DistanceMeters(p, nodes_[i].position);
323 // Passing the final point's infinite line is not arrival at the destination.
324 if (i + 1 == nodes_.size()) return distance <= 20.0f;
325 if (distance <= 4.0f) return true;
326 if (i == 0) return false;
327 float t;
328 SegmentDistance(p, nodes_[i - 1].position, nodes_[i].position, t);
329 const auto a = nodes_[i - 1].position;
330 const auto b = nodes_[i].position;
331 const Point projected = { a.x + t * (b.x - a.x), a.y + t * (b.y - a.y) };
332 if (t >= 1.0f && DistanceMeters(p, projected) <= 20.0f) return true;
333 if (i + 1 < nodes_.size())
334 {
335 float nextT;
336 const float nextDistance = SegmentDistance(p, b, nodes_[i + 1].position, nextT);
337 if (nextT > 0.0f && nextT <= 1.0f && nextDistance <= 5.0f && nextDistance < DistanceMeters(p, projected))
338 return true;
339 }
340 return false;
341 }
342 bool IsManeuver(std::size_t i) const
343 {
344 return i < maneuverExits_.size() && maneuverExits_[i] != None;
345 }
346 std::size_t ManeuverExit(std::size_t i) const
347 {
348 return IsManeuver(i) ? maneuverExits_[i] : i;
349 }
351 {
352 maneuverExits_.assign(nodes_.size(), None);
353 for (std::size_t i = 1; i + 1 < nodes_.size(); ++i)
354 {
355 const float incoming = Heading(nodes_[i - 1].position, nodes_[i].position);
356 // Names can change on a straight 4 m lane link before the actual turn.
357 // Treat the short links inside one junction as a single maneuver, using
358 // the heading/name of the road leaving it. Keep separate junctions separate.
359 // Measure the combined angle before testing the cutoff: a rounded
360 // 45-degree bend can consist entirely of smaller angle changes.
361 std::size_t exit = i;
362 float internalMeters = 0.0f;
363 while (exit + 2 < nodes_.size())
364 {
365 const float length = DistanceMeters(nodes_[exit].position, nodes_[exit + 1].position);
366 if (length > 15.0f || internalMeters + length > 20.0f) break;
367 internalMeters += length;
368 ++exit;
369 }
370 const float outgoing = Heading(nodes_[exit].position, nodes_[exit + 1].position);
371 if (nodes_[i].street == nodes_[exit + 1].street &&
372 std::fabs(HeadingChange(outgoing, incoming)) < 30.0f) continue;
373 maneuverExits_[i] = exit;
374 i = exit;
375 }
376 }
377 float TurnAt(std::size_t i) const
378 {
379 const auto exit = ManeuverExit(i);
380 return HeadingChange(Heading(nodes_[exit].position, nodes_[exit + 1].position),
381 Heading(nodes_[i - 1].position, nodes_[i].position));
382 }
383 bool ShouldSpeakExecution(std::size_t i) const
384 {
385 // One advance instruction is enough for a slight bend on the same street.
386 // Keep an immediate cue when the route arrived too late for a warning,
387 // and keep both calls for street changes and sharper turns.
388 if (warned_ != i) return true;
389 const auto cue = ManeuverCue(Execute, i, 0.0f);
390 return !cue.continuesStreet || (cue.direction != 1 && cue.direction != 3);
391 }
392 Cue ManeuverCue(CueType type, std::size_t i, float meters) const
393 {
394 auto outgoing = ManeuverExit(i) + 1;
395 // Retain the first edge carrying the exit street's name for the server.
396 while (outgoing > i + 1 && nodes_[outgoing - 1].street == nodes_[outgoing].street) --outgoing;
397 return { type, nodes_[outgoing].edgeId, meters, Direction(TurnAt(i)),
398 !nodes_[i].street.empty() && nodes_[i].street == nodes_[outgoing].street };
399 }
400};
@ None
Definition ServerTypes.h:97
std::size_t ManeuverExit(std::size_t i) const
std::vector< std::size_t > maneuverExits_
void RecoverPassedNodes(Point position)
bool IsComplete() const
std::size_t next_
bool initialContinuePending_
bool Reached(Point p, std::size_t i) const
std::size_t NextNodeIndex() const
std::size_t executed_
void Reset(std::vector< Node > nodes={}, bool preserveRecalculationCooldown=false)
static float SegmentDistance(Point p, Point a, Point b, float &t)
static float TravelMeters(float speedKph, float seconds)
bool ShouldSpeakExecution(std::size_t i) const
static float ExecuteDistanceMeters(float speedKph)
std::vector< Node > nodes_
void BuildManeuvers()
float TurnAt(std::size_t i) const
bool ReachedRouteEnd(Point position) const
static float Heading(Point a, Point b)
bool ShouldRecalculate(Point position, float seconds, float &deviationMeters)
float deviationSeconds_
bool IsFollowingCurrentEdge(Point previous, Point position) const
std::size_t warned_
static constexpr std::size_t None
static float DistanceMeters(Point a, Point b)
bool IsManeuver(std::size_t i) const
std::size_t reassure_
std::vector< Cue > Update(Point position, float speedKph, float elapsedSeconds=0.0f)
Point previousPosition_
float rerouteWaitSeconds_
static float WarningDistanceMeters(float speedKph)
static float HeadingChange(float to, float from)
Cue ManeuverCue(CueType type, std::size_t i, float meters) const
float bestProgressMeters_
float recalculationCooldownSeconds_
std::vector< float > cumulativeMeters_
static int Direction(float bearing)
char outgoing[80]
Definition globals.cpp:60
float WireDirection() const