-
Notifications
You must be signed in to change notification settings - Fork 1
/
AAIMap.cpp
2030 lines (1666 loc) · 62.9 KB
/
AAIMap.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
// -------------------------------------------------------------------------
// AAI
//
// A skirmish AI for the Spring engine.
// Copyright Alexander Seizinger
//
// Released under GPL license: see LICENSE.html for more information.
// -------------------------------------------------------------------------
#include "AAIMap.h"
#include "AAI.h"
#include "AAIBuildTable.h"
#include "AAIBrain.h"
#include "AAIConfig.h"
#include "AAISector.h"
#include "AAIUnitTable.h"
#include "System/SafeUtil.h"
#include "LegacyCpp/UnitDef.h"
#include <inttypes.h>
using namespace springLegacyAI;
#define MAP_CACHE_PATH "cache/"
float AAIMap::s_maxSquaredMapDist;
int AAIMap::xSize;
int AAIMap::ySize;
int AAIMap::xMapSize;
int AAIMap::yMapSize;
int AAIMap::losMapResolution;
int AAIMap::xLOSMapSize;
int AAIMap::yLOSMapSize;
int AAIMap::xDefMapSize;
int AAIMap::yDefMapSize;
int AAIMap::xSectors;
int AAIMap::ySectors;
int AAIMap::xSectorSize;
int AAIMap::ySectorSize;
int AAIMap::xSectorSizeMap;
int AAIMap::ySectorSizeMap;
bool AAIMap::s_isMetalMap;
std::list<AAIMetalSpot> AAIMap::metal_spots;
int AAIMap::s_metalSpotsOnLand;
int AAIMap::s_metalSpotsInSea;
float AAIMap::s_landTilesRatio;
float AAIMap::s_waterTilesRatio;
AAIContinentMap AAIMap::s_continentMap;
AAIDefenceMaps AAIMap::s_defenceMaps;
AAIMapType AAIMap::s_mapType;
AAITeamSectorMap AAIMap::s_teamSectorMap;
std::vector<BuildMapTileType> AAIMap::s_buildmap;
std::vector<int> AAIMap::blockmap;
std::vector<float> AAIMap::plateau_map;
std::vector<AAIContinent> AAIMap::s_continents;
StatisticalData AAIMap::s_landContinentSizeStatistics;
StatisticalData AAIMap::s_seaContinentSizeStatistics;
AAIMap::AAIMap(AAI *ai, int xMapSize, int yMapSize, int losMapResolution) :
ai(ai),
m_unitsInLOS(cfg->MAX_UNITS, 0),
m_scoutedEnemyUnitsMap(xMapSize, yMapSize, losMapResolution),
m_centerOfEnemyBase(xMapSize/2 , yMapSize/2),
m_lastLOSUpdateInFrame(0)
{
// all static vars are only initialized by the first AAI instance
if(ai->GetAAIInstance() == 1)
{
this->xMapSize = xMapSize;
this->yMapSize = yMapSize;
xSize = xMapSize * SQUARE_SIZE;
ySize = yMapSize * SQUARE_SIZE;
s_maxSquaredMapDist = static_cast<float>(xSize*xSize + ySize*ySize);
this->losMapResolution = losMapResolution;
xLOSMapSize = xMapSize / losMapResolution;
yLOSMapSize = yMapSize / losMapResolution;
xDefMapSize = xMapSize / 4;
yDefMapSize = yMapSize / 4;
// calculate number of sectors
xSectors = floor(0.5f + ((float) xMapSize)/AAIConstants::sectorSize);
ySectors = floor(0.5f + ((float) yMapSize)/AAIConstants::sectorSize);
// calculate effective sector size
xSectorSizeMap = floor( ((float) xMapSize) / ((float) xSectors) );
ySectorSizeMap = floor( ((float) yMapSize) / ((float) ySectors) );
xSectorSize = xSectorSizeMap * SQUARE_SIZE;
ySectorSize = ySectorSizeMap * SQUARE_SIZE;
s_buildmap.resize(xMapSize*yMapSize);
blockmap.resize(xMapSize*yMapSize, 0);
plateau_map.resize(xMapSize/4*xMapSize/4, 0.0f);
s_teamSectorMap.Init(xSectors, ySectors);
s_defenceMaps.Init(xMapSize, yMapSize);
s_continentMap.Init(xMapSize, yMapSize);
InitContinents();
ReadMapCacheFile();
}
ai->Log("Map size: %i x %i LOS map size: %i x %i (los res: %i)\n", xMapSize, yMapSize, xLOSMapSize, yLOSMapSize, losMapResolution);
m_sectorMap.resize(xSectors, std::vector<AAISector>(ySectors));
for(int x = 0; x < xSectors; ++x)
{
for(int y = 0; y < ySectors; ++y)
// provide ai callback to sectors & set coordinates of the sectors
m_sectorMap[x][y].Init(ai, x, y);
}
// add metalspots to their sectors
for(auto& spot : metal_spots)
{
AAISector* sector = GetSectorOfPos(spot.pos);
if(sector)
sector->AddMetalSpot(&spot);
}
ReadMapLearnFile();
// for scouting
m_buildingsOnContinent.resize(s_continents.size(), 0);
// for log file
ai->Log("Map: %s\n",ai->GetAICallback()->GetMapName());
ai->Log("Maptype: %s\n", s_mapType.GetName().c_str());
ai->Log("Land / water ratio: : %f / %f\n", s_landTilesRatio, s_waterTilesRatio);
ai->Log("Mapsize is %i x %i\n", ai->GetAICallback()->GetMapWidth(),ai->GetAICallback()->GetMapHeight());
ai->Log("%i sectors in x direction\n", xSectors);
ai->Log("%i sectors in y direction\n", ySectors);
ai->Log("x-sectorsize is %i (Map %i)\n", xSectorSize, xSectorSizeMap);
ai->Log("y-sectorsize is %i (Map %i)\n", ySectorSize, ySectorSizeMap);
ai->Log( _STPF_ " metal spots found (%i are on land, %i under water) \n \n", metal_spots.size(), s_metalSpotsOnLand, s_metalSpotsInSea);
ai->Log( _STPF_ " continents found on map\n", s_continents.size());
ai->Log("%u land and %u water continents\n", s_landContinentSizeStatistics.GetSampleSize(), s_seaContinentSizeStatistics.GetSampleSize());
ai->Log("Average land continent size is %f\n", s_landContinentSizeStatistics.GetAvgValue());
ai->Log("Average water continent size is %f\n", s_seaContinentSizeStatistics.GetAvgValue());
//debug
/*for(int x = 0; x < xMapSize; x+=4)
{
for(int y = 0; y < yMapSize; y+=4)
{
//if((buildmap[x + y*xMapSize] == 1) || (buildmap[x + y*xMapSize] == 5) )
if(s_continentMap.GetContinentID(MapPos(x, y)) == 1)
{
float3 myPos;
myPos.x = x;
myPos.z = y;
BuildMapPos2Pos(&myPos, ai->GetAICallback()->GetUnitDef("armmine1"));
myPos.y = ai->GetAICallback()->GetElevation(myPos.x, myPos.z);
ai->GetAICallback()->DrawUnit("armmine1", myPos, 0.0f, 4000, ai->GetAICallback()->GetMyAllyTeam(), true, true);
}
}
}*/
}
AAIMap::~AAIMap(void)
{
UpdateLearningData();
// delete common data only if last AAI instance is deleted
if(ai->GetNumberOfAAIInstances() == 0)
{
ai->Log("Saving map learn file\n");
const std::string mapLearningDataFilename = LocateMapLearnFile();
// save map data
FILE *file = fopen(mapLearningDataFilename.c_str(), "w+");
fprintf(file, "%s\n", MAP_LEARN_VERSION);
for(int y = 0; y < ySectors; ++y)
{
for(int x = 0; x < xSectors; ++x)
m_sectorMap[x][y].SaveDataToFile(file);
fprintf(file, "\n");
}
fclose(file);
s_buildmap.clear();
blockmap.clear();
plateau_map.clear();
}
m_unitsInLOS.clear();
}
void AAIMap::ReadMapCacheFile()
{
// try to read cache file
bool loaded = false;
const size_t buffer_sizeMax = 512;
char buffer[buffer_sizeMax];
const std::string mapCache_filename = LocateMapCacheFile();
FILE *file;
if((file = fopen(mapCache_filename.c_str(), "r")) != NULL)
{
// check if correct version
fscanf(file, "%s ", buffer);
if(strcmp(buffer, MAP_CACHE_VERSION))
{
ai->LogConsole("Mapcache out of date - creating new one");
fclose(file);
}
else
{
int temp;
float temp_float;
// load if its a metal map
fscanf(file, "%i ", &temp);
s_isMetalMap = (bool)temp;
// load map type
fscanf(file, "%s ", buffer);
if(!strcmp(buffer, "LAND_MAP"))
s_mapType.SetMapType(EMapType::LAND);
else if(!strcmp(buffer, "LAND_WATER_MAP"))
s_mapType.SetMapType(EMapType::LAND_WATER);
else if(!strcmp(buffer, "WATER_MAP"))
s_mapType.SetMapType(EMapType::WATER);
else
s_mapType.SetMapType(EMapType::UNKNOWN);
// load water ratio
fscanf(file, "%f ", &s_waterTilesRatio);
// load buildmap
for(int y = 0; y < yMapSize; ++y)
{
for(int x = 0; x < xMapSize; ++x)
{
unsigned int value;
fscanf(file, "%u", &value);
const int cell = x + y * xMapSize;
s_buildmap[cell].m_tileType = static_cast<uint8_t>(value);
}
}
//const springLegacyAI::UnitDef* def = ai->GetAICallback()->GetUnitDef("armmine1");
// load plateau map
for(int y = 0; y < yMapSize/4; ++y)
{
for(int x = 0; x < xMapSize/4; ++x)
{
const int cell = x + y * (xMapSize/4);
fscanf(file, "%f ", &plateau_map[cell]);
/*if( plateau_map[cell] > 0.0f)
{
float3 myPos(static_cast<float>(x*4), 0.0, static_cast<float>(y*4) );
BuildMapPos2Pos(&myPos, def);
myPos.y = ai->GetAICallback()->GetElevation(myPos.x, myPos.z);
ai->GetAICallback()->DrawUnit("armmine1", myPos, 0.0f, 1000, ai->GetAICallback()->GetMyAllyTeam(), true, true);
}*/
}
}
// load metal spots
AAIMetalSpot spot;
fscanf(file, "%i ", &temp);
for(int i = 0; i < temp; ++i)
{
fscanf(file, "%f %f %f %f ", &(spot.pos.x), &(spot.pos.y), &(spot.pos.z), &(spot.amount));
spot.occupied = false;
metal_spots.push_back(spot);
}
fscanf(file, "%i %i ", &s_metalSpotsOnLand, &s_metalSpotsInSea);
fclose(file);
ai->Log("Map cache file successfully loaded\n");
loaded = true;
}
}
if(!loaded) // create new map data
{
// detect cliffs/water and create plateau map
AnalyseMap();
DetermineMapType();
// search for metal spots after analysis of map for cliffs/water to avoid overriding of blocked underwater metal spots (5) with water (4)
DetectMetalSpots();
//////////////////////////////////////////////////////////////////////////////////////////////////////
// save mod independent map data
const std::string mapCache_filename = LocateMapCacheFile();
file = fopen(mapCache_filename.c_str(), "w+");
fprintf(file, "%s\n", MAP_CACHE_VERSION);
// save if its a metal map
fprintf(file, "%i\n", (int)s_isMetalMap);
const char *temp_buffer = GetMapTypeString(s_mapType);
// save map type
fprintf(file, "%s\n", temp_buffer);
// save water ratio
fprintf(file, "%f\n", s_waterTilesRatio);
// save buildmap
for(int y = 0; y < yMapSize; ++y)
{
for(int x = 0; x < xMapSize; ++x)
{
const int cell = x + y * xMapSize;
fprintf(file, "%u ", s_buildmap[cell].m_tileType);
}
fprintf(file, "\n");
}
// save plateau map
for(int y = 0; y < yMapSize/4; ++y)
{
for(int x = 0; x < xMapSize/4; ++x)
{
const int cell = x + y * (xMapSize/4);
fprintf(file, "%f ", plateau_map[cell]);
}
fprintf(file, "\n");
}
// save mex spots
s_metalSpotsOnLand = 0;
s_metalSpotsInSea = 0;
fprintf(file, "%u\n", static_cast<unsigned int>(metal_spots.size()) );
for(std::list<AAIMetalSpot>::iterator spot = metal_spots.begin(); spot != metal_spots.end(); ++spot)
{
fprintf(file, "%f %f %f %f \n", spot->pos.x, spot->pos.y, spot->pos.z, spot->amount);
if(spot->pos.y >= 0.0f)
++s_metalSpotsOnLand;
else
++s_metalSpotsInSea;
}
fprintf(file, "%i %i\n", s_metalSpotsOnLand, s_metalSpotsInSea);
fclose(file);
ai->Log("New map cache-file created\n");
}
}
void AAIMap::InitContinents()
{
//-----------------------------------------------------------------------------------------------------------------
// try to load continent data from cache file
//-----------------------------------------------------------------------------------------------------------------
const std::string continentsCachefilename = cfg->GetFileName(ai->GetAICallback(), cfg->GetUniqueName(ai->GetAICallback(), true, false, true, false), MAP_CACHE_PATH, "_continent.dat", true);
const bool continentsLoadedFromCache = ReadContinentFile(continentsCachefilename);
//-----------------------------------------------------------------------------------------------------------------
// create new continent data and store them to cache file if loading failed
//-----------------------------------------------------------------------------------------------------------------
if(continentsLoadedFromCache == false)
{
// create new continent maps
const float *heightMap = ai->GetAICallback()->GetHeightMap();
s_continentMap.DetectContinents(s_continents, heightMap, xMapSize, yMapSize);
// store results to cache file
FILE* file = fopen(continentsCachefilename.c_str(), "w+");
fprintf(file, "%s\n", CONTINENT_DATA_VERSION);
// save continent map
s_continentMap.SaveToFile(file);
// save continents
fprintf(file, "\n%i\n", static_cast<int>(s_continents.size()) );
for(size_t c = 0; c < s_continents.size(); ++c)
fprintf(file, "%i %i\n", s_continents[c].size, static_cast<int>(s_continents[c].water) );
fclose(file);
}
//-----------------------------------------------------------------------------------------------------------------
// calculate continent statistics
//-----------------------------------------------------------------------------------------------------------------
for(const auto& continent : s_continents)
{
if(continent.water)
s_seaContinentSizeStatistics.AddValue( static_cast<float>(continent.size) );
else
s_landContinentSizeStatistics.AddValue( static_cast<float>(continent.size) );
}
s_landContinentSizeStatistics.Finalize();
s_seaContinentSizeStatistics.Finalize();
}
bool AAIMap::ReadContinentFile(const std::string& filename)
{
FILE* file = fopen(filename.c_str(), "r");
if(file != NULL)
{
char buffer[4096];
// check if correct version
fscanf(file, "%s ", buffer);
if(strcmp(buffer, CONTINENT_DATA_VERSION))
{
ai->LogConsole("Continent cache out of date - creating new one");
fclose(file);
return false;
}
else
{
s_continentMap.LoadFromFile(file);
// load continents
int numberOfContinents;
fscanf(file, "%i ", &numberOfContinents);
s_continents.resize(numberOfContinents);
for(int i = 0; i < numberOfContinents; ++i)
{
int seaContinent;
fscanf(file, "%i %i ", &s_continents[i].size, &seaContinent);
s_continents[i].water = static_cast<bool>(seaContinent);
s_continents[i].id = i;
}
fclose(file);
ai->Log("Continent cache file successfully loaded\n");
return true;
}
}
else
{
return false;
}
}
std::string AAIMap::LocateMapLearnFile() const
{
return cfg->GetFileName(ai->GetAICallback(), cfg->GetUniqueName(ai->GetAICallback(), true, true, true, true), MAP_LEARN_PATH, "_maplearn.dat", true);
}
std::string AAIMap::LocateMapCacheFile() const
{
return cfg->GetFileName(ai->GetAICallback(), cfg->GetUniqueName(ai->GetAICallback(), false, false, true, true), MAP_LEARN_PATH, "_mapcache.dat", true);
}
void AAIMap::ReadMapLearnFile()
{
const std::string mapLearn_filename = LocateMapLearnFile();
const size_t buffer_sizeMax = 2048;
char buffer[buffer_sizeMax];
// open learning files
FILE *load_file = fopen(mapLearn_filename.c_str(), "r");
// check if correct map file version
if(load_file)
{
fscanf(load_file, "%s", buffer);
// file version out of date
if(strcmp(buffer, MAP_LEARN_VERSION))
{
ai->LogConsole("Map learning file version out of date, creating new one");
fclose(load_file);
load_file = 0;
}
}
// load sector data from file or init with default values
for(int j = 0; j < ySectors; ++j)
{
for(int i = 0; i < xSectors; ++i)
{
//---------------------------------------------------------------------------------------------------------
// load learned sector data from file (if available) or init with default data
//---------------------------------------------------------------------------------------------------------
m_sectorMap[i][j].LoadDataFromFile(load_file);
//---------------------------------------------------------------------------------------------------------
// determine movement types that are suitable to maneuvre
//---------------------------------------------------------------------------------------------------------
AAIMapType mapType(EMapType::LAND);
if(m_sectorMap[i][j].GetWaterTilesRatio() > 0.7f)
mapType.SetMapType(EMapType::WATER);
else if(m_sectorMap[i][j].GetWaterTilesRatio() > 0.3f)
mapType.SetMapType(EMapType::LAND_WATER);
m_sectorMap[i][j].m_suitableMovementTypes = GetSuitableMovementTypes(mapType);
}
}
//-----------------------------------------------------------------------------------------------------------------
// determine land/water ratio of total map
//-----------------------------------------------------------------------------------------------------------------
s_waterTilesRatio = 0.0f;
for(int j = 0; j < ySectors; ++j)
{
for(int i = 0; i < xSectors; ++i)
{
s_waterTilesRatio += m_sectorMap[i][j].GetWaterTilesRatio();
}
}
s_waterTilesRatio /= (float)(xSectors * ySectors);
s_landTilesRatio = 1.0f - s_waterTilesRatio;
if(load_file)
fclose(load_file);
else
ai->LogConsole("New map-learning file created");
}
void AAIMap::UpdateLearningData()
{
for(int y = 0; y < ySectors; ++y)
{
for(int x = 0; x < xSectors; ++x)
{
m_sectorMap[x][y].UpdateLearnedData();
}
}
}
bool AAIMap::IsSectorBorderToBase(int x, int y) const
{
return (m_sectorMap[x][y].m_distanceToBase > 0)
&& (m_sectorMap[x][y].m_alliedBuildings < 5)
&& (s_teamSectorMap.IsOccupiedByTeam(SectorIndex(x,y), ai->GetMyTeamId()) == false);
}
int AAIMap::DetermineSmartContinentID(float3 pos, const AAIMovementType& moveType) const
{
// check if non sea/amphib unit in shallow water
if( (ai->GetAICallback()->GetElevation(pos.x, pos.z) < 0.0f)
&& (moveType.GetMovementType() == EMovementType::MOVEMENT_TYPE_GROUND) )
{
//look for closest land cell
for(int k = 1; k < 10; ++k)
{
if(ai->GetAICallback()->GetElevation(pos.x + k * 16, pos.z) >= 0.0f)
{
pos.x += static_cast<float>(k * 16);
break;
}
else if(ai->GetAICallback()->GetElevation(pos.x - k * 16, pos.z) >= 0.0f)
{
pos.x -= static_cast<float>(k * 16);
break;
}
else if(ai->GetAICallback()->GetElevation(pos.x, pos.z + k * 16) >= 0.0f)
{
pos.z += static_cast<float>(k * 16);
break;
}
else if(ai->GetAICallback()->GetElevation(pos.x, pos.z - k * 16) >= 0.0f)
{
pos.z -= static_cast<float>(k * 16);
break;
}
}
}
return s_continentMap.GetContinentID(pos);
}
// converts unit positions to cell coordinates
void AAIMap::Pos2BuildMapPos(float3 *position, const UnitDef* def) const
{
// get cell index of middlepoint
int x = (int) (position->x/SQUARE_SIZE);
int z = (int) (position->z/SQUARE_SIZE);
// shift to the leftmost uppermost cell
x -= def->xsize/2;
z -= def->zsize/2;
// check if pos is still in that map, otherwise retun 0
if(x < 0)
position->x = 0.0f;
else
position->x = static_cast<float>(x);
if(z < 0)
position->z = 0.0f;
else
position->z = static_cast<float>(z);
}
void AAIMap::ConvertPositionToFinalBuildsite(float3& buildsite, const UnitFootprint& footprint) const
{
if(footprint.xSize&2) // check if xSize is a multiple of 4
buildsite.x = floor( (buildsite.x) / (2*SQUARE_SIZE) ) * 2 * SQUARE_SIZE + 8;
else
buildsite.x = floor( (buildsite.x+8) / (2*SQUARE_SIZE) ) * 2 * SQUARE_SIZE;
if(footprint.ySize&2) // check if ySize is a multiple of 4
buildsite.z = floor( (buildsite.z) / (2*SQUARE_SIZE) ) * 2 * SQUARE_SIZE + 8;
else
buildsite.z = floor( (buildsite.z+8) / (2*SQUARE_SIZE) ) * 2 * SQUARE_SIZE;
}
void AAIMap::ChangeBuildMapOccupation(int xPos, int yPos, int xSize, int ySize, bool occupy)
{
// ensure that that cell index may not run outside of the map (should not happen as buildings cannot be placed so close to the map edge)
const int xEnd = std::min(xPos + xSize, xMapSize);
const int yEnd = std::min(yPos + ySize, yMapSize);
for(int y = yPos; y < yEnd; ++y)
{
for(int x = xPos; x < xEnd; ++x)
{
if(occupy)
s_buildmap[x+y*xMapSize].OccupyTile();
else
s_buildmap[x+y*xMapSize].FreeTile();
// debug
/*if(x%2 == 0 && y%2 == 0)
{
const springLegacyAI::UnitDef* unitDef = ai->GetAICallback()->GetUnitDef("armmine1");
float3 myPos;
ConvertMapPosToUnitPos(MapPos(x,y), myPos, ai->s_buildTree.GetFootprint(unitDef->id) );
myPos.y = ai->GetAICallback()->GetElevation(myPos.x, myPos.z);
ai->GetAICallback()->DrawUnit("armmine1", myPos, 0.0f, 2000, ai->GetAICallback()->GetMyAllyTeam(), true, true);
}*/
}
}
}
BuildSite AAIMap::DetermineRandomBuildsite(UnitDefId unitDefId, int xStart, int xEnd, int yStart, int yEnd, int tries) const
{
const UnitFootprint footprint = DetermineRequiredFreeBuildspace(unitDefId);
const springLegacyAI::UnitDef* unitDef = &ai->BuildTable()->GetUnitDef(unitDefId.id);
const int randomXRange = xEnd - xStart - footprint.xSize;
const int randomYRange = yEnd - yStart - footprint.ySize;
for(int i = 0; i < tries; i++)
{
// determine random position within given rectangle
MapPos mapPos(xStart, yStart);
if( randomXRange > 0)
mapPos.x += rand()%randomXRange;
if( randomYRange > 0)
mapPos.y += rand()%randomYRange;
BuildSite buildSite = CheckIfSuitableBuildSite(footprint, unitDef, mapPos);
if(buildSite.IsValid())
return buildSite;
}
return BuildSite();
}
BuildSite AAIMap::FindBuildsiteCloseToUnit(UnitDefId buildingDefId, UnitId unitId) const
{
const float3 unitPosition = ai->GetAICallback()->GetUnitPos(unitId.id);
const UnitFootprint footprint = DetermineRequiredFreeBuildspace(buildingDefId);
const springLegacyAI::UnitDef* unitDef = &ai->BuildTable()->GetUnitDef(buildingDefId.id);
// check rect
const int xStart = unitPosition.x / SQUARE_SIZE;
const int yStart = unitPosition.z / SQUARE_SIZE;
BuildSite buildSite;
for(int xInc = 0; xInc < 24; xInc += 2)
{
for(int yInc = 0; yInc < 24; yInc += 2)
{
buildSite = CheckIfSuitableBuildSite(footprint, unitDef, MapPos(xStart - xInc, yStart - yInc) );
if(buildSite.IsValid() == false)
buildSite = CheckIfSuitableBuildSite(footprint, unitDef, MapPos(xStart - xInc, yStart + yInc) );
if(buildSite.IsValid() == false)
buildSite = CheckIfSuitableBuildSite(footprint, unitDef, MapPos(xStart + xInc, yStart - yInc) );
if(buildSite.IsValid() == false)
buildSite = CheckIfSuitableBuildSite(footprint, unitDef, MapPos(xStart + xInc, yStart + yInc) );
if(buildSite.IsValid())
return buildSite;
}
}
return buildSite;
}
BuildSite AAIMap::DetermineBuildsiteInSector(UnitDefId buildingDefId, const AAISector* sector) const
{
int xStart, xEnd, yStart, yEnd;
sector->DetermineBuildsiteRectangle(&xStart, &xEnd, &yStart, &yEnd);
const UnitFootprint footprint = DetermineRequiredFreeBuildspace(buildingDefId);
const springLegacyAI::UnitDef* unitDef = &ai->BuildTable()->GetUnitDef(buildingDefId.id);
// check rect
for(int yPos = yStart; yPos < yEnd; yPos += 2)
{
for(int xPos = xStart; xPos < xEnd; xPos += 2)
{
const MapPos mapPos(xPos, yPos);
BuildSite buildSite = CheckIfSuitableBuildSite(footprint, unitDef, mapPos);
if(buildSite.IsValid())
return buildSite;
}
}
return BuildSite();
}
BuildSite AAIMap::DetermineElevatedBuildsite(UnitDefId buildingDefId, int xStart, int xEnd, int yStart, int yEnd, float range) const
{
// convert range from unit coordinates to build map coordinates
range /= static_cast<float>(SQUARE_SIZE);
const UnitFootprint footprint = DetermineRequiredFreeBuildspace(buildingDefId);
const bool water = ai->s_buildTree.GetMovementType(buildingDefId).IsSea();
const float maxEdgeDistance = 0.5f * static_cast<float>( std::min(AAIMap::xMapSize, AAIMap::yMapSize));
BuildSite bestBuildSite;
for(int yPos = yStart; yPos < yEnd; yPos += 2)
{
for(int xPos = xStart; xPos < xEnd; xPos += 2)
{
const MapPos mapPos(xPos, yPos);
if(CanBuildAt(mapPos, footprint))
{
// distance to map edge factor ranging from 0 (at the edge) to 1 (distance to edge equals/exceeds range)
const float edgeDistanceFactor = std::min(static_cast<float>(GetEdgeDistance(xPos, yPos)) / range, 1.0f);
// elevated terrain factor ranges from to 0 (in valley) to 1 (on plateau) (only relevant for land based buildings)
float elevatedTerrainFactor(0.0f);
if(water == false)
{
const int plateauMapCellIndex = xPos/4 + yPos/4 * (xMapSize/4);
elevatedTerrainFactor = 0.5f * (1.0f + 0.01f * std::max(-100.0f, std::min( plateau_map[plateauMapCellIndex], 100.0f)));
}
const float rating = 0.05f * (float)(rand()%20) + 5.0f * edgeDistanceFactor + 3.0 * elevatedTerrainFactor;
if(rating > bestBuildSite.GetRating())
{
float3 possibleBuildsite = ConvertMapPosToUnitPos(mapPos, footprint);
ConvertPositionToFinalBuildsite(possibleBuildsite, footprint);
const springLegacyAI::UnitDef* unitDef = &ai->BuildTable()->GetUnitDef(buildingDefId.id);
if(ai->GetAICallback()->CanBuildAt(unitDef, possibleBuildsite))
{
bestBuildSite.SetBuildSite(possibleBuildsite, rating);
}
}
}
}
}
return bestBuildSite;
}
float3 AAIMap::DetermineBuildsiteForStaticDefence(UnitDefId staticDefence, const AAISector* sector, const AAITargetType& targetType, float terrainModifier) const
{
const springLegacyAI::UnitDef *def = &ai->BuildTable()->GetUnitDef(staticDefence.id);
const int range = static_cast<int>(ai->s_buildTree.GetMaxRange(staticDefence)) / SQUARE_SIZE;
const UnitFootprint footprint = DetermineRequiredFreeBuildspace(staticDefence);
//-----------------------------------------------------------------------------------------------------------------
// determine search horizontal and vertical search range
//-----------------------------------------------------------------------------------------------------------------
const SectorIndex& index = sector->GetSectorIndex();
const int xStart = index.x * xSectorSizeMap;
const int xEnd = (index.x + 1) * xSectorSizeMap;
const int yStart = index.y * ySectorSizeMap;
const int yEnd = (index.y + 1) * ySectorSizeMap;
//-----------------------------------------------------------------------------------------------------------------
// determine distances to center of base of tiles to be checked and statistcis (for calculation of rating later)
//-----------------------------------------------------------------------------------------------------------------
const int numberOfTilesToBeChecked = (1+(xEnd-xStart)/4) * (1+(yEnd-yStart)/4);
std::vector<float> distancesToBaseCenter(numberOfTilesToBeChecked);
StatisticalData distanceStatistics;
int distanceToBaseArrayIndex(0);
const MapPos& baseCenter = ai->Brain()->GetCenterOfBase();
for(int yPos = yStart; yPos < yEnd; yPos += 4)
{
for(int xPos = xStart; xPos < xEnd; xPos += 4)
{
const int dx = xPos - baseCenter.x;
const int dy = yPos - baseCenter.y;
const float squaredDist = static_cast<float>(dx*dx + dy*dy);
distancesToBaseCenter[distanceToBaseArrayIndex] = squaredDist;
distanceStatistics.AddValue(squaredDist);
++distanceToBaseArrayIndex;
}
}
distanceStatistics.Finalize();
//-----------------------------------------------------------------------------------------------------------------
// find highest rated positon with search range
//-----------------------------------------------------------------------------------------------------------------
float3 buildsite(ZeroVector);
float highestRating(0.0f);
distanceToBaseArrayIndex = 0;
/*FILE* file(nullptr);
const std::string filename = cfg->GetFileName(ai->GetAICallback(), "AAIDebug.txt", "", "", true);
file = fopen(filename.c_str(), "w+");
fprintf(file, "Base center: %i, %i\n", baseCenter.x, baseCenter.y);
fprintf(file, "Defence Map: Defence value / distance value / terrain value\n");*/
for(int yPos = yStart; yPos < yEnd; yPos += 4)
{
for(int xPos = xStart; xPos < xEnd; xPos += 4)
{
const MapPos mapPos(xPos, yPos);
if(CanBuildAt(mapPos, footprint))
{
// criterion 1: how well is tile already covered by existing static defences
const float defenceValue = 2.5f * AAIConstants::maxCombatPower / (1.0f + 0.35f * s_defenceMaps.GetValue(mapPos, targetType) );
// criterion 2: distance to center of base (prefer static defences closer to base)
const float distanceValue = 0.75f * AAIConstants::maxCombatPower * distanceStatistics.GetNormalizedDeviationFromMax(distancesToBaseCenter[distanceToBaseArrayIndex]);
// criterion 3: terrain (prefer defences on high ground, avoid defences close to walls of canyons/valleys)
const int cell = (xPos/4 + (xMapSize/4) * yPos/4);
const float terrainValue = std::min(AAIConstants::maxCombatPower, terrainModifier * plateau_map[cell]);
float rating = defenceValue + distanceValue + terrainValue + 0.2f * (float)(rand()%10);
// determine minimum distance from buildpos to the edges of the map
const int edge_distance = GetEdgeDistance(xPos, yPos);
// prevent aai from building defences too close to the edges of the map
if( edge_distance < range)
rating *= (1.0f - (range - edge_distance) / range);
if(rating > highestRating)
{
float3 possibleBuildsite = ConvertMapPosToUnitPos(mapPos, footprint);
ConvertPositionToFinalBuildsite(possibleBuildsite, footprint);
if(ai->GetAICallback()->CanBuildAt(def, possibleBuildsite))
{
buildsite = possibleBuildsite;
highestRating = rating;
}
}
}
++distanceToBaseArrayIndex;
}
}
//fclose(file);
return buildsite;
}
BuildSite AAIMap::CheckIfSuitableBuildSite(const UnitFootprint& footprint, const springLegacyAI::UnitDef* unitDef, const MapPos& mapPos) const
{
if(CanBuildAt(mapPos, footprint))
{
float3 possibleBuildsite = ConvertMapPosToUnitPos(mapPos, footprint);
ConvertPositionToFinalBuildsite(possibleBuildsite, footprint);
if(ai->GetAICallback()->CanBuildAt(unitDef, possibleBuildsite))
{
const SectorIndex sector(possibleBuildsite.x/xSectorSize, possibleBuildsite.z/ySectorSize);
if(IsValidSector(sector))
return BuildSite(possibleBuildsite, 1.0f, true);
}
}
return BuildSite();
}
bool AAIMap::CanBuildAt(const MapPos& mapPos, const UnitFootprint& footprint) const
{
if( (mapPos.x+footprint.xSize > xMapSize) || (mapPos.y+footprint.ySize > yMapSize) )
return false; // buildsite too close to edges of map
else
{
for(int y = mapPos.y; y < mapPos.y+footprint.ySize; ++y)
{
for(int x = mapPos.x; x < mapPos.x+footprint.xSize; ++x)
{
// all squares must be valid
if(s_buildmap[x+y*xMapSize].IsTileTypeSet(footprint.invalidTileTypes))
return false;
}
}
return true;
}
}
void AAIMap::CheckRows(int xPos, int yPos, int xSize, int ySize, bool add)
{
const BuildMapTileType nonOccupiedTile(EBuildMapTileType::FREE, EBuildMapTileType::BLOCKED_SPACE);
// check horizontal space
if( (xPos+xSize+cfg->MAX_XROW <= xMapSize) && (xPos - cfg->MAX_XROW >= 0) )
{
for(int y = yPos; y < yPos + ySize; ++y)
{
if(y >= yMapSize)
{
ai->Log("ERROR: y = %i index out of range when checking horizontal rows", y);
return;
}
// check to the right
int occupiedMapTiles(xSize);
int xRight(-1);
for(int x = xPos+xSize; x < xPos+xSize+cfg->MAX_XROW; ++x)
{
// abort when first non occupied tile is found
if(s_buildmap[x+y*xMapSize].IsTileTypeSet(nonOccupiedTile))
{
xRight = x;
break;
}
++occupiedMapTiles;
}
// check to the left
int xLeft(-1);
for(int x = xPos-1; x >= xPos - cfg->MAX_XROW; --x)
{
if(s_buildmap[x+y*xMapSize].IsTileTypeSet(nonOccupiedTile))
{
xLeft = x;