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