-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTAppBase.cpp
executable file
·2039 lines (1763 loc) · 58.2 KB
/
HTAppBase.cpp
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
#include "common.h"
#include "HTAppBase.h"
#include "mynetwork.h"
#include "packets.h"
#include "eventlog.h"
#include "ScenarioData.h"
#include "ScenarioHandler.h"
#include "units/UnitTank.h"
#include "units/UnitRemote.h"
#include "units/UnitSoldier.h"
#include "units/UnitGroup.h"
#include "units/UnitObserver.h"
#include "models/inc/InverseModel.h"
#include "HTPhysicsController.h"
#include "models/inc/Targets.h"
#include "models/inc/Observations.h"
#include "hypotheses/HypothesisManager.h"
#include "hypotheses/HypothesisClient.h"
#include "models/games/DefaultGame.h"
#include "models/games/EvasionGame.h"
#include "models/games/DirectionGame.h"
#include "models/games/CaptureBaseGame.h"
#include "models/games/MazeGame.h"
#include "Watchdog.h"
#pragma GCC diagnostic ignored "-Wextra"
#include <dtCore/transform.h>
#include <dtCore/globals.h>
#include <dtCore/object.h>
#include <dtCore/orbitmotionmodel.h>
#include <dtCore/camera.h>
#include <dtCore/scene.h>
#include <dtCore/object.h>
#include <dtCore/enveffect.h>
#include <dtCore/deltawin.h>
#include <dtCore/infinitelight.h>
#include <dtCore/object.h>
#include <dtCore/globals.h>
#include <dtCore/orbitmotionmodel.h>
#include <dtCore/camera.h>
#include <dtCore/system.h>
#include <dtCore/skydome.h>
#include <dtCore/infiniteterrain.h>
#include <dtCore/isector.h>
#if DELTA3D_VER >= 23
#include <ode/odeinit.h>
#endif
#include <dtCore/shadermanager.h>
#include <dtCore/shaderparameter.h>
#include <dtABC/application.h>
#include <dtUtil/mathdefines.h>
#include <dtUtil/boundingshapeutils.h>
#include <dtNet/dtnet.h>
#include <osg/Math>
#include <osg/LineSegment>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <ode/ode.h>
#include <cassert>
#include <queue>
#include <sstream>
#include <cstdlib>
#include <map>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <gnelib/GNEDebug.h>
#include <dtUtil/xercesparser.h>
#include <dtUtil/xercesutils.h>
#include <xercesc/util/XMLString.hpp>
#include <gsl/gsl_randist.h>
#include <QDateTime>
#include <QtXml/QtXml>
#include <unistd.h>
#pragma GCC diagnostic warning "-Wignored-qualifiers"
#pragma GCC diagnostic warning "-Wextra"
const float cMapHorizontalSize = 5000.0f;
HTAppBase::HTAppBase( const std::string& configFilename,
const std::string& hostName, int port, bool wait_for_client, const std::string& scenarioFilename, int id, std::string& replayFile, std::string& configFile) :
dtABC::BaseABC("Application"),
mLaunch(false),
m_HostName(hostName),
m_PortNum(port),
m_WaitForClient(wait_for_client),
m_SimTime(0),
m_MySide(RED),
m_RedPaused(false),
m_BluePaused(false),
m_InstanceID(id),
mScenarioFilename(scenarioFilename),
mPathPlanning(false),
m_ForwardModel(false),
m_AttackerOnGoalTime(0),
m_PauseEnabled(true),
m_NumRemoteUnits(0),
m_NumRemoteUnitsReceived(0),
mAddingPrediction(false),
mReplayFile(replayFile),
mReplayCommandIndex(0),
mReplay(false),
mConfigFile(configFile),
mNumClients(2),
mLaunchClients(true),
mGame(NULL),
mAttackingSide(RED),
mDefendingSide(BLUE)
{
dtUtil::LogFile::SetFileName("delta3d_log_"+boost::lexical_cast<std::string>(id)+".html");
mRng = gsl_rng_alloc (gsl_rng_default);
QDateTime date = QDateTime::currentDateTime();
mStartTimeStr = date.toString("yyyyMMdd-hh:mm:ss").toStdString();
CreateInstances();
// initialize shaders
dtCore::ShaderManager::GetInstance().LoadShaderDefinitions("Shaders/ShaderDefs.xml", false);
mClientHosts.push_back(new HypothesisHost("localhost",1,"~/development/workspace/hammerQt", "hammerQt"));
if (m_HostName.empty()) {
//start a 10 second timeout on the main loop (on server)
mWatchdog = new Watchdog(10);
mWatchdog->go();
}
}
HTAppBase::~HTAppBase()
{
/*for (unsigned int i=0; i<m_Units.size(); i++)
delete m_Units[i];*/
/*for (unsigned int i=0; i<Projectile::projectiles.size(); i++)
delete Projectile::projectiles[i];
for (unsigned int i=0; i<Projectile::projectilesToDetonate.size(); i++)
delete Projectile::projectilesToDetonate[i];*/
for (unsigned int i=0; i<mClientHosts.size(); i++)
delete mClientHosts[i];
delete mWatchdog;
dJointGroupDestroy(m_ContactGroup);
}
void HTAppBase::Init() {
#if DELTA3D_VER >= 23
dInitODE2(0);
#endif
//instantiate observation manager
mObservations = new Observations();
SetupNetwork();
CreateEnvironment();
CreateLogic();
Config();
CreateActors();
int replay = loadReplay(mReplayFile);
if (replay < 0) {
LOG_ERROR("Could not load replay file")
} else {
mReplay = true;
}
InitHypothesisManager();
}
///Override baseABC to create the basic instances, and call Scene with our own physics controller
void HTAppBase::CreateInstances() {
// create the camera
assert(mViewList[0].get());
mViewList[0]->SetCamera(new dtCore::Camera("defaultCam"));
HTPhysicsController* physics = new HTPhysicsController(this);
physics->SetMaxPhysicsStep(0.2);
mViewList[0]->SetScene(new dtCore::Scene(physics, "defaultScene"));
GetKeyboard()->SetName("defaultKeyboard");
GetMouse()->SetName("defaultMouse");
}
void HTAppBase::SetupNetwork() {
m_Net = new MyNetwork( GetScene() );
std::string logFilename;
if (m_HostName.empty()) logFilename = std::string("server.log");
else logFilename = std::string("client.log");
//initialize the game name, version number, and a networking log file
m_Net->InitializeGame("HTNetwork", 1, logFilename);
#ifdef DEBUG
GNE::initDebug(GNE::DLEVEL1 | GNE::DLEVEL2 | GNE::DLEVEL3 | GNE::DLEVEL4 | GNE::DLEVEL5, logFilename.c_str());
#endif
//register our custom packet with GNE
//must come *after* NetMgr::InitializeGame()
GNE::PacketParser::defaultRegisterPacket<PositionPacket>();
GNE::PacketParser::defaultRegisterPacket<PlayerQuitPacket>();
GNE::PacketParser::defaultRegisterPacket<InitializingPacket>();
GNE::PacketParser::defaultRegisterPacket<InitializingUnitsPacket>();
GNE::PacketParser::defaultRegisterPacket<UnitInitPacket>();
GNE::PacketParser::defaultRegisterPacket<EventPacket>();
GNE::PacketParser::defaultRegisterPacket<IdPacket>();
GNE::PacketParser::defaultRegisterPacket<UnitSavePacketRequest>();
GNE::PacketParser::defaultRegisterPacket<UnitSavePacket>();
GNE::PacketParser::defaultRegisterPacket<CommandPacket>();
//--- setup network connection and mScenarioData ---
// if no hostname was supplied, create a server, otherwise create a client
if (m_HostName.empty()) // SERVER
{
LOG_INFO("Acting as server.")
std::string scenarioPath = "";
//get path from filename
if (!mScenarioFilename.empty()) {
scenarioPath = dtCore::FindFileInPathList( "scenarios/" + mScenarioFilename );
if (scenarioPath.empty()) {
LOG_ERROR("Could not find scenario file to load. Missing file name is """ + mScenarioFilename + """" );
}
}
//parse
if (!parseScenarioFile(scenarioPath)) {
LOG_ERROR("Could not parse scenario XML file: "+ mScenarioFilename);
}
//server is always blue (used for showing paused messages) TODO replace this with m_InstanceID
m_MySide = BLUE;
// assemble and set initializing packet for client(s)
InitializingPacket mypacket(mScenarioData);
m_Net->SetInitializingPacket(mypacket);
// now wait for client to connect if told so
if (mScenarioData->numInstances > 1) {
m_Net->SetupServer( m_PortNum );
for (int i=0; i < mScenarioData->numInstances; i++) {
std::ostringstream oss;
oss << "Waiting for " << (mScenarioData->numInstances - (i+1)) << " clients to connect...";
LOG_INFO(oss.str());
// block until a client is connected TODO this only works for 1 client?
m_Net->WaitForClient();
}
}
if (m_WaitForClient) {
LOG_INFO("Waiting for the controller to connect...");
m_Net->SetupServer( m_PortNum );
// block until a client is connected
m_Net->WaitForClient();
}
}
else // CLIENT
{
LOG_INFO("Acting as client.")
m_Net->SetupClient( m_HostName, m_PortNum );
// client is always red
m_MySide = RED;
// wait for initializing data from server
LOG_INFO("Waiting for the server for initial data...");
if (!m_Net->WaitForServer()) {
LOG_ERROR("No data received from the server, giving up...");
Quit();
}
InitializingPacket mypacket = m_Net->GetInitializingPacket();
mScenarioData = mypacket.mScenarioData;
}
m_MapName = mScenarioData->mapName;
for (unsigned int i=0; i < mScenarioData->sides.size(); i++) {
int total = mScenarioData->sides[i]->total;
switch (mScenarioData->sides[i]->side) {
case BLUE:
m_NumBlue = total;
break;
case RED:
default:
m_NumRed = total;
break;
}
}
m_ControllerId = mScenarioData->controllerId;
m_ForwardModel = mScenarioData->forwardModel;
mRemainingTime = mScenarioData->timeLimit;
//--- setup logging ---
EventLog::SetLogSide(m_MySide);
//setup event logger for 1 second interval of logging of position and heading (after we know which side we are)
EventLog::GetInstance().setLogInterval(1);
//initialise logger with the number of units on each side
EventLog::GetInstance().init(m_NumBlue, m_NumRed, m_MapName);
if (!mConfigFile.empty()) {
EventLog::GetInstance().logEvent("LOG Using config file "+mConfigFile);
}
std::string game = mScenarioData->gameType;
if (game.empty() || game == "default") {
mGame = new DefaultGame();
} else if (game == "evasion") {
mGame = new EvasionGame();
} else if (game == "direction") {
mGame = new DirectionGame();
} else if (game == "capture") {
mGame = new CaptureBaseGame();
} else if (game == "maze") {
mGame = new MazeGame();
}
}
bool HTAppBase::parseScenarioFile(const std::string& file)
{
ScenarioHandler handler;
dtUtil::XercesParser parser;
bool parsed_well = parser.Parse(file, handler, "scenario.xsd");
mScenarioData = handler.mScenarioData;
return parsed_well;
}
void HTAppBase::CreateLogic()
{
m_PlanAdaptor = new PlanAdaptor();
m_PlanCombiner = new PlanCombiner();
}
//////////////////////////////////////////////////////////////////////////
void HTAppBase::CreateEnvironment()
{
//Create basic environment to attach terrain to
dtABC::Weather *weather = new dtABC::Weather();
weather->SetTheme(dtABC::Weather::THEME_FAIR);
m_Environment = weather->GetEnvironment();
m_Environment->SetDateTime(2005,6,21,20,0,0);
m_Environment->SetVisibility(1000000);
m_Environment->SetFogEnable(false);
m_Environment->SetFogMode(dtCore::Environment::EXP2);
// mEnvironment->SetSkyColor(osg::Vec3(0,0,0));
GetScene()->UseSceneLight(false);
mInfiniteLight = new dtCore::InfiniteLight(0,"MyLight");
#if DELTA3D_VER >= 23
dtCore::Transform transform;
transform.SetRotation(37.0f, 10.0f, 0.0f );
mInfiniteLight->SetTransform(transform);
#else
mInfiniteLight->SetAzimuthElevation( 37.0f, 10.0f );
#endif
mInfiniteLight->SetDiffuse( 255.0f, 255.0f, 255.0f, 1.0f );
mInfiniteLight->SetSpecular( 255.0f, 255.0f, 255.0f, 1.0f );
mInfiniteLight->SetEnabled( true );
GetScene()->AddDrawable( mInfiniteLight.get() );
m_Terrain = new Terrain(m_MapName, !isHeadless());
//add the environment to the scene
GetScene()->AddDrawable( m_Environment.get());
//sync names
m_sWorldName = m_Terrain->GetName();
//create map (upon which to perform the A* search)
mTerrainMap = new TerrainMap(m_Terrain.get());
mTargets = new Targets(m_Terrain.get(), &m_Units, &mGroups);
}
void HTAppBase::Config()
{
dtABC::BaseABC::Config();
m_Gravity = -15.0f;
GetScene()->SetGravity( 0.0f, 0.0f, m_Gravity );
//Setup ODE collision callback
m_ContactGroup = dJointGroupCreate (0);
GetScene()->SetUserCollisionCallback(nearCallback, this);
//Set physics updates to be a constant 60Hz (value needs tuning)
//fixes large step size when resizing the screen
//GetScene()->SetPhysicsStepSize(0.01);
//dynamic_cast<Scene_HT*>(GetScene())->SetMaxPhysicsStep(0.02);
GetScene()->SetPhysicsStepSize(0.02);
//Max physics step moved to the create instances function
//GetScene()->SetMaxPhysicsStep(0.16);
dWorldSetAutoDisableFlag (GetScene()->GetWorldID(),0);
dWorldSetERP ( GetScene()->GetWorldID() , 0.1f);
dWorldSetCFM (GetScene()->GetWorldID(),1e-5);
dWorldSetContactMaxCorrectingVel (GetScene()->GetWorldID(), 1.0f );
//dWorldSetContactSurfaceLayer (GetScene()->GetWorldID(),0.001);
}
void HTAppBase::CreateActors()
{
// create units instantiated on this network instance
// all other units will be created when registered with the network
int globalUnitIndex = 0;
m_NumRemoteUnits = 0;
for (unsigned int i=0; i < mScenarioData->sides.size(); i++) {
int unitIndex = 0;
for (unsigned int j=0; j < mScenarioData->sides.at(i)->units.size(); j++) {
//create local units
if (mScenarioData->sides.at(i)->units.at(j)->instance == m_InstanceID) {
//
for (int k=0; k < mScenarioData->sides.at(i)->units.at(j)->number; k++) {
std::ostringstream oss;
switch (mScenarioData->sides.at(i)->side) {
case BLUE: oss << "Blue"; break;
case RED: oss << "Red"; break;
default: break;
}
osg::Vec2 pos2;
if (mScenarioData->sides.at(i)->units.at(j)->number > 1) {
//if number specified, linearly space them between a start and end position
osg::Vec2 startPos = mScenarioData->sides.at(i)->units.at(j)->positions.at(0);
osg::Vec2 endPos = mScenarioData->sides.at(i)->units.at(j)->positions.at(1);
pos2 = ((endPos - startPos)/(mScenarioData->sides.at(i)->units.at(j)->number) * k) + startPos;
} else {
//else just use specified position
pos2 = mScenarioData->sides.at(i)->units.at(j)->positions.at(k);
}
osg::Vec3 pos(pos2[0], pos2[1], 0);
Unit* unit = NULL;
switch (mScenarioData->sides.at(i)->units.at(j)->type) {
case SOLDIER:
oss << "Soldier" << unitIndex;
unit = new UnitSoldier(oss.str(), mapPointToTerrain(pos), 0, mScenarioData->sides.at(i)->side, true, getInstanceID(), globalUnitIndex);
break;
case TANK:
oss << "Tank" << unitIndex;
unit = new UnitTank(oss.str(), mapPointToTerrain(pos), 0, mScenarioData->sides.at(i)->side, true, getInstanceID(), globalUnitIndex);
break;
}
if (unit != NULL) {
if (!mScenarioData->autoFire) {
UnitFiring* u = dynamic_cast<UnitFiring*>(unit);
if (u) u->setAutoFire(false);
}
AddUnit(unit);
m_Net->RegisterInitPacket( UnitInitPacket(unit) );
unitIndex++;
globalUnitIndex++;
}
}
} else {
//count the remote units
m_NumRemoteUnits++;
}
}
}
if (m_HostName.empty() && !mConfigFile.empty()) {
//parse config file to create observers and record num of clients and hostnames
QDomDocument doc( "Config" );
LOG_DEBUG("Parsing config: " + mConfigFile + "...");
std::string configFilePath = dtCore::FindFileInPathList( "scenarios/config/" + mConfigFile + ".xml");
if (configFilePath.empty()) {
LOG_ERROR("Could not find config to load: " + configFilePath );
}
QFile file( QString(configFilePath.c_str()) );
if( !file.open( QFile::ReadOnly ) )
LOG_ERROR("Cannot open config definition file: " + configFilePath);
QString errormsg;
int errorline;
if( !doc.setContent( &file, &errormsg, &errorline ) )
{
file.close();
LOG_ERROR("Cannot parse config definition file " + mConfigFile + " at line " +
boost::lexical_cast<std::string>(errorline) + ": " + errormsg.toStdString() );
}
file.close();
QDomElement root = doc.documentElement();
int numObservers = 0;
if( !root.isNull() ) {
if( root.tagName() == "config" ) {
QDomElement e = root.firstChild().toElement();
while (!e.isNull() ) {
if( e.tagName() == "game" ) {
DirectionGame* game = dynamic_cast<DirectionGame*>(mGame);
if (game) {
if (e.hasAttribute("segments")) {
game->setNumSegments(e.attribute("segments").toInt());
}
if (e.hasAttribute("levels")) {
game->setNumLevels(e.attribute("levels").toInt());
}
}
}
if( e.tagName() == "clients" ) {
if (e.hasAttribute("launch")) {
mLaunchClients = boost::lexical_cast<int>((e.attribute("launch")).toStdString());
}
//the number of clients to launch
if (e.hasAttribute("num")) {
mNumClients = e.attribute("num").toInt();
} else {
mNumClients = 1;
}
//remove default client hosts
for (unsigned int i=0; i<mClientHosts.size(); i++)
delete mClientHosts[i];
mClientHosts.clear();
QDomElement h = e.firstChild().toElement();
while (!h.isNull() ) {
if ( h.tagName() == "host") {
int cores = 1;
if (h.hasAttribute("cores")) {
cores = h.attribute("cores").toInt();
}
std::string path = "~/development/workspace/hammerQt";
if (h.hasAttribute("path")) {
path = h.attribute("path").toStdString();
}
std::string exec = "hammerQt";
if (h.hasAttribute("exec")) {
exec = h.attribute("exec").toStdString();
}
mClientHosts.push_back(new HypothesisHost(h.text().toStdString(),cores, path, exec));
}
h = h.nextSibling().toElement();
}
}
if( e.tagName() == "observers" ) {
QDomElement o = e.firstChild().toElement();
while (!o.isNull() ) {
if ( o.tagName() == "observer") {
QString observer = o.text();
if (observer == "global") {
mObservations->addObserver(createObserver(GLOBAL));
} else if (observer == "round-robin") {
mObservations->addObserver(createObserver(ROUND_ROBIN));
numObservers++;
} else if (observer == "sequential") {
mObservations->addObserver(createObserver(SEQUENTIAL));
numObservers++;
} else if (observer == "threat") {
mObservations->addObserver(createObserver(THREAT));
numObservers++;
}
}
o = o.nextSibling().toElement();
}
}
e = e.nextSibling().toElement();
}
}
}
EventLog::GetInstance().logEvent("OBSN "+boost::lexical_cast<std::string>(numObservers));
EventLog::GetInstance().logEvent("CLNT "+boost::lexical_cast<std::string>(mNumClients));
/*mObservations->addObserver(createObserver(GLOBAL));
mObservations->addObserver(createObserver(ROUND_ROBIN));
mObservations->addObserver(createObserver(ROUND_ROBIN));
//mObservations->addObserver(createObserver(SEQUENTIAL));
//mObservations->addObserver(createObserver(SEQUENTIAL));
//mObservations->addObserver(createObserver(SEQUENTIAL));*/
}
}
/**
* Loads the GOAL commands from a log file.
* The commands are triggered from HTAppBase::PreFrame().
*
* Assumes the log file is from the same scenario that is loaded
*/
int HTAppBase::loadReplay(std::string replayFile) {
std::string replayPath = "";
if (!replayFile.empty()) {
replayPath = dtCore::FindFileInPathList( "results/logs/" + replayFile );
if (replayPath.empty()) {
//assume an absolute filename
replayPath = replayFile;
}
} else {
LOG_ERROR("No replay file specified")
return -1;
}
std::ifstream ifs(replayPath.c_str(),std::ifstream::in);
if (!ifs.is_open()) {
LOG_ERROR("Could not find log file to load. Missing file is """ + replayPath + """" );
return -1;
}
double timeOffset = 0;
if (dtCore::System::GetInstance().IsRunning()) {
timeOffset = theApp->getSimTime();
restartScenario();
}
double timeStamp;
//parse log file for GOAL commands
while (ifs.good()) {
std::string command;
ifs >> timeStamp >> command;
//check that we're loading the correct log file
if (command == "MAP") {
std::string mapName;
ifs >> mapName;
if (mapName != m_MapName) {
LOG_ERROR("The log file loaded for replay does not match the loaded scenario. Scenario map is "+m_MapName+", but the replay map is "+mapName+".")
return -2;
}
}
else if (command == "BLUE") {
int numUnits;
ifs >> numUnits;
//check num blue
/*if (m_NumBlue != numUnits) {
LOG_ERROR("The log file loaded for replay does not match the loaded scenario. Number of blue units in the scenario is "+boost::lexical_cast<std::string>(m_NumBlue)+", but the number in the replay is "+boost::lexical_cast<std::string>(numUnits))
return -2;
}*/
}
else if (command == "RED") {
int numUnits;
ifs >> numUnits;
//check num red
/*if (m_NumRed != numUnits) {
LOG_ERROR("The log file loaded for replay does not match the loaded scenario. Number of red units in the scenario is "+boost::lexical_cast<std::string>(m_NumRed)+", but the number in the replay is "+boost::lexical_cast<std::string>(numUnits))
return -2;
}*/
}
//parse all the goal commands
else if (command == "GOAL") {
//got goal
std::string unit;
double posX, posY, posZ;
ifs >> unit >> posX >> posY >> posZ;
Unit* u = getUnitByName(unit);
UnitObserver* o = dynamic_cast<UnitObserver*>(u);
if (u != NULL && o == NULL) {
osg::Vec3 pos = osg::Vec3(posX,posY,posZ);
mReplayCommands.push_back(new ReplayCommand(timeStamp+timeOffset,u,pos));
} else {
if (u == NULL && o == NULL) LOG_ERROR("Unknown unit "+unit)
}
} else {
//discard
ifs.ignore(1024,'\n');
}
}
//set the time limit to be the last timestamp in the log
LOG_INFO("Setting replay time limit to "+boost::lexical_cast<std::string>(timeStamp+timeOffset));
mRemainingTime = mScenarioData->timeLimit = timeStamp+timeOffset;
return 0;
}
void HTAppBase::InitHypothesisManager() {
//create hypothesis manager (creates server on this host on another port)
if (m_HostName.empty()) {
HypothesisManager::create(getHostname(), 4449, mTargets, mObservations, NULL);
}
//if not launching clients, they must be manually launched with the same ids as below
if (!mLaunchClients) {
for (unsigned int i=0; i < mNumClients; i++) {
new HypothesisClient(i+100);
}
}
}
std::string HTAppBase::getHostname() {
char h[255];
if (gethostname(h, 255) == 0) {
return std::string(h);
} else {
return "localhost";
}
}
void HTAppBase::Run()
{
dtCore::System::GetInstance().Run();
}
/**
* Resets all the units back to their original positions
*/
void HTAppBase::restartScenario() {
dtCore::System::GetInstance().SetPause(1);
clearScene();
CreateActors();
mRemainingTime = mScenarioData->timeLimit;
m_AttackerOnGoalTime = 0;
dtCore::System::GetInstance().SetPause(0);
}
void HTAppBase::AddUnit(Unit* unit) {
GetScene()->AddDrawable(unit);
// two-stage initialization
// thats because physics can only be setup after an object has been added to the scene
unit->init();
m_Units.insert(dtCore::RefPtr<Unit>(unit));
//tell the inverse models that a unit has been added
for (unsigned int i=0; i < mInverseModels.size(); i++) {
mInverseModels.at(i)->addUnit(unit);
}
}
void HTAppBase::RemoveUnit(Unit* unit, bool clear)
{
UnitObserver* o = dynamic_cast<UnitObserver*>(unit);
if (o != NULL) {
mObservations->removeObserver(o);
}
//tell the inverse models that a unit has been removed
for (std::vector<dtCore::RefPtr<InverseModel> >::iterator it=mInverseModels.begin(); it != mInverseModels.end();) {
(*it)->removeUnit(unit, clear);
//if all units have been removed from an IM then delete it
if (!(*it)->valid()) {
it = mInverseModels.erase(it);
} else {
it++;
}
}
//tell the hypothesis manager that a unit has been removed (to keep the observer up to date)
//HypothesisManager* m = HypothesisManager::getManager();
//if (m != NULL) m->removeUnit(unit);
unit_it it;
// find it
for (it = m_Units.begin(); it != m_Units.end(); it++)
{
if ((*it).get() == unit) break;
}
EventLog::GetInstance().logEvent("DEAD "+unit->getName());
//remove unit from units lists (RefPtr count should then be zero)
GetScene()->RemoveDrawable((*it).get());
m_Units.erase(it);
}
/**
* Override of dtABC::PreFrame
* Called automatically before each frame is rendered
* Used to update object properties
*/
void HTAppBase::PreFrame( const double deltaFrameTime )
{
//maintain a global simulation time variable
m_SimTime += deltaFrameTime;
m_FrameTime = deltaFrameTime;
if (m_HostName.empty()) {
mWatchdog->frame(m_SimTime);
}
// net traffic
m_Net->PreFrame( deltaFrameTime );
mRemainingTime -= m_FrameTime;
signed rem_sec = (signed)mRemainingTime;//mScenarioData->timeLimit - (signed)(m_SimTime);
//loop through all units
bool found_attacker_on_goal = false;
bool found_attacker = false, found_defender = false;
signed int goal_index = m_Terrain->GetLayerIndex("goal");
signed long int goal_mask = 1l << goal_index;
for (unit_it it = m_Units.begin(); it != m_Units.end(); it++) {
(*it)->update();
// check whether any of the red ones are on the goal
if ((*it)->getSide() == mAttackingSide) {
found_attacker = true;
osg::Vec3 act_pos = (*it)->getPosition();
long unsigned int layer_bits = m_Terrain->GetLayerBitsAt(act_pos.x(), act_pos.y());
if (layer_bits & goal_mask) {
// it is in the goal area
found_attacker_on_goal = true;
}
} else if ((*it)->getSide() == mDefendingSide) {
found_defender = true;
}
}
if (found_attacker_on_goal) {
m_AttackerOnGoalTime += deltaFrameTime;
} else { // reset counter
m_AttackerOnGoalTime = 0;
}
//run the update fn on all active projectiles
std::set<dtCore::RefPtr<Projectile> >::iterator projIter;
for (projIter = Projectile::projectiles.begin(); projIter != Projectile::projectiles.end(); projIter++)
{
// skip if projectile already detonated
if ( (*projIter).get()->getDetonateTime() != 0 ) continue;
//update returns true if projectile has intersected with unit or gone below the terrain...
if ((*projIter)->update()) {
//get yield and position before projectile is detonated
float projYield = (*projIter)->getYield();
osg::Vec3 projPos = (*projIter)->getPosition();
//boom
(*projIter)->detonate();
BroadcastEvent(Event::DETONATION, (*projIter)->getOwner(), NULL, (*projIter)->getPosition());
//see how much it hurt
for (unit_it unitIter = m_Units.begin(); unitIter != m_Units.end(); unitIter++) {
float health;
double hurt = 0;
if ((*projIter)->getType() == Projectile::SHELL) {
double dist2 = ((*unitIter)->getPosition() - projPos).length2();
// blast radius is inverse square of yield with distance
hurt = projYield / dist2;
hurt *= getTerrain()->GetShellYieldAt(projPos.x(), projPos.y());
} else if ((*projIter)->getType() == Projectile::BULLET) {
//only get hurt from a bullet if it hit the unit directly
if ((*projIter)->isDirectHit((*unitIter).get())) {
hurt = projYield;
}
hurt *= getTerrain()->GetBulletYieldAt(projPos.x(), projPos.y());
}
hurt *= 1 / (*unitIter)->getArmour();
//limit hurt to 100
if (hurt > 100)
hurt = 100;
if (hurt > 0) {
health = (*unitIter)->decrementHealth(hurt);
BroadcastEvent(Event::HURT, (*projIter)->getOwner(), (*unitIter).get(), osg::Vec3(hurt, NAN, NAN));
}
}
}
}
// remove units which are dead (only in the real world sim)
if (!isForwardModel()) {
bool checked = false;
while (!checked)
{
checked = true;
for (unit_it it = m_Units.begin(); it != m_Units.end(); it++)
{
if ( (*it)->getHealth() <= 0 )
{
RemoveUnit((*it).get());
//remove unit from scene
checked = false;
break;
}
}
}
}
//loop through all inverse models
for (unsigned int i=0; i < mInverseModels.size(); i++) {
mInverseModels.at(i)->update();
}
//group units
mTargets->update();
//GAME
if (mGame && mGame->isInitialised()) {
mGame->update();
} else {
if (mScenarioData->gameType == "capture") {
mGame->init();
}
}
//-- cleanup --
//delete projectile object and explosion object after 6 seconds
for (projIter = Projectile::projectiles.begin(); projIter != Projectile::projectiles.end();)
{
if ((*projIter).get()->getDetonateTime() != 0 &&
(*projIter).get()->getDetonateTime() + 6 <= getSimTime())
{
Projectile::projectiles.erase(projIter++);
} else {
projIter++;
}
}
//(remove collision joints)
dJointGroupEmpty(m_ContactGroup);
//Syncronise clients each log interval
if (getIsServer() && EventLog::GetInstance().isTimeForNextLog()) {
BroadcastEvent(Event::TIME_SYNC);
}
if (!isForwardModel()) {
// handle game over cases
// time is out for attackers
if (rem_sec <= 0) {
// assuming blue is defender
EndGame(mDefendingSide);
}
// when time on goal is out for defenders
else if (m_AttackerOnGoalTime >= mScenarioData->goalTime) {
// assuming blue is defender
EndGame(mAttackingSide);
}
// lost all units
else if ((m_NumRemoteUnits == m_NumRemoteUnitsReceived) && !found_attacker) {
EndGame(mDefendingSide);
} else if ((m_NumRemoteUnits == m_NumRemoteUnitsReceived) && !found_defender) {
EndGame(mAttackingSide);
}
}
//replays
if (!mReplayCommands.empty()) {
if (mReplayCommandIndex < mReplayCommands.size()) {
double simTime = theApp->getSimTime();
ReplayCommand* c = mReplayCommands[mReplayCommandIndex];
while (c->time <= simTime) {
LOG_INFO("Setting a new goal for "+c->unit->getName())
c->unit->setGoalPosition(c->pos);
delete c;
if (++mReplayCommandIndex == mReplayCommands.size()) {
break;
}
c = mReplayCommands[mReplayCommandIndex];
}
}
}
// update terrain drawings if necessary
m_Terrain->UpdatePrimitives();
m_PlanCombiner->AnimatePlansDemo();
//Observers update all units observed positions (if a server)
if (m_HostName.empty()) mObservations->update(deltaFrameTime);
if (mLaunch) {
launchHypotheses();
mLaunch = false;
}
//preframe updates for hypothesis manager
HypothesisManager* m = HypothesisManager::getManager();
if (m != NULL) m->update();
//Preframe for subclasses to override
PreFrameGUI(deltaFrameTime);
//Reset log interval
EventLog::GetInstance().intervalDone();
}
/**
* Overridden by subclasses
*/
void HTAppBase::PreFrameGUI( const double deltaFrameTime ) {
}
Unit* HTAppBase::getUnitByName(std::string name)
{
for (unit_it it = m_Units.begin(); it != m_Units.end(); it++)
{
if (name == (*it)->getName())