-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathRadarCalculation.cpp
More file actions
2183 lines (1819 loc) · 103 KB
/
RadarCalculation.cpp
File metadata and controls
2183 lines (1819 loc) · 103 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
/* Bridge Command 5.0 Ship Simulator
Copyright (C) 2014 James Packer
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation
This program 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 this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "RadarCalculation.hpp"
#include "Terrain.hpp"
#include "OwnShip.hpp"
#include "Buoys.hpp"
#include "OtherShips.hpp"
#include "RadarData.hpp"
#include "Angles.hpp"
#include "Constants.hpp"
#include "IniFile.hpp"
#include "NumberToImage.hpp"
#include "Utilities.hpp"
#include <iostream>
#include <cmath>
#include <cstdlib> //For rand()
#include <algorithm> //For sort()
#ifdef WITH_PROFILING
#include "iprof.hpp"
#else
#define IPROF(a) //intentionally empty placeholder
#endif
////using namespace irr;
RadarCalculation::RadarCalculation() : rangeResolution(128), angularResolution(360)
{
//Initial values for controls, all 0-100:
radarGain = 50;
radarRainClutterReduction=0;
radarSeaClutterReduction=0;
currentRadarColourChoice=0;
EBLRangeNm=0;
EBLBrg=0;
CursorRangeNm = 0;
CursorBrg = 0;
cursorRangeXNm = 0;
cursorRangeYNm = 0;
radarCursorsLastUpdated = clock();
radarOn = true;
brilliance = 1.0;
//Radar modes: North up (false, false). Course up (true, true). Head up (true, false)
headUp = false;
stabilised = false;
trueVectors = true;
vectorLengthMinutes = 6;
arpaMode = 0;
// What's selected in the GUI arpa list
arpaListSelection = -1;
//Hard coded in GUI and here for 10 parallel index lines
for(irr::u32 i=0; i<10; i++) {
piBearings.push_back(0.0);
piRanges.push_back(0.0);
}
radarScreenStale = true;
radarRadiusPx = 10; //Set to an arbitrary value initially, will be set later.
currentScanAngle = 0;
currentScanLine = 0;
}
RadarCalculation::~RadarCalculation()
{
//dtor
}
void RadarCalculation::load(std::string radarConfigFile, irr::IrrlichtDevice* dev)
{
device = dev;
// Radar resolution defaults from bc5.ini
std::string userFolder = Utilities::getUserDir();
std::string iniFilename = "bc5.ini";
if (Utilities::pathExists(userFolder + iniFilename)) {
iniFilename = userFolder + iniFilename;
}
rangeResolution = IniFile::iniFileTou32(iniFilename, "RADAR_RangeRes", rangeResolution);
angularResolution = IniFile::iniFileTou32(iniFilename, "RADAR_AngularRes", angularResolution);
irr::u32 rangeResolution_max = IniFile::iniFileTou32(iniFilename, "RADAR_RangeRes_Max");
irr::u32 angularResolution_max = IniFile::iniFileTou32(iniFilename, "RADAR_AngularRes_Max");
//Load parameters from the radarConfig file (if it exists)
irr::u32 numberOfRadarRanges = IniFile::iniFileTou32(radarConfigFile,"NumberOfRadarRanges");
if (numberOfRadarRanges==0) {
//Assume file doesn't exist, and load defaults
//Set radar ranges:
radarRangeNm.push_back(0.5);
radarRangeNm.push_back(1.0);
radarRangeNm.push_back(1.5);
radarRangeNm.push_back(3.0);
radarRangeNm.push_back(6.0);
radarRangeNm.push_back(12.0);
radarRangeNm.push_back(24.0);
//Initial radar range
radarRangeIndex=3;
radarScannerHeight = 2.0;
radarNoiseLevel = 0.000000000005;
radarSeaClutter = 0.000000001;
radarRainClutter = 0.00001;
rangeSensitivity = 20;
irr::video::SColor radarBackgroundColour;
irr::video::SColor radarForegroundColour;
irr::video::SColor radarSurroundColour;
radarBackgroundColour.setAlpha(255);
radarBackgroundColour.setRed(0);
radarBackgroundColour.setGreen(0);
radarBackgroundColour.setBlue(200);
radarForegroundColour.setAlpha(255);
radarForegroundColour.setRed(255);
radarForegroundColour.setGreen(220);
radarForegroundColour.setBlue(0);
radarSurroundColour.setAlpha(255);
radarSurroundColour.setRed(128);
radarSurroundColour.setGreen(128);
radarSurroundColour.setBlue(128);
radarBackgroundColours.push_back(radarBackgroundColour);
radarForegroundColours.push_back(radarForegroundColour);
// Check in case resolution is set to an invalid value
if (rangeResolution < 1) {rangeResolution = 128;}
if (angularResolution < 1) {angularResolution = 360;}
// Limit to maximum (if set)
if (rangeResolution_max > 0 && rangeResolution > rangeResolution_max) {
rangeResolution = rangeResolution_max;
}
if (angularResolution_max > 0 && angularResolution > angularResolution_max) {
angularResolution = angularResolution_max;
}
} else {
//Load from file, but check plausibility where required
//Use numberOfRadarRanges, which we know is at least 1, to fill the radarRangeNm vector
for (unsigned int i = 1; i <= numberOfRadarRanges; i++) {
irr::f32 thisRadarRange = IniFile::iniFileTof32(radarConfigFile,IniFile::enumerate1("RadarRange",i));
if (thisRadarRange<=0) {thisRadarRange = 1;} //Check value is reasonable
radarRangeNm.push_back(thisRadarRange);
}
std::sort(radarRangeNm.begin(), radarRangeNm.end());
//Initial radar range
radarRangeIndex=numberOfRadarRanges/2;
//Radar scanner height (Metres)
radarScannerHeight = IniFile::iniFileTof32(radarConfigFile,"radar_height");
//Noise parameters
radarNoiseLevel = IniFile::iniFileTof32(radarConfigFile,"radar_noise");
radarSeaClutter = IniFile::iniFileTof32(radarConfigFile,"radar_sea_clutter");
radarRainClutter=IniFile::iniFileTof32(radarConfigFile,"radar_rain_clutter");
rangeSensitivity = IniFile::iniFileTof32(radarConfigFile,"radar_range_sensitivity");
if (radarNoiseLevel < 0) {radarNoiseLevel = 0.000000000005;}
if (radarSeaClutter < 0) {radarSeaClutter = 0.000000001;}
if (radarRainClutter< 0) {radarRainClutter= 0.00001;}
if (rangeSensitivity< 0) {rangeSensitivity=20;}
irr::u32 numberOfRadarColourSets = IniFile::iniFileTof32(radarConfigFile,"NumberOfRadarColourSets");
if (numberOfRadarColourSets == 0) {
//legacy loading
irr::video::SColor radarBackgroundColour;
irr::video::SColor radarForegroundColour;
irr::video::SColor radarSurroundColour;
radarBackgroundColour.setAlpha(255);
radarBackgroundColour.setRed(IniFile::iniFileTou32(radarConfigFile,"radar_bg_red"));
radarBackgroundColour.setGreen(IniFile::iniFileTou32(radarConfigFile,"radar_bg_green"));
radarBackgroundColour.setBlue(IniFile::iniFileTou32(radarConfigFile,"radar_bg_blue"));
radarForegroundColour.setAlpha(255);
radarForegroundColour.setRed(IniFile::iniFileTou32(radarConfigFile,"radar1_red"));
radarForegroundColour.setGreen(IniFile::iniFileTou32(radarConfigFile,"radar1_green"));
radarForegroundColour.setBlue(IniFile::iniFileTou32(radarConfigFile,"radar1_blue"));
radarSurroundColour.setAlpha(255);
radarSurroundColour.setRed(IniFile::iniFileTou32(radarConfigFile, "radar_surround_red", 128));
radarSurroundColour.setGreen(IniFile::iniFileTou32(radarConfigFile, "radar1_green", 128));
radarSurroundColour.setBlue(IniFile::iniFileTou32(radarConfigFile, "radar1_blue", 128));
radarBackgroundColours.push_back(radarBackgroundColour);
radarForegroundColours.push_back(radarForegroundColour);
radarSurroundColours.push_back(radarSurroundColour);
} else {
for (unsigned int i = 1; i <= numberOfRadarColourSets; i++) {
irr::video::SColor radarBackgroundColour;
irr::video::SColor radarForegroundColour;
irr::video::SColor radarSurroundColour;
radarBackgroundColour.setAlpha(255);
radarBackgroundColour.setRed(IniFile::iniFileTou32(radarConfigFile,IniFile::enumerate1("radar_bg_red",i)));
radarBackgroundColour.setGreen(IniFile::iniFileTou32(radarConfigFile,IniFile::enumerate1("radar_bg_green",i)));
radarBackgroundColour.setBlue(IniFile::iniFileTou32(radarConfigFile,IniFile::enumerate1("radar_bg_blue",i)));
radarForegroundColour.setAlpha(255);
radarForegroundColour.setRed(IniFile::iniFileTou32(radarConfigFile,IniFile::enumerate1("radar1_red",i)));
radarForegroundColour.setGreen(IniFile::iniFileTou32(radarConfigFile,IniFile::enumerate1("radar1_green",i)));
radarForegroundColour.setBlue(IniFile::iniFileTou32(radarConfigFile,IniFile::enumerate1("radar1_blue",i)));
radarSurroundColour.setAlpha(255);
radarSurroundColour.setRed(IniFile::iniFileTou32(radarConfigFile, IniFile::enumerate1("radar_surround_red", i), 128));
radarSurroundColour.setGreen(IniFile::iniFileTou32(radarConfigFile, IniFile::enumerate1("radar_surround_green", i), 128));
radarSurroundColour.setBlue(IniFile::iniFileTou32(radarConfigFile, IniFile::enumerate1("radar_surround_blue", i), 128));
radarBackgroundColours.push_back(radarBackgroundColour);
radarForegroundColours.push_back(radarForegroundColour);
radarSurroundColours.push_back(radarSurroundColour);
}
}
// Resolution settings:
// Override resolution if set in own ship's radar.ini file
rangeResolution = IniFile::iniFileTou32(radarConfigFile, "RADAR_RangeRes", rangeResolution);
angularResolution = IniFile::iniFileTou32(radarConfigFile, "RADAR_AngularRes", angularResolution);
// Check in case resolution is still not valid
if (rangeResolution < 1) {rangeResolution = 128;}
if (angularResolution < 1) {angularResolution = 360;}
// Limit to maximum (if set)
if (rangeResolution_max > 0 && rangeResolution > rangeResolution_max) {
rangeResolution = rangeResolution_max;
}
if (angularResolution_max > 0 && angularResolution > angularResolution_max) {
angularResolution = angularResolution_max;
}
}
//initialise scanArray size (angularResolution x rangeResolution points per scan)
scanArray.resize(angularResolution,std::vector<irr::f32>(rangeResolution,0.0));
scanArrayAmplified.resize(angularResolution,std::vector<irr::f32>(rangeResolution,0.0));
scanArrayToPlot.resize(angularResolution,std::vector<irr::f32>(rangeResolution,0.0));
scanArrayToPlotPrevious.resize(angularResolution,std::vector<irr::f32>(rangeResolution,0.0));
toReplot.resize(angularResolution);
//initialise arrays
for(irr::u32 i = 0; i<angularResolution; i++) {
for(irr::u32 j = 0; j<rangeResolution; j++) {
scanArray[i][j] = 0.0;
scanArrayAmplified[i][j] = 0.0;
scanArrayToPlot[i][j] = 0.0;
scanArrayToPlotPrevious[i][j] = -1.0;
}
}
scanAngleStep = 360.0f / (irr::f32) angularResolution;
}
void RadarCalculation::decreaseRange()
{
if (radarRangeIndex>0) {
radarRangeIndex--;
}
}
void RadarCalculation::increaseRange()
{
if (radarRangeIndex<radarRangeNm.size()-1) {
radarRangeIndex++;
}
}
irr::f32 RadarCalculation::getRangeNm() const
{
return radarRangeNm.at(radarRangeIndex); //Assume that radarRangeIndex is in bounds
}
void RadarCalculation::setGain(irr::f32 value)
{
radarGain = value;
}
void RadarCalculation::setClutter(irr::f32 value)
{
radarSeaClutterReduction = value;
}
void RadarCalculation::setRainClutter(irr::f32 value)
{
radarRainClutterReduction = value;
}
irr::f32 RadarCalculation::getGain() const
{
return radarGain;
}
irr::f32 RadarCalculation::getClutter() const
{
return radarSeaClutterReduction;
}
irr::f32 RadarCalculation::getRainClutter() const
{
return radarRainClutterReduction;
}
void RadarCalculation::increaseClutter(irr::f32 value)
{
radarSeaClutterReduction += value;
if (radarSeaClutterReduction > 100) {
radarSeaClutterReduction = 100;
}
}
void RadarCalculation::decreaseClutter(irr::f32 value)
{
radarSeaClutterReduction -= value;
if (radarSeaClutterReduction < 0) {
radarSeaClutterReduction = 0;
}
}
void RadarCalculation::increaseRainClutter(irr::f32 value)
{
radarRainClutterReduction += value;
if (radarRainClutterReduction > 100) {
radarRainClutterReduction = 100;
}
}
void RadarCalculation::decreaseRainClutter(irr::f32 value)
{
radarRainClutterReduction -= value;
if (radarRainClutterReduction < 0) {
radarRainClutterReduction = 0;
}
}
void RadarCalculation::increaseGain(irr::f32 value)
{
radarGain += value;
if (radarGain > 100) {
radarGain = 100;
}
}
void RadarCalculation::decreaseGain(irr::f32 value)
{
radarGain -= value;
if (radarGain < 0) {
radarGain = 0;
}
}
irr::f32 RadarCalculation::getEBLRangeNm() const
{
return EBLRangeNm;
}
irr::f32 RadarCalculation::getCursorBrg() const
{
return CursorBrg;
}
irr::f32 RadarCalculation::getCursorRangeNm() const
{
return CursorRangeNm;
}
irr::f32 RadarCalculation::getEBLBrg() const
{
return EBLBrg;
}
void RadarCalculation::setPIData(irr::s32 PIid, irr::f32 PIbearing, irr::f32 PIrange)
{
if (PIid >= 0 && PIid < (irr::s32)piBearings.size() && PIid < (irr::s32)piRanges.size()) {
piBearings.at(PIid) = PIbearing;
piRanges.at(PIid) = PIrange;
}
}
irr::f32 RadarCalculation::getPIbearing(irr::s32 PIid) const
{
if (PIid >= 0 && PIid < (irr::s32)piBearings.size()) {
return piBearings.at(PIid);
} else {
return 0;
}
}
irr::f32 RadarCalculation::getPIrange(irr::s32 PIid) const
{
if (PIid >= 0 && PIid < (irr::s32)piRanges.size()) {
return piRanges.at(PIid);
} else {
return 0;
}
}
void RadarCalculation::increaseCursorRangeXNm()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
irr::f32 oldCursorRangeXNm = cursorRangeXNm;
cursorRangeXNm += getRangeNm()/100;
// Limit:
irr::f32 testCursorRangeNm = pow(pow(cursorRangeXNm,2)+pow(cursorRangeYNm,2),0.5);
if (testCursorRangeNm > getRangeNm()) {
irr::f32 testCursorBrgRad = std::atan2(oldCursorRangeXNm,cursorRangeYNm);
cursorRangeXNm = getRangeNm() * sin(testCursorBrgRad);
cursorRangeYNm = getRangeNm() * cos(testCursorBrgRad);
}
}
}
void RadarCalculation::decreaseCursorRangeXNm()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
irr::f32 oldCursorRangeXNm = cursorRangeXNm;
cursorRangeXNm -= getRangeNm()/100;
// Limit:
irr::f32 testCursorRangeNm = pow(pow(cursorRangeXNm,2)+pow(cursorRangeYNm,2),0.5);
if (testCursorRangeNm > getRangeNm()) {
irr::f32 testCursorBrgRad = std::atan2(oldCursorRangeXNm,cursorRangeYNm);
cursorRangeXNm = getRangeNm() * sin(testCursorBrgRad);
cursorRangeYNm = getRangeNm() * cos(testCursorBrgRad);
}
}
}
void RadarCalculation::increaseCursorRangeYNm()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
irr::f32 oldCursorRangeYNm = cursorRangeYNm;
cursorRangeYNm += getRangeNm()/100;
// Limit:
irr::f32 testCursorRangeNm = pow(pow(cursorRangeXNm,2)+pow(cursorRangeYNm,2),0.5);
if (testCursorRangeNm > getRangeNm()) {
irr::f32 testCursorBrgRad = std::atan2(cursorRangeXNm,oldCursorRangeYNm);
cursorRangeXNm = getRangeNm() * sin(testCursorBrgRad);
cursorRangeYNm = getRangeNm() * cos(testCursorBrgRad);
}
}
}
void RadarCalculation::decreaseCursorRangeYNm()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
irr::f32 oldCursorRangeYNm = cursorRangeYNm;
cursorRangeYNm -= getRangeNm()/100;
// Limit:
irr::f32 testCursorRangeNm = pow(pow(cursorRangeXNm,2)+pow(cursorRangeYNm,2),0.5);
if (testCursorRangeNm > getRangeNm()) {
irr::f32 testCursorBrgRad = std::atan2(cursorRangeXNm,oldCursorRangeYNm);
cursorRangeXNm = getRangeNm() * sin(testCursorBrgRad);
cursorRangeYNm = getRangeNm() * cos(testCursorBrgRad);
}
}
}
void RadarCalculation::increaseEBLRange()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
EBLRangeNm += getRangeNm()/100;
}
}
void RadarCalculation::decreaseEBLRange()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
EBLRangeNm -= getRangeNm()/100;
if (EBLRangeNm<0) {
EBLRangeNm = 0;
}
}
}
void RadarCalculation::increaseEBLBrg()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
EBLBrg++;
while (EBLBrg >= 360) {
EBLBrg -= 360;
}
}
}
void RadarCalculation::decreaseEBLBrg()
{
//Only trigger this if there's been enough time since the last update.
clock_t clockNow = clock();
float elapsed = (float)(clockNow - radarCursorsLastUpdated)/CLOCKS_PER_SEC;
if (elapsed > 0.03) {
radarCursorsLastUpdated = clockNow;
EBLBrg--;
while (EBLBrg < 0) {
EBLBrg += 360;
}
}
}
void RadarCalculation::setNorthUp()
{
//Radar modes: North up (false, false). Course up (true, true). Head up (true, false)
headUp = false;
stabilised = false;
radarScreenStale = true;
}
void RadarCalculation::setCourseUp()
{
//Radar modes: North up (false, false). Course up (true, true). Head up (true, false)
headUp = true;
stabilised = true;
radarScreenStale = true;
}
void RadarCalculation::setHeadUp()
{
//Radar modes: North up (false, false). Course up (true, true). Head up (true, false)
headUp = true;
stabilised = false;
radarScreenStale = true;
}
bool RadarCalculation::getHeadUp() const//Head or course up
{
return headUp;
}
bool RadarCalculation::getStabilised() const
{
return stabilised;
}
void RadarCalculation::toggleRadarOn()
{
radarOn = !radarOn;
if (!radarOn) {
//Reset array to empty
for (irr::u32 i = 0; i < angularResolution; i++) {
for (irr::u32 j = 0; j < rangeResolution; j++) {
scanArrayToPlot[i][j] = 0.0;
}
}
radarScreenStale = true;
}
}
bool RadarCalculation::isRadarOn() const
{
return radarOn;
}
int RadarCalculation::getArpaMode() const
{
return arpaMode;
}
void RadarCalculation::setArpaMode(int mode)
{
// 0: Off/Manual, 1: MARPA, 2: ARPA
arpaMode = mode;
if (arpaMode < 1) {
// Clear arpa scans:
// Remove all ARPA (not manual) contacts from arpaContacts. Clear arpaTracks, but reset estimate.displayID to 0 for manual contacts, so it is regenerated
for (int i = arpaContacts.size() - 1; i >= 0; i--) {
// Iterate from end to start, as we may be removing items
if (arpaContacts.at(i).contactType == CONTACT_MANUAL) {
arpaContacts.at(i).estimate.displayID = 0;
} else {
// Remove it
arpaContacts.erase(arpaContacts.begin() + i);
}
}
arpaTracks.clear(); // This will be regenerated as we have set display ID to 0
}
}
void RadarCalculation::setRadarARPARel()
{
trueVectors = false;
}
void RadarCalculation::setRadarARPATrue()
{
trueVectors = true;
}
void RadarCalculation::setArpaListSelection(irr::s32 selection)
{
arpaListSelection = selection;
}
irr::s32 RadarCalculation::getArpaListSelection() const
{
return arpaListSelection;
}
void RadarCalculation::setRadarARPAVectors(irr::f32 vectorMinutes)
{
vectorLengthMinutes = vectorMinutes;
}
void RadarCalculation::setRadarDisplayRadius(irr::u32 radiusPx)
{
if (radarRadiusPx != radiusPx) { //If changed
radarRadiusPx = radiusPx;
radarScreenStale=true;
}
}
irr::u32 RadarCalculation::getARPATracksSize() const
{
return arpaTracks.size();
}
int RadarCalculation::getARPAContactIDFromTrackIndex(irr::u32 trackIndex) const
{
if (trackIndex >= 0 && trackIndex < arpaTracks.size()) {
return arpaTracks.at(trackIndex);
} else {
// Not found
return -1;
}
}
ARPAContact RadarCalculation::getARPAContactFromTrackIndex(irr::u32 trackIndex) const
{
int contactID = getARPAContactIDFromTrackIndex(trackIndex);
if(contactID >=0 && contactID < arpaContacts.size()){
return arpaContacts.at(contactID);
} else {
ARPAContact emptyContact;
return emptyContact;
}
}
void RadarCalculation::changeRadarColourChoice()
{
currentRadarColourChoice++;
if (currentRadarColourChoice >= radarBackgroundColours.size()) {
//Assume radarBackgroundColours and radarForegroundColours are the same size
//We check size of both before using currentRadarColourChoice
currentRadarColourChoice = 0;
}
radarScreenStale = true;
}
void RadarCalculation::update(irr::video::IImage * radarImage, irr::video::IImage * radarImageOverlaid, irr::core::vector3d<int64_t> offsetPosition, const Terrain& terrain, const OwnShip& ownShip, const Buoys& buoys, const OtherShips& otherShips, irr::f32 weather, irr::f32 rain, irr::f32 tideHeight, irr::f32 deltaTime, uint64_t absoluteTime, irr::f32 scenarioTime, irr::core::vector2di mouseRelPosition, bool isMouseDown)
{
#ifdef WITH_PROFILING
IPROF_FUNC;
#endif
{ IPROF("Set up");
//Reset screen if needed
if(radarScreenStale) {
radarImage->fill(getRadarSurroundColour());
//Reset 'previous' array so it will all get re-drawn
for(irr::u32 i = 0; i<angularResolution; i++) {
toReplot[i] = true;
for(irr::u32 j = 0; j<rangeResolution; j++) {
scanArrayToPlotPrevious[i][j] = -1.0;
}
}
radarScreenStale = false;
}
} { IPROF("Mouse cursor");
//Find position of mouse cursor for radar cursor
if (isMouseDown) {
irr::f32 mouseCursorRangeXNm = (irr::f32)mouseRelPosition.X/(irr::f32)radarRadiusPx*radarRangeNm.at(radarRangeIndex);//Nm
irr::f32 mouseCursorRangeYNm = -1.0*(irr::f32)mouseRelPosition.Y/(irr::f32)radarRadiusPx*radarRangeNm.at(radarRangeIndex);//Nm
irr::f32 mouseCursorRange = pow(pow(mouseCursorRangeXNm,2)+pow(mouseCursorRangeYNm,2),0.5);
//Check if in range
if (mouseCursorRange <= radarRangeNm.at(radarRangeIndex) ) {
// Store
cursorRangeXNm = mouseCursorRangeXNm;
cursorRangeYNm = mouseCursorRangeYNm;
}
}
// Always update the CursorRangeNm and CursorBrg from the current cursorRangeXNm and cursorRangeYNm
CursorBrg = irr::core::RADTODEG*std::atan2(cursorRangeXNm,cursorRangeYNm);
if (headUp) {
// Adjust angle if needed
CursorBrg += ownShip.getHeading();
}
CursorBrg = Angles::normaliseAngle(CursorBrg);
CursorRangeNm = pow(pow(cursorRangeXNm,2)+pow(cursorRangeYNm,2),0.5);
} { IPROF("Scan");
scan(offsetPosition, terrain, ownShip, buoys, otherShips, weather, rain, tideHeight, deltaTime, absoluteTime, scenarioTime); // scan into scanArray[row (angle)][column (step)], and with filtering and amplification into scanArrayAmplified[][]
} { IPROF("Update ARPA");
updateARPA(offsetPosition, ownShip, absoluteTime); //From data in arpaContacts, updated in scan()
} { IPROF("Render");
render(radarImage, radarImageOverlaid, ownShip.getCOG(), ownShip.getSOG()); //From scanArrayAmplified[row (angle)][column (step)], render to radarImage
}
}
void RadarCalculation::scan(irr::core::vector3d<int64_t> offsetPosition, const Terrain& terrain, const OwnShip& ownShip, const Buoys& buoys, const OtherShips& otherShips, irr::f32 weather, irr::f32 rain, irr::f32 tideHeight, irr::f32 deltaTime, uint64_t absoluteTime, irr::f32 scenarioTime)
{
//IPROF_FUNC;
const irr::u32 SECONDS_BETWEEN_SCANS = 2;
irr::core::vector3df position = ownShip.getPosition();
//Get absolute position relative to SW corner of world model
irr::core::vector3d<int64_t> absolutePosition = offsetPosition;
absolutePosition.X += position.X;
absolutePosition.Y += position.Y;
absolutePosition.Z += position.Z;
//Some tuning constants
irr::f32 radarFactorLand=2.0;
irr::f32 radarFactorVessel=0.0001;
irr::f32 radarFactorRACON= radarFactorVessel * pow(1852.0/200.0, 2); // for Equivalent RCS of 1m2 at 200m(Fig 8.11, Target detection by marine radar)
//Convert range to cell size
irr::f32 cellLength = M_IN_NM*radarRangeNm.at(radarRangeIndex)/rangeResolution; ; //Assume that radarRangeIndex is in bounds
//Load radar data for other contacts
std::vector<RadarData> radarData;
//For other ships
for (std::vector<RadarData>::size_type contactID=1; contactID<=otherShips.getNumber(); contactID++) {
radarData.push_back(otherShips.getRadarData(contactID,position));
}
//For buoys
for (std::vector<RadarData>::size_type contactID=1; contactID<=buoys.getNumber(); contactID++) {
radarData.push_back(buoys.getRadarData(contactID,position));
}
const irr::f32 RADAR_RPM = 25; //Todo: Make a ship parameter
const irr::f32 RPMtoDEGPERSECOND = 6;
irr::u32 scansPerLoop = RADAR_RPM * RPMtoDEGPERSECOND * deltaTime / (irr::f32) scanAngleStep + (irr::f32) rand() / RAND_MAX ; //Add random value (0-1, mean 0.5), so with rounding, we get the correct radar speed, even though we can only do an integer number of scans
if (scansPerLoop > 30) {scansPerLoop = 30;} //Limit to reasonable bounds
for(irr::u32 i = 0; i<scansPerLoop;i++) { //Start of repeatable scan section
// the actual angle we want to work with has to be determined here
currentScanAngle = ((irr::f32) currentScanLine / (irr::f32) angularResolution) * 360.0f;
irr::f32 scanSlope = -0.5; //Slope at start of scan (in metres/metre) - Make slightly negative so vessel contacts close in get detected
// clear this line (before the main scan loop, so we can add things like racon which will appear beyond contact
for (irr::u32 currentStep = 1; currentStep < rangeResolution; currentStep++) { //Note that currentStep starts as 1, not 0. This is used in anti-rain clutter filter, which checks element at currentStep-1
scanArray[currentScanLine][currentStep] = 0.0;
}
for (irr::u32 currentStep = 1; currentStep<rangeResolution; currentStep++) { //Note that currentStep starts as 1, not 0. This is used in anti-rain clutter filter, which checks element at currentStep-1
//scan into array, accessed as scanArray[row (angle)][column (step)]
//Get location of area being scanned
irr::f32 localRange = cellLength*currentStep;
irr::f32 relX = localRange*sin(currentScanAngle*irr::core::DEGTORAD); //Distance from ship
irr::f32 relZ = localRange*cos(currentScanAngle*irr::core::DEGTORAD);
irr::f32 localX = position.X + relX;
irr::f32 localZ = position.Z + relZ;
//get extents
irr::f32 minCellAngle = Angles::normaliseAngle(currentScanAngle - scanAngleStep/2.0);
irr::f32 maxCellAngle = Angles::normaliseAngle(currentScanAngle + scanAngleStep/2.0);
irr::f32 minCellRange = localRange - cellLength/2.0;
irr::f32 maxCellRange = localRange + cellLength/2.0;
// Get extreme points
irr::f32 relXCorner1 = minCellRange*sin(minCellAngle*irr::core::DEGTORAD);
irr::f32 relXCorner2 = minCellRange*sin(maxCellAngle*irr::core::DEGTORAD);
irr::f32 relXCorner3 = maxCellRange*sin(minCellAngle*irr::core::DEGTORAD);
irr::f32 relXCorner4 = maxCellRange*sin(maxCellAngle*irr::core::DEGTORAD);
irr::f32 relZCorner1 = minCellRange*cos(minCellAngle*irr::core::DEGTORAD);
irr::f32 relZCorner2 = minCellRange*cos(maxCellAngle*irr::core::DEGTORAD);
irr::f32 relZCorner3 = maxCellRange*cos(minCellAngle*irr::core::DEGTORAD);
irr::f32 relZCorner4 = maxCellRange*cos(maxCellAngle*irr::core::DEGTORAD);
//get adjustment of height for earth's curvature
irr::f32 dropWithCurvature = std::pow(localRange,2)/(2*EARTH_RAD_M*EARTH_RAD_CORRECTION);
//Calculate noise
irr::f32 localNoise = radarNoise(radarNoiseLevel,radarSeaClutter,radarRainClutter,weather,localRange,currentScanAngle,0,scanSlope,rain); //FIXME: Needs wind direction
//Scan other contacts here
for(unsigned int thisContact = 0; thisContact<radarData.size(); thisContact++) {
irr::f32 contactHeightAboveLine = (radarData.at(thisContact).height - radarScannerHeight - dropWithCurvature) - scanSlope*localRange;
if (contactHeightAboveLine > 0) {
//Contact would be visible if in this cell. Check if it is
//Ellipse based check - check if any corner point of the cell is within the contact ellipse. If so, then it's definitely visible. If not, fall back to old checks
bool contactEllipseFound = false;
if (isPointInEllipse(relX, relZ, radarData.at(thisContact).relX, radarData.at(thisContact).relZ, radarData.at(thisContact).width, radarData.at(thisContact).length, radarData.at(thisContact).heading)) {
contactEllipseFound = true;
} else if (isPointInEllipse(relXCorner1, relZCorner1, radarData.at(thisContact).relX, radarData.at(thisContact).relZ, radarData.at(thisContact).width, radarData.at(thisContact).length, radarData.at(thisContact).heading)) {
contactEllipseFound = true;
} else if (isPointInEllipse(relXCorner2, relZCorner2, radarData.at(thisContact).relX, radarData.at(thisContact).relZ, radarData.at(thisContact).width, radarData.at(thisContact).length, radarData.at(thisContact).heading)) {
contactEllipseFound = true;
} else if (isPointInEllipse(relXCorner3, relZCorner3, radarData.at(thisContact).relX, radarData.at(thisContact).relZ, radarData.at(thisContact).width, radarData.at(thisContact).length, radarData.at(thisContact).heading)) {
contactEllipseFound = true;
} else if (isPointInEllipse(relXCorner4, relZCorner4, radarData.at(thisContact).relX, radarData.at(thisContact).relZ, radarData.at(thisContact).width, radarData.at(thisContact).length, radarData.at(thisContact).heading)) {
contactEllipseFound = true;
}
//Start of B3D code
//Check if centre of target within the cell. If not then check if Either min range or max range of contact is within the cell, or min and max span the cell
if (contactEllipseFound
|| (radarData.at(thisContact).range >= minCellRange && radarData.at(thisContact).range <= maxCellRange)
|| (radarData.at(thisContact).minRange >= minCellRange && radarData.at(thisContact).minRange <= maxCellRange)
|| (radarData.at(thisContact).maxRange >= minCellRange && radarData.at(thisContact).maxRange <= maxCellRange)
|| (radarData.at(thisContact).minRange < minCellRange && radarData.at(thisContact).maxRange > maxCellRange)) {
//Check if centre of target within the cell. If not then check if either min angle or max angle of contact is within the cell, or min and max span the cell
if (contactEllipseFound
|| (Angles::isAngleBetween(radarData.at(thisContact).angle,minCellAngle,maxCellAngle))
|| (Angles::isAngleBetween(radarData.at(thisContact).minAngle,minCellAngle,maxCellAngle))
|| (Angles::isAngleBetween(radarData.at(thisContact).maxAngle,minCellAngle,maxCellAngle))
|| (Angles::normaliseAngle(radarData.at(thisContact).minAngle-minCellAngle) > 270 && Angles::normaliseAngle(radarData.at(thisContact).maxAngle-maxCellAngle) < 90)) {
irr::f32 rangeAtCellMin = rangeAtAngle(minCellAngle,radarData.at(thisContact).relX,radarData.at(thisContact).relZ,radarData.at(thisContact).heading);
irr::f32 rangeAtCellMax = rangeAtAngle(maxCellAngle,radarData.at(thisContact).relX,radarData.at(thisContact).relZ,radarData.at(thisContact).heading);
//check if the contact intersects this exact cell, if its extremes overlap it
//Also check if the target centre is in the cell, or the extended target spans the cell (ie RangeAtCellMin less than minCellRange and rangeAtCellMax greater than maxCellRange and vice versa)
if (contactEllipseFound
|| (((radarData.at(thisContact).range >= minCellRange && radarData.at(thisContact).range <= maxCellRange)
&& (Angles::isAngleBetween(radarData.at(thisContact).angle,minCellAngle,maxCellAngle)))
|| (rangeAtCellMin >= minCellRange && rangeAtCellMin <= maxCellRange)
|| (rangeAtCellMax >= minCellRange && rangeAtCellMax <= maxCellRange)
|| (rangeAtCellMin < minCellRange && rangeAtCellMax > maxCellRange)
|| (rangeAtCellMax < minCellRange && rangeAtCellMin > maxCellRange))) {
irr::f32 radarEchoStrength = radarFactorVessel * std::pow(M_IN_NM/localRange,4) * radarData.at(thisContact).rcs;
scanArray[currentScanLine][currentStep] += radarEchoStrength;
if (radarData.at(thisContact).racon != "") {
if (std::fmod(scenarioTime + radarData.at(thisContact).raconOffsetTime, 60.0f) <= radarData.at(thisContact).raconOnTime) {
irr::f32 raconEchoStrength = radarFactorRACON * std::pow(M_IN_NM / localRange, 2); //RACON / SART goes with inverse square law as we are receiving the direct signal, not echo
addRaconString(raconEchoStrength, cellLength, localRange, radarData.at(thisContact).racon);
}
}
//Start ARPA section
// ARPA mode - 0: Off/Manual, 1: MARPA, 2: ARPA
if (arpaMode > 0 && radarEchoStrength*2 > localNoise) {
//Contact is detectable in noise
//Iterate through arpaContacts array, checking if this contact is in the list (by checking the if the 'contact' pointer is to the same underlying ship/buoy)
int existingArpaContact=-1;
for (unsigned int j = 0; j<arpaContacts.size(); j++) {
if (arpaContacts.at(j).contact == radarData.at(thisContact).contact) {
existingArpaContact = j;
}
}
//If it doesn't exist, add it, and make existingArpaContact point to it
if (existingArpaContact<0) {
ARPAContact newContact;
newContact.contact = radarData.at(thisContact).contact;
newContact.contactType=CONTACT_NORMAL;
//newContact.displayID = 0; //Initially not displayed
newContact.totalXMovementEst = 0;
newContact.totalZMovementEst = 0;
//Zeros for estimated state
newContact.estimate.displayID = 0;
newContact.estimate.stationary = true;
newContact.estimate.lost = false;
newContact.estimate.absVectorX = 0;
newContact.estimate.absVectorZ = 0;
newContact.estimate.absHeading = 0;
newContact.estimate.bearing = 0;
newContact.estimate.range = 0;
newContact.estimate.speed = 0;
newContact.estimate.contactType = newContact.contactType; //Redundant here, but useful to pass to the GUI later
arpaContacts.push_back(newContact);
existingArpaContact = arpaContacts.size()-1;
//std::cout << "Adding contact " << existingArpaContact << std::endl;
}
//Add this scan (if not already scanned in the last X seconds
size_t scansSize = arpaContacts.at(existingArpaContact).scans.size();
if (scansSize==0 || absoluteTime > SECONDS_BETWEEN_SCANS + arpaContacts.at(existingArpaContact).scans.at(scansSize-1).timeStamp) {
ARPAScan newScan;
newScan.timeStamp = absoluteTime;
//Add noise/uncertainty
irr::f32 angleUncertainty = scanAngleStep/2.0 * (2.0*(irr::f32)rand()/RAND_MAX - 1);
irr::f32 rangeUncertainty = rangeSensitivity * (2.0*(irr::f32)rand()/RAND_MAX - 1)/M_IN_NM;
newScan.bearingDeg = angleUncertainty + radarData.at(thisContact).angle;
newScan.rangeNm = rangeUncertainty + radarData.at(thisContact).range / M_IN_NM;
newScan.x = absolutePosition.X + newScan.rangeNm*M_IN_NM * sin(newScan.bearingDeg*RAD_IN_DEG);
newScan.z = absolutePosition.Z + newScan.rangeNm*M_IN_NM * cos(newScan.bearingDeg*RAD_IN_DEG);;
//newScan.estimatedRCS = 100;//Todo: Implement
//Keep track of estimated total movement if in full ARPA
// 0: Off/Manual, 1: MARPA, 2: ARPA
if (scansSize > 0 && arpaMode == 2) {
arpaContacts.at(existingArpaContact).totalXMovementEst += arpaContacts.at(existingArpaContact).scans.at(scansSize-1).x - newScan.x;
arpaContacts.at(existingArpaContact).totalZMovementEst += arpaContacts.at(existingArpaContact).scans.at(scansSize-1).z - newScan.z;
} else {
arpaContacts.at(existingArpaContact).totalXMovementEst = 0;
arpaContacts.at(existingArpaContact).totalZMovementEst = 0;
}
if (arpaContacts.at(existingArpaContact).estimate.stationary) {
// If stationary, don't keep previous scans (we are about to add the most recent)
arpaContacts.at(existingArpaContact).scans.clear();
}
arpaContacts.at(existingArpaContact).scans.push_back(newScan);
//std::cout << "ARPA update on " << existingArpaContact << std::endl;
//Todo: should we limit the size of this, so it doesn't continue accumulating?
}
} //End ARPA Section
//Todo: Also check for contacts beyond the current scan range.
/*
;check how visible against noise/clutter. If visible, record as detected for ARPA tracking
If radarEchoStrength#*2 > radarNoiseValueNoBlock(radarNoiseLevel#, radarSeaClutter#, radarRainClutter#, weather#, AllRadarTargets(i)\range, rainIntensity)
;DebugLog "Contact:"
;DebugLog Str(radarNoiseValueNoBlock(radarNoiseLevel#, radarSeaClutter#, radarRainClutter#, weather#, AllRadarTargets(i)\range, rainIntensity))
;DebugLog radarEchoStrength#*2
contactLastDetected(i) = absolute_time