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