-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathcontextsimulatorimpl.cpp
More file actions
1258 lines (1102 loc) · 54.8 KB
/
contextsimulatorimpl.cpp
File metadata and controls
1258 lines (1102 loc) · 54.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
#include "core/context/contextsimulatorimpl.h"
#include <QMetaObject>
#include <QPointer>
#include <QStringBuilder>
#include <QStringList>
#include <QThread>
#include <Qt>
#include <QtGlobal>
#include "config/buildconfig.h"
#include "core/application.h"
#include "core/context/contextapplication.h"
#include "core/context/contextnetwork.h"
#include "core/context/contextnetworkimpl.h"
#include "core/context/contextownaircraft.h"
#include "core/context/contextownaircraftimpl.h"
#include "core/corefacade.h"
#include "core/db/databaseutils.h"
#include "core/pluginmanagersimulator.h"
#include "core/simulator.h"
#include "misc/aviation/callsign.h"
#include "misc/dbusserver.h"
#include "misc/logcategories.h"
#include "misc/loghandler.h"
#include "misc/logmessage.h"
#include "misc/mixin/mixincompare.h"
#include "misc/pq/units.h"
#include "misc/simplecommandparser.h"
#include "misc/simulation/matchingutils.h"
#include "misc/simulation/simulatedaircraft.h"
#include "misc/simulation/xplane/xplaneutil.h"
#include "misc/statusmessage.h"
#include "misc/threadutils.h"
#include "misc/verify.h"
using namespace swift::config;
using namespace swift::core::db;
using namespace swift::misc;
using namespace swift::misc::physical_quantities;
using namespace swift::misc::aviation;
using namespace swift::misc::network;
using namespace swift::misc::simulation;
using namespace swift::misc::simulation::xplane;
using namespace swift::misc::geo;
using namespace swift::misc::weather;
using namespace swift::misc::simulation;
using namespace swift::misc::simulation::settings;
using namespace swift::misc::simulation::data;
namespace swift::core::context
{
CContextSimulator::CContextSimulator(CCoreFacadeConfig::ContextMode mode, CCoreFacade *runtime)
: IContextSimulator(mode, runtime), CIdentifiable(this), m_plugins(new CPluginManagerSimulator(this))
{
this->setObjectName("CContextSimulator");
CContextSimulator::registerHelp();
Q_ASSERT_X(sApp, Q_FUNC_INFO, "Need sApp");
MatchingLog logMatchingMessages =
CBuildConfig::isLocalDeveloperDebugBuild() ? MatchingLogAll : MatchingLogSimplified;
m_logMatchingMessages = logMatchingMessages;
m_plugins->collectPlugins();
this->restoreSimulatorPlugins();
connect(&m_aircraftMatcher, &CAircraftMatcher::setupChanged, this, &CContextSimulator::matchingSetupChanged);
connect(&CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance(),
&CCentralMultiSimulatorModelSetCachesProvider::cacheChanged, this, &CContextSimulator::modelSetChanged);
// deferred init of last model set, if no other data are set in meantime
const QPointer<CContextSimulator> myself(this);
QTimer::singleShot(2500, this, [=] {
if (!myself) { return; }
this->initByLastUsedModelSet();
m_aircraftMatcher.setSetup(m_matchingSettings.get());
if (m_aircraftMatcher.getModelSetCount() <= MatchingLogMaxModelSetSize)
{
this->enableMatchingMessages(logMatchingMessages);
}
});
// Validation
m_validator = new CBackgroundValidation(this);
this->setValidator(this->getSimulatorPluginInfo().getSimulator());
connect(this, &CContextSimulator::simulatorChanged, this, &CContextSimulator::setValidator);
connect(m_validator, &CBackgroundValidation::validated, this, &CContextSimulator::validatedModelSet,
Qt::QueuedConnection);
m_validator->start(QThread::LowestPriority);
m_validator->startUpdating(60);
}
void CContextSimulator::setValidator(const CSimulatorInfo &simulator)
{
if (simulator.isSingleSimulator())
{
const QString simDir = m_multiSimulatorSettings.getSimulatorDirectoryOrDefault(simulator);
m_validator->setCurrentSimulator(simulator, simDir);
}
else { m_validator->setCurrentSimulator(CSimulatorInfo::None, {}); }
}
CContextSimulator *CContextSimulator::registerWithDBus(CDBusServer *server)
{
if (!server || getMode() != CCoreFacadeConfig::LocalInDBusServer) { return this; }
server->addObject(CContextSimulator::ObjectPath(), this);
return this;
}
bool CContextSimulator::isSimulatorPluginAvailable() const
{
return m_simulatorPlugin.second && IContextSimulator::isSimulatorAvailable();
}
CContextSimulator::~CContextSimulator() { this->gracefulShutdown(); }
void CContextSimulator::gracefulShutdown()
{
if (m_validator)
{
disconnect(m_validator);
m_validator->quitAndWait();
m_validator->deleteLater();
m_validator = nullptr;
}
this->stopSimulatorListeners();
this->disconnect();
this->unloadSimulatorPlugin();
// give listeners a head start
// if simconnect is running remotely it can take a while until it shutdowns
m_listenersThread.quit();
m_listenersThread.wait(10 * 1000);
}
CSimulatorPluginInfoList CContextSimulator::getAvailableSimulatorPlugins() const
{
if (!m_plugins) { return {}; }
return m_plugins->getAvailableSimulatorPlugins();
}
CSimulatorSettings CContextSimulator::getSimulatorSettings() const
{
const CSimulatorPluginInfo p = this->getSimulatorPluginInfo();
if (!p.isValid()) { return {}; }
const CSimulatorInfo sim = p.getSimulatorInfo();
if (!sim.isSingleSimulator()) { return {}; }
return m_multiSimulatorSettings.getSettings(sim);
}
bool CContextSimulator::setSimulatorSettings(const CSimulatorSettings &settings, const CSimulatorInfo &simulator)
{
if (!simulator.isSingleSimulator()) { return false; }
const CSimulatorSettings simSettings = m_multiSimulatorSettings.getSettings(simulator);
if (simSettings == settings) { return false; }
const CStatusMessage msg = m_multiSimulatorSettings.setSettings(settings, simulator);
CLogMessage::preformatted(msg);
emit this->simulatorSettingsChanged();
return true;
}
bool CContextSimulator::startSimulatorPlugin(const CSimulatorPluginInfo &simulatorInfo)
{
return this->listenForSimulator(simulatorInfo);
}
void CContextSimulator::stopSimulatorPlugin(const CSimulatorPluginInfo &simulatorInfo)
{
if (!m_simulatorPlugin.first.isUnspecified() && m_simulatorPlugin.first == simulatorInfo)
{
this->unloadSimulatorPlugin();
}
ISimulatorListener *listener = m_plugins->getListener(simulatorInfo.getIdentifier());
Q_ASSERT(listener);
QMetaObject::invokeMethod(listener, &ISimulatorListener::stop, Qt::QueuedConnection);
}
int CContextSimulator::checkListeners()
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_plugins) { return 0; }
return m_plugins->checkAvailableListeners();
}
int CContextSimulator::getSimulatorStatus() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return 0; }
return m_simulatorPlugin.second->getSimulatorStatus();
}
CSimulatorPluginInfo CContextSimulator::getSimulatorPluginInfo() const
{
static const CSimulatorPluginInfo unspecified;
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return unspecified; }
if (m_simulatorPlugin.first.getSimulator().contains("emulated", Qt::CaseInsensitive))
{
return m_simulatorPlugin.second->getSimulatorPluginInfo();
}
return m_simulatorPlugin.first;
}
CSimulatorInternals CContextSimulator::getSimulatorInternals() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CSimulatorInternals(); }
return m_simulatorPlugin.second->getSimulatorInternals();
}
CAirportList CContextSimulator::getAirportsInRange(bool recalculateDistance) const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
// If no ISimulator object is available, return a dummy.
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CAirportList(); }
return m_simulatorPlugin.second->getAirportsInRange(recalculateDistance);
}
CAircraftModelList CContextSimulator::getModelSet() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
const CSimulatorInfo simulator = this->getModelSetLoaderSimulator();
if (!simulator.isSingleSimulator()) { return CAircraftModelList(); }
CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance().synchronizeCache(simulator);
return CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance().getCachedModels(simulator);
}
CSimulatorInfo CContextSimulator::getModelSetLoaderSimulator() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (m_simulatorPlugin.second)
{
if (m_simulatorPlugin.second->isConnected())
{
if (m_simulatorPlugin.second->isEmulatedDriver())
{
// specialized version returning the "emulated info"
return this->getSimulatorPluginInfo().getSimulatorInfo();
}
return m_simulatorPlugin.first.getSimulatorInfo();
}
}
return m_modelSetSimulator.get();
}
void CContextSimulator::setModelSetLoaderSimulator(const CSimulatorInfo &simulator)
{
Q_ASSERT_X(simulator.isSingleSimulator(), Q_FUNC_INFO, "Need single simulator");
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (this->isSimulatorAvailable()) { return; } // if a plugin is loaded, do ignore this
m_modelSetSimulator.set(simulator);
const CAircraftModelList models = this->getModelSet(); // cache synced
m_aircraftMatcher.setModelSet(models, simulator, false);
}
CSimulatorInfo CContextSimulator::simulatorsWithInitializedModelSet() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
return CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance().simulatorsWithInitializedCache();
}
CStatusMessageList CContextSimulator::verifyPrerequisites() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
CStatusMessageList msgs;
const CSimulatorInfo simulators = this->simulatorsWithInitializedModelSet();
if (simulators.isNoSimulator())
{
msgs.push_back(CStatusMessage(this).validationError(
u"No model set so far, you need at least one model set. Hint: You can create a model set in the "
u"mapping tool, or copy an existing set in the launcher."));
}
return msgs;
}
QStringList CContextSimulator::getModelSetStrings() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
return this->getModelSet().getModelStringList(false);
}
bool CContextSimulator::isKnownModelInSet(const QString &modelString) const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
const bool known = this->getModelSet().containsModelString(modelString);
return known;
}
int CContextSimulator::removeModelsFromSet(const CAircraftModelList &removeModels)
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (removeModels.isEmpty()) { return 0; }
const CSimulatorInfo simulator = m_modelSetSimulator.get();
if (!simulator.isSingleSimulator()) { return 0; }
CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance().synchronizeCache(simulator);
CAircraftModelList models =
CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance().getCachedModels(simulator);
const int removed = models.removeModelsWithString(removeModels, Qt::CaseInsensitive);
if (removed > 0)
{
CCentralMultiSimulatorModelSetCachesProvider::modelCachesInstance().setCachedModels(models, simulator);
}
return removed;
}
QStringList CContextSimulator::getModelSetCompleterStrings(bool sorted) const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO << sorted; }
return this->getModelSet().toCompleterStrings(sorted);
}
int CContextSimulator::getModelSetCount() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return 0; }
return this->getModelSet().size();
}
void CContextSimulator::disableModelsForMatching(const CAircraftModelList &removedModels, bool incremental)
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return; }
m_aircraftMatcher.disableModelsForMatching(removedModels, incremental);
}
CAircraftModelList CContextSimulator::getDisabledModelsForMatching() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CAircraftModelList(); }
return m_aircraftMatcher.getDisabledModelsForMatching();
}
void CContextSimulator::restoreDisabledModels()
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return; }
m_aircraftMatcher.restoreDisabledModels();
}
bool CContextSimulator::isValidationInProgress() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_validator) { return false; }
return m_validator->isValidating();
}
bool CContextSimulator::triggerModelSetValidation(const CSimulatorInfo &simulator)
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_validator) { return false; }
const QString simDir =
simulator.isSingleSimulator() ? m_multiSimulatorSettings.getSimulatorDirectoryOrDefault(simulator) : "";
return m_validator->triggerValidation(simulator, simDir);
}
CAircraftModelList CContextSimulator::getModelSetModelsStartingWith(const QString &modelString) const
{
if (isDebugEnabled())
{
CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO << modelString;
}
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CAircraftModelList(); }
return this->getModelSet().findModelsStartingWith(modelString);
}
bool CContextSimulator::setTimeSynchronization(bool enable, const CTime &offset)
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return false; }
const bool c = m_simulatorPlugin.second->setTimeSynchronization(enable, offset);
if (!c) { return false; }
CLogMessage(this).info(enable ? QStringLiteral("Set time synchronization to %1").arg(offset.toQString()) :
QStringLiteral("Disabled time syncrhonization"));
return true;
}
bool CContextSimulator::isTimeSynchronized() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return false; }
return m_simulatorPlugin.second->isTimeSynchronized();
}
CInterpolationAndRenderingSetupGlobal CContextSimulator::getInterpolationAndRenderingSetupGlobal() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return m_renderSettings.get(); }
return m_simulatorPlugin.second->getInterpolationSetupGlobal();
}
CInterpolationSetupList CContextSimulator::getInterpolationAndRenderingSetupsPerCallsign() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CInterpolationSetupList(); }
return m_simulatorPlugin.second->getInterpolationSetupsPerCallsign();
}
CInterpolationAndRenderingSetupPerCallsign
CContextSimulator::getInterpolationAndRenderingSetupPerCallsignOrDefault(const CCallsign &callsign) const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified())
{
return CInterpolationAndRenderingSetupPerCallsign();
}
return m_simulatorPlugin.second->getInterpolationSetupPerCallsignOrDefault(callsign);
}
bool CContextSimulator::setInterpolationAndRenderingSetupsPerCallsign(const CInterpolationSetupList &setups,
bool ignoreSameAsGlobal)
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return false; }
return m_simulatorPlugin.second->setInterpolationSetupsPerCallsign(setups, ignoreSameAsGlobal);
}
void CContextSimulator::setInterpolationAndRenderingSetupGlobal(const CInterpolationAndRenderingSetupGlobal &setup)
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO << setup; }
// anyway save for future reference
const CStatusMessage m = m_renderSettings.setAndSave(setup);
CLogMessage::preformatted(m);
// transfer to sim
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return; }
m_simulatorPlugin.second->setInterpolationSetupGlobal(setup);
}
CStatusMessageList CContextSimulator::getInterpolationMessages(const CCallsign &callsign) const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (callsign.isEmpty()) { return CStatusMessageList(); }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CStatusMessageList(); }
return m_simulatorPlugin.second->getInterpolationMessages(callsign);
}
CTime CContextSimulator::getTimeSynchronizationOffset() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified())
{
return CTime(0, CTimeUnit::hrmin());
}
return m_simulatorPlugin.second->getTimeSynchronizationOffset();
}
bool CContextSimulator::loadSimulatorPlugin(const CSimulatorPluginInfo &simulatorPluginInfo)
{
Q_ASSERT(this->getIContextApplication());
Q_ASSERT(this->getIContextApplication()->isUsingImplementingObject());
Q_ASSERT(!simulatorPluginInfo.isUnspecified());
Q_ASSERT(CThreadUtils::thisIsMainThread()); // only run in main thread
// Is a plugin already loaded?
if (!m_simulatorPlugin.first.isUnspecified())
{
// This can happen, if a listener emitted simulatorStarted twice or two different simulators
// are running at the same time. In this case, we leave the loaded plugin and just return.
return false;
}
if (!simulatorPluginInfo.isValid())
{
CLogMessage(this).error(u"Illegal plugin");
return false;
}
ISimulatorFactory *factory = m_plugins->getFactory(simulatorPluginInfo.getIdentifier());
Q_ASSERT_X(factory, Q_FUNC_INFO, "no factory");
// We assume we run in the same process as the own aircraft context
// Hence we pass in memory reference to own aircraft object
Q_ASSERT_X(this->getIContextOwnAircraft()->isUsingImplementingObject(), Q_FUNC_INFO,
"Need implementing object");
Q_ASSERT_X(this->getIContextNetwork()->isUsingImplementingObject(), Q_FUNC_INFO, "Need implementing object");
IOwnAircraftProvider *ownAircraftProvider = this->getRuntime()->getCContextOwnAircraft();
IRemoteAircraftProvider *renderedAircraftProvider = this->getRuntime()->getCContextNetwork();
IClientProvider *clientProvider = this->getRuntime()->getCContextNetwork();
ISimulator *simulator =
factory->create(simulatorPluginInfo, ownAircraftProvider, renderedAircraftProvider, clientProvider);
Q_ASSERT_X(simulator, Q_FUNC_INFO, "no simulator driver can be created");
this->setRemoteAircraftProvider(renderedAircraftProvider);
// use simulator info from ISimulator as it can access the emulated driver settings
CSimulatorInfo simInfo = simulator->getSimulatorInfo();
if (!simInfo.isSingleSimulator())
{
SWIFT_VERIFY_X(false, Q_FUNC_INFO, "Invalid simulator from plugin");
simInfo = CSimulatorInfo::p3d();
if (simulator->isEmulatedDriver())
{
CLogMessage(this).error(
u"Emulated driver does NOT provide valid simulator, using default '%1', plugin: '%2'")
<< simInfo.toQString(true) << simulatorPluginInfo.toQString(true);
}
else
{
CLogMessage(this).error(u"Invalid driver using default '%1', plugin: '%2'")
<< simInfo.toQString(true) << simulatorPluginInfo.toQString(true);
}
}
Q_ASSERT_X(simInfo.isSingleSimulator(), Q_FUNC_INFO, "need single simulator");
m_modelSetSimulator.set(simInfo);
const CAircraftModelList modelSetModels = this->getModelSet(); // synced
m_aircraftMatcher.setModelSet(modelSetModels, simInfo, true);
m_aircraftMatcher.setDefaultModel(simulator->getDefaultModel());
bool c =
connect(simulator, &ISimulator::simulatorStatusChanged, this, &CContextSimulator::onSimulatorStatusChanged);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::physicallyAddingRemoteModelFailed, this,
&CContextSimulator::onAddingRemoteAircraftFailed);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::ownAircraftModelChanged, this,
&CContextSimulator::onOwnSimulatorModelChanged);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::aircraftRenderingChanged, this,
&IContextSimulator::aircraftRenderingChanged);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::renderRestrictionsChanged, this,
&IContextSimulator::renderRestrictionsChanged);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::interpolationAndRenderingSetupChanged, this,
&IContextSimulator::interpolationAndRenderingSetupChanged);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::airspaceSnapshotHandled, this, &IContextSimulator::airspaceSnapshotHandled);
Q_ASSERT(c);
c = connect(simulator, &ISimulator::driverMessages, this, &IContextSimulator::driverMessages);
Q_ASSERT(c);
// disconnect for X-Plane FPS below 20
c = connect(simulator, &ISimulator::insufficientFrameRateDetected, this, [this](bool fatal) {
if (fatal) { emit this->vitalityLost(); }
});
Q_ASSERT(c);
c = connect(simulator, &ISimulator::insufficientFrameRateDetected, this,
&IContextSimulator::insufficientFrameRateDetected);
Q_ASSERT(c);
// log from context to simulator
c = connect(CLogHandler::instance(), &CLogHandler::localMessageLogged, this,
&CContextSimulator::relayStatusMessageToSimulator);
Q_ASSERT(c);
c = connect(CLogHandler::instance(), &CLogHandler::remoteMessageLogged, this,
&CContextSimulator::relayStatusMessageToSimulator);
Q_ASSERT(c);
Q_UNUSED(c)
// Once the simulator signaled it is ready to simulate, add all known aircraft
m_initallyAddAircraft = true;
m_wasSimulating = false;
m_matchingMessages.clear();
m_failoverAddingCounts.clear();
// try to connect to simulator
const bool connected = simulator->connectTo();
if (!connected)
{
CLogMessage(this).error(u"Simulator plugin connection to simulator '%1' failed")
<< simulatorPluginInfo.toQString(true);
return false;
}
// when everything is set up connected, update the current plugin info
m_simulatorPlugin.first = simulatorPluginInfo;
m_simulatorPlugin.second = simulator;
m_simulatorPlugin.second->setInterpolationSetupGlobal(m_renderSettings.get());
// Emit signal after this function completes completely decoupled
QPointer<CContextSimulator> myself(this);
QTimer::singleShot(25, this, [=] {
if (!myself || !sApp || sApp->isShuttingDown()) { return; }
if (m_simulatorPlugin.second)
{
CLogMessage(this).info(u"Simulator plugin loaded: '%1' connected: %2")
<< simulatorPluginInfo.toQString(true) << boolToYesNo(connected);
// use the real driver as this will also work eith emulated driver
emit this->simulatorPluginChanged(m_simulatorPlugin.second->getSimulatorPluginInfo());
emit this->simulatorChanged(m_simulatorPlugin.second->getSimulatorInfo());
}
});
return true;
}
bool CContextSimulator::listenForSimulator(const CSimulatorPluginInfo &simulatorInfo)
{
Q_ASSERT(this->getIContextApplication());
Q_ASSERT(this->getIContextApplication()->isUsingImplementingObject());
Q_ASSERT(!simulatorInfo.isUnspecified());
Q_ASSERT(m_simulatorPlugin.first.isUnspecified());
if (!m_listenersThread.isRunning())
{
m_listenersThread.setObjectName("CContextSimulator: Thread for listener " + simulatorInfo.getIdentifier());
m_listenersThread.start(QThread::LowPriority);
}
ISimulatorListener *listener = m_plugins->createListener(simulatorInfo.getIdentifier());
if (!listener) { return false; }
if (listener->thread() != &m_listenersThread)
{
Q_ASSERT_X(!listener->parent(), Q_FUNC_INFO, "Objects with parent cannot be moved to thread");
const bool c = connect(listener, &ISimulatorListener::simulatorStarted, this,
&CContextSimulator::onSimulatorStarted, Qt::QueuedConnection);
if (!c)
{
CLogMessage(this).error(u"Unable to use '%1'") << simulatorInfo.toQString();
return false;
}
listener->setProperty("isInitialized", true);
listener->moveToThread(&m_listenersThread);
}
// start if not already running
if (!listener->isRunning())
{
const bool s = QMetaObject::invokeMethod(listener, &ISimulatorListener::start, Qt::QueuedConnection);
Q_ASSERT_X(s, Q_FUNC_INFO, "cannot invoke method");
Q_UNUSED(s)
}
CLogMessage(this).info(u"Listening for simulator '%1'") << simulatorInfo.getIdentifier();
return true;
}
void CContextSimulator::listenForAllSimulators()
{
const auto plugins = getAvailableSimulatorPlugins();
for (const CSimulatorPluginInfo &p : plugins)
{
Q_ASSERT(!p.isUnspecified());
if (p.isValid()) { this->listenForSimulator(p); }
}
}
void CContextSimulator::unloadSimulatorPlugin()
{
if (!m_simulatorPlugin.first.isUnspecified())
{
ISimulator *simulator = m_simulatorPlugin.second;
if (simulator && simulator->isConnected())
{
// we are about to unload an connected simulator
this->updateMarkAllAsNotRendered(); // without plugin nothing can be rendered
emit this->simulatorStatusChanged(ISimulator::Disconnected);
}
m_simulatorPlugin.second = nullptr;
m_simulatorPlugin.first = CSimulatorPluginInfo();
Q_ASSERT(this->getIContextNetwork());
Q_ASSERT(this->getIContextNetwork()->isLocalObject());
// unload and disconnect
if (simulator)
{
// disconnect signals and delete
simulator->disconnect(this);
simulator->unload();
simulator->deleteLater();
emit this->simulatorPluginChanged(CSimulatorPluginInfo());
emit this->simulatorChanged(CSimulatorInfo());
}
if (m_wasSimulating) { emit this->vitalityLost(); }
m_wasSimulating = false;
}
}
void CContextSimulator::xCtxAddedRemoteAircraftReadyForModelMatching(const CSimulatedAircraft &remoteAircraft)
{
if (!this->isSimulatorPluginAvailable()) { return; }
const CCallsign callsign = remoteAircraft.getCallsign();
SWIFT_VERIFY_X(!callsign.isEmpty(), Q_FUNC_INFO, "Remote aircraft with empty callsign");
if (callsign.isEmpty()) { return; }
// here we find the best simulator model for a resolved model
// in the first step we already tried to find accurate ICAO codes etc.
// coming from CAirspaceMonitor::sendReadyForModelMatching
MatchingLog whatToLog = m_logMatchingMessages;
CStatusMessageList matchingMessages;
CStatusMessageList *pMatchingMessages = m_logMatchingMessages > 0 ? &matchingMessages : nullptr;
CAircraftModel aircraftModel =
m_aircraftMatcher.getClosestMatch(remoteAircraft, whatToLog, pMatchingMessages, true);
Q_ASSERT_X(remoteAircraft.getCallsign() == aircraftModel.getCallsign(), Q_FUNC_INFO, "Mismatching callsigns");
// decide CG
const CLength cgModel = aircraftModel.getCG();
const CLength cgSim = m_simulatorPlugin.second->getSimulatorCGPerModelString(aircraftModel.getModelString());
const CSimulatorSettings simSettings = this->getSimulatorSettings();
switch (simSettings.getCGSource())
{
case CSimulatorSettings::CGFromSimulatorOnly: aircraftModel.setCG(cgSim); break;
case CSimulatorSettings::CGFromSimulatorFirst:
if (!cgSim.isNull()) { aircraftModel.setCG(cgSim); }
break;
case CSimulatorSettings::CGFromDBFirst:
if (cgModel.isNull()) { aircraftModel.setCG(cgSim); }
break;
// case CSimulatorSettings::CGFromDBOnly:
default: break; // leave CG from model alone
}
const CLength overriddenCG =
m_simulatorPlugin.second->overriddenCGorDefault(CLength::null(), aircraftModel.getModelString());
if (!overriddenCG.isNull()) { aircraftModel.setCG(overriddenCG); }
// model in provider
this->updateAircraftModel(callsign, aircraftModel, this->identifier());
const CSimulatedAircraft aircraftAfterModelApplied =
this->getAircraftInRangeForCallsign(remoteAircraft.getCallsign());
if (!aircraftAfterModelApplied.hasModelString())
{
if (!aircraftAfterModelApplied.hasCallsign()) { return; } // removed
if (this->isAircraftInRange(aircraftAfterModelApplied.getCallsign()))
{
return;
} // removed, but callsig, we did crosscheck
// callsign, but no model string
CLogMessage(this).error(u"Matching error for '%1', no model string")
<< aircraftAfterModelApplied.getCallsign().asString();
CSimulatedAircraft brokenAircraft(aircraftAfterModelApplied);
brokenAircraft.setEnabled(false);
brokenAircraft.setRendered(false);
CCallsign::addLogDetailsToList(
pMatchingMessages, callsign,
QStringLiteral("Cannot add remote aircraft, no model string: '%1'").arg(brokenAircraft.toQString()));
emit this->aircraftRenderingChanged(brokenAircraft);
return;
}
// here the model is added to the simulator
m_simulatorPlugin.second->logicallyAddRemoteAircraft(aircraftAfterModelApplied);
CCallsign::addLogDetailsToList(
pMatchingMessages, callsign,
QStringLiteral("Logically added remote aircraft: %1").arg(aircraftAfterModelApplied.toQString()));
this->clearMatchingMessages(callsign);
this->addMatchingMessages(callsign, matchingMessages);
// done
emit this->modelMatchingCompleted(aircraftAfterModelApplied);
}
void CContextSimulator::xCtxRemovedRemoteAircraft(const CCallsign &callsign)
{
if (!this->isSimulatorAvailable()) { return; }
m_simulatorPlugin.second->logicallyRemoveRemoteAircraft(callsign);
m_failoverAddingCounts.remove(callsign);
}
void CContextSimulator::onSimulatorStatusChanged(ISimulator::SimulatorStatus status)
{
m_wasSimulating = m_wasSimulating || status.testFlag(ISimulator::Simulating);
if (m_initallyAddAircraft && status.testFlag(ISimulator::Simulating))
{
// use network to initally add aircraft
IContextNetwork *networkContext = this->getIContextNetwork();
Q_ASSERT_X(networkContext, Q_FUNC_INFO, "Need context");
Q_ASSERT_X(networkContext->isLocalObject(), Q_FUNC_INFO, "Need local object");
// initially add aircraft
const CSimulatedAircraftList aircraft = networkContext->getAircraftInRange();
for (const CSimulatedAircraft &simulatedAircraft : aircraft)
{
SWIFT_VERIFY_X(!simulatedAircraft.getCallsign().isEmpty(), Q_FUNC_INFO, "Need callsign");
this->xCtxAddedRemoteAircraftReadyForModelMatching(simulatedAircraft);
}
m_initallyAddAircraft = false;
}
if (!status.testFlag(ISimulator::Connected))
{
// we got disconnected, plugin no longer needed
this->updateMarkAllAsNotRendered(); // without plugin nothing can be rendered
this->unloadSimulatorPlugin();
this->restoreSimulatorPlugins();
if (m_wasSimulating) { emit this->vitalityLost(); }
m_wasSimulating = false;
}
emit this->simulatorStatusChanged(status);
}
void CContextSimulator::xCtxTextMessagesReceived(const network::CTextMessageList &textMessages)
{
if (!this->isSimulatorAvailable()) { return; }
if (!this->getIContextOwnAircraft()) { return; }
const CSimulatorMessagesSettings settings = m_messageSettings.getThreadLocal();
const CSimulatedAircraft ownAircraft = this->getIContextOwnAircraft()->getOwnAircraft();
for (const auto &tm : textMessages)
{
if (!settings.relayThisTextMessage(tm, ownAircraft)) { continue; }
m_simulatorPlugin.second->displayTextMessage(tm);
}
}
void CContextSimulator::xCtxChangedRemoteAircraftModel(const CSimulatedAircraft &aircraft,
const swift::misc::CIdentifier &originator)
{
if (CIdentifiable::isMyIdentifier(originator)) { return; }
if (!this->isSimulatorAvailable()) { return; }
m_simulatorPlugin.second->changeRemoteAircraftModel(aircraft);
}
void CContextSimulator::xCtxChangedOwnAircraftModel(const CAircraftModel &aircraftModel,
const CIdentifier &originator)
{
if (CIdentifiable::isMyIdentifier(originator)) { return; }
if (!this->isSimulatorAvailable()) { return; }
emit this->ownAircraftModelChanged(aircraftModel);
}
void CContextSimulator::xCtxChangedRemoteAircraftEnabled(const CSimulatedAircraft &aircraft)
{
if (!this->isSimulatorAvailable()) { return; }
m_simulatorPlugin.second->changeRemoteAircraftEnabled(aircraft);
}
void CContextSimulator::xCtxNetworkConnectionStatusChanged(const CConnectionStatus &from,
const CConnectionStatus &to)
{
Q_UNUSED(from)
SWIFT_VERIFY_X(this->getIContextNetwork(), Q_FUNC_INFO, "Missing network context");
if (to.isConnected() && this->getIContextNetwork())
{
m_networkSessionId = this->getIContextNetwork()->getConnectedServer().getServerSessionId(false);
if (m_simulatorPlugin.second) // check in case the plugin has been unloaded
{
m_simulatorPlugin.second->setFlightNetworkConnected(true);
}
}
else if (to.isDisconnected())
{
m_networkSessionId.clear();
m_aircraftMatcher.clearMatchingStatistics();
m_matchingMessages.clear();
m_failoverAddingCounts.clear();
if (m_simulatorPlugin.second) // check in case the plugin has been unloaded
{
m_simulatorPlugin.second->removeAllRemoteAircraft(); // also removes aircraft
m_simulatorPlugin.second->setFlightNetworkConnected(false);
}
}
}
void CContextSimulator::onAddingRemoteAircraftFailed(const CSimulatedAircraft &remoteAircraft, bool disabled,
bool requestFailover, const CStatusMessage &message)
{
if (!this->isSimulatorAvailable()) { return; }
if (disabled) { m_aircraftMatcher.addingRemoteModelFailed(remoteAircraft); }
const CCallsign cs = remoteAircraft.getCallsign();
if (cs.isEmpty()) { return; }
bool failover = requestFailover;
if (requestFailover)
{
const CAircraftMatcherSetup setup = m_aircraftMatcher.getSetup();
if (setup.doModelAddFailover())
{
const int trial = m_failoverAddingCounts.value(cs, 0);
if (trial < MaxModelAddedFailoverTrials)
{
m_failoverAddingCounts[cs] = trial + 1;
this->doMatchingAgain(cs); // has its own single shot logic
}
else
{
failover = false;
CLogMessage(this).warning(u"Model for '%1' failed adding, tried %2 time(s) to resolve, giving up")
<< cs.toQString(true) << (trial + 1);
}
}
}
emit this->addingRemoteModelFailed(remoteAircraft, disabled, failover, message);
}
void CContextSimulator::xCtxUpdateSimulatorCockpitFromContext(const CSimulatedAircraft &ownAircraft,
const CIdentifier &originator)
{
if (!this->isSimulatorAvailable()) { return; }
if (originator.getName().isEmpty() || originator == IContextSimulator::InterfaceName()) { return; }
// update
m_simulatorPlugin.second->updateOwnSimulatorCockpit(ownAircraft, originator);
}
void CContextSimulator::xCtxUpdateSimulatorSelcalFromContext(const CSelcal &selcal, const CIdentifier &originator)
{
if (!this->isSimulatorAvailable()) { return; }
if (originator.getName().isEmpty() || originator == IContextSimulator::InterfaceName()) { return; }
// update
m_simulatorPlugin.second->updateOwnSimulatorSelcal(selcal, originator);
}
void CContextSimulator::xCtxNetworkRequestedNewAircraft(const CCallsign &callsign, const QString &aircraftIcao,
const QString &airlineIcao, const QString &livery)
{
if (m_networkSessionId.isEmpty()) { return; }
m_aircraftMatcher.evaluateStatisticsEntry(m_networkSessionId, callsign, aircraftIcao, airlineIcao, livery);
}
void CContextSimulator::relayStatusMessageToSimulator(const swift::misc::CStatusMessage &message)
{
if (!this->isSimulatorAvailable()) { return; }
if (!sApp || sApp->isShuttingDown()) { return; }
const CSimulatorMessagesSettings simMsg = m_messageSettings.getThreadLocal();
if (simMsg.relayThisStatusMessage(message) && m_simulatorPlugin.second)
{
m_simulatorPlugin.second->displayStatusMessage(message);
}
}
void CContextSimulator::changeEnabledSimulators()
{
CSimulatorPluginInfo currentPluginInfo = m_simulatorPlugin.first;
const QStringList enabledSimulators = m_enabledSimulators.getThreadLocal();
// Unload the current plugin, if it is no longer enabled
if (!currentPluginInfo.isUnspecified() && !enabledSimulators.contains(currentPluginInfo.getIdentifier()))
{
unloadSimulatorPlugin();
emit simulatorStatusChanged(ISimulator::Disconnected);
}
restoreSimulatorPlugins();
}
void CContextSimulator::restoreSimulatorPlugins()
{
if (!m_simulatorPlugin.first.isUnspecified()) { return; }
this->stopSimulatorListeners();
const QStringList enabledSimulators = m_enabledSimulators.getThreadLocal();
const CSimulatorPluginInfoList allSimulators = m_plugins->getAvailableSimulatorPlugins();
for (const CSimulatorPluginInfo &s : allSimulators)
{
if (enabledSimulators.contains(s.getIdentifier())) { startSimulatorPlugin(s); }
}
}
CPixmap CContextSimulator::iconForModel(const QString &modelString) const
{
if (!m_simulatorPlugin.second || m_simulatorPlugin.first.isUnspecified()) { return CPixmap(); }
// load from file
CStatusMessage msg;
const CAircraftModel model(this->getModelSet().findFirstByModelStringAliasOrDefault(modelString));
const CPixmap pm(model.loadIcon(msg));
if (!msg.isEmpty()) { CLogMessage::preformatted(msg); }
return pm;
}
CStatusMessageList CContextSimulator::getMatchingMessages(const CCallsign &callsign) const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO << callsign; }
return m_matchingMessages[callsign];
}
MatchingLog CContextSimulator::isMatchingMessagesEnabled() const
{
if (isDebugEnabled()) { CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO; }
return m_logMatchingMessages;
}
void CContextSimulator::enableMatchingMessages(MatchingLog enabled)
{
if (isDebugEnabled())
{
CLogMessage(this, CLogCategories::contextSlot()).debug() << Q_FUNC_INFO << matchingLogToString(enabled);
}
if (m_logMatchingMessages == enabled) { return; }
m_logMatchingMessages = enabled;
emit IContext::changedLogOrDebugSettings();
}