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