Repository navigation
Expand file tree
/
Copy pathTerrainModifier.cpp
More file actions
1337 lines (1183 loc) · 41 KB
/
Copy pathTerrainModifier.cpp
File metadata and controls
1337 lines (1183 loc) · 41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 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/>.
*/
#define _USE_MATH_DEFINES
#include <cmath>
#include <set>
#include "TerrainModifier.h"
#include "SDL.h"
#include "BattleAIState.h"
#include "AggroBAIState.h"
#include "../Savegame/SavedBattleGame.h"
#include "../Savegame/Tile.h"
#include "../Savegame/BattleUnit.h"
#include "../Savegame/Soldier.h"
#include "../Savegame/Alien.h"
#include "../Engine/RNG.h"
#include "../Ruleset/MapDataSet.h"
#include "../Ruleset/MapData.h"
#include "../Ruleset/RuleAlien.h"
#include "../Ruleset/RuleSoldier.h"
#include "../Resource/ResourcePack.h"
namespace OpenXcom
{
/**
* Sets up a TerrainModifier.
* @param save pointer to SavedBattleGame object.
*/
TerrainModifier::TerrainModifier(SavedBattleGame *save, std::vector<Uint16> *voxelData) : _save(save), _voxelData(voxelData)
{
}
/**
* Deletes the TerrainModifier.
*/
TerrainModifier::~TerrainModifier()
{
}
/**
* Calculate sun shading for the whole terrain.
*/
void TerrainModifier::calculateSunShading()
{
for (int i = 0; i < _save->getWidth() * _save->getLength() * _save->getHeight(); ++i)
{
calculateSunShading(_save->getTiles()[i]);
}
}
/**
* Calculate sun shading for 1 tile. Sun comes from above and is blocked by floors or objects.
* @param tile The tile to calculate sun shading for.
*/
void TerrainModifier::calculateSunShading(Tile *tile)
{
const int layer = 0; // Ambient lighting layer.
int power = 15 - _save->getGlobalShade();
// At night/dusk sun isn't dropping shades
if (_save->getGlobalShade() <= 5)
{
if (verticalBlockage(_save->getTile(Position(tile->getPosition().x, tile->getPosition().y, _save->getHeight() - 1)), tile, DT_NONE))
{
power-=2;
}
}
tile->addLight(power, layer);
}
/**
* Recalculate lighting for the terrain: objects,items,fire.
*/
void TerrainModifier::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->getWidth() * _save->getLength() * _save->getHeight(); ++i)
{
_save->getTiles()[i]->resetLight(layer);
}
// add lighting of terrain
for (int i = 0; i < _save->getWidth() * _save->getLength() * _save->getHeight(); ++i)
{
// only floors and objects can light up
if (_save->getTiles()[i]->getMapData(MapData::O_FLOOR)
&& _save->getTiles()[i]->getMapData(MapData::O_FLOOR)->getLightSource())
{
addLight(_save->getTiles()[i]->getPosition(), _save->getTiles()[i]->getMapData(MapData::O_FLOOR)->getLightSource(), layer);
}
if (_save->getTiles()[i]->getMapData(MapData::O_OBJECT)
&& _save->getTiles()[i]->getMapData(MapData::O_OBJECT)->getLightSource())
{
addLight(_save->getTiles()[i]->getPosition(), _save->getTiles()[i]->getMapData(MapData::O_OBJECT)->getLightSource(), layer);
}
// fires
if (_save->getTiles()[i]->getFire())
{
addLight(_save->getTiles()[i]->getPosition(), fireLightPower, layer);
}
}
// todo: add lighting of items (flares)
}
/**
* Recalculate lighting for the units.
*/
void TerrainModifier::calculateUnitLighting()
{
const int layer = 2; // Dynamic lighting layer.
const int personalLightPower = 15; // amount of light a unit generates
// reset all light to 0 first
for (int i = 0; i < _save->getWidth() * _save->getLength() * _save->getHeight(); ++i)
{
_save->getTiles()[i]->resetLight(layer);
}
// add lighting of soldiers
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if ((*i)->getFaction() == FACTION_PLAYER && !(*i)->isOut())
{
addLight((*i)->getPosition(), personalLightPower, layer);
}
}
}
/**
* Adds circular light pattern starting from center and loosing power with distance travelled.
* @param center
* @param power
* @param layer Light is seperated in 3 layers: Ambient, Static and Dynamic.
*/
void TerrainModifier::addLight(const Position ¢er, 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->getHeight(); z++)
{
int distance = int(floor(sqrt(float(x*x + y*y)) + 0.5));
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 versus terrain. For every visible tile fog of war is removed.
* @param unit
*/
void TerrainModifier::calculateFOVTerrain(BattleUnit *unit)
{
// units see 90 degrees sidewards.
int startAngle[8] = { 45, 0, -45, 270, 225, 180, 135, 90 };
int endAngle[8] = { 135, 90, 45, 360, 315, 270, 225, 180 };
double centerZ = (unit->getPosition().z * 2) + 1.5;
double centerX = unit->getPosition().x + 0.5;
double centerY = unit->getPosition().y + 0.5;
int objectViewDistance;
// units see 90 degrees down and 60 degrees up.
int startFi = -90;
int endFi = 60;
std::set<Tile*> tilesAffected;
std::pair<std::set<Tile*>::iterator,bool> ret;
if (unit->getPosition().z == 0)
{
startFi = 0;
}
// non players don't care about terrain FOV
if (unit->getFaction() != FACTION_PLAYER)
{
return;
}
// we see the tile we are standing on
unit->getTile()->setDiscovered(true, 2);
// raytrace up and down
for (int fi = startFi; fi <= endFi; fi += 6)
{
double cos_fi = cos(fi * M_PI / 180.0);
double sin_fi = sin(fi * M_PI / 180.0);
// raytrace every 3 degrees makes sure we cover all tiles in a circle.
for (int te = startAngle[unit->getDirection()]; te <= endAngle[unit->getDirection()]; te += 3)
{
double cos_te = cos(te * M_PI / 180.0);
double sin_te = sin(te * M_PI / 180.0);
Tile *origin = unit->getTile();
double l = 0;
double vx, vy, vz;
int tileX, tileY, tileZ;
objectViewDistance = MAX_VIEW_DISTANCE;
while (objectViewDistance > 0)
{
l++;
vx = centerX + l * cos_te * cos_fi;
vy = centerY + l * sin_te * cos_fi;
vz = centerZ + l * sin_fi;
tileZ = int(floor(vz / 2.0));
tileX = int(floor(vx));
tileY = int(floor(vy));
objectViewDistance--;
Tile *dest = _save->getTile(Position(tileX, tileY, tileZ));
if (!dest) break; // out of map!
// horizontal blockage by walls
objectViewDistance -= horizontalBlockage(origin, dest, DT_NONE);
// vertical blockage by ceilings/floors
objectViewDistance -= verticalBlockage(origin, dest, DT_NONE);
if (objectViewDistance > 0)
{
ret = tilesAffected.insert(dest); // check if we had this tile already
if (ret.second)
{
dest->setDiscovered(true, 2);
// walls to the east or south of a visible tile, we see that too
Tile* t = _save->getTile(Position(tileX + 1, tileY, tileZ));
if (t) t->setDiscovered(true, 0);
t = _save->getTile(Position(tileX, tileY - 1, tileZ));
if (t) t->setDiscovered(true, 1);
}
}
origin = dest;
}
}
}
}
/**
* Calculates line of sight of a soldier versus units.
* @param unit
* @return true when new aliens spotted
*/
bool TerrainModifier::calculateFOVUnits(BattleUnit *unit)
{
int visibleUnitsChecksum = 0;
Position center = unit->getPosition();
Position test;
bool swap = (unit->getDirection()==0 || unit->getDirection()==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;
// calculate a visible units checksum - if it changed during this step, the soldier stops walking
for (std::vector<BattleUnit*>::iterator i = unit->getVisibleUnits()->begin(); i != unit->getVisibleUnits()->end(); ++i)
visibleUnitsChecksum += (*i)->getId()+1;
unit->clearVisibleUnits();
for (int x = 0; x <= MAX_VIEW_DISTANCE; ++x)
{
if (unit->getDirection()%2)
{
y1 = 0;
y2 = MAX_VIEW_DISTANCE - x;
}
else
{
y1 = -x;
y2 = x;
}
for (int y = y1; y <= y2; ++y)
{
for (int z = 0; z < _save->getHeight(); z++)
{
int distance = int(floor(sqrt(float(x*x + y*y)) + 0.5));
test.z = z;
if (distance <= MAX_VIEW_DISTANCE)
{
test.x = center.x + signX[unit->getDirection()]*(swap?y:x);
test.y = center.y + signY[unit->getDirection()]*(swap?x:y);
if (_save->getTile(test))
{
checkIfUnitVisible(unit, _save->getTile(test)->getUnit());
}
}
}
}
}
int newChecksum = 0;
for (std::vector<BattleUnit*>::iterator i = unit->getVisibleUnits()->begin(); i != unit->getVisibleUnits()->end(); ++i)
newChecksum += (*i)->getId()+1;
return visibleUnitsChecksum < newChecksum;
}
/**
* Check for an opposing unit on this tile
* @param currentUnit the watcher
* @param otherUnit the unit to check for
*/
bool TerrainModifier::checkIfUnitVisible(BattleUnit *currentUnit, BattleUnit *otherUnit)
{
// only check if unit is alive
if (otherUnit == 0 || otherUnit->isOut())
{
return false;
}
// only check for opposing factions
if (currentUnit->getFaction() == FACTION_PLAYER && (otherUnit->getFaction() == FACTION_PLAYER || otherUnit->getFaction() == FACTION_NEUTRAL))
{
return false;
}
if (currentUnit->getFaction() == FACTION_HOSTILE && otherUnit->getFaction() == FACTION_HOSTILE)
{
return false;
}
// if the tile is too dark, we can't see the unit
if (_save->getTile(otherUnit->getPosition())->getShade() > MAX_DARKNESS_TO_SEE_UNITS)
{
return false;
}
// determine the origin and target voxels for the raytrace
Position originVoxel, targetVoxel;
std::vector<Position> _trajectory;
originVoxel = Position((currentUnit->getPosition().x * 16) + 8, (currentUnit->getPosition().y * 16) + 8, currentUnit->getPosition().z*24);
originVoxel.z += -_save->getTile(currentUnit->getPosition())->getTerrainLevel();
if (currentUnit->isKneeled())
{
originVoxel.z += currentUnit->getUnit()->getKneelHeight();
}
else
{
originVoxel.z += currentUnit->getUnit()->getStandHeight();
}
bool unitSeen = false;
targetVoxel = Position((otherUnit->getPosition().x * 16) + 8, (otherUnit->getPosition().y * 16) + 8, otherUnit->getPosition().z*24);
int targetMinHeight = targetVoxel.z - _save->getTile(otherUnit->getPosition())->getTerrainLevel();
int targetMaxHeight;
if (otherUnit->isKneeled())
{
targetMaxHeight = targetMinHeight + otherUnit->getUnit()->getKneelHeight();
}
else
{
targetMaxHeight = targetMinHeight + otherUnit->getUnit()->getStandHeight();
}
// scan ray from top to bottom
for (int i = targetMaxHeight; i > targetMinHeight; i-=2)
{
targetVoxel.z = i;
_trajectory.clear();
int test = calculateLine(originVoxel, targetVoxel, false, &_trajectory, currentUnit);
if (test == 4)
{
Position hitPosition = Position(_trajectory.at(0).x/16, _trajectory.at(0).y/16, _trajectory.at(0).z/24);
if (otherUnit->getPosition() == hitPosition)
{
unitSeen = true;
break;
}
}
if (test == -1)
{
unitSeen = true;
break;
}
}
if (unitSeen)
{
// now check if we really see it taking into account smoke tiles
// initial smoke "density" of a smoke grenade is around 10 per tile
// we do density/2 to get the decay of visibility, so in fresh smoke we only have 4 tiles of visibility
_trajectory.clear();
calculateLine(originVoxel, targetVoxel, true, &_trajectory, currentUnit);
Tile *t = _save->getTile(currentUnit->getPosition());
int maxViewDistance = MAX_VIEW_DISTANCE - (t->getSmoke()/2);
for (unsigned int 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));
maxViewDistance -= t->getSmoke()/2;
}
}
int x = abs(currentUnit->getPosition().x - otherUnit->getPosition().x);
int y = abs(currentUnit->getPosition().y - otherUnit->getPosition().y);
int distance = int(floor(sqrt(float(x*x + y*y)) + 0.5));
if (distance <= maxViewDistance)
{
currentUnit->addToVisibleUnits(otherUnit);
}
else
{
unitSeen = false;
}
}
return unitSeen;
}
/**
* Calculates line of sight of a soldiers within range of the Position
* (used when terrain has changed, which can reveil new parts of terrain or units)
* @param position Position of the changed terrain.
*/
void TerrainModifier::calculateFOV(const Position &position)
{
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
int x = abs(position.x - (*i)->getPosition().x);
int y = abs(position.y - (*i)->getPosition().y);
int distance = int(floor(sqrt(float(x*x + y*y)) + 0.5));
if (distance < 20 && (*i)->getFaction() == _save->getSide())
{
calculateFOVTerrain(*i);
calculateFOVUnits(*i);
}
}
}
/**
* Checks if of the opposing faction a sniper 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 available.
* @param unit
* @param action
* @param potentialVictim The unit that is targetted when shot.
* @param recalculateFOV Whether to recalculate first the FOV of the units within range.
*/
bool TerrainModifier::checkReactionFire(BattleUnit *unit, BattleAction *action, BattleUnit *potentialVictim, bool recalculateFOV)
{
double highestReactionScore = 0;
action->actor = 0;
// reaction fire only triggered when the actioning unit is of the currently playing side
if (unit->getFaction() != _save->getSide())
{
return false;
}
// from time to time just don't do a reaction shot
// (implemented this after doing lots of test cycles - in the original x-com on average we get to see far less reaction shots although the formula used is the one on UFOPAEDIA)
if (RNG::generate(0, 4) == 1)
{
return false;
}
if (potentialVictim && RNG::generate(0, 4) == 1 && potentialVictim->getFaction() == FACTION_HOSTILE)
{
potentialVictim->lookAt(unit->getPosition());
while (potentialVictim->getStatus() == STATUS_TURNING)
{
recalculateFOV = true;
potentialVictim->turn();
}
}
// we reset the unit to false here - if it is seen by any unit in range below the unit becomes visible again
unit->setVisible(false);
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
int x = abs(unit->getPosition().x - (*i)->getPosition().x);
int y = abs(unit->getPosition().y - (*i)->getPosition().y);
int distance = int(floor(sqrt(float(x*x + y*y)) + 0.5));
if (distance < 19 && (*i)->getFaction() != _save->getSide() && !(*i)->isOut())
{
if (recalculateFOV)
{
calculateFOVUnits(*i);
}
for (std::vector<BattleUnit*>::iterator j = (*i)->getVisibleUnits()->begin(); j != (*i)->getVisibleUnits()->end(); ++j)
{
if ((*j) == unit && (*i)->getReactionScore() > highestReactionScore)
{
// I see you!
highestReactionScore = (*i)->getReactionScore();
action->actor = (*i);
}
}
}
}
if (action->actor && highestReactionScore > unit->getReactionScore())
{
action->type = BA_SNAPSHOT;
action->target = unit->getPosition();
// lets try and shoot
action->weapon = action->actor->getMainHandWeapon();
int tu = action->actor->getActionTUs(action->type, action->weapon);
if (action->weapon && action->weapon->getAmmoItem() && action->weapon->getAmmoItem()->getAmmoQuantity())
{
if (action->actor->spendTimeUnits(tu, _save->getDebugMode()))
{
// if the target is hostile, it will aggro
if (unit->getFaction() == FACTION_HOSTILE)
{
AggroBAIState *aggro = dynamic_cast<AggroBAIState*>(unit->getCurrentAIState());
if (aggro == 0)
{
aggro = new AggroBAIState(_save, unit);
unit->setAIState(aggro);
}
aggro->setAggroTarget(action->actor);
}
// if the shooter is hostile, he will aggro
if (action->actor->getFaction() == FACTION_HOSTILE)
{
AggroBAIState *aggro = dynamic_cast<AggroBAIState*>(action->actor->getCurrentAIState());
if (aggro == 0)
{
aggro = new AggroBAIState(_save, action->actor);
action->actor->setAIState(aggro);
}
aggro->setAggroTarget(unit);
}
return true;
}
}
}
return false;
}
/**
* HE, smoke and fire explodes in a circular pattern on 1 level only. HE however damages floor tiles of the above level. Not the units on it.
* HE destroys an object if its armor is lower than the explosive power, then it's HE blockage is applied for further propagation.
* See http://www.ufopaedia.org/index.php?title=Explosions for more info.
* @param center Center of the explosion in voxelspace.
* @param power Power of the explosion.
* @param type The damage type of the explosion.
* @param maxRadius The maximum radius othe explosion.
* @param unit The unit that caused the explosion.
*/
void TerrainModifier::explode(const Position ¢er, int power, ItemDamageType type, int maxRadius, BattleUnit *unit)
{
if (type == DT_AP || type == DT_PLASMA)
{
int part = voxelCheck(center, unit);
if (part >= 0 && part <= 3)
{
// power 25% to 75%
int rndPower = RNG::generate(power/4, (power*3)/4); //RNG::boxMuller(power, power/6)
_save->getTile(Position(center.x/16, center.y/16, center.z/24))->damage(part, rndPower);
}
else if (part == 4)
{
// power 0 - 200%
int rndPower = RNG::generate(0, power*2); // RNG::boxMuller(power, power/3)
_save->getTile(Position(center.x/16, center.y/16, center.z/24))->getUnit()->damage(Position(center.x%16, center.y%16, center.z%24), rndPower);
// conventional weapons can cause additional stun damage
if (type == DT_AP)
{
_save->getTile(Position(center.x/16, center.y/16, center.z/24))->getUnit()->stun(RNG::generate(0, rndPower/4));
}
}
}
else
{
double centerZ = (int)(center.z / 24) + 0.5;
double centerX = (int)(center.x / 16) + 0.5;
double centerY = (int)(center.y / 16) + 0.5;
int power_;
std::set<Tile*> tilesAffected;
std::pair<std::set<Tile*>::iterator,bool> ret;
if (type == DT_IN)
{
power /= 2;
}
// raytrace every 3 degrees makes sure we cover all tiles in a circle.
for (int te = 0; te <= 360; te += 3)
{
double cos_te = cos(te * M_PI / 180.0);
double sin_te = sin(te * M_PI / 180.0);
Tile *origin = _save->getTile(center);
double l = 0;
double vx, vy, vz;
int tileX, tileY, tileZ;
power_ = power + 1;
while (power_ > 0 && l <= maxRadius)
{
vx = centerX + l * cos_te;
vy = centerY + l * sin_te;
vz = centerZ;
tileZ = int(floor(vz));
tileX = int(floor(vx));
tileY = int(floor(vy));
Tile *dest = _save->getTile(Position(tileX, tileY, tileZ));
if (!dest) break; // out of map!
// horizontal blockage by walls
power_ -= horizontalBlockage(origin, dest, type);
if (power_ > 0)
{
if (type == DT_HE)
{
// explosives do 1/2 damage to terrain and 1/2 up to 3/2 random damage to units
dest->setExplosive(power_ / 2);
}
ret = tilesAffected.insert(dest); // check if we had this tile already
if (ret.second)
{
if (type == DT_HE)
{
// power 50 - 150%
if (dest->getUnit())
dest->getUnit()->damage(Position(0, 0, 0), (int)(RNG::generate(power_/2.0, power_*1.5)));
// destroy floors above
Tile *tileAbove = _save->getTile(Position(tileX, tileY, tileZ+1));
if ( tileAbove && tileAbove->getMapData(MapData::O_FLOOR) && power_ / 2 >= tileAbove->getMapData(MapData::O_FLOOR)->getArmor())
{
tileAbove->destroy(MapData::O_FLOOR);
}
// very slight chance (0-25%) to minor damage to units above or below explosion
if (tileAbove->getUnit())
tileAbove->getUnit()->damage(Position(0, 0, 0), (int)(RNG::generate(0.0, power_/4.0)));
Tile *tileBelow = _save->getTile(Position(tileX, tileY, tileZ-1));
if (tileBelow && !dest->getMapData(MapData::O_FLOOR) && tileBelow->getUnit())
tileBelow->getUnit()->damage(Position(0, 0, 0), (int)(RNG::generate(0.0, power_/4.0)));
}
if (type == DT_SMOKE)
{
// smoke from explosions always stay 6 to 14 turns - power of a smoke grenade is 60
if (dest->getSmoke() < 10)
{
dest->addSmoke(RNG::generate(power_/10, 14));
}
}
if (type == DT_IN)
{
if (dest->getFire() == 0)
{
dest->ignite();
}
if (dest->getUnit())
{
dest->getUnit()->damage(Position(0, 0, 0), RNG::generate(0, power_/3)); // immediate IN damage
dest->getUnit()->setFire(RNG::generate(1, 5)); // catch fire and burn for 1-5 rounds
}
}
}
}
power_ -= 10; // explosive damage decreases by 10
origin = dest;
l++;
}
}
// now detonate the tiles affected with HE
if (type == DT_HE)
{
for (std::set<Tile*>::iterator i = tilesAffected.begin(); i != tilesAffected.end(); ++i)
{
(*i)->detonate();
}
}
}
calculateFOV(center);
calculateTerrainLighting(); // fires could have been started
}
/**
* Chained explosions are explosions wich occur after an explosive map object is destroyed.
* May be due a direct hit, other explosion or fire.
* @return tile on which a explosion occured
*/
Tile *TerrainModifier::checkForTerrainExplosions()
{
for (int i = 0; i < _save->getWidth() * _save->getLength() * _save->getHeight(); ++i)
{
if (_save->getTiles()[i]->getExplosive())
{
return _save->getTiles()[i];
}
}
return 0;
}
/**
* The amount of power that is blocked going from one tile to another on a different level.
* Can cross more than one level. Only floor tiles are taken into account.
* @param startTile The tile where the power starts.
* @param endTile The adjecant tile where the power ends.
* @param type The type of power/damage.
* @return Amount of blockage of this power.
*/
int TerrainModifier::verticalBlockage(Tile *startTile, Tile *endTile, ItemDamageType type)
{
int block = 0;
// safety check
if (startTile == 0 || endTile == 0) return 0;
int direction = endTile->getPosition().z - startTile->getPosition().z;
int x = startTile->getPosition().x;
int y = startTile->getPosition().y;
if (direction < 0) // down
{
for (int z = startTile->getPosition().z; z > endTile->getPosition().z; z--)
{
block += blockage(_save->getTile(Position(x, y, z)), MapData::O_FLOOR, type);
}
}
else if (direction > 0) // up
{
for (int z = startTile->getPosition().z + 1; z <= endTile->getPosition().z; z++)
{
block += blockage(_save->getTile(Position(x, y, z)), MapData::O_FLOOR, type);
}
}
return block;
}
/**
* The amount of power that is blocked going from one tile to another on the same level.
* @param startTile The tile where the power starts.
* @param endTile The adjecant tile where the power ends.
* @param type The type of power/damage.
* @return amount of blockage
*/
int TerrainModifier::horizontalBlockage(Tile *startTile, Tile *endTile, ItemDamageType type)
{
static const Position oneTileNorth = Position(0, 1, 0);
static const Position oneTileEast = Position(1, 0, 0);
static const Position oneTileSouth = Position(0, -1, 0);
static const Position oneTileWest = Position(-1, 0, 0);
// safety check
if (startTile == 0 || endTile == 0) return 0;
int direction = vectorToDirection(endTile->getPosition() - startTile->getPosition());
if (direction == -1) return 0;
int block = 0;
switch(direction)
{
case 0: // north
block = blockage(startTile, MapData::O_NORTHWALL, type);
break;
case 1: // north east
block = (blockage(startTile,MapData::O_NORTHWALL, type) + blockage(endTile,MapData::O_WESTWALL, type))/2
+ (blockage(_save->getTile(startTile->getPosition() + oneTileEast),MapData::O_WESTWALL, type)
+ blockage(_save->getTile(startTile->getPosition() + oneTileEast),MapData::O_NORTHWALL, type))/2;
block += (blockage(_save->getTile(startTile->getPosition() + oneTileNorth),MapData::O_OBJECT, type) +
blockage(_save->getTile(startTile->getPosition() + oneTileEast),MapData::O_OBJECT, type))/2;
break;
case 2: // east
block = blockage(endTile,MapData::O_WESTWALL, type);
break;
case 3: // south east
block = (blockage(endTile,MapData::O_WESTWALL, type) + blockage(endTile,MapData::O_NORTHWALL, type))/2
+ (blockage(_save->getTile(startTile->getPosition() + oneTileEast),MapData::O_WESTWALL, type)
+ blockage(_save->getTile(startTile->getPosition() + oneTileSouth),MapData::O_NORTHWALL, type))/2;
block += (blockage(_save->getTile(startTile->getPosition() + oneTileSouth),MapData::O_OBJECT, type) +
blockage(_save->getTile(startTile->getPosition() + oneTileEast),MapData::O_OBJECT, type))/2;
break;
case 4: // south
block = blockage(endTile,MapData::O_NORTHWALL, type);
break;
case 5: // south west
block = (blockage(endTile,MapData::O_NORTHWALL, type) + blockage(startTile,MapData::O_WESTWALL, type))/2
+ (blockage(_save->getTile(startTile->getPosition() + oneTileSouth),MapData::O_WESTWALL, type)
+ blockage(_save->getTile(startTile->getPosition() + oneTileSouth),MapData::O_NORTHWALL, type))/2;
block += (blockage(_save->getTile(startTile->getPosition() + oneTileSouth),MapData::O_OBJECT, type) +
blockage(_save->getTile(startTile->getPosition() + oneTileWest),MapData::O_OBJECT, type))/2;
break;
case 6: // west
block = blockage(startTile,MapData::O_WESTWALL, type);
break;
case 7: // north west
block = (blockage(startTile,MapData::O_WESTWALL, type) + blockage(startTile,MapData::O_NORTHWALL, type))/2
+ (blockage(_save->getTile(startTile->getPosition() + oneTileNorth),MapData::O_WESTWALL, type)
+ blockage(_save->getTile(startTile->getPosition() + oneTileWest),MapData::O_NORTHWALL, type))/2;
block += (blockage(_save->getTile(startTile->getPosition() + oneTileNorth),MapData::O_OBJECT, type) +
blockage(_save->getTile(startTile->getPosition() + oneTileWest),MapData::O_OBJECT, type))/2;
break;
}
block += blockage(startTile, MapData::O_OBJECT, type);
return block;
}
/*
* The amount this certain wall or floor-part of the tile blocks.
* @param startTile The tile where the power starts.
* @param part The part of the tile the power needs to go through.
* @param type The type of power/damage.
* @return amount of blockage
*/
int TerrainModifier::blockage(Tile *tile, const int part, ItemDamageType type)
{
int blockage = 0;
if (tile == 0) return 0; // probably outside the map here
if (part == MapData::O_FLOOR && tile->getMapData(MapData::O_FLOOR))
{
// blockage modifiers of floors in ufo only counted for horizontal stuff, so this is kind of an experiment
if (type == DT_HE)
blockage += 15;
else
blockage += 255;
}
else
{
if (tile->getMapData(part))
blockage += tile->getMapData(part)->getBlock(type);
// open ufo doors are actually still closed behind the scenes
// so a special trick is needed to see if they are open, if they are, they obviously don't block anything
if (tile->isUfoDoorOpen(part))
blockage = 0;
}
return blockage;
}
/*
* Converts direction to a vector. Direction starts north = 0 and goes clockwise.
* @param vector pointer to a position (which acts as a vector)
* @return direction
*/
int TerrainModifier::vectorToDirection(const Position &vector)
{
int x[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int y[8] = {1, 1, 0, -1, -1, -1, 0, 1};
for (int i=0;i<9;++i)
{
if (x[i] == vector.x && y[i] == vector.y)
return i;
}
return -1;
}
/**
* Soldier opens a door (if any) by rightclick, or by walking through it. The unit has to face in the right direction.
* @param unit
* @return -1 there is no door, you can walk through.
* 0 normal door opened, make a squeeky sound and you can walk through.
* 1 ufo door is starting to open, make a woosh sound, don't walk through.
* 3 ufo door is still opening, don't walk through it yet. (have patience, futuristic technology...)
*/
int TerrainModifier::unitOpensDoor(BattleUnit *unit)
{
int door = -1;
Tile *tile = unit->getTile();
switch(unit->getDirection())
{
case 0: // north
door = tile->openDoor(MapData::O_NORTHWALL);
if (door == 1)
{
// check for adjacent door(s)
tile = _save->getTile(unit->getPosition() + Position(1, 0, 0));
if (tile) tile->openDoor(MapData::O_NORTHWALL);
tile = _save->getTile(unit->getPosition() + Position(-1, 0, 0));
if (tile) tile->openDoor(MapData::O_NORTHWALL);
}
break;
case 2: // east
tile = _save->getTile(tile->getPosition() + Position(1, 0, 0));
if (tile) door = tile->openDoor(MapData::O_WESTWALL);
if (door == 1)
{
// check for adjacent door(s)
tile = _save->getTile(unit->getPosition() + Position(1, -1, 0));
if (tile) tile->openDoor(MapData::O_WESTWALL);
tile = _save->getTile(unit->getPosition() + Position(1, 1, 0));
if (tile) tile->openDoor(MapData::O_WESTWALL);
}
break;
case 4: // south
tile = _save->getTile(tile->getPosition() + Position(0, -1, 0));
if (tile) door = tile->openDoor(MapData::O_NORTHWALL);
if (door == 1)
{
// check for adjacent door(s)
tile = _save->getTile(unit->getPosition() + Position(1, -1, 0));
if (tile) tile->openDoor(MapData::O_NORTHWALL);
tile = _save->getTile(unit->getPosition() + Position(-1, -1, 0));
if (tile) tile->openDoor(MapData::O_NORTHWALL);
}
break;
case 6: // west
door = tile->openDoor(MapData::O_WESTWALL);
if (door == 1)
{
// check for adjacent door(s)
tile = _save->getTile(unit->getPosition() + Position(0, -1, 0));
if (tile) tile->openDoor(MapData::O_WESTWALL);
tile = _save->getTile(unit->getPosition() + Position(0, 1, 0));
if (tile) tile->openDoor(MapData::O_WESTWALL);
}
break;
}
if (door == 0 || door == 1)
{
_save->getTerrainModifier()->calculateFOV(tile->getPosition());
}
return door;
}
/**
* calculateLine. Using bresenham algorithm in 3D.
* @param origin
* @param target
* @param storeTrajectory true will store the whole trajectory - otherwise it just stores the last position.
* @param trajector A vector of positions in which the trajectory is stored.
* @param excludeUnit Excludes this unit in the collision detection.
* @return the objectnumber(0-3) or unit(4) or out of map (5) or -1(hit nothing)
*/
int TerrainModifier::calculateLine(const Position& origin, const Position& target, bool storeTrajectory, std::vector<Position> *trajectory, BattleUnit *excludeUnit)
{
int x, x0, x1, delta_x, step_x;
int y, y0, y1, delta_y, step_y;
int z, z0, z1, delta_z, step_z;
int swap_xy, swap_xz;
int drift_xy, drift_xz;
int cx, cy, cz;
//start and end points
x0 = origin.x; x1 = target.x;
y0 = origin.y; y1 = target.y;