Debian Codegraph @

DataModel/Track.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 RailControl - Model Railway Control Software
3
4 Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org
5
6 RailControl is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 RailControl is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with RailControl; see the file LICENCE. If not see
18 <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <deque>
23 #include <map>
24 #include <random>
25 #include <string>
26
27 #include "DataModel/Feedback.h"
28 #include "DataModel/Loco.h"
29 #include "DataModel/Track.h"
30 #include "Manager.h"
31 #include "Utils/Integer.h"
32
33 using std::deque;
34 using std::map;
35 using std::string;
36 using std::to_string;
37 using std::vector;
38
39 namespace DataModel
40 {
41 std::string Track::Serialize() const
42 {
43 std::string str;
•44 str = "objectType=Track;";
45 str += LayoutItem::Serialize();
46 str += ";";
47 str += LockableItem::Serialize();
48 str += ";selectrouteapproach=";
49 str += to_string(selectRouteApproach);
50 str += ";trackstate=";
51 str += to_string(trackState);
52 str += ";trackstatedelayed=";
53 str += to_string(trackStateDelayed);
54 str += ";locoorientation=";
55 str += to_string(locoBaseOrientation);
56 str += ";blocked=";
57 str += to_string(blocked);
58 str += ";locodelayed=";
59 str += to_string(locoBaseDelayed.GetObjectID());
60 str += ";locotypedelayed=";
61 str += to_string(locoBaseDelayed.GetObjectType());
62 str += ";allowlocoturn=";
63 str += to_string(allowLocoTurn);
64 str += ";releasewhenfree=";
65 str += to_string(releaseWhenFree);
66 str += ";showname=";
67 str += to_string(showName);
68 str += ";displayname=";
69 str += displayName;
70 str += ";tracktype=";
71 str += to_string(trackType);
72 str += ";main=";
73 str += to_string(mainID);
74 return str;
75 }
76
•77 void Track::Deserialize(const std::string& serialized)
78 {
79 map<string, string> arguments;
80 ParseArguments(serialized, arguments);
81 string objectType = Utils::Utils::GetStringMapEntry(arguments, "objectType");
82 if (objectType.compare("Track") != 0)
83 {
•84 return;
85 }
86 LayoutItem::Deserialize(arguments);
87 LockableItem::Deserialize(arguments);
88
89 // FIXME: remove later: 2024-03-22 feedback vector has been replaced by relation
90 string feedbackStrings = Utils::Utils::GetStringMapEntry(arguments, "feedbacks");
91 deque<string> feedbackStringVector;
92 Utils::Utils::SplitString(feedbackStrings, ",", feedbackStringVector);
93 for (auto& feedbackString : feedbackStringVector)
94 {
95 const FeedbackID feedbackID = Utils::Integer::StringToInteger(feedbackString);
96 Feedback* feedback = manager->GetFeedback(feedbackID);
97 if (!feedback)
98 {
99 continue;
100 }
101 feedback->SetTrack(this);
102 feedbacks.push_back(new Relation(manager,
103 ObjectIdentifier(ObjectTypeTrack, GetID()),
104 ObjectIdentifier(ObjectTypeFeedback, feedbackID),
105 Relation::RelationTypeTrackFeedback));
106 }
107
108 selectRouteApproach = static_cast<SelectRouteApproach>(Utils::Utils::GetIntegerMapEntry(arguments, "selectrouteapproach", SelectRouteSystemDefault));
109 trackState = static_cast<DataModel::Feedback::FeedbackState>(Utils::Utils::GetBoolMapEntry(arguments, "trackstate", DataModel::Feedback::FeedbackStateFree));
110 trackStateDelayed = static_cast<DataModel::Feedback::FeedbackState>(Utils::Utils::GetBoolMapEntry(arguments, "trackstatedelayed", trackState));
111 locoBaseOrientation = static_cast<Orientation>(Utils::Utils::GetBoolMapEntry(arguments, "locoorientation", OrientationRight));
112 blocked = Utils::Utils::GetBoolMapEntry(arguments, "blocked", false);
113 const ObjectIdentifier& locoBaseDelayedIdentifier = GetLocoBase();
114 locoBaseDelayed.SetObjectID(Utils::Utils::GetIntegerMapEntry(arguments, "locodelayed", locoBaseDelayedIdentifier.GetObjectID()));
115 locoBaseDelayed.SetObjectType(static_cast<ObjectType>(Utils::Utils::GetIntegerMapEntry(arguments, "locotypedelayed", locoBaseDelayedIdentifier.GetObjectType())));
116 allowLocoTurn = Utils::Utils::GetBoolMapEntry(arguments, "allowlocoturn", true);
117 releaseWhenFree = Utils::Utils::GetBoolMapEntry(arguments, "releasewhenfree", false);
118 showName = Utils::Utils::GetBoolMapEntry(arguments, "showname", true);
119 displayName = Utils::Utils::GetStringMapEntry(arguments, "displayname", GetName());
120 SetWidth(Width1);
121 SetVisible(VisibleYes);
122 trackType = static_cast<TrackType>(Utils::Utils::GetIntegerMapEntry(arguments, "tracktype", TrackTypeStraight));
123 switch (trackType)
124 {
125 case TrackTypeTurn:
126 case TrackTypeTunnelEnd:
127 SetHeight(Height1);
128 break;
129
130 case TrackTypeCrossingLeft:
131 case TrackTypeCrossingRight:
132 case TrackTypeCrossingSymetric:
133 SetHeight(Height2);
134 break;
135
136 default:
137 break;
138 }
139 mainID = static_cast<TrackID>(Utils::Utils::GetIntegerMapEntry(arguments, "master", TrackNone)); // FIXME: 2025-02-28 can be removed later
140 mainID = static_cast<TrackID>(Utils::Utils::GetIntegerMapEntry(arguments, "main", mainID));
141 }
142
143 void Track::DeleteFeedbacks()
144 {
145 while (feedbacks.size() > 0)
146 {
147 Relation* feedbackRelation = feedbacks.back();
148 Feedback* feedback = manager->GetFeedback(feedbackRelation->ObjectID2());
149 if (feedback)
150 {
151 feedback->SetTrack();
152 }
153 feedbacks.pop_back();
154 delete feedbackRelation;
155 }
156 }
157
158 void Track::AssignFeedbacks(const std::vector<DataModel::Relation*>& newFeedbacks)
159 {
160 DeleteFeedbacks();
161 feedbacks = newFeedbacks;
162 for (auto feedbackRelation : feedbacks)
163 {
164 Feedback* feedback = manager->GetFeedback(feedbackRelation->ObjectID2());
165 if (feedback)
166 {
167 feedback->SetTrack(this);
168 }
169 }
170 }
171
172 void Track::DeleteSignals()
173 {
174 while (signals.size() > 0)
175 {
176 Relation* signalRelation = signals.back();
177 Signal* signal = manager->GetSignal(signalRelation->ObjectID2());
178 if (signal)
179 {
180 signal->SetTrack();
181 }
182 signals.pop_back();
183 delete signalRelation;
184 }
185 }
186
187 void Track::AssignSignals(const std::vector<DataModel::Relation*>& newSignals)
188 {
189 DeleteSignals();
190 signals = newSignals;
191 for (auto signalRelation : signals)
192 {
193 Signal* signal = manager->GetSignal(signalRelation->ObjectID2());
194 if (signal)
195 {
196 signal->SetTrack(this);
197 }
198 }
199 }
200
201 void Track::StopAllSignals(const ObjectIdentifier& locoBaseIdentifier)
202 {
203 for (auto signalRelation : signals)
204 {
205 Signal* signal = manager->GetSignal(signalRelation->ObjectID2());
206 if (!signal)
207 {
208 continue;
209 }
210 const ObjectIdentifier& locoBaseOfSignal = signal->GetLocoBase();
211 if (locoBaseOfSignal.IsSet() && (locoBaseIdentifier != locoBaseOfSignal))
212 {
213 continue;
214 }
215 manager->SignalState(ControlTypeInternal, signal, SignalStateStop, true);
216 }
217 }
218
219 bool Track::CanSetLocoBaseOrientation(const Orientation orientation, const ObjectIdentifier& locoBaseIdentifier)
220 {
221 if (locoBaseOrientation == orientation)
222 {
223 return true;
224 }
225
226 if (cluster)
227 {
228 return cluster->CanSetLocoBaseOrientation(static_cast<Orientation>(orientation ^ clusterInverted), locoBaseIdentifier);
229 }
230
231 const DataModel::LockableItem::LockState lockState = GetLockState();
232 return ((lockState == DataModel::LockableItem::LockStateFree)
233 || ((lockState == DataModel::LockableItem::LockStateReserved)
234 && (!locoBaseIdentifier.IsSet()
235 || (locoBaseIdentifier == GetLocoBase()))));
236 }
237
238 bool Track::SetLocoBaseOrientation(const Orientation orientation)
239 {
240 if (locoBaseOrientation == orientation)
241 {
242 return true;
243 }
244
245 if (cluster)
246 {
247 return cluster->SetLocoBaseOrientation(static_cast<Orientation>(orientation ^ clusterInverted), GetLocoBase());
248 }
249
250 locoBaseOrientation = orientation;
251 return true;
252 }
253
254 bool Track::Reserve(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier)
255 {
256 std::lock_guard<std::mutex> Guard(updateMutex);
257 if (this->locoBaseDelayed.IsSet() && (this->locoBaseDelayed != locoBaseIdentifier))
258 {
259 logger->Debug(Languages::TextTrackIsUsedByLoco, GetName(), manager->GetLocoBaseName(locoBaseDelayed));
260 return false;
261 }
262 if (blocked)
263 {
264 logger->Debug(Languages::TextTrackStatusIsBlocked, GetName());
265 return false;
266 }
267 if (trackState != DataModel::Feedback::FeedbackStateFree)
268 {
269 logger->Debug(Languages::TextIsNotFree, GetName());
270 return false;
271 }
272 return ReserveForce(logger, locoBaseIdentifier);
273 }
274
275 bool Track::ReserveForce(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier)
276 {
277 bool ret = LockableItem::Reserve(logger, locoBaseIdentifier);
278 if (!ret)
279 {
280 return false;
281 }
282
283 this->locoBaseDelayed = locoBaseIdentifier;
284 return true;
285 }
286
287 bool Track::Lock(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier)
288 {
289 bool ret = LockableItem::Lock(logger, locoBaseIdentifier);
290 if (ret)
291 {
292 PublishState();
293 }
294
295 return ret;
296 }
297
298 bool Track::Release(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier)
299 {
300 StopAllSignals(locoBaseIdentifier);
301 {
302 std::lock_guard<std::mutex> Guard(updateMutex);
303 bool ret = LockableItem::Release(logger, locoBaseIdentifier);
304 if (!ret)
305 {
306 return false;
307 }
308
309 if (trackState != DataModel::Feedback::FeedbackStateFree)
310 {
311 return true;
312 }
313 this->locoBaseDelayed.Clear();
314 this->trackStateDelayed = DataModel::Feedback::FeedbackStateFree;
315 }
316 PublishState();
317 return true;
318 }
319
320 bool Track::ReleaseForce(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier)
321 {
322 StopAllSignals(locoBaseIdentifier);
323 bool ret;
324 {
325 std::lock_guard<std::mutex> Guard(updateMutex);
326 ret = ReleaseForceUnlocked(logger, locoBaseIdentifier);
327 }
328 PublishState();
329 return ret;
330 }
331
332 bool Track::ReleaseForceUnlocked(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier)
333 {
334 bool ret = LockableItem::Release(logger, locoBaseIdentifier);
335 this->trackState = DataModel::Feedback::FeedbackStateFree;
336 this->locoBaseDelayed.Clear();
337 this->trackStateDelayed = DataModel::Feedback::FeedbackStateFree;
338 return ret;
339 }
340
341 bool Track::SetFeedbackState(const FeedbackID feedbackID, const DataModel::Feedback::FeedbackState newTrackState)
342 {
343 {
344 std::lock_guard<std::mutex> Guard(updateMutex);
345 const DataModel::Feedback::FeedbackState oldTrackState = this->trackState;
346 const bool oldBlocked = blocked;
347 const bool ret = FeedbackStateInternal(feedbackID, newTrackState);
348 if (!ret)
349 {
350 return false;
351 }
352 if ((oldTrackState == newTrackState) && (oldBlocked == blocked))
353 {
354 return true;
355 }
356 }
357 PublishState();
358 return true;
359 }
360
361 bool Track::FeedbackStateInternal(const FeedbackID feedbackID, const DataModel::Feedback::FeedbackState newTrackState)
362 {
363 if (newTrackState == DataModel::Feedback::FeedbackStateOccupied)
364 {
365 LocoBase* locoBase = manager->GetLocoBase(GetLocoBaseDelayed());
366 if (!locoBase)
367 {
368 if ((!blocked) && manager->GetStopOnFeedbackInFreeTrack())
369 {
370 manager->Booster(ControlTypeInternal, BoosterStateStop);
371 blocked = true;
372 }
373 }
374 else
375 {
376 locoBase->LocationReached(feedbackID);
377 }
378
379 this->trackState = DataModel::Feedback::FeedbackStateOccupied;
380 this->trackStateDelayed = DataModel::Feedback::FeedbackStateOccupied;
381 return true;
382 }
383
384 for (auto feedbackRelation : feedbacks)
385 {
386 DataModel::Feedback* feedback = manager->GetFeedbackUnlocked(feedbackRelation->ObjectID2());
387 if (!feedback)
388 {
389 continue;
390 }
391 if (feedback->GetState() != DataModel::Feedback::FeedbackStateFree)
392 {
393 // if another feedback is still occupied
394 return false;
395 }
396 }
397 this->trackState = DataModel::Feedback::FeedbackStateFree;
398
399 const ObjectIdentifier& locoBaseIdentifier = GetLocoBase();
400 if (releaseWhenFree)
401 {
402 const LocoBase* locoBase = manager->GetLocoBase(locoBaseIdentifier);
403 if (locoBase && locoBase->CheckFreeingTrack(GetID()))
404 {
405 StopAllSignals(locoBaseIdentifier);
406 const bool ret = ReleaseForceUnlocked(locoBase->GetLogger(), locoBaseIdentifier);
407 PublishState();
408 return ret;
409 }
410 }
411
412 if (locoBaseIdentifier.IsSet())
413 {
414 return true;
415 }
416
417 this->trackStateDelayed = DataModel::Feedback::FeedbackStateFree;
418 this->locoBaseDelayed.Clear();
419 return true;
420 }
421
422 bool Track::AddRoute(Route* route)
423 {
424 std::lock_guard<std::mutex> Guard(updateMutex);
425 for (auto r : routes)
426 {
427 if (r == route)
428 {
429 return false;
430 }
431 }
432 routes.push_back(route);
433 return true;
434 }
435
436 bool Track::DeleteRoute(Route* route)
437 {
438 std::lock_guard<std::mutex> Guard(updateMutex);
439 size_t sizeBefore = routes.size();
440 routes.erase(std::remove(routes.begin(), routes.end(), route), routes.end());
441 size_t sizeAfter = routes.size();
442 return sizeBefore > sizeAfter;
443 }
444
445 bool Track::AddExtension(Track* track)
446 {
447 if (mainID != TrackNone)
448 {
449 return false;
450 }
451
452 std::lock_guard<std::mutex> Guard(updateMutex);
453 for (auto& extension : extensions)
454 {
455 if (extension == track)
456 {
457 return false;
458 }
459 }
460 extensions.push_back(track);
461 return true;
462 }
463
464 bool Track::DeleteExtension(const Track* track)
465 {
466 std::lock_guard<std::mutex> Guard(updateMutex);
467 size_t sizeBefore = extensions.size();
468 extensions.erase(std::remove(extensions.begin(), extensions.end(), track), extensions.end());
469 size_t sizeAfter = extensions.size();
470 return sizeBefore > sizeAfter;
471 }
472
473 void Track::UpdateMain()
474 {
475 mainTrack = (mainID == TrackNone ? nullptr : manager->GetTrack(mainID));
476 }
477
478 SelectRouteApproach Track::GetSelectRouteApproachCalculated() const
479 {
480 if (selectRouteApproach == SelectRouteSystemDefault)
481 {
482 return manager->GetSelectRouteApproach();
483 }
484 return selectRouteApproach;
485 }
486
487 bool Track::GetValidRoutes(Logger::Logger* logger,
488 const LocoBase* loco,
489 const bool allowLocoTurn,
490 std::vector<Route*>& validRoutes) const
491 {
492 {
493 std::lock_guard<std::mutex> Guard(updateMutex);
494 for (auto route : routes)
495 {
496 if (route->FromTrackOrientation(logger, GetID(), locoBaseOrientation, loco, allowLocoTurn))
497 {
498 validRoutes.push_back(route);
499 }
500 }
501 }
502 OrderValidRoutes(validRoutes);
503 return true;
504 }
505
506 void Track::OrderValidRoutes(vector<Route*>& validRoutes) const
507 {
508 switch (GetSelectRouteApproachCalculated())
509 {
510
511 case SelectRouteRandom:
512 {
513 static std::random_device rd;
514 static std::mt19937 g(rd());
515 std::shuffle(validRoutes.begin(), validRoutes.end(), g);
516 return;
517 }
518
519 case SelectRouteMinTrackLength:
520 std::sort(validRoutes.begin(), validRoutes.end(), Route::CompareShortest);
521 return;
522
523 case SelectRouteLongestUnused:
524 std::sort(validRoutes.begin(), validRoutes.end(), Route::CompareLastUsed);
525 return;
526
527 case SelectRouteDoNotCare:
528 default:
529 // do nothing
530 return;
531 }
532 }
533
534 void Track::PublishState() const
535 {
536 manager->TrackPublishState(this);
537 }
538 } // namespace DataModel