forked from Warzone2100/warzone2100
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisibility.cpp
1158 lines (1024 loc) · 35.2 KB
/
visibility.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
/*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2019 Warzone 2100 Project
Warzone 2100 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 2 of the License, or
(at your option) any later version.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file visibility.c
* Handles object visibility.
* Pumpkin Studios, Eidos Interactive 1996.
*/
#include "lib/framework/frame.h"
#include "lib/framework/fixedpoint.h"
#include "lib/gamelib/gtime.h"
#include "lib/sound/audio.h"
#include "lib/sound/audio_id.h"
#include "lib/ivis_opengl/ivisdef.h"
#include "visibility.h"
#include "objects.h"
#include "map.h"
#include "loop.h"
#include "raycast.h"
#include "geometry.h"
#include "hci.h"
#include "mapgrid.h"
#include "research.h"
#include "scriptextern.h"
#include "structure.h"
#include "projectile.h"
#include "display.h"
#include "multiplay.h"
#include "qtscript.h"
#include "wavecast.h"
// accuracy for the height gradient
#define GRAD_MUL 10000
// rate to change visibility level
static const int VIS_LEVEL_INC = 255 * 2;
static const int VIS_LEVEL_DEC = 50;
// integer amount to change visibility this turn
static SDWORD visLevelInc, visLevelDec;
class SPOTTER
{
public:
SPOTTER(int x, int y, int plr, int radius, int type, uint32_t expiry = 0)
: pos(x, y, 0), player(plr), sensorRadius(radius), sensorType(type), expiryTime(expiry), numWatchedTiles(0), watchedTiles(nullptr)
{
id = generateSynchronisedObjectId();
}
~SPOTTER();
Position pos;
int player;
int sensorRadius;
int sensorType; // 0 - vision, 1 - radar
uint32_t expiryTime; // when to self-destruct, zero if never
int numWatchedTiles;
TILEPOS *watchedTiles;
uint32_t id;
};
static std::vector<SPOTTER *> apsInvisibleViewers;
// horrible hack because this code is full of them and I ain't rewriting it all - Per
#define MAX_SEEN_TILES (29*29 * 355/113) // Increased hack to support 28 tile sensor radius. - Cyp
#define MIN_VIS_HEIGHT 80
struct VisibleObjectHelp_t
{
bool rayStart; // Whether this is the first point on the ray
const bool wallsBlock; // Whether walls block line of sight
const int startHeight; // The height at the view point
const Vector2i final; // The final tile of the ray cast
int lastHeight, lastDist; // The last height and distance
int currGrad; // The current obscuring gradient
int numWalls; // Whether the LOS has hit a wall
Vector2i wall; // The position of a wall if it is on the LOS
};
static int *gNumWalls = nullptr;
static Vector2i *gWall = nullptr;
// forward declarations
static void setSeenBy(BASE_OBJECT *psObj, unsigned viewer, int val);
// initialise the visibility stuff
bool visInitialise()
{
visLevelInc = 1;
visLevelDec = 0;
return true;
}
// update the visibility change levels
void visUpdateLevel()
{
visLevelInc = gameTimeAdjustedAverage(VIS_LEVEL_INC);
visLevelDec = gameTimeAdjustedAverage(VIS_LEVEL_DEC);
}
static inline void updateTileVis(MAPTILE *psTile)
{
for (int i = 0; i < MAX_PLAYERS; i++)
{
/// The definition of whether a player can see something on a given tile or not
if (psTile->watchers[i] > 0 || (psTile->sensors[i] > 0 && !(psTile->jammerBits & ~alliancebits[i])))
{
psTile->sensorBits |= (1 << i); // mark it as being seen
}
else
{
psTile->sensorBits &= ~(1 << i); // mark as hidden
}
}
}
uint32_t addSpotter(int x, int y, int player, int radius, bool radar, uint32_t expiry)
{
SPOTTER *psSpot = new SPOTTER(x, y, player, radius, (int)radar, expiry);
size_t size;
const WavecastTile *tiles = getWavecastTable(radius, &size);
psSpot->watchedTiles = (TILEPOS *)malloc(size * sizeof(*psSpot->watchedTiles));
for (unsigned i = 0; i < size; ++i)
{
const int mapX = x + tiles[i].dx;
const int mapY = y + tiles[i].dy;
if (mapX < 0 || mapX >= mapWidth || mapY < 0 || mapY >= mapHeight)
{
continue;
}
MAPTILE *psTile = mapTile(mapX, mapY);
psTile->tileExploredBits |= alliancebits[player];
uint8_t *visionType = (!radar) ? psTile->watchers : psTile->sensors;
if (visionType[player] < UBYTE_MAX)
{
TILEPOS tilePos = {uint8_t(mapX), uint8_t(mapY), uint8_t(radar)};
visionType[player]++; // we observe this tile
updateTileVis(psTile);
psSpot->watchedTiles[psSpot->numWatchedTiles++] = tilePos; // record having seen it
}
}
apsInvisibleViewers.push_back(psSpot);
return psSpot->id;
}
bool removeSpotter(uint32_t id)
{
for (unsigned i = 0; i < apsInvisibleViewers.size(); i++)
{
SPOTTER *psSpot = apsInvisibleViewers.at(i);
if (psSpot->id == id)
{
delete psSpot;
apsInvisibleViewers.erase(apsInvisibleViewers.begin() + i);
return true;
}
}
return false;
}
void removeSpotters()
{
while (!apsInvisibleViewers.empty())
{
SPOTTER *psSpot = apsInvisibleViewers.back();
delete psSpot;
apsInvisibleViewers.pop_back();
}
}
static void updateSpotters()
{
static GridList gridList; // static to avoid allocations.
for (unsigned i = 0; i < apsInvisibleViewers.size(); i++)
{
SPOTTER *psSpot = apsInvisibleViewers.at(i);
if (psSpot->expiryTime != 0 && psSpot->expiryTime < gameTime)
{
delete psSpot;
apsInvisibleViewers.erase(apsInvisibleViewers.begin() + i);
continue;
}
// else, ie if not expired, show objects around it
gridList = gridStartIterateUnseen(world_coord(psSpot->pos.x), world_coord(psSpot->pos.y), psSpot->sensorRadius, psSpot->player);
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
BASE_OBJECT *psObj = *gi;
// Tell system that this side can see this object
setSeenBy(psObj, psSpot->player, UBYTE_MAX);
}
}
}
SPOTTER::~SPOTTER()
{
for (int i = 0; i < numWatchedTiles; i++)
{
const TILEPOS tilePos = watchedTiles[i];
MAPTILE *psTile = mapTile(tilePos.x, tilePos.y);
uint8_t *visionType = (tilePos.type == 0) ? psTile->watchers : psTile->sensors;
ASSERT(visionType[player] > 0, "Not watching watched tile (%d, %d)", (int)tilePos.x, (int)tilePos.y);
visionType[player]--;
updateTileVis(psTile);
}
free(watchedTiles);
}
/* Record all tiles that some object confers visibility to. Only record each tile
* once. Note that there is both a limit to how many objects can watch any given
* tile, and a limit to how many tiles each object can watch. Strange but non fatal
* things will happen if these limits are exceeded. This function uses icky globals. */
static inline void visMarkTile(const BASE_OBJECT *psObj, int mapX, int mapY, MAPTILE *psTile, TILEPOS *recordTilePos, int *lastRecordTilePos)
{
const int rayPlayer = psObj->player;
const int xdiff = map_coord(psObj->pos.x) - mapX;
const int ydiff = map_coord(psObj->pos.y) - mapY;
const int distSq = xdiff * xdiff + ydiff * ydiff;
const bool inRange = (distSq < 16);
uint8_t *visionType = inRange ? psTile->watchers : psTile->sensors;
if (visionType[rayPlayer] < UBYTE_MAX && *lastRecordTilePos < MAX_SEEN_TILES)
{
TILEPOS tilePos = {uint8_t(mapX), uint8_t(mapY), uint8_t(inRange)};
visionType[rayPlayer]++; // we observe this tile
if (psObj->flags.test(OBJECT_FLAG_JAMMED_TILES)) // we are a jammer object
{
psTile->jammers[rayPlayer]++;
psTile->jammerBits |= (1 << rayPlayer); // mark it as being jammed
}
updateTileVis(psTile);
recordTilePos[*lastRecordTilePos] = tilePos; // record having seen it
++*lastRecordTilePos;
}
}
/* The terrain revealing ray callback */
static void doWaveTerrain(const BASE_OBJECT *psObj, TILEPOS *recordTilePos, int *lastRecordTilePos)
{
const int sx = psObj->pos.x;
const int sy = psObj->pos.y;
const int sz = psObj->pos.z + MAX(MIN_VIS_HEIGHT, psObj->sDisplay.imd->max.y);
const unsigned radius = objSensorRange(psObj);
const int rayPlayer = psObj->player;
size_t size;
const WavecastTile *tiles = getWavecastTable(radius, &size);
#define MAX_WAVECAST_LIST_SIZE 1360 // Trivial upper bound to what a fully upgraded WSS can use (its number of angles). Should probably be some factor times the maximum possible radius. Is probably a lot more than needed. Tested to need at least 180.
int heights[2][MAX_WAVECAST_LIST_SIZE];
size_t angles[2][MAX_WAVECAST_LIST_SIZE + 1];
int readListSize = 0, readListPos = 0, writeListPos = 0; // readListSize, readListPos dummy initialisations.
int readList = 0; // Reading from this list, writing to the other. Could also initialise to rand()%2.
int lastHeight = 0; // lastHeight dummy initialisation.
size_t lastAngle = std::numeric_limits<size_t>::max();
// Start with full vision of all angles. (If someday wanting to make droids that can only look in one direction, change here, after getting the original angle values saved in the wavecast table.)
heights[!readList][writeListPos] = -0x7FFFFFFF - 1; // Smallest integer.
angles[!readList][writeListPos] = 0; // Smallest angle.
++writeListPos;
for (size_t i = 0; i < size; ++i)
{
const int mapX = map_coord(sx) + tiles[i].dx;
const int mapY = map_coord(sy) + tiles[i].dy;
if (mapX < 0 || mapX >= mapWidth || mapY < 0 || mapY >= mapHeight)
{
continue;
}
MAPTILE *psTile = mapTile(mapX, mapY);
int tileHeight = std::max(psTile->height, psTile->waterLevel); // If we can see the water surface, then let us see water-covered tiles too.
int perspectiveHeight = (tileHeight - sz) * tiles[i].invRadius;
int perspectiveHeightLeeway = (tileHeight - sz + MIN_VIS_HEIGHT) * tiles[i].invRadius;
if (tiles[i].angBegin < lastAngle)
{
// Gone around the circle. (Or just started scan.)
angles[!readList][writeListPos] = lastAngle;
// Flip the lists.
readList = !readList;
readListPos = 0;
readListSize = writeListPos;
writeListPos = 0;
lastHeight = 1; // Impossible value since tiles[i].invRadius > 1 for all i, so triggers writing first entry in list.
}
lastAngle = tiles[i].angEnd;
while (angles[readList][readListPos + 1] <= tiles[i].angBegin && readListPos < readListSize)
{
++readListPos; // Skip, not relevant.
}
bool seen = false;
while (angles[readList][readListPos] < tiles[i].angEnd && readListPos < readListSize)
{
int oldHeight = heights[readList][readListPos];
int newHeight = MAX(oldHeight, perspectiveHeight);
seen = seen || perspectiveHeightLeeway >= oldHeight; // consider point slightly above ground in case there is something on the tile
if (newHeight != lastHeight)
{
heights[!readList][writeListPos] = newHeight;
angles[!readList][writeListPos] = MAX(angles[readList][readListPos], tiles[i].angBegin);
lastHeight = newHeight;
++writeListPos;
ASSERT_OR_RETURN(, writeListPos <= MAX_WAVECAST_LIST_SIZE, "Visibility too complicated! Need to increase MAX_WAVECAST_LIST_SIZE.");
}
++readListPos;
}
--readListPos;
if (seen)
{
// Can see this tile.
psTile->tileExploredBits |= alliancebits[rayPlayer]; // Share exploration with allies too
visMarkTile(psObj, mapX, mapY, psTile, recordTilePos, lastRecordTilePos); // Mark this tile as seen by our sensor
}
}
}
/* The los ray callback */
static bool rayLOSCallback(Vector2i pos, int32_t dist, void *data)
{
VisibleObjectHelp_t *help = (VisibleObjectHelp_t *)data;
ASSERT(pos.x >= 0 && pos.x < world_coord(mapWidth) && pos.y >= 0 && pos.y < world_coord(mapHeight), "rayLOSCallback: coords off map");
if (help->rayStart)
{
help->rayStart = false;
}
else
{
// Calculate the current LOS gradient
int newGrad = (help->lastHeight - help->startHeight) * GRAD_MUL / MAX(1, help->lastDist);
if (newGrad >= help->currGrad)
{
help->currGrad = newGrad;
}
}
help->lastDist = dist;
help->lastHeight = map_Height(pos.x, pos.y);
if (help->wallsBlock)
{
// Store the height at this tile for next time round
Vector2i tile = map_coord(pos.xy());
if (tile != help->final)
{
MAPTILE *psTile = mapTile(tile);
if (TileHasWall(psTile) && !TileHasSmallStructure(psTile))
{
help->lastHeight = 2 * UBYTE_MAX * ELEVATION_SCALE;
help->wall = pos.xy();
help->numWalls++;
}
}
}
return true;
}
/* Remove tile visibility from object */
void visRemoveVisibility(BASE_OBJECT *psObj)
{
if (psObj->watchedTiles && mapWidth && mapHeight)
{
for (int i = 0; i < psObj->numWatchedTiles; i++)
{
const TILEPOS pos = psObj->watchedTiles[i];
// FIXME: the mapTile might have been swapped out, see swapMissionPointers()
MAPTILE *psTile = mapTile(pos.x, pos.y);
ASSERT(pos.type < 2, "Invalid visibility type %d", (int)pos.type);
uint8_t *visionType = (pos.type == 0) ? psTile->sensors : psTile->watchers;
if (visionType[psObj->player] == 0 && game.type == CAMPAIGN) // hack
{
continue;
}
ASSERT(visionType[psObj->player] > 0, "No %s on watched tile (%d, %d)", pos.type ? "radar" : "vision", (int)pos.x, (int)pos.y);
visionType[psObj->player]--;
if (psObj->flags.test(OBJECT_FLAG_JAMMED_TILES)) // we are a jammer object — we cannot check objJammerPower(psObj) > 0 directly here, we may be in the BASE_OBJECT destructor).
{
// No jammers in campaign, no need for special hack
ASSERT(psTile->jammers[psObj->player] > 0, "Not jamming watched tile (%d, %d)", (int)pos.x, (int)pos.y);
psTile->jammers[psObj->player]--;
if (psTile->jammers[psObj->player] == 0)
{
psTile->jammerBits &= ~(1 << psObj->player);
}
}
updateTileVis(psTile);
}
}
free(psObj->watchedTiles);
psObj->watchedTiles = nullptr;
psObj->numWatchedTiles = 0;
psObj->flags.set(OBJECT_FLAG_JAMMED_TILES, false);
}
void visRemoveVisibilityOffWorld(BASE_OBJECT *psObj)
{
free(psObj->watchedTiles);
psObj->watchedTiles = nullptr;
psObj->numWatchedTiles = 0;
}
/* Check which tiles can be seen by an object */
void visTilesUpdate(BASE_OBJECT *psObj)
{
TILEPOS recordTilePos[MAX_SEEN_TILES];
int lastRecordTilePos = 0;
ASSERT(psObj->type != OBJ_FEATURE, "visTilesUpdate: visibility updates are not for features!");
// Remove previous map visibility provided by object
visRemoveVisibility(psObj);
if (psObj->type == OBJ_STRUCTURE)
{
STRUCTURE *psStruct = (STRUCTURE *)psObj;
if (psStruct->status != SS_BUILT ||
psStruct->pStructureType->type == REF_WALL || psStruct->pStructureType->type == REF_WALLCORNER || psStruct->pStructureType->type == REF_GATE)
{
// unbuilt structures and walls do not confer visibility.
return;
}
}
// Do the whole circle in ∞ steps. No more pretty moiré patterns.
psObj->flags.set(OBJECT_FLAG_JAMMED_TILES, objJammerPower(psObj) > 0);
doWaveTerrain(psObj, recordTilePos, &lastRecordTilePos);
// Record new map visibility provided by object
if (lastRecordTilePos > 0)
{
psObj->watchedTiles = (TILEPOS *)malloc(lastRecordTilePos * sizeof(*psObj->watchedTiles));
psObj->numWatchedTiles = lastRecordTilePos;
memcpy(psObj->watchedTiles, recordTilePos, lastRecordTilePos * sizeof(*psObj->watchedTiles));
}
}
/*reveals all the terrain in the map*/
void revealAll(UBYTE player)
{
UWORD i, j;
MAPTILE *psTile;
//reveal all tiles
for (i = 0; i < mapWidth; i++)
{
for (j = 0; j < mapHeight; j++)
{
psTile = mapTile(i, j);
psTile->tileExploredBits |= alliancebits[player];
}
}
//the objects gets revealed in processVisibility()
}
/* Check whether psViewer can see psTarget.
* psViewer should be an object that has some form of sensor,
* currently droids and structures.
* psTarget can be any type of BASE_OBJECT (e.g. a tree).
* struckBlock controls whether structures block LOS
*/
int visibleObject(const BASE_OBJECT *psViewer, const BASE_OBJECT *psTarget, bool wallsBlock)
{
ASSERT_OR_RETURN(0, psViewer != nullptr, "Invalid viewer pointer!");
ASSERT_OR_RETURN(0, psTarget != nullptr, "Invalid viewed pointer!");
int range = objSensorRange(psViewer);
if (!worldOnMap(psViewer->pos.x, psViewer->pos.y) || !worldOnMap(psTarget->pos.x, psTarget->pos.y))
{
//Most likely a VTOL or transporter
debug(LOG_WARNING, "Trying to view something off map!");
return 0;
}
/* Get the sensor range */
switch (psViewer->type)
{
case OBJ_DROID:
{
const DROID *psDroid = (const DROID *)psViewer;
if (psDroid->order.psObj == psTarget && cbSensorDroid(psDroid))
{
// if it is targetted by a counter battery sensor, it is seen
return UBYTE_MAX;
}
break;
}
case OBJ_STRUCTURE:
{
const STRUCTURE *psStruct = (const STRUCTURE *)psViewer;
// a structure that is being built cannot see anything
if (psStruct->status != SS_BUILT)
{
return 0;
}
if (psStruct->pStructureType->type == REF_WALL
|| psStruct->pStructureType->type == REF_GATE
|| psStruct->pStructureType->type == REF_WALLCORNER)
{
return 0;
}
if (psTarget->type == OBJ_DROID && isVtolDroid((const DROID *)psTarget)
&& asWeaponStats[psStruct->asWeaps[0].nStat].surfaceToAir == SHOOT_IN_AIR)
{
range = 3 * range / 2; // increase vision range of AA vs VTOL
}
if (psStruct->psTarget[0] == psTarget && (structCBSensor(psStruct) || structVTOLCBSensor(psStruct)))
{
// if a unit is targetted by a counter battery sensor
// it is automatically seen
return UBYTE_MAX;
}
break;
}
default:
ASSERT(false, "Visibility checking is only implemented for units and structures");
return 0;
break;
}
/* First see if the target is in sensor range */
const int dist = iHypot((psTarget->pos - psViewer->pos).xy());
if (dist == 0)
{
return UBYTE_MAX; // Should never be on top of each other, but ...
}
const MAPTILE *psTile = mapTile(map_coord(psTarget->pos.x), map_coord(psTarget->pos.y));
const bool jammed = psTile->jammerBits & ~alliancebits[psViewer->player];
// Special rule for VTOLs, as they are not affected by ECM
if (((psTarget->type == OBJ_DROID && isVtolDroid((const DROID *)psTarget))
|| (psViewer->type == OBJ_DROID && isVtolDroid((const DROID *)psViewer)))
&& dist < range)
{
return UBYTE_MAX;
}
// initialise the callback variables
VisibleObjectHelp_t help = {
true,
wallsBlock,
psViewer->pos.z + map_Height(psViewer->pos.x, psViewer->pos.y),
map_coord(psTarget->pos.xy()),
0,
0,
-UBYTE_MAX * GRAD_MUL * ELEVATION_SCALE,
0,
Vector2i(0, 0)
};
// Cast a ray from the viewer to the target
rayCast(psViewer->pos.xy(), psTarget->pos.xy(), rayLOSCallback, &help);
if (gWall != nullptr && gNumWalls != nullptr) // Out globals are set
{
*gWall = help.wall;
*gNumWalls = help.numWalls;
}
// See if the target can be seen
int top = psTarget->pos.z + map_Height(psViewer->pos.x, psViewer->pos.y) - help.startHeight;
int targetGrad = top * GRAD_MUL / MAX(1, help.lastDist);
// Show objects hidden by ECM jamming with radar blips
if (psTile->watchers[psViewer->player] == 0 && psTile->sensors[psViewer->player] > 0 && jammed)
{
return UBYTE_MAX / 2;
}
// Show objects that are seen directly or with unjammed sensors
else if ((psTile->watchers[psViewer->player] > 0 && targetGrad >= help.currGrad) || (psTile->sensors[psViewer->player] > 0 && !jammed))
{
return UBYTE_MAX;
}
// Show detected sensors as radar blips
else if (objRadarDetector(psViewer) && objActiveRadar(psTarget) && dist < range * 10)
{
return UBYTE_MAX / 2;
}
// else not seen
return 0;
}
// Find the wall that is blocking LOS to a target (if any)
STRUCTURE *visGetBlockingWall(const BASE_OBJECT *psViewer, const BASE_OBJECT *psTarget)
{
int numWalls = 0;
Vector2i wall;
// HACK Using globals to not clutter visibleObject() interface too much
gNumWalls = &numWalls;
gWall = &wall;
visibleObject(psViewer, psTarget, true);
gNumWalls = nullptr;
gWall = nullptr;
// see if there was a wall in the way
if (numWalls > 0)
{
Vector2i tile = map_coord(wall);
unsigned int player;
for (player = 0; player < MAX_PLAYERS; player++)
{
STRUCTURE *psWall;
for (psWall = apsStructLists[player]; psWall; psWall = psWall->psNext)
{
if (map_coord(psWall->pos) == tile)
{
return psWall;
}
}
}
}
return nullptr;
}
bool hasSharedVision(unsigned viewer, unsigned ally)
{
ASSERT_OR_RETURN(false, viewer < MAX_PLAYERS && ally < MAX_PLAYERS, "Bad viewer %u or ally %u.", viewer, ally);
return viewer == ally || (bMultiPlayer && alliancesSharedVision(game.alliance) && aiCheckAlliances(viewer, ally));
}
static void setSeenBy(BASE_OBJECT *psObj, unsigned viewer, int val /*= UBYTE_MAX*/)
{
//forward out vision to our allies
for (int ally = 0; ally < MAX_PLAYERS; ++ally)
{
if (hasSharedVision(viewer, ally))
{
psObj->seenThisTick[ally] = MAX(psObj->seenThisTick[ally], val);
}
}
}
static void setSeenByInstantly(BASE_OBJECT *psObj, unsigned viewer, int val /*= UBYTE_MAX*/)
{
//forward out vision to our allies
for (int ally = 0; ally < MAX_PLAYERS; ++ally)
{
if (hasSharedVision(viewer, ally))
{
psObj->seenThisTick[ally] = MAX(psObj->seenThisTick[ally], val);
psObj->visible[ally] = MAX(psObj->visible[ally], val);
}
}
}
// Calculate which objects we should know about based on alliances and satellite view.
static void processVisibilitySelf(BASE_OBJECT *psObj)
{
if (psObj->type != OBJ_FEATURE && objSensorRange(psObj) > 0)
{
// one can trivially see oneself
setSeenBy(psObj, psObj->player, UBYTE_MAX);
}
// if a player has a SAT_UPLINK structure, or has godMode enabled,
// they can see everything!
for (unsigned viewer = 0; viewer < MAX_PLAYERS; viewer++)
{
if (getSatUplinkExists(viewer) || (viewer == selectedPlayer && godMode))
{
setSeenBy(psObj, viewer, UBYTE_MAX);
}
}
psObj->flags.set(OBJECT_FLAG_TARGETED, false); // Remove any targetting locks from last update.
// If we're a CB sensor, make our target visible instantly. Although this is actually checking visibility of our target, we do it here anyway.
STRUCTURE *psStruct = castStructure(psObj);
// you can always see anything that a CB sensor is targetting
// Anyone commenting this out again will get a knee capping from John.
// You have been warned!!
if (psStruct != nullptr && (structCBSensor(psStruct) || structVTOLCBSensor(psStruct)) && psStruct->psTarget[0] != nullptr)
{
setSeenByInstantly(psStruct->psTarget[0], psObj->player, UBYTE_MAX);
}
DROID *psDroid = castDroid(psObj);
if (psDroid != nullptr && psDroid->action == DACTION_OBSERVE && cbSensorDroid(psDroid))
{
// Anyone commenting this out will get a knee capping from John.
// You have been warned!!
setSeenByInstantly(psDroid->psActionTarget[0], psObj->player, UBYTE_MAX);
}
}
// Calculate which objects we can see. Better to call after processVisibilitySelf, since that check is cheaper.
static void processVisibilityVision(BASE_OBJECT *psViewer)
{
if (psViewer->type == OBJ_FEATURE)
{
return;
}
// get all the objects from the grid the droid is in
// Will give inconsistent results if hasSharedVision is not an equivalence relation.
static GridList gridList; // static to avoid allocations.
gridList = gridStartIterateUnseen(psViewer->pos.x, psViewer->pos.y, objSensorRange(psViewer), psViewer->player);
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
BASE_OBJECT *psObj = *gi;
int val = visibleObject(psViewer, psObj, false);
// If we've got ranged line of sight...
if (val > 0)
{
// Tell system that this side can see this object
setSeenBy(psObj, psViewer->player, val);
// Check if scripting system wants to trigger an event for this
triggerEventSeen(psViewer, psObj);
}
}
}
/* Find out what can see this object */
// Fade in/out of view. Must be called after calculation of which objects are seen.
static void processVisibilityLevel(BASE_OBJECT *psObj)
{
// update the visibility levels
for (unsigned player = 0; player < MAX_PLAYERS; player++)
{
bool justBecameVisible = false;
int visLevel = psObj->seenThisTick[player];
if (player == psObj->player)
{
// owner can always see it fully
psObj->visible[player] = UBYTE_MAX;
continue;
}
// Droids can vanish from view, other objects will stay
if (psObj->type != OBJ_DROID)
{
visLevel = MAX(visLevel, psObj->visible[player]);
}
if (visLevel > psObj->visible[player])
{
justBecameVisible = psObj->visible[player] <= 0;
psObj->visible[player] = MIN(psObj->visible[player] + visLevelInc, visLevel);
}
else if (visLevel < psObj->visible[player])
{
psObj->visible[player] = MAX(psObj->visible[player] - visLevelDec, visLevel);
}
if (justBecameVisible)
{
/* Make sure all tiles under a feature/structure become visible when you see it */
if (psObj->type == OBJ_STRUCTURE || psObj->type == OBJ_FEATURE)
{
setUnderTilesVis(psObj, player);
}
// if a feature has just become visible set the message blips
if (psObj->type == OBJ_FEATURE)
{
MESSAGE *psMessage;
INGAME_AUDIO type = NO_SOUND;
/* If this is an oil resource we want to add a proximity message for
* the selected Player - if there isn't an Resource Extractor on it. */
if (((FEATURE *)psObj)->psStats->subType == FEAT_OIL_RESOURCE && !TileHasStructure(mapTile(map_coord(psObj->pos.x), map_coord(psObj->pos.y))))
{
type = ID_SOUND_RESOURCE_HERE;
}
else if (((FEATURE *)psObj)->psStats->subType == FEAT_GEN_ARTE)
{
type = ID_SOUND_ARTEFACT_DISC;
}
if (type != NO_SOUND)
{
psMessage = addMessage(MSG_PROXIMITY, true, player);
if (psMessage)
{
psMessage->psObj = psObj;
debug(LOG_MSG, "Added message for oil well or artefact, pViewData=%p", static_cast<void *>(psMessage->pViewData));
}
if (!bInTutorial && player == selectedPlayer)
{
// play message to indicate been seen
audio_QueueTrackPos(type, psObj->pos.x, psObj->pos.y, psObj->pos.z);
}
}
}
}
}
}
void processVisibility()
{
updateSpotters();
for (int player = 0; player < MAX_PLAYERS; ++player)
{
BASE_OBJECT *lists[] = {apsDroidLists[player], apsStructLists[player], apsFeatureLists[player]};
unsigned list;
for (list = 0; list < sizeof(lists) / sizeof(*lists); ++list)
{
for (BASE_OBJECT *psObj = lists[list]; psObj != nullptr; psObj = psObj->psNext)
{
processVisibilitySelf(psObj);
}
}
}
for (int player = 0; player < MAX_PLAYERS; ++player)
{
BASE_OBJECT *lists[] = {apsDroidLists[player], apsStructLists[player]};
unsigned list;
for (list = 0; list < sizeof(lists) / sizeof(*lists); ++list)
{
for (BASE_OBJECT *psObj = lists[list]; psObj != nullptr; psObj = psObj->psNext)
{
processVisibilityVision(psObj);
}
}
}
for (BASE_OBJECT *psObj = apsSensorList[0]; psObj != nullptr; psObj = psObj->psNextFunc)
{
if (objRadarDetector(psObj))
{
for (BASE_OBJECT *psTarget = apsSensorList[0]; psTarget != nullptr; psTarget = psTarget->psNextFunc)
{
if (psObj != psTarget && psTarget->visible[psObj->player] < UBYTE_MAX / 2
&& objActiveRadar(psTarget)
&& iHypot((psTarget->pos - psObj->pos).xy()) < objSensorRange(psObj) * 10)
{
psTarget->visible[psObj->player] = UBYTE_MAX / 2;
}
}
}
}
for (int player = 0; player < MAX_PLAYERS; ++player)
{
BASE_OBJECT *lists[] = {apsDroidLists[player], apsStructLists[player], apsFeatureLists[player]};
unsigned list;
for (list = 0; list < sizeof(lists) / sizeof(*lists); ++list)
{
for (BASE_OBJECT *psObj = lists[list]; psObj != nullptr; psObj = psObj->psNext)
{
processVisibilityLevel(psObj);
}
}
}
}
void setUnderTilesVis(BASE_OBJECT *psObj, UDWORD player)
{
UDWORD i, j;
UDWORD mapX, mapY, width, breadth;
FEATURE *psFeature;
STRUCTURE *psStructure;
FEATURE_STATS const *psStats;
MAPTILE *psTile;
if (psObj->type == OBJ_FEATURE)
{
psFeature = (FEATURE *)psObj;
psStats = psFeature->psStats;
width = psStats->baseWidth;
breadth = psStats->baseBreadth;
mapX = map_coord(psFeature->pos.x - width * TILE_UNITS / 2);
mapY = map_coord(psFeature->pos.y - breadth * TILE_UNITS / 2);
}
else
{
/* Must be a structure */
psStructure = (STRUCTURE *)psObj;
width = psStructure->pStructureType->baseWidth;
breadth = psStructure->pStructureType->baseBreadth;
mapX = map_coord(psStructure->pos.x - width * TILE_UNITS / 2);
mapY = map_coord(psStructure->pos.y - breadth * TILE_UNITS / 2);
}
for (i = 0; i < width + 1; i++) // + 1 because visibility is for top left of tile.
{
for (j = 0; j < breadth + 1; j++) // + 1 because visibility is for top left of tile.
{
psTile = mapTile(mapX + i, mapY + j);
if (psTile)
{
psTile->tileExploredBits |= alliancebits[player];
}
}
}
}
//forward declaration
static int checkFireLine(const SIMPLE_OBJECT *psViewer, const BASE_OBJECT *psTarget, int weapon_slot, bool wallsBlock, bool direct);
/**
* Check whether psViewer can fire directly at psTarget.
* psTarget can be any type of BASE_OBJECT (e.g. a tree).
*/
bool lineOfFire(const SIMPLE_OBJECT *psViewer, const BASE_OBJECT *psTarget, int weapon_slot, bool wallsBlock)
{
WEAPON_STATS *psStats = nullptr;
ASSERT_OR_RETURN(false, psViewer != nullptr, "Invalid shooter pointer!");
ASSERT_OR_RETURN(false, psTarget != nullptr, "Invalid target pointer!");
ASSERT_OR_RETURN(false, psViewer->type == OBJ_DROID || psViewer->type == OBJ_STRUCTURE, "Bad viewer type");
if (psViewer->type == OBJ_DROID)
{
psStats = asWeaponStats + ((const DROID *)psViewer)->asWeaps[weapon_slot].nStat;
}
else if (psViewer->type == OBJ_STRUCTURE)
{
psStats = asWeaponStats + ((const STRUCTURE *)psViewer)->asWeaps[weapon_slot].nStat;
}
// 2d distance
int distance = iHypot((psTarget->pos - psViewer->pos).xy());
int range = proj_GetLongRange(psStats, psViewer->player);
if (proj_Direct(psStats))
{
/** direct shots could collide with ground **/
return range >= distance && LINE_OF_FIRE_MINIMUM <= checkFireLine(psViewer, psTarget, weapon_slot, wallsBlock, true);
}
else
{
/**
* indirect shots always have a line of fire, IF the forced
* minimum angle doesn't move it out of range
**/
int min_angle = checkFireLine(psViewer, psTarget, weapon_slot, wallsBlock, false);
// NOTE This code seems similar to the code in combFire in combat.cpp.
if (min_angle > DEG(PROJ_MAX_PITCH))
{
if (iSin(2 * min_angle) < iSin(2 * DEG(PROJ_MAX_PITCH)))
{
range = (range * iSin(2 * min_angle)) / iSin(2 * DEG(PROJ_MAX_PITCH));
}
}
return range >= distance;
}
}
/* Check how much of psTarget is hitable from psViewer's gun position */
int areaOfFire(const SIMPLE_OBJECT *psViewer, const BASE_OBJECT *psTarget, int weapon_slot, bool wallsBlock)
{
if (psViewer == nullptr)
{
return 0; // Lassat special case, avoid assertion.
}
return checkFireLine(psViewer, psTarget, weapon_slot, wallsBlock, true);
}
/* Check the minimum angle to hitpsTarget from psViewer via indirect shots */
int arcOfFire(const SIMPLE_OBJECT *psViewer, const BASE_OBJECT *psTarget, int weapon_slot, bool wallsBlock)
{
return checkFireLine(psViewer, psTarget, weapon_slot, wallsBlock, false);
}
/* helper function for checkFireLine */
static inline void angle_check(int64_t *angletan, int positionSq, int height, int distanceSq, int targetHeight, bool direct)