]> git.mxchange.org Git - flightgear.git/blob - src/Radio/radio.cxx
Merge branch 'attenuation' into navaids-radio
[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 }
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                         clutterLoss(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                         clutterLoss(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         //cerr << "Clutter loss: " << clutter_loss << endl;
402         //if (errnum == 4)      // if parameters are outside sane values for lrprop, the alternative method is used
403         //      return -1;
404         double sender_heading = 270.0; // due West
405         double tx_antenna_bearing = sender_heading - reverse_course;
406         double rx_antenna_bearing = own_heading - course;
407         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;
408         double tx_elev_angle = 0.0 - rx_elev_angle;
409         _TX_antenna = new FGRadioAntenna("Plot2");
410         _TX_antenna->set_heading(sender_heading);
411         _TX_antenna->set_elevation_angle(0);
412         double tx_pattern_gain = _TX_antenna->calculate_gain(tx_antenna_bearing, tx_elev_angle);
413         _RX_antenna = new FGRadioAntenna("Plot2");
414         _RX_antenna->set_heading(own_heading);
415         _RX_antenna->set_elevation_angle(fgGetDouble("/orientation/pitch-deg"));
416         double rx_pattern_gain = _RX_antenna->calculate_gain(rx_antenna_bearing, rx_elev_angle);
417         
418         delete _TX_antenna;
419         delete _RX_antenna;
420         signal = link_budget - dbloss - clutter_loss + pol_loss;
421         double signal_strength_dbm = signal_strength - dbloss - clutter_loss + pol_loss;
422         double field_strength_uV = dbm_to_microvolt(signal_strength_dbm);
423         _root_node->setDoubleValue("station[0]/signal-dbm", signal_strength_dbm);
424         _root_node->setDoubleValue("station[0]/field-strength-uV", field_strength_uV);
425         _root_node->setDoubleValue("station[0]/signal", signal);
426         _root_node->setDoubleValue("station[0]/tx-erp", tx_erp);
427         _root_node->setDoubleValue("station[0]/tx-pattern-gain", tx_pattern_gain);
428         _root_node->setDoubleValue("station[0]/rx-pattern-gain", rx_pattern_gain);
429         return signal;
430
431 }
432
433 /*** Calculate losses due to vegetation and urban clutter (WIP)
434 *        We are only worried about clutter loss, terrain influence 
435 *        on the first Fresnel zone is calculated in the ITM functions
436 ***/
437 void FGRadioTransmission::clutterLoss(double freq, double itm_elev[], deque<string> materials,
438         double transmitter_height, double receiver_height, int p_mode,
439         double horizons[], double &clutter_loss) {
440         
441         double distance_m = itm_elev[0] * itm_elev[1]; // only consider elevation points
442         
443         if (p_mode == 0) {      // LOS: take each point and see how clutter height affects first Fresnel zone
444                 int mat = 0;
445                 int j=1; 
446                 for (int k=3;k < (int)(itm_elev[0]) + 2;k++) {
447                         
448                         double clutter_height = 0.0;    // mean clutter height for a certain terrain type
449                         double clutter_density = 0.0;   // percent of reflected wave
450                         get_material_properties(materials[mat], clutter_height, clutter_density);
451                         
452                         double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
453                         // First Fresnel radius
454                         double frs_rad = 548 * sqrt( (j * itm_elev[1] * (itm_elev[0] - j) * itm_elev[1] / 1000000) / (  distance_m * freq / 1000) );
455                         
456                         //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
457                         
458                         double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
459                         double d1 = j * itm_elev[1];
460                         if ((itm_elev[2] + transmitter_height) > ( itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) {
461                                 d1 = (itm_elev[0] - j) * itm_elev[1];
462                         }
463                         double ray_height = (grad * d1) + min_elev;
464                         
465                         double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
466                         double intrusion = fabs(clearance);
467                         
468                         if (clearance >= 0) {
469                                 // no losses
470                         }
471                         else if (clearance < 0 && (intrusion < clutter_height)) {
472                                 
473                                 clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
474                         }
475                         else if (clearance < 0 && (intrusion > clutter_height)) {
476                                 clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
477                         }
478                         else {
479                                 // no losses
480                         }
481                         j++;
482                         mat++;
483                 }
484                 
485         }
486         else if (p_mode == 1) {         // diffraction
487                 
488                 if (horizons[1] == 0.0) {       //      single horizon: same as above, except pass twice using the highest point
489                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0]/ distance_m ); 
490                         int num_points_2nd = (int)ceil( (distance_m - horizons[0]) * itm_elev[0] / distance_m ); 
491                         //cerr << "Diffraction 1 horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << endl;
492                         int last = 1;
493                         /** perform the first pass */
494                         int mat = 0;
495                         int j=1; 
496                         for (int k=3;k < num_points_1st + 2;k++) {
497                                 if (num_points_1st < 1)
498                                         break;
499                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
500                                 double clutter_density = 0.0;   // percent of reflected wave
501                                 get_material_properties(materials[mat], clutter_height, clutter_density);
502                                 
503                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
504                                 // First Fresnel radius
505                                 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) );
506                                 
507                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
508                                 
509                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
510                                 double d1 = j * itm_elev[1];
511                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
512                                         d1 = (num_points_1st - j) * itm_elev[1];
513                                 }
514                                 double ray_height = (grad * d1) + min_elev;
515                                 
516                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
517                                 double intrusion = fabs(clearance);
518                                 
519                                 if (clearance >= 0) {
520                                         // no losses
521                                 }
522                                 else if (clearance < 0 && (intrusion < clutter_height)) {
523                                         
524                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
525                                 }
526                                 else if (clearance < 0 && (intrusion > clutter_height)) {
527                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
528                                 }
529                                 else {
530                                         // no losses
531                                 }
532                                 j++;
533                                 mat++;
534                                 last = k;
535                         }
536                         
537                         /** and the second pass */
538                         mat +=1;
539                         j =1; // first point is diffraction edge, 2nd the RX elevation
540                         for (int k=last+2;k < (int)(itm_elev[0]) + 2;k++) {
541                                 if (num_points_2nd < 1)
542                                         break;
543                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
544                                 double clutter_density = 0.0;   // percent of reflected wave
545                                 get_material_properties(materials[mat], clutter_height, clutter_density);
546                                 
547                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
548                                 // First Fresnel radius
549                                 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) );
550                                 
551                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
552                                 
553                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
554                                 double d1 = j * itm_elev[1];
555                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
556                                         d1 = (num_points_2nd - j) * itm_elev[1];
557                                 }
558                                 double ray_height = (grad * d1) + min_elev;
559                                 
560                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
561                                 double intrusion = fabs(clearance);
562                                 
563                                 if (clearance >= 0) {
564                                         // no losses
565                                 }
566                                 else if (clearance < 0 && (intrusion < clutter_height)) {
567                                         
568                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
569                                 }
570                                 else if (clearance < 0 && (intrusion > clutter_height)) {
571                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
572                                 }
573                                 else {
574                                         // no losses
575                                 }
576                                 j++;
577                                 mat++;
578                         }
579                         
580                 }
581                 else {  // double horizon: same as single horizon, except there are 3 segments
582                         
583                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0] / distance_m ); 
584                         int num_points_2nd = (int)floor(horizons[1] * itm_elev[0] / distance_m ); 
585                         int num_points_3rd = (int)itm_elev[0] - num_points_1st - num_points_2nd; 
586                         //cerr << "Double horizon:: horizon1: " << horizons[0] << " horizon2: " << horizons[1] << " distance: " << distance_m << endl;
587                         //cerr << "Double horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << " points3: " << num_points_3rd << endl;
588                         int last = 1;
589                         /** perform the first pass */
590                         int mat = 0;
591                         int j=1; // first point is TX elevation, 2nd is obstruction elevation
592                         for (int k=3;k < num_points_1st +2;k++) {
593                                 if (num_points_1st < 1)
594                                         break;
595                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
596                                 double clutter_density = 0.0;   // percent of reflected wave
597                                 get_material_properties(materials[mat], clutter_height, clutter_density);
598                                 
599                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
600                                 // First Fresnel radius
601                                 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) );
602                                 
603                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
604                                 
605                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
606                                 double d1 = j * itm_elev[1];
607                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
608                                         d1 = (num_points_1st - j) * itm_elev[1];
609                                 }
610                                 double ray_height = (grad * d1) + min_elev;
611                                 
612                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
613                                 double intrusion = fabs(clearance);
614                                 
615                                 if (clearance >= 0) {
616                                         // no losses
617                                 }
618                                 else if (clearance < 0 && (intrusion < clutter_height)) {
619                                         
620                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
621                                 }
622                                 else if (clearance < 0 && (intrusion > clutter_height)) {
623                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
624                                 }
625                                 else {
626                                         // no losses
627                                 }
628                                 j++;
629                                 last = k;
630                         }
631                         mat +=1;
632                         /** and the second pass */
633                         int last2=1;
634                         j =1; // first point is 1st obstruction elevation, 2nd is 2nd obstruction elevation
635                         for (int k=last+2;k < num_points_1st + num_points_2nd +2;k++) {
636                                 if (num_points_2nd < 1)
637                                         break;
638                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
639                                 double clutter_density = 0.0;   // percent of reflected wave
640                                 get_material_properties(materials[mat], clutter_height, clutter_density);
641                                 
642                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) / distance_m;
643                                 // First Fresnel radius
644                                 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) );
645                                 
646                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
647                                 
648                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[num_points_1st + num_points_2nd +2] + clutter_height);
649                                 double d1 = j * itm_elev[1];
650                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) ) { 
651                                         d1 = (num_points_2nd - j) * itm_elev[1];
652                                 }
653                                 double ray_height = (grad * d1) + min_elev;
654                                 
655                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
656                                 double intrusion = fabs(clearance);
657                                 
658                                 if (clearance >= 0) {
659                                         // no losses
660                                 }
661                                 else if (clearance < 0 && (intrusion < clutter_height)) {
662                                         
663                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
664                                 }
665                                 else if (clearance < 0 && (intrusion > clutter_height)) {
666                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
667                                 }
668                                 else {
669                                         // no losses
670                                 }
671                                 j++;
672                                 mat++;
673                                 last2 = k;
674                         }
675                         
676                         /** third and final pass */
677                         mat +=1;
678                         j =1; // first point is 2nd obstruction elevation, 3rd is RX elevation
679                         for (int k=last2+2;k < (int)itm_elev[0] + 2;k++) {
680                                 if (num_points_3rd < 1)
681                                         break;
682                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
683                                 double clutter_density = 0.0;   // percent of reflected wave
684                                 get_material_properties(materials[mat], clutter_height, clutter_density);
685                                 
686                                 double grad = fabs(itm_elev[last2+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
687                                 // First Fresnel radius
688                                 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) );
689                                 
690                                 
691                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
692                                 
693                                 double min_elev = SGMiscd::min(itm_elev[last2+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
694                                 double d1 = j * itm_elev[1];
695                                 if ( (itm_elev[last2+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
696                                         d1 = (num_points_3rd - j) * itm_elev[1];
697                                 }
698                                 double ray_height = (grad * d1) + min_elev;
699                                 
700                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
701                                 double intrusion = fabs(clearance);
702                                 
703                                 if (clearance >= 0) {
704                                         // no losses
705                                 }
706                                 else if (clearance < 0 && (intrusion < clutter_height)) {
707                                         
708                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
709                                 }
710                                 else if (clearance < 0 && (intrusion > clutter_height)) {
711                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
712                                 }
713                                 else {
714                                         // no losses
715                                 }
716                                 j++;
717                                 mat++;
718                                 
719                         }
720                         
721                 }
722         }
723         else if (p_mode == 2) {         //      troposcatter: ignore ground clutter for now...
724                 clutter_loss = 0.0;
725         }
726         
727 }
728
729 /***    Temporary material properties database
730 *               height: median clutter height
731 *               density: radiowave attenuation factor
732 ***/
733 void FGRadioTransmission::get_material_properties(string mat_name, double &height, double &density) {
734         
735         if(mat_name == "Landmass") {
736                 height = 15.0;
737                 density = 0.2;
738         }
739
740         else if(mat_name == "SomeSort") {
741                 height = 15.0;
742                 density = 0.2;
743         }
744
745         else if(mat_name == "Island") {
746                 height = 15.0;
747                 density = 0.2;
748         }
749         else if(mat_name == "Default") {
750                 height = 15.0;
751                 density = 0.2;
752         }
753         else if(mat_name == "EvergreenBroadCover") {
754                 height = 20.0;
755                 density = 0.2;
756         }
757         else if(mat_name == "EvergreenForest") {
758                 height = 20.0;
759                 density = 0.2;
760         }
761         else if(mat_name == "DeciduousBroadCover") {
762                 height = 15.0;
763                 density = 0.3;
764         }
765         else if(mat_name == "DeciduousForest") {
766                 height = 15.0;
767                 density = 0.3;
768         }
769         else if(mat_name == "MixedForestCover") {
770                 height = 20.0;
771                 density = 0.25;
772         }
773         else if(mat_name == "MixedForest") {
774                 height = 15.0;
775                 density = 0.25;
776         }
777         else if(mat_name == "RainForest") {
778                 height = 25.0;
779                 density = 0.55;
780         }
781         else if(mat_name == "EvergreenNeedleCover") {
782                 height = 15.0;
783                 density = 0.2;
784         }
785         else if(mat_name == "WoodedTundraCover") {
786                 height = 5.0;
787                 density = 0.15;
788         }
789         else if(mat_name == "DeciduousNeedleCover") {
790                 height = 5.0;
791                 density = 0.2;
792         }
793         else if(mat_name == "ScrubCover") {
794                 height = 3.0;
795                 density = 0.15;
796         }
797         else if(mat_name == "BuiltUpCover") {
798                 height = 30.0;
799                 density = 0.7;
800         }
801         else if(mat_name == "Urban") {
802                 height = 30.0;
803                 density = 0.7;
804         }
805         else if(mat_name == "Construction") {
806                 height = 30.0;
807                 density = 0.7;
808         }
809         else if(mat_name == "Industrial") {
810                 height = 30.0;
811                 density = 0.7;
812         }
813         else if(mat_name == "Port") {
814                 height = 30.0;
815                 density = 0.7;
816         }
817         else if(mat_name == "Town") {
818                 height = 10.0;
819                 density = 0.5;
820         }
821         else if(mat_name == "SubUrban") {
822                 height = 10.0;
823                 density = 0.5;
824         }
825         else if(mat_name == "CropWoodCover") {
826                 height = 10.0;
827                 density = 0.1;
828         }
829         else if(mat_name == "CropWood") {
830                 height = 10.0;
831                 density = 0.1;
832         }
833         else if(mat_name == "AgroForest") {
834                 height = 10.0;
835                 density = 0.1;
836         }
837         else {
838                 height = 0.0;
839                 density = 0.0;
840         }
841         
842 }
843
844 /*** implement simple LOS propagation model (WIP)
845 ***/
846 double FGRadioTransmission::LOS_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
847         double frq_mhz;
848         if( (freq < 118.0) || (freq > 137.0) )
849                 frq_mhz = 125.0;        // sane value, middle of bandplan
850         else
851                 frq_mhz = freq;
852         double dbloss;
853         double tx_pow = _transmitter_power;
854         double ant_gain = _rx_antenna_gain + _tx_antenna_gain;
855         double signal = 0.0;
856         
857         double sender_alt_ft,sender_alt;
858         double transmitter_height=0.0;
859         double receiver_height=0.0;
860         double own_lat = fgGetDouble("/position/latitude-deg");
861         double own_lon = fgGetDouble("/position/longitude-deg");
862         double own_alt_ft = fgGetDouble("/position/altitude-ft");
863         double own_alt= own_alt_ft * SG_FEET_TO_METER;
864         
865         
866         double link_budget = tx_pow - _receiver_sensitivity - _rx_line_losses - _tx_line_losses + ant_gain;     
867
868         //cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
869         
870         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
871         
872         SGGeod sender_pos = pos;
873         
874         sender_alt_ft = sender_pos.getElevationFt();
875         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
876         
877         receiver_height = own_alt;
878         transmitter_height = sender_alt;
879         
880         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
881         
882         
883         transmitter_height += _tx_antenna_height;
884         receiver_height += _rx_antenna_height;
885         
886         
887         /** radio horizon calculation with wave bending k=4/3 */
888         double receiver_horizon = 4.12 * sqrt(receiver_height);
889         double transmitter_horizon = 4.12 * sqrt(transmitter_height);
890         double total_horizon = receiver_horizon + transmitter_horizon;
891         
892         if (distance_m > total_horizon) {
893                 return -1;
894         }
895         double pol_loss = 0.0;
896         if (_polarization == 1) {
897                 pol_loss = polarization_loss();
898         }
899         // free-space loss (distance calculation should be changed)
900         dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
901         signal = link_budget - dbloss + pol_loss;
902         SG_LOG(SG_GENERAL, SG_BULK,
903                         "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm ");
904         //cerr << "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm " << endl;
905         return signal;
906         
907 }
908
909 /*** calculate loss due to polarization mismatch
910 *       this function is only reliable for vertical polarization
911 *       due to the V-shape of horizontally polarized antennas
912 ***/
913 double FGRadioTransmission::polarization_loss() {
914         
915         double theta_deg;
916         double roll = fgGetDouble("/orientation/roll-deg");
917         if (fabs(roll) > 85.0)
918                 roll = 85.0;
919         double pitch = fgGetDouble("/orientation/pitch-deg");
920         if (fabs(pitch) > 85.0)
921                 pitch = 85.0;
922         double theta = fabs( atan( sqrt( 
923                 pow(tan(roll * SGD_DEGREES_TO_RADIANS), 2) + 
924                 pow(tan(pitch * SGD_DEGREES_TO_RADIANS), 2) )) * SGD_RADIANS_TO_DEGREES);
925         
926         if (_polarization == 0)
927                 theta_deg = 90.0 - theta;
928         else
929                 theta_deg = theta;
930         if (theta_deg > 85.0)   // we don't want to converge into infinity
931                 theta_deg = 85.0;
932         
933         double loss = 10 * log10( pow(cos(theta_deg * SGD_DEGREES_TO_RADIANS), 2) );
934         //cerr << "Polarization loss: " << loss << " dBm " << endl;
935         return loss;
936 }
937
938
939 double FGRadioTransmission::watt_to_dbm(double power_watt) {
940         return 10 * log10(1000 * power_watt);   // returns dbm
941 }
942
943 double FGRadioTransmission::dbm_to_watt(double dbm) {
944         return exp( (dbm-30) * log(10) / 10);   // returns Watts
945 }
946
947 double FGRadioTransmission::dbm_to_microvolt(double dbm) {
948         return sqrt(dbm_to_watt(dbm) * 50) * 1000000;   // returns microvolts
949 }
950
951