Rise
The Vieneo Province
Loading...
Searching...
No Matches
TurnByTurn.cpp
Go to the documentation of this file.
1#include "TurnByTurn.h"
2#include "globals.h"
3
4TurnByTurn::TurnByTurn(Bus* pBus, Logger* pLogger, Networking* pNetworking)
5{
6 bus = pBus;
7 networking = pNetworking;
8 logger = pLogger;
9 logger->AddToCallStack("TurnByTurn::ctor");
10}
11
16
17void TurnByTurn::Update(bool pIsGrndVehicle, float pElapsedTime)
18{
19 logger->AddToCallStack("TurnByTurn::Update");
20 if (!pIsGrndVehicle || !bus->streetViewConfigured)
21 {
24 nextNodeIndex = 0;
27 return;
28 }
29
30 vehiclePosTcp.x = static_cast<float>(bus->tcp.u) + bus->assayProgressU;
31 vehiclePosTcp.y = static_cast<float>(bus->tcp.v) + bus->assayProgressV;
32
34 {
35 // A replacement arrives as a header followed by node packets. Preserve
36 // the reroute cooldown across both resets for the same destination only.
37 const bool sameDestination = routeWaypointId == bus->WPtargetC && bus->turnByTurnExpectedNodes > 0;
39 guidance.Reset({}, sameDestination);
40 nextNodeIndex = 0;
41 lineCount = 0;
43 {
44 std::vector<RouteGuidance::Node> route;
45 for (const auto& node : bus->nodes)
46 route.push_back({ { node.position.x, node.position.y }, node.edgeId, node.streetName });
47 guidance.Reset(std::move(route), true);
48 }
50 bus->turnByTurnDirty = false;
51 }
52
54 return;
55
56 const auto oldIndex = nextNodeIndex;
57 const auto cues = guidance.Update({ vehiclePosTcp.x, vehiclePosTcp.y }, bus->SpeedometerKPH, pElapsedTime);
59 if (nextNodeIndex > oldIndex + 1)
60 {
61 char msg[256];
62 sprintf_s(msg, sizeof msg, "Advanced route from node %zu to %zu at %.4f,%.4f (%.1f km/h)",
64 Trace(msg);
65 }
66 bus->DebugNextIndex = static_cast<int>(nextNodeIndex);
67 if (nextNodeIndex < bus->nodes.size())
69
70 for (const auto& cue : cues)
71 {
72 char msg[256];
73 sprintf_s(msg, sizeof msg, "Cue type %i edge %i direction %i distance %.1fm next node %zu at %.4f,%.4f (%.1f km/h)",
74 cue.type, cue.edgeId, cue.direction, cue.meters, nextNodeIndex,
76 Trace(msg);
77 auto type = static_cast<UpdateType>(cue.type);
78 if (cue.type == RouteGuidance::Completed && bus->turnByTurnRoutingType != 1)
80 sendUpdateToServer(cue.edgeId, cue.meters, cue.WireDirection(), type);
81 }
82 if (guidance.IsComplete())
83 {
84 bus->nodes.clear();
86 nextNodeIndex = 0;
87 lineCount = 0;
89 return;
90 }
91
92 logger->AddToCallStack("TurnByTurn::Update DONE!");
93}
94
96{
97 logger->AddToCallStack("TurnByTurn::Draw");
98
100 return;
101 UpdateVB(map);
102 if (lineCount == 0)
103 return;
104
105 // This draw is inside StreetView's sprite batch. Do not leak line-rendering
106 // state into its markers, text, or the other cockpit instruments.
107 Rendering::RenderStateSnapshot* savedState = nullptr;
108 if (FAILED(pd3dDevice->CreateStateBlock(0, &savedState)))
109 return;
110
111 HRESULT hr;
112 Rendering::Viewport mvp, oldmvp;
113 mvp.X = map.x;
114 mvp.Y = map.y;
115 mvp.Width = map.width;
116 mvp.Height = map.height;
117 mvp.MinZ = 0.0f; mvp.MaxZ = 1.0f;
118 V(pd3dDevice->GetViewport(&oldmvp));
119 V(pd3dDevice->SetViewport(&mvp));
120
122 V(pd3dDevice->SetVertexShader(nullptr));
123 V(pd3dDevice->SetPixelShader(nullptr));
127 V(pd3dDevice->SetStreamSource(0, m_avRouteMap, 0, sizeof(RiseScreenVertex)));
128 V(pd3dDevice->SetFVF(RISE_FVF_SCREEN));
130
131 V(pd3dDevice->SetViewport(&oldmvp));
132 V(savedState->Apply());
133 SAFE_RELEASE(savedState);
134
135 logger->AddToCallStack("TurnByTurn::Draw DONE!");
136}
137
139{
140 logger->AddToCallStack("TurnByTurn::CreateVB");
141
142 if (!bus)
143 return;
144
146 lineCount = 0;
147 if (!bus->streetViewConfigured || !pd3dDevice || bus->nodes.empty() || bus->nodes.size() != bus->turnByTurnExpectedNodes) return;
148 HRESULT hr = pd3dDevice->CreateVertexBuffer((bus->nodes.size() + 1) * sizeof RiseScreenVertex,
151 if (FAILED(hr))
152 {
153 char msg[999];
154 sprintf_s(msg, sizeof msg, "CreateVertexBuffer failed %x with length %zu", hr, (bus->nodes.size() + 1) * sizeof RiseScreenVertex);
156 }
157
158 logger->AddToCallStack("TurnByTurn::CreateVB DONE!");
159}
160
162{
163 logger->AddToCallStack("TurnByTurn::UpdateVB");
164 lineCount = 0;
165 if (!bus || !map.valid || !m_avRouteMap || bus->turnByTurnDirty ||
166 bus->nodes.size() != bus->turnByTurnExpectedNodes || nextNodeIndex >= bus->nodes.size())
167 return;
168
169 HRESULT hr;
170 RiseScreenVertex* vtxs;
171 V(m_avRouteMap->Lock(0, 0, reinterpret_cast<void**>(&vtxs), Rendering::LockFlags::DISCARD));
172 if (FAILED(hr))
173 return;
174
175 const auto center = map.OverlayToScreen(map.centerTexture);
176 vtxs->x = center.x; vtxs->y = center.y; vtxs->z = 0.0f; vtxs->w = 1.0f;
177 vtxs->diffuse = Rendering::ColorRGB(255, 255, 255);
178 vtxs++;
179
180 for (auto iter = bus->nodes.begin() + nextNodeIndex; iter != bus->nodes.end(); iter++)
181 {
182 const auto mapPosition = map.WorldToScreen({ iter->position.x, iter->position.y });
183 vtxs->x = mapPosition.x; vtxs->y = mapPosition.y; vtxs->z = 0.0f; vtxs->w = 1.0f;
184 vtxs->diffuse = Rendering::ColorRGB(255, 255, 0);
185 vtxs++;
186 lineCount++;
187 }
188
190 logger->AddToCallStack("TurnByTurn::UpdateVB DONE!");
191}
192
198
199void TurnByTurn::sendUpdateToServer(int pEdgeId, float pDistance, float pDirection, UpdateType pType) const
200{
202 return;
203 // Communication to server
204 // So in the packets you send me I need the edgeId of course (unless you don't want it to say the street name because it isn't changing then sent -1)
205 SClientPacket outpacket;
206 outpacket.type = 25; // TurnByTurn
207 outpacket.f_x = static_cast<float>(pEdgeId); // edgeId
208 outpacket.f_y = pDistance; // distance in meters
209 outpacket.f_z = pDirection; // direction plus RouteGuidance's same-street marker
210 outpacket.f_w = static_cast<float>(pType); // type
211 networking->SendToServer(&outpacket, sizeof(SClientPacket), true);
212}
213
215{
216 Direction direction = Direction::STRAIGHT;
217 if (bearing < -30.0f && bearing >= -60.0f)
218 direction = Direction::BEAR_LEFT;
219 else if (bearing < -60.0f && bearing > -130.0f)
220 direction = Direction::TURN_LEFT;
221 else if (bearing > 30.0f && bearing <= 60.0f)
222 direction = Direction::BEAR_RIGHT;
223 else if (bearing > 60.0f && bearing < 130.0f)
224 direction = Direction::TURN_RIGHT;
225 else if (bearing > 130.0f || bearing < -130.0f)
226 direction = Direction::U_TURN;
227
228 return direction;
229}
230
232{
233 const float heading = angleBetweenPositionsDeg(bus->nodes.at(nextNodeIndex).position, bus->nodes.at(nextNodeIndex + 1).position);
234 return getHeadingChange(heading, bus->HeadingTrueDegrees);
235}
236
238{
239 const RiseMath::Vector2 directionVector = targetPos - startingPos;
240 RiseMath::Vector2 normalizedDirVector;
241 RiseMath::Vec2Normalize(&normalizedDirVector, &directionVector);
242 return vectorToDegrees(normalizedDirVector);
243}
244
246{
247 const float radians = atan2f(vec.y, vec.x);
248 float result;
249 if (radians < 0.0f)
250 result = fmodf(RiseMath::Tau + radians + RiseMath::HalfPi, RiseMath::Tau) * (180.0f / RiseMath::Pi);
251 else
252 result = fmodf(radians + RiseMath::HalfPi, RiseMath::Tau) * (180.0f / RiseMath::Pi);
253 result = roundf(result);
254 if (result == 0.0f)
255 result = 360.0f;
256 return result;
257}
258
260{
261 const RiseMath::Vector2 distanceVec = positionB - positionA;
262 return RiseMath::Vec2Length(&distanceVec);
263}
264
266{
267 // Based on that coordinates 0.0 to 1.0 = 2000meter roughly
268 return dist * 2000.0f;
269}
270
271float TurnByTurn::getHeadingChange(float pTargetHeading, float pCurrentHeading)
272{
273 float headingChange = pTargetHeading - pCurrentHeading;
274 return headingChange = customModulo(headingChange + 180.0f, 360.0f) - 180.0f;
275}
276
277/*
278* Implemented this function since the standard cmath modulo keeps the - sign which is not what we want
279*/
280float TurnByTurn::customModulo(float a, float n)
281{
282 return a - floorf(a / n) * n;
283}
284
285void TurnByTurn::Trace(char* msg, Logger::Level severity) const
286{
287 char newmsg[999];
288 sprintf_s(newmsg, sizeof newmsg, "TURNBYTURN: %s", msg);
289 logger->Log(newmsg, severity);
290}
#define SAFE_RELEASE(value)
#define V(expression)
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
Definition Bus.h:20
VECTOR2SHORT tcp
Definition Bus.h:314
bool turnByTurnDirty
Definition Bus.h:512
float DebugDistanceToNextNode
Definition Bus.h:553
size_t DebugNextIndex
Definition Bus.h:554
void ClearTurnByTurn()
Definition Bus.h:517
bool streetViewConfigured
Definition Bus.h:510
std::vector< Snode > nodes
Definition Bus.h:511
float HeadingTrueDegrees
Definition Bus.h:41
unsigned char turnByTurnRoutingType
Definition Bus.h:514
float assayProgressV
Definition Bus.h:496
float SpeedometerKPH
Definition Bus.h:180
size_t turnByTurnExpectedNodes
Definition Bus.h:513
int WPtargetC
Definition Bus.h:499
float assayProgressU
Definition Bus.h:496
void Log(const char *msg, Level level=Info, int errorCode=0)
Definition Logger.cpp:283
void AddToCallStack(const char *msg)
Definition Logger.cpp:355
Level
Definition Logger.h:23
@ Error
Definition Logger.h:28
void SendToServer(void *pData, DWORD dwSize, bool bGuaranteed, PacketOrdering order=ORDERING_NONE) const
HRESULT Lock(UINT offset, UINT bytes, void **output, DWORD flags)
HRESULT DrawPrimitive(Primitive type, UINT first, UINT count)
HRESULT CreateStateBlock(UINT type, RenderStateSnapshot **result)
HRESULT SetPixelShader(std::nullptr_t)
HRESULT GetViewport(Viewport *value) const
HRESULT SetStreamSource(UINT stream, RenderBuffer *buffer, UINT offset, UINT stride)
HRESULT SetRenderState(DWORD state, DWORD value)
HRESULT SetFVF(DWORD value)
HRESULT SetViewport(const Viewport *value)
HRESULT CreateVertexBuffer(UINT bytes, DWORD usage, DWORD format, ResourcePool pool, RenderBuffer **result, void *shared)
HRESULT SetTextureStageState(DWORD stage, DWORD state, DWORD value)
HRESULT SetVertexShader(std::nullptr_t)
bool IsComplete() const
std::size_t NextNodeIndex() const
void Reset(std::vector< Node > nodes={}, bool preserveRecalculationCooldown=false)
std::vector< Cue > Update(Point position, float speedKph, float elapsedSeconds=0.0f)
@ TYPE_MAPPED_ROUTE_ENDED
Definition TurnByTurn.h:29
static float angleBetweenPositionsDeg(const RiseMath::Vector2 &vectorA, const RiseMath::Vector2 &vectorB)
static float convertDistanceToMeters(float dist)
void ReleaseResources()
static float distanceBetweenPositions(const RiseMath::Vector2 &vectorA, const RiseMath::Vector2 &vectorB)
Direction GetDirection(float bearing) const
void CreateVB(Rendering::RenderDevice *pd3dDevice)
static float vectorToDegrees(const RiseMath::Vector2 &vec)
static float customModulo(float a, float n)
void Trace(char *msg, Logger::Level severity=Logger::Level::Info) const
size_t lineCount
Definition TurnByTurn.h:19
float GetHeadingToNextNode() const
size_t nextNodeIndex
Definition TurnByTurn.h:17
int routeWaypointId
Definition TurnByTurn.h:18
void Update(bool pIsGrndVehicle, float pElasedTime)
TurnByTurn(Bus *pBus, Logger *pLoggger, Networking *pNetworking)
Definition TurnByTurn.cpp:4
static float getHeadingChange(float targetHeading, float currentHeading)
RouteGuidance guidance
Definition TurnByTurn.h:20
Rendering::RenderBuffer * m_avRouteMap
Definition TurnByTurn.h:14
RiseMath::Vector2 vehiclePosTcp
Definition TurnByTurn.h:16
void sendUpdateToServer(int pEdgeId, float pDistance, float pDirection, UpdateType pType) const
Logger * logger
Definition TurnByTurn.h:12
void Draw(Rendering::RenderDevice *pd3dDevice, const StreetMapProjection &map)
void UpdateVB(const StreetMapProjection &map)
Bus * bus
Definition TurnByTurn.h:11
Networking * networking
Definition TurnByTurn.h:13
#define RISE_FVF_SCREEN
Definition globals.h:126
constexpr uint32_t DYNAMIC
constexpr uint32_t WRITEONLY
constexpr uint32_t DISCARD
constexpr uint32_t ALPHABLENDENABLE
constexpr uint32_t DIFFUSE
constexpr uint32_t DISABLE
constexpr uint32_t SELECTARG2
constexpr uint32_t COLOROP
constexpr uint32_t COLORARG2
constexpr PackedColor ColorRGB(unsigned r, unsigned g, unsigned b)
RenderDevice * ClientRenderer()
constexpr float Pi
Definition ClientMath.h:12
float Vec2Length(const Vector2 *a)
Definition ClientMath.h:92
Vector2 * Vec2Normalize(Vector2 *out, const Vector2 *a)
Definition ClientMath.h:101
constexpr float Tau
Definition ClientMath.h:12
constexpr float HalfPi
Definition ClientMath.h:12
unsigned char type
Point WorldToScreen(Point position) const
Point OverlayToScreen(Point texturePosition) const