]> git.mxchange.org Git - flightgear.git/blob - src/Radio/radio.cxx
Send geod from Nasal, properly document the code, take some parameters from properties
[flightgear.git] / src / Radio / radio.cxx
1 // radio.cxx -- implementation of FGRadio
2 // Class to manage radio propagation using the ITM model
3 // Written by Adrian Musceac, started August 2011.
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <math.h>
26
27 #include <stdlib.h>
28 #include <deque>
29 #include "radio.hxx"
30 #include <simgear/scene/material/mat.hxx>
31 #include <Scenery/scenery.hxx>
32
33 #define WITH_POINT_TO_POINT 1
34 #include "itm.cpp"
35
36
37 FGRadioTransmission::FGRadioTransmission() {
38         
39         
40         _receiver_sensitivity = -105.0; // typical AM receiver sensitivity seems to be 0.8 microVolt at 12dB SINAD or less
41         
42         /** AM transmitter power in dBm.
43         *       Typical output powers for ATC ground equipment, VHF-UHF:
44         *       40 dBm - 10 W (ground, clearance)
45         *       44 dBm - 20 W (tower)
46         *       47 dBm - 50 W (center, sectors)
47         *       50 dBm - 100 W (center, sectors)
48         *       53 dBm - 200 W (sectors, on directional arrays)
49         **/
50         _transmitter_power = 43.0;
51         
52         _tx_antenna_height = 2.0; // TX antenna height above ground level
53         
54         _rx_antenna_height = 2.0; // RX antenna height above ground level
55         
56         
57         _rx_antenna_gain = 1.0; // maximum antenna gain expressed in dBi
58         _tx_antenna_gain = 1.0;
59         
60         _rx_line_losses = 2.0;  // to be configured for each station
61         _tx_line_losses = 2.0;
62         
63         _polarization = 1; // default vertical
64         
65         _propagation_model = 2; 
66         
67         _root_node = fgGetNode("sim/radio", true);
68         _terrain_sampling_distance = _root_node->getDoubleValue("sampling-distance", 90.0); // regular SRTM is 90 meters
69         
70         
71 }
72
73 FGRadioTransmission::~FGRadioTransmission() 
74 {
75 }
76
77
78 double FGRadioTransmission::getFrequency(int radio) {
79         double freq = 118.0;
80         switch (radio) {
81                 case 1:
82                         freq = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
83                         break;
84                 case 2:
85                         freq = fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
86                         break;
87                 default:
88                         freq = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
89                         
90         }
91         return freq;
92 }
93
94
95 void FGRadioTransmission::receiveChat(SGGeod tx_pos, double freq, string text, int ground_to_air) {
96
97 }
98
99
100 double FGRadioTransmission::receiveNav(SGGeod tx_pos, double freq, int transmission_type) {
101         
102         // typical VOR/LOC transmitter power appears to be 100 - 200 Watt i.e 50 - 53 dBm
103         // vor/loc typical sensitivity between -107 and -101 dBm
104         // glideslope sensitivity between -85 and -81 dBm
105         if ( _propagation_model == 1) {
106                 return LOS_calculate_attenuation(tx_pos, freq, 1);
107         }
108         else if ( _propagation_model == 2) {
109                 return ITM_calculate_attenuation(tx_pos, freq, 1);
110         }
111         
112         return -1;
113
114 }
115
116
117 double FGRadioTransmission::receiveBeacon(SGGeod &tx_pos, double heading, double pitch) {
118         
119         // these properties should be set by an instrument
120         _receiver_sensitivity = _root_node->getDoubleValue("station[0]/rx-sensitivity", _receiver_sensitivity);
121         _transmitter_power = watt_to_dbm(_root_node->getDoubleValue("station[0]/tx-power-watt", _transmitter_power));
122         _polarization = _root_node->getIntValue("station[0]/polarization", 1);
123         _tx_antenna_height += _root_node->getDoubleValue("station[0]/tx-antenna-height", 0);
124         _rx_antenna_height += _root_node->getDoubleValue("station[0]/rx-antenna-height", 0);
125         _tx_antenna_gain += _root_node->getDoubleValue("station[0]/tx-antenna-gain", 0);
126         _rx_antenna_gain += _root_node->getDoubleValue("station[0]/rx-antenna-gain", 0);
127         
128         double freq = _root_node->getDoubleValue("station[0]/frequency", 144.8);        // by default stay in the ham 2 meter band
129         
130         double comm1 = getFrequency(1);
131         double comm2 = getFrequency(2);
132         if ( !(fabs(freq - comm1) <= 0.0001) &&  !(fabs(freq - comm2) <= 0.0001) ) {
133                 return -1;
134         }
135         
136         double signal = ITM_calculate_attenuation(tx_pos, freq, 1);
137         
138         return signal;
139 }
140
141
142
143 void FGRadioTransmission::receiveATC(SGGeod tx_pos, double freq, string text, int ground_to_air) {
144
145         // adjust some default parameters in case the ATC code does not set them
146         if(ground_to_air == 1) {
147                 _transmitter_power += 4.0;
148                 _tx_antenna_height += 30.0;
149                 _tx_antenna_gain += 2.0; 
150         }
151         
152         double comm1 = getFrequency(1);
153         double comm2 = getFrequency(2);
154         if ( !(fabs(freq - comm1) <= 0.0001) &&  !(fabs(freq - comm2) <= 0.0001) ) {
155                 return;
156         }
157         else {
158         
159                 if ( _propagation_model == 0) {         // skip propagation routines entirely
160                         fgSetString("/sim/messages/atc", text.c_str());
161                 }
162                 else if ( _propagation_model == 1 ) {           // Use free-space, round earth
163                         
164                         double signal = LOS_calculate_attenuation(tx_pos, freq, ground_to_air);
165                         if (signal <= 0.0) {
166                                 return;
167                         }
168                         else {
169                                 fgSetString("/sim/messages/atc", text.c_str());
170                         }
171                 }
172                 else if ( _propagation_model == 2 ) {   // Use ITM propagation model
173                         
174                         double signal = ITM_calculate_attenuation(tx_pos, freq, ground_to_air);
175                         if (signal <= 0.0) {
176                                 return;
177                         }
178                         if ((signal > 0.0) && (signal < 12.0)) {
179                                 /** for low SNR values need a way to make the conversation
180                                 *       hard to understand but audible
181                                 *       in the real world, the receiver AGC fails to capture the slope
182                                 *       and the signal, due to being amplitude modulated, decreases volume after demodulation
183                                 *       the workaround below is more akin to what would happen on a FM transmission
184                                 *       therefore the correct way would be to work on the volume
185                                 **/
186                                 /*
187                                 string hash_noise = " ";
188                                 int reps = (int) (fabs(floor(signal - 11.0)) * 2);
189                                 int t_size = text.size();
190                                 for (int n = 1; n <= reps; ++n) {
191                                         int pos = rand() % (t_size -1);
192                                         text.replace(pos,1, hash_noise);
193                                 }
194                                 */
195                                 //double volume = (fabs(signal - 12.0) / 12);
196                                 //double old_volume = fgGetDouble("/sim/sound/voices/voice/volume");
197                                 
198                                 //fgSetDouble("/sim/sound/voices/voice/volume", volume);
199                                 fgSetString("/sim/messages/atc", text.c_str());
200                                 //fgSetDouble("/sim/sound/voices/voice/volume", old_volume);
201                         }
202                         else {
203                                 fgSetString("/sim/messages/atc", text.c_str());
204                         }
205                 }
206         }
207 }
208
209
210 double FGRadioTransmission::ITM_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
211
212         
213         
214         /** ITM default parameters 
215                 TODO: take them from tile materials (especially for sea)?
216         **/
217         double eps_dielect=15.0;
218         double sgm_conductivity = 0.005;
219         double eno = 301.0;
220         double frq_mhz = freq;
221         
222         int radio_climate = 5;          // continental temperate
223         int pol= _polarization; 
224         double conf = 0.90;     // 90% of situations and time, take into account speed
225         double rel = 0.90;      
226         double dbloss;
227         char strmode[150];
228         int p_mode = 0; // propgation mode selector: 0 LOS, 1 diffraction dominant, 2 troposcatter
229         double horizons[2];
230         int errnum;
231         
232         double clutter_loss = 0.0;      // loss due to vegetation and urban
233         double tx_pow = _transmitter_power;
234         double ant_gain = _rx_antenna_gain + _tx_antenna_gain;
235         double signal = 0.0;
236         
237         
238         double link_budget = tx_pow - _receiver_sensitivity - _rx_line_losses - _tx_line_losses + ant_gain;     
239         double signal_strength = tx_pow - _rx_line_losses - _tx_line_losses + ant_gain; 
240         double tx_erp = dbm_to_watt(tx_pow + _tx_antenna_gain - _tx_line_losses);
241         
242
243         FGScenery * scenery = globals->get_scenery();
244         
245         double own_lat = fgGetDouble("/position/latitude-deg");
246         double own_lon = fgGetDouble("/position/longitude-deg");
247         double own_alt_ft = fgGetDouble("/position/altitude-ft");
248         double own_heading = fgGetDouble("/orientation/heading-deg");
249         double own_alt= own_alt_ft * SG_FEET_TO_METER;
250         
251         
252         
253         
254         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
255         SGGeod max_own_pos = SGGeod::fromDegM( own_lon, own_lat, SG_MAX_ELEVATION_M );
256         SGGeoc center = SGGeoc::fromGeod( max_own_pos );
257         SGGeoc own_pos_c = SGGeoc::fromGeod( own_pos );
258         
259         
260         double sender_alt_ft,sender_alt;
261         double transmitter_height=0.0;
262         double receiver_height=0.0;
263         SGGeod sender_pos = pos;
264         
265         sender_alt_ft = sender_pos.getElevationFt();
266         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
267         SGGeod max_sender_pos = SGGeod::fromGeodM( pos, SG_MAX_ELEVATION_M );
268         SGGeoc sender_pos_c = SGGeoc::fromGeod( sender_pos );
269         
270         
271         double point_distance= _terrain_sampling_distance; 
272         double course = SGGeodesy::courseRad(own_pos_c, sender_pos_c);
273         double reverse_course = SGGeodesy::courseRad(sender_pos_c, own_pos_c);
274         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
275         double probe_distance = 0.0;
276         /** If distance larger than this value (300 km), assume reception imposssible to spare CPU cycles */
277         if (distance_m > 300000)
278                 return -1.0;
279         /** If above 8000 meters, consider LOS mode and calculate free-space att to spare CPU cycles */
280         if (own_alt > 8000) {
281                 dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
282                 SG_LOG(SG_GENERAL, SG_BULK,
283                         "ITM Free-space mode:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, free-space attenuation");
284                 //cerr << "ITM Free-space mode:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, free-space attenuation" << endl;
285                 signal = link_budget - dbloss;
286                 return signal;
287         }
288         
289                 
290         int max_points = (int)floor(distance_m / point_distance);
291         double delta_last = fmod(distance_m, point_distance);
292         
293         deque<double> elevations;
294         deque<string> materials;
295         
296
297         double elevation_under_pilot = 0.0;
298         if (scenery->get_elevation_m( max_own_pos, elevation_under_pilot, NULL )) {
299                 receiver_height = own_alt - elevation_under_pilot; 
300         }
301
302         double elevation_under_sender = 0.0;
303         if (scenery->get_elevation_m( max_sender_pos, elevation_under_sender, NULL )) {
304                 transmitter_height = sender_alt - elevation_under_sender;
305         }
306         else {
307                 transmitter_height = sender_alt;
308         }
309         
310         
311         transmitter_height += _tx_antenna_height;
312         receiver_height += _rx_antenna_height;
313         
314         //cerr << "ITM:: RX-height: " << receiver_height << " meters, TX-height: " << transmitter_height << " meters, Distance: " << distance_m << " meters" << endl;
315         _root_node->setDoubleValue("station[0]/rx-height", receiver_height);
316         _root_node->setDoubleValue("station[0]/tx-height", transmitter_height);
317         _root_node->setDoubleValue("station[0]/distance", distance_m / 1000);
318         
319         unsigned int e_size = (deque<unsigned>::size_type)max_points;
320         
321         while (elevations.size() <= e_size) {
322                 probe_distance += point_distance;
323                 SGGeod probe = SGGeod::fromGeoc(center.advanceRadM( course, probe_distance ));
324                 const SGMaterial *mat = 0;
325                 double elevation_m = 0.0;
326         
327                 if (scenery->get_elevation_m( probe, elevation_m, &mat )) {
328                         if((transmission_type == 3) || (transmission_type == 4)) {
329                                 elevations.push_back(elevation_m);
330                                 if(mat) {
331                                         const std::vector<string> mat_names = mat->get_names();
332                                         materials.push_back(mat_names[0]);
333                                 }
334                                 else {
335                                         materials.push_back("None");
336                                 }
337                         }
338                         else {
339                                  elevations.push_front(elevation_m);
340                                  if(mat) {
341                                          const std::vector<string> mat_names = mat->get_names();
342                                          materials.push_front(mat_names[0]);
343                                 }
344                                 else {
345                                         materials.push_front("None");
346                                 }
347                         }
348                 }
349                 else {
350                         if((transmission_type == 3) || (transmission_type == 4)) {
351                                 elevations.push_back(0.0);
352                                 materials.push_back("None");
353                         }
354                         else {
355                                 elevations.push_front(0.0);
356                                 materials.push_front("None");
357                         }
358                 }
359         }
360         if((transmission_type == 3) || (transmission_type == 4)) {
361                 elevations.push_front(elevation_under_pilot);
362                 if (delta_last > (point_distance / 2) )                 // only add last point if it's farther than half point_distance
363                         elevations.push_back(elevation_under_sender);
364         }
365         else {
366                 elevations.push_back(elevation_under_pilot);
367                 if (delta_last > (point_distance / 2) )
368                         elevations.push_front(elevation_under_sender);
369         }
370         
371         
372         double num_points= (double)elevations.size();
373
374
375         elevations.push_front(point_distance);
376         elevations.push_front(num_points -1);
377
378         int size = elevations.size();
379         double *itm_elev;
380         itm_elev = new double[size];
381
382         for(int i=0;i<size;i++) {
383                 itm_elev[i]=elevations[i];
384         }
385         
386         if((transmission_type == 3) || (transmission_type == 4)) {
387                 // the sender and receiver roles are switched
388                 point_to_point(itm_elev, receiver_height, transmitter_height,
389                         eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
390                         pol, conf, rel, dbloss, strmode, p_mode, horizons, errnum);
391                 if( _root_node->getBoolValue( "use-clutter-attenuation", false ) )
392                         calculate_clutter_loss(frq_mhz, itm_elev, materials, receiver_height, transmitter_height, p_mode, horizons, clutter_loss);
393         }
394         else {
395                 point_to_point(itm_elev, transmitter_height, receiver_height,
396                         eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
397                         pol, conf, rel, dbloss, strmode, p_mode, horizons, errnum);
398                 if( _root_node->getBoolValue( "use-clutter-attenuation", false ) )
399                         calculate_clutter_loss(frq_mhz, itm_elev, materials, transmitter_height, receiver_height, p_mode, horizons, clutter_loss);
400         }
401         
402         double pol_loss = 0.0;
403         // TODO: remove this check after we check a bit the axis calculations in this function
404         if (_polarization == 1) {
405                 pol_loss = polarization_loss();
406         }
407         //SG_LOG(SG_GENERAL, SG_BULK,
408         //              "ITM:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum);
409         //cerr << "ITM:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum << endl;
410         _root_node->setDoubleValue("station[0]/link-budget", link_budget);
411         _root_node->setDoubleValue("station[0]/terrain-attenuation", dbloss);
412         _root_node->setStringValue("station[0]/prop-mode", strmode);
413         _root_node->setDoubleValue("station[0]/clutter-attenuation", clutter_loss);
414         _root_node->setDoubleValue("station[0]/polarization-attenuation", pol_loss);
415         //if (errnum == 4)      // if parameters are outside sane values for lrprop, bail out fast
416         //      return -1;
417         
418         // temporary, keep this antenna radiation pattern code here
419         double tx_pattern_gain = 0.0;
420         double rx_pattern_gain = 0.0;
421         double sender_heading = 270.0; // due West
422         double tx_antenna_bearing = sender_heading - reverse_course * SGD_RADIANS_TO_DEGREES;
423         double rx_antenna_bearing = own_heading - course * SGD_RADIANS_TO_DEGREES;
424         double rx_elev_angle = atan((itm_elev[2] + transmitter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m) * SGD_RADIANS_TO_DEGREES;
425         double tx_elev_angle = 0.0 - rx_elev_angle;
426         if (_root_node->getBoolValue("use-tx-antenna-pattern", false)) {
427                 FGRadioAntenna* TX_antenna;
428                 TX_antenna = new FGRadioAntenna("Plot2");
429                 TX_antenna->set_heading(sender_heading);
430                 TX_antenna->set_elevation_angle(0);
431                 tx_pattern_gain = TX_antenna->calculate_gain(tx_antenna_bearing, tx_elev_angle);
432                 delete TX_antenna;
433         }
434         if (_root_node->getBoolValue("use-rx-antenna-pattern", false)) {
435                 FGRadioAntenna* RX_antenna;
436                 RX_antenna = new FGRadioAntenna("Plot2");
437                 RX_antenna->set_heading(own_heading);
438                 RX_antenna->set_elevation_angle(fgGetDouble("/orientation/pitch-deg"));
439                 rx_pattern_gain = RX_antenna->calculate_gain(rx_antenna_bearing, rx_elev_angle);
440                 delete RX_antenna;
441         }
442         
443         signal = link_budget - dbloss - clutter_loss + pol_loss + rx_pattern_gain + tx_pattern_gain;
444         double signal_strength_dbm = signal_strength - dbloss - clutter_loss + pol_loss + rx_pattern_gain + tx_pattern_gain;
445         double field_strength_uV = dbm_to_microvolt(signal_strength_dbm);
446         _root_node->setDoubleValue("station[0]/signal-dbm", signal_strength_dbm);
447         _root_node->setDoubleValue("station[0]/field-strength-uV", field_strength_uV);
448         _root_node->setDoubleValue("station[0]/signal", signal);
449         _root_node->setDoubleValue("station[0]/tx-erp", tx_erp);
450
451         //_root_node->setDoubleValue("station[0]/tx-pattern-gain", tx_pattern_gain);
452         //_root_node->setDoubleValue("station[0]/rx-pattern-gain", rx_pattern_gain);
453
454         delete[] itm_elev;
455
456         return signal;
457
458 }
459
460
461 void FGRadioTransmission::calculate_clutter_loss(double freq, double itm_elev[], deque<string> &materials,
462         double transmitter_height, double receiver_height, int p_mode,
463         double horizons[], double &clutter_loss) {
464         
465         double distance_m = itm_elev[0] * itm_elev[1]; // only consider elevation points
466         
467         if (p_mode == 0) {      // LOS: take each point and see how clutter height affects first Fresnel zone
468                 int mat = 0;
469                 int j=1; 
470                 for (int k=3;k < (int)(itm_elev[0]) + 2;k++) {
471                         
472                         double clutter_height = 0.0;    // mean clutter height for a certain terrain type
473                         double clutter_density = 0.0;   // percent of reflected wave
474                         get_material_properties(materials[mat], clutter_height, clutter_density);
475                         
476                         double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
477                         // First Fresnel radius
478                         double frs_rad = 548 * sqrt( (j * itm_elev[1] * (itm_elev[0] - j) * itm_elev[1] / 1000000) / (  distance_m * freq / 1000) );
479                         
480                         //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
481                         
482                         double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
483                         double d1 = j * itm_elev[1];
484                         if ((itm_elev[2] + transmitter_height) > ( itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) {
485                                 d1 = (itm_elev[0] - j) * itm_elev[1];
486                         }
487                         double ray_height = (grad * d1) + min_elev;
488                         
489                         double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
490                         double intrusion = fabs(clearance);
491                         
492                         if (clearance >= 0) {
493                                 // no losses
494                         }
495                         else if (clearance < 0 && (intrusion < clutter_height)) {
496                                 
497                                 clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
498                         }
499                         else if (clearance < 0 && (intrusion > clutter_height)) {
500                                 clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
501                         }
502                         else {
503                                 // no losses
504                         }
505                         j++;
506                         mat++;
507                 }
508                 
509         }
510         else if (p_mode == 1) {         // diffraction
511                 
512                 if (horizons[1] == 0.0) {       //      single horizon: same as above, except pass twice using the highest point
513                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0]/ distance_m ); 
514                         int num_points_2nd = (int)ceil( (distance_m - horizons[0]) * itm_elev[0] / distance_m ); 
515                         //cerr << "Diffraction 1 horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << endl;
516                         int last = 1;
517                         /** perform the first pass */
518                         int mat = 0;
519                         int j=1; 
520                         for (int k=3;k < num_points_1st + 2;k++) {
521                                 if (num_points_1st < 1)
522                                         break;
523                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
524                                 double clutter_density = 0.0;   // percent of reflected wave
525                                 get_material_properties(materials[mat], clutter_height, clutter_density);
526                                 
527                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
528                                 // First Fresnel radius
529                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_1st - j) * itm_elev[1] / 1000000) / ( num_points_1st * itm_elev[1] * freq / 1000) );
530                                 
531                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
532                                 
533                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
534                                 double d1 = j * itm_elev[1];
535                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
536                                         d1 = (num_points_1st - j) * itm_elev[1];
537                                 }
538                                 double ray_height = (grad * d1) + min_elev;
539                                 
540                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
541                                 double intrusion = fabs(clearance);
542                                 
543                                 if (clearance >= 0) {
544                                         // no losses
545                                 }
546                                 else if (clearance < 0 && (intrusion < clutter_height)) {
547                                         
548                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
549                                 }
550                                 else if (clearance < 0 && (intrusion > clutter_height)) {
551                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
552                                 }
553                                 else {
554                                         // no losses
555                                 }
556                                 j++;
557                                 mat++;
558                                 last = k;
559                         }
560                         
561                         /** and the second pass */
562                         mat +=1;
563                         j =1; // first point is diffraction edge, 2nd the RX elevation
564                         for (int k=last+2;k < (int)(itm_elev[0]) + 2;k++) {
565                                 if (num_points_2nd < 1)
566                                         break;
567                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
568                                 double clutter_density = 0.0;   // percent of reflected wave
569                                 get_material_properties(materials[mat], clutter_height, clutter_density);
570                                 
571                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
572                                 // First Fresnel radius
573                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_2nd - j) * itm_elev[1] / 1000000) / (  num_points_2nd * itm_elev[1] * freq / 1000) );
574                                 
575                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
576                                 
577                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
578                                 double d1 = j * itm_elev[1];
579                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
580                                         d1 = (num_points_2nd - j) * itm_elev[1];
581                                 }
582                                 double ray_height = (grad * d1) + min_elev;
583                                 
584                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
585                                 double intrusion = fabs(clearance);
586                                 
587                                 if (clearance >= 0) {
588                                         // no losses
589                                 }
590                                 else if (clearance < 0 && (intrusion < clutter_height)) {
591                                         
592                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
593                                 }
594                                 else if (clearance < 0 && (intrusion > clutter_height)) {
595                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
596                                 }
597                                 else {
598                                         // no losses
599                                 }
600                                 j++;
601                                 mat++;
602                         }
603                         
604                 }
605                 else {  // double horizon: same as single horizon, except there are 3 segments
606                         
607                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0] / distance_m ); 
608                         int num_points_2nd = (int)floor(horizons[1] * itm_elev[0] / distance_m ); 
609                         int num_points_3rd = (int)itm_elev[0] - num_points_1st - num_points_2nd; 
610                         //cerr << "Double horizon:: horizon1: " << horizons[0] << " horizon2: " << horizons[1] << " distance: " << distance_m << endl;
611                         //cerr << "Double horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << " points3: " << num_points_3rd << endl;
612                         int last = 1;
613                         /** perform the first pass */
614                         int mat = 0;
615                         int j=1; // first point is TX elevation, 2nd is obstruction elevation
616                         for (int k=3;k < num_points_1st +2;k++) {
617                                 if (num_points_1st < 1)
618                                         break;
619                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
620                                 double clutter_density = 0.0;   // percent of reflected wave
621                                 get_material_properties(materials[mat], clutter_height, clutter_density);
622                                 
623                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
624                                 // First Fresnel radius
625                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_1st - j) * itm_elev[1] / 1000000) / (  num_points_1st * itm_elev[1] * freq / 1000) );
626                                 
627                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
628                                 
629                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
630                                 double d1 = j * itm_elev[1];
631                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
632                                         d1 = (num_points_1st - j) * itm_elev[1];
633                                 }
634                                 double ray_height = (grad * d1) + min_elev;
635                                 
636                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
637                                 double intrusion = fabs(clearance);
638                                 
639                                 if (clearance >= 0) {
640                                         // no losses
641                                 }
642                                 else if (clearance < 0 && (intrusion < clutter_height)) {
643                                         
644                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
645                                 }
646                                 else if (clearance < 0 && (intrusion > clutter_height)) {
647                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
648                                 }
649                                 else {
650                                         // no losses
651                                 }
652                                 j++;
653                                 last = k;
654                         }
655                         mat +=1;
656                         /** and the second pass */
657                         int last2=1;
658                         j =1; // first point is 1st obstruction elevation, 2nd is 2nd obstruction elevation
659                         for (int k=last+2;k < num_points_1st + num_points_2nd +2;k++) {
660                                 if (num_points_2nd < 1)
661                                         break;
662                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
663                                 double clutter_density = 0.0;   // percent of reflected wave
664                                 get_material_properties(materials[mat], clutter_height, clutter_density);
665                                 
666                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) / distance_m;
667                                 // First Fresnel radius
668                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_2nd - j) * itm_elev[1] / 1000000) / (  num_points_2nd * itm_elev[1] * freq / 1000) );
669                                 
670                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
671                                 
672                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[num_points_1st + num_points_2nd +2] + clutter_height);
673                                 double d1 = j * itm_elev[1];
674                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) ) { 
675                                         d1 = (num_points_2nd - j) * itm_elev[1];
676                                 }
677                                 double ray_height = (grad * d1) + min_elev;
678                                 
679                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
680                                 double intrusion = fabs(clearance);
681                                 
682                                 if (clearance >= 0) {
683                                         // no losses
684                                 }
685                                 else if (clearance < 0 && (intrusion < clutter_height)) {
686                                         
687                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
688                                 }
689                                 else if (clearance < 0 && (intrusion > clutter_height)) {
690                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
691                                 }
692                                 else {
693                                         // no losses
694                                 }
695                                 j++;
696                                 mat++;
697                                 last2 = k;
698                         }
699                         
700                         /** third and final pass */
701                         mat +=1;
702                         j =1; // first point is 2nd obstruction elevation, 3rd is RX elevation
703                         for (int k=last2+2;k < (int)itm_elev[0] + 2;k++) {
704                                 if (num_points_3rd < 1)
705                                         break;
706                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
707                                 double clutter_density = 0.0;   // percent of reflected wave
708                                 get_material_properties(materials[mat], clutter_height, clutter_density);
709                                 
710                                 double grad = fabs(itm_elev[last2+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
711                                 // First Fresnel radius
712                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_3rd - j) * itm_elev[1] / 1000000) / (  num_points_3rd * itm_elev[1] * freq / 1000) );
713                                 
714                                 
715                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
716                                 
717                                 double min_elev = SGMiscd::min(itm_elev[last2+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
718                                 double d1 = j * itm_elev[1];
719                                 if ( (itm_elev[last2+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
720                                         d1 = (num_points_3rd - j) * itm_elev[1];
721                                 }
722                                 double ray_height = (grad * d1) + min_elev;
723                                 
724                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
725                                 double intrusion = fabs(clearance);
726                                 
727                                 if (clearance >= 0) {
728                                         // no losses
729                                 }
730                                 else if (clearance < 0 && (intrusion < clutter_height)) {
731                                         
732                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
733                                 }
734                                 else if (clearance < 0 && (intrusion > clutter_height)) {
735                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
736                                 }
737                                 else {
738                                         // no losses
739                                 }
740                                 j++;
741                                 mat++;
742                                 
743                         }
744                         
745                 }
746         }
747         else if (p_mode == 2) {         //      troposcatter: ignore ground clutter for now... maybe do something with weather
748                 clutter_loss = 0.0;
749         }
750         
751 }
752
753
754 void FGRadioTransmission::get_material_properties(string mat_name, double &height, double &density) {
755         
756         if(mat_name == "Landmass") {
757                 height = 15.0;
758                 density = 0.2;
759         }
760
761         else if(mat_name == "SomeSort") {
762                 height = 15.0;
763                 density = 0.2;
764         }
765
766         else if(mat_name == "Island") {
767                 height = 15.0;
768                 density = 0.2;
769         }
770         else if(mat_name == "Default") {
771                 height = 15.0;
772                 density = 0.2;
773         }
774         else if(mat_name == "EvergreenBroadCover") {
775                 height = 20.0;
776                 density = 0.2;
777         }
778         else if(mat_name == "EvergreenForest") {
779                 height = 20.0;
780                 density = 0.2;
781         }
782         else if(mat_name == "DeciduousBroadCover") {
783                 height = 15.0;
784                 density = 0.3;
785         }
786         else if(mat_name == "DeciduousForest") {
787                 height = 15.0;
788                 density = 0.3;
789         }
790         else if(mat_name == "MixedForestCover") {
791                 height = 20.0;
792                 density = 0.25;
793         }
794         else if(mat_name == "MixedForest") {
795                 height = 15.0;
796                 density = 0.25;
797         }
798         else if(mat_name == "RainForest") {
799                 height = 25.0;
800                 density = 0.55;
801         }
802         else if(mat_name == "EvergreenNeedleCover") {
803                 height = 15.0;
804                 density = 0.2;
805         }
806         else if(mat_name == "WoodedTundraCover") {
807                 height = 5.0;
808                 density = 0.15;
809         }
810         else if(mat_name == "DeciduousNeedleCover") {
811                 height = 5.0;
812                 density = 0.2;
813         }
814         else if(mat_name == "ScrubCover") {
815                 height = 3.0;
816                 density = 0.15;
817         }
818         else if(mat_name == "BuiltUpCover") {
819                 height = 30.0;
820                 density = 0.7;
821         }
822         else if(mat_name == "Urban") {
823                 height = 30.0;
824                 density = 0.7;
825         }
826         else if(mat_name == "Construction") {
827                 height = 30.0;
828                 density = 0.7;
829         }
830         else if(mat_name == "Industrial") {
831                 height = 30.0;
832                 density = 0.7;
833         }
834         else if(mat_name == "Port") {
835                 height = 30.0;
836                 density = 0.7;
837         }
838         else if(mat_name == "Town") {
839                 height = 10.0;
840                 density = 0.5;
841         }
842         else if(mat_name == "SubUrban") {
843                 height = 10.0;
844                 density = 0.5;
845         }
846         else if(mat_name == "CropWoodCover") {
847                 height = 10.0;
848                 density = 0.1;
849         }
850         else if(mat_name == "CropWood") {
851                 height = 10.0;
852                 density = 0.1;
853         }
854         else if(mat_name == "AgroForest") {
855                 height = 10.0;
856                 density = 0.1;
857         }
858         else {
859                 height = 0.0;
860                 density = 0.0;
861         }
862         
863 }
864
865
866 double FGRadioTransmission::LOS_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
867         
868         double frq_mhz = freq;
869         double dbloss;
870         double tx_pow = _transmitter_power;
871         double ant_gain = _rx_antenna_gain + _tx_antenna_gain;
872         double signal = 0.0;
873         
874         double sender_alt_ft,sender_alt;
875         double transmitter_height=0.0;
876         double receiver_height=0.0;
877         double own_lat = fgGetDouble("/position/latitude-deg");
878         double own_lon = fgGetDouble("/position/longitude-deg");
879         double own_alt_ft = fgGetDouble("/position/altitude-ft");
880         double own_alt= own_alt_ft * SG_FEET_TO_METER;
881         
882         
883         double link_budget = tx_pow - _receiver_sensitivity - _rx_line_losses - _tx_line_losses + ant_gain;     
884
885         //cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
886         
887         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
888         
889         SGGeod sender_pos = pos;
890         
891         sender_alt_ft = sender_pos.getElevationFt();
892         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
893         
894         receiver_height = own_alt;
895         transmitter_height = sender_alt;
896         
897         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
898         
899         
900         transmitter_height += _tx_antenna_height;
901         receiver_height += _rx_antenna_height;
902         
903         
904         /** radio horizon calculation with wave bending k=4/3 */
905         double receiver_horizon = 4.12 * sqrt(receiver_height);
906         double transmitter_horizon = 4.12 * sqrt(transmitter_height);
907         double total_horizon = receiver_horizon + transmitter_horizon;
908         
909         if (distance_m > total_horizon) {
910                 return -1;
911         }
912         double pol_loss = 0.0;
913         if (_polarization == 1) {
914                 pol_loss = polarization_loss();
915         }
916         // free-space loss (distance calculation should be changed)
917         dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
918         signal = link_budget - dbloss + pol_loss;
919
920         //cerr << "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm " << endl;
921         return signal;
922         
923 }
924
925 /*** calculate loss due to polarization mismatch
926 *       this function is only reliable for vertical polarization
927 *       due to the V-shape of horizontally polarized antennas
928 ***/
929 double FGRadioTransmission::polarization_loss() {
930         
931         double theta_deg;
932         double roll = fgGetDouble("/orientation/roll-deg");
933         if (fabs(roll) > 85.0)
934                 roll = 85.0;
935         double pitch = fgGetDouble("/orientation/pitch-deg");
936         if (fabs(pitch) > 85.0)
937                 pitch = 85.0;
938         double theta = fabs( atan( sqrt( 
939                 pow(tan(roll * SGD_DEGREES_TO_RADIANS), 2) + 
940                 pow(tan(pitch * SGD_DEGREES_TO_RADIANS), 2) )) * SGD_RADIANS_TO_DEGREES);
941         
942         if (_polarization == 0)
943                 theta_deg = 90.0 - theta;
944         else
945                 theta_deg = theta;
946         if (theta_deg > 85.0)   // we don't want to converge into infinity
947                 theta_deg = 85.0;
948         
949         double loss = 10 * log10( pow(cos(theta_deg * SGD_DEGREES_TO_RADIANS), 2) );
950         //cerr << "Polarization loss: " << loss << " dBm " << endl;
951         return loss;
952 }
953
954
955 double FGRadioTransmission::watt_to_dbm(double power_watt) {
956         return 10 * log10(1000 * power_watt);   // returns dbm
957 }
958
959 double FGRadioTransmission::dbm_to_watt(double dbm) {
960         return exp( (dbm-30) * log(10.0) / 10.0);       // returns Watts
961 }
962
963 double FGRadioTransmission::dbm_to_microvolt(double dbm) {
964         return sqrt(dbm_to_watt(dbm) * 50) * 1000000;   // returns microvolts
965 }
966
967