/
TileEngine.cpp
3248 lines (3008 loc) · 99.8 KB
/
TileEngine.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
/*
* Copyright 2010-2016 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenXcom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <climits>
#include <set>
#include "TileEngine.h"
#include <SDL.h>
#include "AIModule.h"
#include "Map.h"
#include "Camera.h"
#include "Projectile.h"
#include "../Savegame/SavedGame.h"
#include "../Savegame/SavedBattleGame.h"
#include "ExplosionBState.h"
#include "../Savegame/Tile.h"
#include "../Savegame/BattleItem.h"
#include "../Savegame/BattleUnit.h"
#include "../Engine/RNG.h"
#include "BattlescapeState.h"
#include "../Mod/MapDataSet.h"
#include "../Mod/Unit.h"
#include "../Mod/Mod.h"
#include "../Mod/Armor.h"
#include "Pathfinding.h"
#include "../Engine/Options.h"
#include "ProjectileFlyBState.h"
#include "MeleeAttackBState.h"
#include "../fmath.h"
namespace OpenXcom
{
const int TileEngine::heightFromCenter[11] = {0,-2,+2,-4,+4,-6,+6,-8,+8,-12,+12};
/**
* Sets up a TileEngine.
* @param save Pointer to SavedBattleGame object.
* @param voxelData List of voxel data.
*/
TileEngine::TileEngine(SavedBattleGame *save, std::vector<Uint16> *voxelData) : _save(save), _voxelData(voxelData), _personalLighting(true), _cacheTile(0), _cacheTileBelow(0)
{
_cacheTilePos = Position(-1,-1,-1);
}
/**
* Deletes the TileEngine.
*/
TileEngine::~TileEngine()
{
}
/**
* Calculates sun shading for the whole terrain.
*/
void TileEngine::calculateSunShading()
{
const int layer = 0; // Ambient lighting layer.
for (int i = 0; i < _save->getMapSizeXYZ(); ++i)
{
_save->getTiles()[i]->resetLight(layer);
calculateSunShading(_save->getTiles()[i]);
}
}
/**
* Calculates sun shading for 1 tile. Sun comes from above and is blocked by floors or objects.
* TODO: angle the shadow according to the time? - link to Options::globeSeasons (or whatever the realistic lighting one is)
* @param tile The tile to calculate sun shading for.
*/
void TileEngine::calculateSunShading(Tile *tile)
{
const int layer = 0; // Ambient lighting layer.
int power = 15 - _save->getGlobalShade();
// At night/dusk sun isn't dropping shades blocked by roofs
if (_save->getGlobalShade() <= 4)
{
int block = 0;
int x = tile->getPosition().x;
int y = tile->getPosition().y;
for (int z = _save->getMapSizeZ()-1; z > tile->getPosition().z ; z--)
{
block += blockage(_save->getTile(Position(x, y, z)), O_FLOOR, DT_NONE);
block += blockage(_save->getTile(Position(x, y, z)), O_OBJECT, DT_NONE, Pathfinding::DIR_DOWN);
}
if (block>0)
{
power -= 2;
}
}
tile->addLight(power, layer);
}
/**
* Recalculates lighting for the terrain: objects,items,fire.
*/
void TileEngine::calculateTerrainLighting()
{
const int layer = 1; // Static lighting layer.
const int fireLightPower = 15; // amount of light a fire generates
// reset all light to 0 first
for (int i = 0; i < _save->getMapSizeXYZ(); ++i)
{
_save->getTiles()[i]->resetLight(layer);
}
// add lighting of terrain
for (int i = 0; i < _save->getMapSizeXYZ(); ++i)
{
// only floors and objects can light up
if (_save->getTiles()[i]->getMapData(O_FLOOR)
&& _save->getTiles()[i]->getMapData(O_FLOOR)->getLightSource())
{
addLight(_save->getTiles()[i]->getPosition(), _save->getTiles()[i]->getMapData(O_FLOOR)->getLightSource(), layer);
}
if (_save->getTiles()[i]->getMapData(O_OBJECT)
&& _save->getTiles()[i]->getMapData(O_OBJECT)->getLightSource())
{
addLight(_save->getTiles()[i]->getPosition(), _save->getTiles()[i]->getMapData(O_OBJECT)->getLightSource(), layer);
}
// fires
if (_save->getTiles()[i]->getFire())
{
addLight(_save->getTiles()[i]->getPosition(), fireLightPower, layer);
}
for (std::vector<BattleItem*>::iterator it = _save->getTiles()[i]->getInventory()->begin(); it != _save->getTiles()[i]->getInventory()->end(); ++it)
{
if ((*it)->getRules()->getBattleType() == BT_FLARE)
{
addLight(_save->getTiles()[i]->getPosition(), (*it)->getRules()->getPower(), layer);
}
}
}
}
/**
* Recalculates lighting for the units.
*/
void TileEngine::calculateUnitLighting()
{
const int layer = 2; // Dynamic lighting layer.
const int personalLightPower = 15; // amount of light a unit generates
const int fireLightPower = 15; // amount of light a fire generates
// reset all light to 0 first
for (int i = 0; i < _save->getMapSizeXYZ(); ++i)
{
_save->getTiles()[i]->resetLight(layer);
}
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
// add lighting of soldiers
if (_personalLighting && (*i)->getFaction() == FACTION_PLAYER && !(*i)->isOut())
{
addLight((*i)->getPosition(), personalLightPower, layer);
}
// add lighting of units on fire
if ((*i)->getFire())
{
addLight((*i)->getPosition(), fireLightPower, layer);
}
}
}
/**
* Adds circular light pattern starting from center and losing power with distance travelled.
* @param center Center.
* @param power Power.
* @param layer Light is separated in 3 layers: Ambient, Static and Dynamic.
*/
void TileEngine::addLight(Position center, int power, int layer)
{
// only loop through the positive quadrant.
for (int x = 0; x <= power; ++x)
{
for (int y = 0; y <= power; ++y)
{
for (int z = 0; z < _save->getMapSizeZ(); z++)
{
int distance = (int)Round(sqrt(float(x*x + y*y)));
if (_save->getTile(Position(center.x + x,center.y + y, z)))
_save->getTile(Position(center.x + x,center.y + y, z))->addLight(power - distance, layer);
if (_save->getTile(Position(center.x - x,center.y - y, z)))
_save->getTile(Position(center.x - x,center.y - y, z))->addLight(power - distance, layer);
if (_save->getTile(Position(center.x - x,center.y + y, z)))
_save->getTile(Position(center.x - x,center.y + y, z))->addLight(power - distance, layer);
if (_save->getTile(Position(center.x + x,center.y - y, z)))
_save->getTile(Position(center.x + x,center.y - y, z))->addLight(power - distance, layer);
}
}
}
}
/**
* Calculates line of sight of a soldier.
* @param unit Unit to check line of sight of.
* @return True when new aliens are spotted.
*/
bool TileEngine::calculateFOV(BattleUnit *unit)
{
size_t oldNumVisibleUnits = unit->getUnitsSpottedThisTurn().size();
Position center = unit->getPosition();
Position test;
int direction;
bool swap;
std::vector<Position> _trajectory;
if (Options::strafe && (unit->getTurretType() > -1)) {
direction = unit->getTurretDirection();
}
else
{
direction = unit->getDirection();
}
swap = (direction==0 || direction==4);
int signX[8] = { +1, +1, +1, +1, -1, -1, -1, -1 };
int signY[8] = { -1, -1, -1, +1, +1, +1, -1, -1 };
int y1, y2;
unit->clearVisibleUnits();
unit->clearVisibleTiles();
if (unit->isOut())
return false;
Position pos = unit->getPosition();
if ((unit->getHeight() + unit->getFloatHeight() + -_save->getTile(unit->getPosition())->getTerrainLevel()) >= 24 + 4)
{
Tile *tileAbove = _save->getTile(pos + Position(0,0,1));
if (tileAbove && tileAbove->hasNoFloor(0))
{
++pos.z;
}
}
for (int x = 0; x <= MAX_VIEW_DISTANCE; ++x)
{
if (direction%2)
{
y1 = 0;
y2 = MAX_VIEW_DISTANCE;
}
else
{
y1 = -x;
y2 = x;
}
for (int y = y1; y <= y2; ++y)
{
for (int z = 0; z < _save->getMapSizeZ(); z++)
{
const int distanceSqr = x*x + y*y;
test.z = z;
if (distanceSqr <= MAX_VIEW_DISTANCE_SQR)
{
test.x = center.x + signX[direction]*(swap?y:x);
test.y = center.y + signY[direction]*(swap?x:y);
if (_save->getTile(test))
{
BattleUnit *visibleUnit = _save->getTile(test)->getUnit();
if (visibleUnit && !visibleUnit->isOut() && visible(unit, _save->getTile(test)))
{
if (unit->getFaction() == FACTION_PLAYER)
{
visibleUnit->getTile()->setVisible(+1);
visibleUnit->setVisible(true);
}
if ((visibleUnit->getFaction() == FACTION_HOSTILE && unit->getFaction() == FACTION_PLAYER)
|| (visibleUnit->getFaction() != FACTION_HOSTILE && unit->getFaction() == FACTION_HOSTILE))
{
unit->addToVisibleUnits(visibleUnit);
unit->addToVisibleTiles(visibleUnit->getTile());
if (unit->getFaction() == FACTION_HOSTILE && visibleUnit->getFaction() != FACTION_HOSTILE)
{
visibleUnit->setTurnsSinceSpotted(0);
}
}
}
if (unit->getFaction() == FACTION_PLAYER)
{
// this sets tiles to discovered if they are in LOS - tile visibility is not calculated in voxelspace but in tilespace
// large units have "4 pair of eyes"
int size = unit->getArmor()->getSize();
for (int xo = 0; xo < size; xo++)
{
for (int yo = 0; yo < size; yo++)
{
Position poso = pos + Position(xo,yo,0);
_trajectory.clear();
int tst = calculateLine(poso, test, true, &_trajectory, unit, false);
size_t tsize = _trajectory.size();
if (tst>127) --tsize; //last tile is blocked thus must be cropped
for (size_t i = 0; i < tsize; i++)
{
Position posi = _trajectory.at(i);
//mark every tile of line as visible (as in original)
//this is needed because of bresenham narrow stroke.
_save->getTile(posi)->setVisible(+1);
_save->getTile(posi)->setDiscovered(true, 2);
// walls to the east or south of a visible tile, we see that too
Tile* t = _save->getTile(Position(posi.x + 1, posi.y, posi.z));
if (t) t->setDiscovered(true, 0);
t = _save->getTile(Position(posi.x, posi.y + 1, posi.z));
if (t) t->setDiscovered(true, 1);
}
}
}
}
}
}
}
}
}
// we only react when there are at least the same amount of visible units as before AND the checksum is different
// this way we stop if there are the same amount of visible units, but a different unit is seen
// or we stop if there are more visible units seen
if (unit->getUnitsSpottedThisTurn().size() > oldNumVisibleUnits && !unit->getVisibleUnits()->empty())
{
return true;
}
return false;
}
/**
* Gets the origin voxel of a unit's eyesight
* @param currentUnit The watcher.
* @return Approximately an eyeball voxel.
*/
Position TileEngine::getSightOriginVoxel(BattleUnit *currentUnit)
{
// determine the origin and target voxels for the raytrace
Position originVoxel;
originVoxel = Position((currentUnit->getPosition().x * 16) + 8, (currentUnit->getPosition().y * 16) + 8, currentUnit->getPosition().z*24);
originVoxel.z += -_save->getTile(currentUnit->getPosition())->getTerrainLevel();
originVoxel.z += currentUnit->getHeight() + currentUnit->getFloatHeight() - 1; //one voxel lower (eye level)
Tile *tileAbove = _save->getTile(currentUnit->getPosition() + Position(0,0,1));
if (currentUnit->getArmor()->getSize() > 1)
{
originVoxel.x += 8;
originVoxel.y += 8;
originVoxel.z += 1; //topmost voxel
}
if (originVoxel.z >= (currentUnit->getPosition().z + 1)*24 && (!tileAbove || !tileAbove->hasNoFloor(0)))
{
while (originVoxel.z >= (currentUnit->getPosition().z + 1)*24)
{
originVoxel.z--;
}
}
return originVoxel;
}
/**
* Checks for an opposing unit on this tile.
* @param currentUnit The watcher.
* @param tile The tile to check for
* @return True if visible.
*/
bool TileEngine::visible(BattleUnit *currentUnit, Tile *tile)
{
// if there is no tile or no unit, we can't see it
if (!tile || !tile->getUnit())
{
return false;
}
// aliens can see in the dark, xcom can see at a distance of 9 or less, further if there's enough light.
if ((currentUnit->getFaction() == FACTION_PLAYER &&
distance(currentUnit->getPosition(), tile->getPosition()) > 9 &&
tile->getShade() > MAX_DARKNESS_TO_SEE_UNITS) ||
distance(currentUnit->getPosition(), tile->getPosition()) > MAX_VIEW_DISTANCE)
{
return false;
}
if (currentUnit->getFaction() == tile->getUnit()->getFaction()) return true; // friendlies are always seen
Position originVoxel = getSightOriginVoxel(currentUnit);
bool unitSeen = false;
// for large units origin voxel is in the middle
Position scanVoxel;
std::vector<Position> _trajectory;
unitSeen = canTargetUnit(&originVoxel, tile, &scanVoxel, currentUnit, false);
if (unitSeen)
{
// now check if we really see it taking into account smoke tiles
// initial smoke "density" of a smoke grenade is around 15 per tile
// we do density/3 to get the decay of visibility
// so in fresh smoke we should only have 4 tiles of visibility
// this is traced in voxel space, with smoke affecting visibility every step of the way
_trajectory.clear();
calculateLine(originVoxel, scanVoxel, true, &_trajectory, currentUnit);
Tile *t = _save->getTile(currentUnit->getPosition());
size_t visibleDistance = _trajectory.size();
for (size_t i = 0; i < _trajectory.size(); i++)
{
if (t != _save->getTile(Position(_trajectory.at(i).x/16,_trajectory.at(i).y/16, _trajectory.at(i).z/24)))
{
t = _save->getTile(Position(_trajectory.at(i).x/16,_trajectory.at(i).y/16, _trajectory.at(i).z/24));
}
if (t->getFire() == 0)
{
visibleDistance += t->getSmoke() / 3;
}
if (visibleDistance > (unsigned)MAX_VOXEL_VIEW_DISTANCE)
{
unitSeen = false;
break;
}
}
}
return unitSeen;
}
/**
* Checks for how exposed unit is for another unit.
* @param originVoxel Voxel of trace origin (eye or gun's barrel).
* @param tile The tile to check for.
* @param excludeUnit Is self (not to hit self).
* @param excludeAllBut [Optional] is unit which is the only one to be considered for ray hits.
* @return Degree of exposure (as percent).
*/
int TileEngine::checkVoxelExposure(Position *originVoxel, Tile *tile, BattleUnit *excludeUnit, BattleUnit *excludeAllBut)
{
Position targetVoxel = Position((tile->getPosition().x * 16) + 8, (tile->getPosition().y * 16) + 8, tile->getPosition().z * 24);
Position scanVoxel;
std::vector<Position> _trajectory;
BattleUnit *otherUnit = tile->getUnit();
if (otherUnit == 0) return 0; //no unit in this tile, even if it elevated and appearing in it.
if (otherUnit == excludeUnit) return 0; //skip self
int targetMinHeight = targetVoxel.z - tile->getTerrainLevel();
if (otherUnit)
targetMinHeight += otherUnit->getFloatHeight();
// if there is an other unit on target tile, we assume we want to check against this unit's height
int heightRange;
int unitRadius = otherUnit->getLoftemps(); //width == loft in default loftemps set
if (otherUnit->getArmor()->getSize() > 1)
{
unitRadius = 3;
}
// vector manipulation to make scan work in view-space
Position relPos = targetVoxel - *originVoxel;
float normal = unitRadius/sqrt((float)(relPos.x*relPos.x + relPos.y*relPos.y));
int relX = floor(((float)relPos.y)*normal+0.5);
int relY = floor(((float)-relPos.x)*normal+0.5);
int sliceTargets[] = {0,0, relX,relY, -relX,-relY};
if (!otherUnit->isOut())
{
heightRange = otherUnit->getHeight();
}
else
{
heightRange = 12;
}
int targetMaxHeight=targetMinHeight+heightRange;
// scan ray from top to bottom plus different parts of target cylinder
int total=0;
int visible=0;
for (int i = heightRange; i >=0; i-=2)
{
++total;
scanVoxel.z=targetMinHeight+i;
for (int j = 0; j < 3; ++j)
{
scanVoxel.x=targetVoxel.x + sliceTargets[j*2];
scanVoxel.y=targetVoxel.y + sliceTargets[j*2+1];
_trajectory.clear();
int test = calculateLine(*originVoxel, scanVoxel, false, &_trajectory, excludeUnit, true, false, excludeAllBut);
if (test == V_UNIT)
{
//voxel of hit must be inside of scanned box
if (_trajectory.at(0).x/16 == scanVoxel.x/16 &&
_trajectory.at(0).y/16 == scanVoxel.y/16 &&
_trajectory.at(0).z >= targetMinHeight &&
_trajectory.at(0).z <= targetMaxHeight)
{
++visible;
}
}
}
}
return (visible*100)/total;
}
/**
* Checks for another unit available for targeting and what particular voxel.
* @param originVoxel Voxel of trace origin (eye or gun's barrel).
* @param tile The tile to check for.
* @param scanVoxel is returned coordinate of hit.
* @param excludeUnit is self (not to hit self).
* @param rememberObstacles Remember obstacles for no LOF indicator?
* @param potentialUnit is a hypothetical unit to draw a virtual line of fire for AI. if left blank, this function behaves normally.
* @return True if the unit can be targetted.
*/
bool TileEngine::canTargetUnit(Position *originVoxel, Tile *tile, Position *scanVoxel, BattleUnit *excludeUnit, bool rememberObstacles, BattleUnit *potentialUnit)
{
Position targetVoxel = Position((tile->getPosition().x * 16) + 8, (tile->getPosition().y * 16) + 8, tile->getPosition().z * 24);
std::vector<Position> _trajectory;
bool hypothetical = potentialUnit != 0;
if (potentialUnit == 0)
{
potentialUnit = tile->getUnit();
if (potentialUnit == 0) return false; //no unit in this tile, even if it elevated and appearing in it.
}
if (potentialUnit == excludeUnit) return false; //skip self
int targetMinHeight = targetVoxel.z - tile->getTerrainLevel();
targetMinHeight += potentialUnit->getFloatHeight();
int targetMaxHeight = targetMinHeight;
int targetCenterHeight;
// if there is an other unit on target tile, we assume we want to check against this unit's height
int heightRange;
int unitRadius = potentialUnit->getLoftemps(); //width == loft in default loftemps set
int targetSize = potentialUnit->getArmor()->getSize() - 1;
int xOffset = potentialUnit->getPosition().x - tile->getPosition().x;
int yOffset = potentialUnit->getPosition().y - tile->getPosition().y;
if (targetSize > 0)
{
unitRadius = 3;
}
// vector manipulation to make scan work in view-space
Position relPos = targetVoxel - *originVoxel;
float normal = unitRadius/sqrt((float)(relPos.x*relPos.x + relPos.y*relPos.y));
int relX = floor(((float)relPos.y)*normal+0.5);
int relY = floor(((float)-relPos.x)*normal+0.5);
int sliceTargets[] = {0,0, relX,relY, -relX,-relY, relY,-relX, -relY,relX};
if (!potentialUnit->isOut())
{
heightRange = potentialUnit->getHeight();
}
else
{
heightRange = 12;
}
targetMaxHeight += heightRange;
targetCenterHeight=(targetMaxHeight+targetMinHeight)/2;
heightRange/=2;
if (heightRange>10) heightRange=10;
if (heightRange<=0) heightRange=0;
// scan ray from top to bottom plus different parts of target cylinder
for (int i = 0; i <= heightRange; ++i)
{
scanVoxel->z=targetCenterHeight+heightFromCenter[i];
for (int j = 0; j < 5; ++j)
{
if (i < (heightRange-1) && j>2) break; //skip unnecessary checks
scanVoxel->x=targetVoxel.x + sliceTargets[j*2];
scanVoxel->y=targetVoxel.y + sliceTargets[j*2+1];
_trajectory.clear();
int test = calculateLine(*originVoxel, *scanVoxel, false, &_trajectory, excludeUnit, true, false);
if (test == V_UNIT)
{
for (int x = 0; x <= targetSize; ++x)
{
for (int y = 0; y <= targetSize; ++y)
{
//voxel of hit must be inside of scanned box
if (_trajectory.at(0).x/16 == (scanVoxel->x/16) + x + xOffset &&
_trajectory.at(0).y/16 == (scanVoxel->y/16) + y + yOffset &&
_trajectory.at(0).z >= targetMinHeight &&
_trajectory.at(0).z <= targetMaxHeight)
{
return true;
}
}
}
}
else if (test == V_EMPTY && hypothetical && !_trajectory.empty())
{
return true;
}
if (rememberObstacles && _trajectory.size()>0)
{
Tile *tileObstacle = _save->getTile(Position(_trajectory.at(0).x / 16, _trajectory.at(0).y / 16, _trajectory.at(0).z / 24));
if (tileObstacle) tileObstacle->setObstacle(test);
}
}
}
return false;
}
/**
* Checks for a tile part available for targeting and what particular voxel.
* @param originVoxel Voxel of trace origin (gun's barrel).
* @param tile The tile to check for.
* @param part Tile part to check for.
* @param scanVoxel Is returned coordinate of hit.
* @param excludeUnit Is self (not to hit self).
* @param rememberObstacles Remember obstacles for no LOF indicator?
* @return True if the tile can be targetted.
*/
bool TileEngine::canTargetTile(Position *originVoxel, Tile *tile, int part, Position *scanVoxel, BattleUnit *excludeUnit, bool rememberObstacles)
{
static int sliceObjectSpiral[82] = {8,8, 8,6, 10,6, 10,8, 10,10, 8,10, 6,10, 6,8, 6,6, //first circle
8,4, 10,4, 12,4, 12,6, 12,8, 12,10, 12,12, 10,12, 8,12, 6,12, 4,12, 4,10, 4,8, 4,6, 4,4, 6,4, //second circle
8,1, 12,1, 15,1, 15,4, 15,8, 15,12, 15,15, 12,15, 8,15, 4,15, 1,15, 1,12, 1,8, 1,4, 1,1, 4,1}; //third circle
static int westWallSpiral[14] = {0,7, 0,9, 0,6, 0,11, 0,4, 0,13, 0,2};
static int northWallSpiral[14] = {7,0, 9,0, 6,0, 11,0, 4,0, 13,0, 2,0};
Position targetVoxel = Position((tile->getPosition().x * 16), (tile->getPosition().y * 16), tile->getPosition().z * 24);
std::vector<Position> _trajectory;
int *spiralArray;
int spiralCount;
int minZ = 0, maxZ = 0;
bool minZfound = false, maxZfound = false;
bool dummy = false;
if (part == O_OBJECT)
{
spiralArray = sliceObjectSpiral;
spiralCount = 41;
}
else
if (part == O_NORTHWALL)
{
spiralArray = northWallSpiral;
spiralCount = 7;
}
else
if (part == O_WESTWALL)
{
spiralArray = westWallSpiral;
spiralCount = 7;
}
else if (part == O_FLOOR)
{
spiralArray = sliceObjectSpiral;
spiralCount = 41;
minZfound = true; minZ=0;
maxZfound = true; maxZ=0;
}
else if (part == MapData::O_DUMMY) // used only for no line of fire indicator
{
spiralArray = sliceObjectSpiral;
spiralCount = 41;
minZfound = true; minZ = 12;
maxZfound = true; maxZ = 12;
}
else
{
return false;
}
voxelCheckFlush();
// find out height range
if (!minZfound)
{
for (int j = 1; j < 12; ++j)
{
if (minZfound) break;
for (int i = 0; i < spiralCount; ++i)
{
int tX = spiralArray[i*2];
int tY = spiralArray[i*2+1];
if (voxelCheck(Position(targetVoxel.x + tX, targetVoxel.y + tY, targetVoxel.z + j*2),0,true) == part) //bingo
{
if (!minZfound)
{
minZ = j*2;
minZfound = true;
break;
}
}
}
}
}
if (!minZfound)
{
if (rememberObstacles)
{
// dummy attempt (only to highlight obstacles)
minZfound = true;
minZ = 10;
dummy = true;
}
else
{
return false;//empty object!!!
}
}
if (!maxZfound)
{
for (int j = 10; j >= 0; --j)
{
if (maxZfound) break;
for (int i = 0; i < spiralCount; ++i)
{
int tX = spiralArray[i*2];
int tY = spiralArray[i*2+1];
if (voxelCheck(Position(targetVoxel.x + tX, targetVoxel.y + tY, targetVoxel.z + j*2),0,true) == part) //bingo
{
if (!maxZfound)
{
maxZ = j*2;
maxZfound = true;
break;
}
}
}
}
}
if (!maxZfound)
{
if (rememberObstacles)
{
// dummy attempt (only to highlight obstacles)
maxZfound = true;
maxZ = 10;
dummy = true;
}
else
{
return false;//it's impossible to get there
}
}
if (minZ > maxZ) minZ = maxZ;
int rangeZ = maxZ - minZ;
if (rangeZ>10) rangeZ = 10; //as above, clamping height range to prevent buffer overflow
int centerZ = (maxZ + minZ)/2;
for (int j = 0; j <= rangeZ; ++j)
{
scanVoxel->z = targetVoxel.z + centerZ + heightFromCenter[j];
for (int i = 0; i < spiralCount; ++i)
{
scanVoxel->x = targetVoxel.x + spiralArray[i*2];
scanVoxel->y = targetVoxel.y + spiralArray[i*2+1];
_trajectory.clear();
int test = calculateLine(*originVoxel, *scanVoxel, false, &_trajectory, excludeUnit, true);
if (test == part && !dummy) //bingo
{
if (_trajectory.at(0).x/16 == scanVoxel->x/16 &&
_trajectory.at(0).y/16 == scanVoxel->y/16 &&
_trajectory.at(0).z/24 == scanVoxel->z/24)
{
return true;
}
}
if (rememberObstacles && _trajectory.size()>0)
{
Tile *tileObstacle = _save->getTile(Position(_trajectory.at(0).x / 16, _trajectory.at(0).y / 16, _trajectory.at(0).z / 24));
if (tileObstacle) tileObstacle->setObstacle(test);
}
}
}
return false;
}
/**
* Calculates line of sight of a soldiers within range of the Position
* (used when terrain has changed, which can reveal new parts of terrain or units).
* @param position Position of the changed terrain.
*/
void TileEngine::calculateFOV(Position position)
{
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if (distanceSq(position, (*i)->getPosition()) <= MAX_VIEW_DISTANCE_SQR)
{
calculateFOV(*i);
}
}
}
/**
* Checks if a sniper from the opposing faction sees this unit. The unit with the highest reaction score will be compared with the current unit's reaction score.
* If it's higher, a shot is fired when enough time units, a weapon and ammo are available.
* @param unit The unit to check reaction fire upon.
* @return True if reaction fire took place.
*/
bool TileEngine::checkReactionFire(BattleUnit *unit)
{
// reaction fire only triggered when the actioning unit is of the currently playing side, and is still on the map (alive)
if (unit->getFaction() != _save->getSide() || unit->getTile() == 0)
{
return false;
}
std::vector<std::pair<BattleUnit *, int> > spotters = getSpottingUnits(unit);
bool result = false;
// not mind controlled, or controlled by the player
if (unit->getFaction() == unit->getOriginalFaction()
|| unit->getFaction() != FACTION_HOSTILE)
{
// get the first man up to bat.
int attackType;
BattleUnit *reactor = getReactor(spotters, attackType, unit);
// start iterating through the possible reactors until the current unit is the one with the highest score.
while (reactor != unit)
{
if (!tryReaction(reactor, unit, attackType))
{
// can't make a reaction snapshot for whatever reason, boot this guy from the vector.
for (std::vector<std::pair<BattleUnit *, int> >::iterator i = spotters.begin(); i != spotters.end(); ++i)
{
if ((*i).first == reactor)
{
spotters.erase(i);
break;
}
}
// avoid setting result to true, but carry on, just cause one unit can't react doesn't mean the rest of the units in the vector (if any) can't
reactor = getReactor(spotters, attackType, unit);
continue;
}
// nice shot, kid. don't get cocky.
reactor = getReactor(spotters, attackType, unit);
result = true;
}
}
return result;
}
/**
* Creates a vector of units that can spot this unit.
* @param unit The unit to check for spotters of.
* @return A vector of units that can see this unit.
*/
std::vector<std::pair<BattleUnit *, int> > TileEngine::getSpottingUnits(BattleUnit* unit)
{
std::vector<std::pair<BattleUnit *, int> > spotters;
Tile *tile = unit->getTile();
// no reaction on civilian turn.
if (_save->getSide() != FACTION_NEUTRAL)
{
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
// not dead/unconscious
if (!(*i)->isOut() &&
// not dying
(*i)->getHealth() != 0 &&
// not about to pass out
(*i)->getStunlevel() < (*i)->getHealth() &&
// not a friend
(*i)->getFaction() != _save->getSide() &&
// not a civilian
(*i)->getFaction() != FACTION_NEUTRAL &&
// closer than 20 tiles
distanceSq(unit->getPosition(), (*i)->getPosition()) <= MAX_VIEW_DISTANCE_SQR)
{
BattleAction falseAction;
falseAction.type = BA_SNAPSHOT;
falseAction.actor = *i;
falseAction.target = unit->getPosition();
Position originVoxel = getOriginVoxel(falseAction, 0);
Position targetVoxel;
AIModule *ai = (*i)->getAIModule();
// Inquisitor's note regarding 'gotHit' variable
// in vanilla, the 'hitState' flag is the only part of this equation that comes into play.
// any time a unit takes damage, this flag is set, then it would be reset by a call to
// a function analogous to SavedBattleGame::resetUnitHitStates(), any time:
// 1: a unit was selected by being clicked on.
// 2: either "next unit" button was pressed.
// 3: the inventory screen was accessed. (i didn't look too far into this one, it's possible it's only called in the pre-mission equip screen)
// 4: the same place where we call it, immediately before every move the AI makes.
// this flag is responsible for units turning around to respond to hits, and is in keeping with the details listed on http://www.ufopaedia.org/index.php/Reaction_fire_triggers
// we've gone for a slightly different implementation: AI units keep a list of which units have hit them and don't forget until the end of the player's turn.
// this method is in keeping with the spirit of the original feature, but much less exploitable by players.
// the hitState flag in our implementation allows player units to turn and react as they did in the original, (which is far less cumbersome than giving them all an AI module)
// we don't extend the same "enhanced aggressor memory" courtesy to players, because in the original, they could only turn and react to damage immediately after it happened.
// this is because as much as we want the player's soldiers dead, we don't want them to feel like we're being unfair about it.
bool gotHit = (ai != 0 && ai->getWasHitBy(unit->getId())) || (ai == 0 && (*i)->getHitState());
// can actually see the target Tile, or we got hit
if (((*i)->checkViewSector(unit->getPosition()) || gotHit) &&
// can actually target the unit
canTargetUnit(&originVoxel, tile, &targetVoxel, *i, false) &&
// can actually see the unit
visible(*i, tile))
{
if ((*i)->getFaction() == FACTION_PLAYER)
{
unit->setVisible(true);
}
(*i)->addToVisibleUnits(unit);
int attackType = determineReactionType(*i, unit);
if (attackType != BA_NONE)
{
spotters.push_back(std::make_pair(*i, attackType));
}
}
}
}
}
return spotters;
}
/**
* Gets the unit with the highest reaction score from the spotter vector.
* @param spotters The vector of spotting units.
* @param unit The unit to check scores against.
* @return The unit with the highest reactions.
*/
BattleUnit* TileEngine::getReactor(std::vector<std::pair<BattleUnit *, int> > spotters, int &attackType, BattleUnit *unit)
{
int bestScore = -1;
BattleUnit *bu = 0;
for (std::vector<std::pair<BattleUnit *, int> >::iterator i = spotters.begin(); i != spotters.end(); ++i)
{
if (!(*i).first->isOut() &&
!(*i).first->getRespawn() &&
determineReactionType((*i).first, unit) != BA_NONE &&
(*i).first->getReactionScore() > bestScore)
{
bestScore = (*i).first->getReactionScore();
bu = (*i).first;
attackType = (*i).second;
}
}
if (unit->getReactionScore() <= bestScore)
{
if (bu->getOriginalFaction() == FACTION_PLAYER)
{
bu->addReactionExp();
}
}
else
{
bu = unit;
attackType = BA_NONE;
}
return bu;
}
/**
* Checks the validity of a snap shot performed here.
* @param unit The unit to check sight from.
* @param target The unit to check sight TO.
* @return True if the target is valid.
*/
int TileEngine::determineReactionType(BattleUnit *unit, BattleUnit *target)
{
// prioritize melee
BattleItem *meleeWeapon = unit->getMeleeWeapon();
if (meleeWeapon &&
// has a melee weapon and is in melee range
validMeleeRange(unit, target, unit->getDirection()) &&
unit->getActionTUs(BA_HIT, meleeWeapon) > 0 &&
unit->getTimeUnits() > unit->getActionTUs(BA_HIT, meleeWeapon) &&