]> git.mxchange.org Git - flightgear.git/blob - src/ATC/ground.cxx
emit to different message properties:
[flightgear.git] / src / ATC / ground.cxx
1 // FGGround - a class to provide ground control at larger airports.
2 //
3 // Written by David Luff, started March 2002.
4 //
5 // Copyright (C) 2002  David C. Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/misc/sg_path.hxx>
26 #include <simgear/math/sg_random.h>
27 #include <simgear/debug/logstream.hxx>
28 #include <simgear/misc/sgstream.hxx>
29 #include <simgear/constants.h>
30 #include <Main/globals.hxx>
31
32 #include <stdlib.h>
33 #include STL_FSTREAM
34
35 #include "ground.hxx"
36 #include "ATCmgr.hxx"
37 #include "ATCutils.hxx"
38 #include "ATCdisplay.hxx"
39 #include "AILocalTraffic.hxx"
40
41 SG_USING_STD(ifstream);
42 SG_USING_STD(cout);
43
44 node::node() {
45 }
46
47 node::~node() {
48         for(unsigned int i=0; i < arcs.size(); ++i) {
49                 delete arcs[i];
50         }
51 }
52
53 // Make sure that a_path.cost += distance is safe from the moment it's created.
54 a_path::a_path() {
55         cost = 0;
56 }
57
58 FGGround::FGGround() {
59         ATCmgr = globals->get_ATC_mgr();
60         _type = GROUND;
61         networkLoadOK = false;
62         ground_traffic.erase(ground_traffic.begin(), ground_traffic.end());
63         ground_traffic_itr = ground_traffic.begin();
64         
65         // Init the property nodes - TODO - need to make sure we're getting surface winds.
66         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
67         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
68         
69         // TODO - get the actual airport elevation
70         aptElev = 0.0;
71 }
72
73 FGGround::FGGround(const string& id) {
74         ATCmgr = globals->get_ATC_mgr();
75         networkLoadOK = false;
76         ground_traffic.erase(ground_traffic.begin(), ground_traffic.end());
77         ground_traffic_itr = ground_traffic.begin();
78         ident = id;
79         
80         // Init the property nodes - TODO - need to make sure we're getting surface winds.
81         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
82         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
83         
84         // TODO - get the actual airport elevation
85         aptElev = 0.0;
86 }
87
88 FGGround::~FGGround() {
89 }
90
91 void FGGround::ParseRwyExits(node* np, char* es) {
92         char* token;
93         char estr[20];
94         strcpy(estr, es);
95         const char delimiters[] = "-";
96         token = strtok(estr, delimiters);
97         while(token != NULL) {
98                 int i = atoi(token);
99                 //cout << "token = " << token << endl;
100                 //cout << "rwy number = " << i << endl;
101                 //runways[(atoi(token))].exits.push_back(np);
102                 runways[i].exits.push_back(np);
103                 //cout << "token = " << token << '\n';
104                 token = strtok(NULL, delimiters);
105         }
106 }
107         
108
109 // Load the ground logical network of the current instances airport
110 // Return true if successfull.
111 // TODO - currently the file is assumed to reside in the base/ATC directory.
112 // This might change to something more thought out in the future.
113 // NOTE - currently it is assumed that all nodes are loaded before any arcs.
114 // It won't work ATM if this doesn't hold true.
115 bool FGGround::LoadNetwork() {
116         node* np;
117         arc* ap;
118         Gate* gp;
119         
120         int gateCount = 0;      // This is used to allocate gateID's from zero upwards
121         // This may well change in the future - probably to reading in the real-world
122         // gate numbers from file.
123         
124         ifstream fin;
125         SGPath path = globals->get_fg_root();
126         //string taxiPath = "ATC/" + ident + ".taxi";
127         string taxiPath = "ATC/KEMT.taxi";      // FIXME - HARDWIRED FOR TESTING
128         path.append(taxiPath);
129         
130         SG_LOG(SG_ATC, SG_INFO, "Trying to read taxiway data for " << ident << "...");
131         //cout << "Trying to read taxiway data for " << ident << "..." << endl;
132         fin.open(path.c_str(), ios::in);
133         if(!fin) {
134                 SG_LOG(SG_ATC, SG_ALERT, "Unable to open taxiway data input file " << path.c_str());
135                 //cout << "Unable to open taxiway data input file " << path.c_str() << endl;
136                 return(false);
137         }
138         
139         char ch;
140         char buf[30];
141         while(!fin.eof()) {
142                 fin >> buf;
143                 // Node, arc, or [End]?
144                 //cout << "Read in ground network element type = " << buf << endl;
145                 if(!strcmp(buf, "[End]")) {             // TODO - maybe make this more robust to spelling errors by just looking for '['
146                         SG_LOG(SG_ATC, SG_INFO, "Done reading " << path.c_str() << endl);
147                         break;
148                 } else if(!strcmp(buf, "N")) {
149                         // Node
150                         np = new node;
151                         np->struct_type = NODE;
152                         fin >> buf;
153                         np->nodeID = atoi(buf);
154                         fin >> buf;
155                         np->pos.setlon(atof(buf));
156                         fin >> buf;
157                         np->pos.setlat(atof(buf));
158                         fin >> buf;
159                         np->pos.setelev(atof(buf));
160                         fin >> buf;             // node type
161                         if(!strcmp(buf, "J")) {
162                                 np->type = JUNCTION;
163                         } else if(!strcmp(buf, "T")) {
164                                 np->type = TJUNCTION;
165                         } else if(!strcmp(buf, "H")) {
166                                 np->type = HOLD;
167                         } else {
168                                 SG_LOG(SG_ATC, SG_ALERT, "**** ERROR ***** Unknown node type in taxi network...\n");
169                                 delete np;
170                                 return(false);
171                         }
172                         fin >> buf;             // rwy exit information - gets parsed later - FRAGILE - will break if buf is reused.
173                         // Now the name
174                         fin >> ch;      // strip the leading " off
175                         np->name = "";
176                         while(1) {
177                                 fin.unsetf(ios::skipws);
178                                 fin >> ch;
179                                 if((ch == '"') || (ch == 0x0A)) {
180                                         break;
181                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
182                                 np->name += ch;
183                         }
184                         fin.setf(ios::skipws);
185                         network.push_back(np);
186                         // FIXME - fragile - replies on buf not getting modified from exits read to here
187                         // see if we also need to push it onto the runway exit list
188                         //cout << "strlen(buf) = " << strlen(buf) << endl;
189                         if(strlen(buf) > 2) {
190                                 //cout << "Calling ParseRwyExits for " << buf << endl;
191                                 ParseRwyExits(np, buf);
192                         }
193                 } else if(!strcmp(buf, "A")) {
194                         ap = new arc;
195                         ap->struct_type = ARC;
196                         fin >> buf;
197                         ap->n1 = atoi(buf);
198                         fin >> buf;
199                         ap->n2 = atoi(buf);
200                         fin >> buf;
201                         if(!strcmp(buf, "R")) {
202                                 ap->type = RUNWAY;
203                         } else if(!strcmp(buf, "T")) {
204                                 ap->type = TAXIWAY;
205                         } else {
206                                 SG_LOG(SG_ATC, SG_ALERT, "**** ERROR ***** Unknown arc type in taxi network...\n");
207                                 delete ap;
208                                 return(false);
209                         }
210                         // directed?
211                         fin >> buf;
212                         if(!strcmp(buf, "Y")) {
213                                 ap->directed = true;
214                         } else if(!strcmp(buf, "N")) {
215                                 ap->directed = false;
216                         } else {
217                                 SG_LOG(SG_ATC, SG_ALERT, "**** ERROR ***** Unknown arc directed value in taxi network - should be Y/N !!!\n");
218                                 delete ap;
219                                 return(false);
220                         }                       
221                         // Now the name
222                         ap->name = "";
223                         while(1) {
224                                 fin.unsetf(ios::skipws);
225                                 fin >> ch;
226                                 ap->name += ch;
227                                 if((ch == '"') || (ch == 0x0A)) {
228                                         break;
229                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
230                         }
231                         fin.setf(ios::skipws);
232                         ap->distance = (int)dclGetHorizontalSeparation(network[ap->n1]->pos, network[ap->n2]->pos);
233                         //cout << "Distance  = " << ap->distance << '\n';
234                         network[ap->n1]->arcs.push_back(ap);
235                         network[ap->n2]->arcs.push_back(ap);
236                 } else if(!strcmp(buf, "G")) {
237                         gp = new Gate;
238                         gp->struct_type = NODE;
239                         gp->type = GATE;
240                         fin >> buf;
241                         gp->nodeID = atoi(buf);
242                         fin >> buf;
243                         gp->pos.setlon(atof(buf));
244                         fin >> buf;
245                         gp->pos.setlat(atof(buf));
246                         fin >> buf;
247                         gp->pos.setelev(atof(buf));
248                         fin >> buf;             // gate type - ignore this for now
249                         fin >> buf;             // gate heading
250                         gp->heading = atoi(buf);
251                         // Now the name
252                         gp->name = "";
253                         while(1) {
254                                 fin.unsetf(ios::skipws);
255                                 fin >> ch;
256                                 gp->name += ch;
257                                 if((ch == '"') || (ch == 0x0A)) {
258                                         break;
259                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
260                         }
261                         fin.setf(ios::skipws);
262                         gp->id = gateCount;             // Warning - this will likely change in the future.
263                         gp->used = false;
264                         network.push_back(gp);
265                         gates[gateCount] = gp;
266                         gateCount++;
267                 } else {
268                         // Something has gone seriously pear-shaped
269                         SG_LOG(SG_ATC, SG_ALERT, "********* ERROR - unknown ground network element type... aborting read of " << path.c_str() << '\n');
270                         return(false);
271                 }
272                 
273                 fin >> skipeol;         
274         }
275         return(true);
276 }
277
278 void FGGround::Init() {
279         untowered = false;
280         
281         // Figure out which is the active runway - TODO - it would be better to have ground call tower
282         // for runway operation details, but at the moment we can't guarantee that tower control at a given airport
283         // will be initialised before ground so we can't do that.
284         DoRwyDetails();
285         //cout << "In FGGround::Init, active rwy is " << activeRwy << '\n';
286         ortho.Init(rwy.threshold_pos, rwy.hdg);
287
288         networkLoadOK = LoadNetwork();
289 }
290
291 void FGGround::Update(double dt) {
292         // Each time step, what do we need to do?
293         // We need to go through the list of outstanding requests and acknowedgements
294         // and process at least one of them.
295         // We need to go through the list of planes under our control and check if
296         // any need to be addressed.
297         // We need to check for planes not under our control coming within our 
298         // control area and address if necessary.
299         
300         // Lets take the example of a plane which has just contacted ground
301         // following landing - presumably requesting where to go?
302         // First we need to establish the position of the plane within the logical network.
303         // Next we need to decide where its going.
304         
305         if(ground_traffic.size()) {
306                 if(ground_traffic_itr == ground_traffic.end()) {
307                         ground_traffic_itr = ground_traffic.begin();
308                 }
309                 
310                 //Process(*ground_traffic_itr);
311                 GroundRec* g = *ground_traffic_itr;
312                 if(g->taxiRequestOutstanding) {
313                         double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
314                         if(g->clearanceCounter > responseTime) {
315                                 // DO CLEARANCE
316                                 // TODO - move the mechanics of making up the transmission out of the main Update(...) routine.
317                                 string trns = "";
318                                 trns += g->plane.callsign;
319                                 trns += " taxi holding point runway ";  // TODO - add the holding point name
320                                 // eg " taxi holding point G2 runway "
321                                 trns += ConvertRwyNumToSpokenString(activeRwy);
322                                 if(_display) {
323                                         fgSetString("/sim/messages/ground", trns.c_str());
324                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
325                                 }
326                                 g->planePtr->RegisterTransmission(1);   // cleared to taxi
327                                 g->clearanceCounter = 0.0;
328                                 g->taxiRequestOutstanding = false;
329                         } else {
330                                 g->clearanceCounter += (dt * ground_traffic.size());
331                         }
332                 } else if(((FGAILocalTraffic*)(g->planePtr))->AtHoldShort()) {          // That's a hack - eventually we should monitor actual position
333                         // HACK ALERT - the automatic cast to AILocalTraffic has to go once we have other sorts working!!!!! FIXME TODO
334                         // NOTE - we don't need to do the contact tower bit unless we have separate tower and ground
335                         string trns = g->plane.callsign;
336                         trns += " contact Tower ";
337                         double f = globals->get_ATC_mgr()->GetFrequency(ident, TOWER) / 100.0;
338                         char buf[10];
339                         sprintf(buf, "%.2f", f);
340                         trns += buf;
341                         if(_display) {
342                                 fgSetString("/sim/messages/ground", trns.c_str());
343                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
344                         }
345                         g->planePtr->RegisterTransmission(2);   // contact tower
346                         delete *ground_traffic_itr;
347                         ground_traffic.erase(ground_traffic_itr);
348                         ground_traffic_itr = ground_traffic.begin();
349                 }                               
350                 ++ground_traffic_itr;
351         }
352         
353         // Call the base class update for the response time handling.
354         FGATC::Update(dt);
355 }
356
357 // Figure out which runways are active.
358 // For now we'll just be simple and do one active runway - eventually this will get much more complex
359 // Copied from FGTower - TODO - it would be better to implement this just once, and have ground call tower
360 // for runway operation details, but at the moment we can't guarantee that tower control at a given airport
361 // will be initialised before ground so we can't do that.
362 void FGGround::DoRwyDetails() {
363         //cout << "GetRwyDetails called" << endl;
364         
365         // Based on the airport-id and wind get the active runway
366         
367         //wind
368         double hdg = wind_from_hdg->getDoubleValue();
369         double speed = wind_speed_knots->getDoubleValue();
370         hdg = (speed == 0.0 ? 270.0 : hdg);
371         //cout << "Heading = " << hdg << '\n';
372         
373         FGRunway runway;
374         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
375         if(rwyGood) {
376                 activeRwy = runway._rwy_no;
377                 rwy.rwyID = runway._rwy_no;
378                 SG_LOG(SG_ATC, SG_INFO, "In FGGround, active runway for airport " << ident << " is " << activeRwy);
379                 
380                 // Get the threshold position
381                 double other_way = runway._heading - 180.0;
382                 while(other_way <= 0.0) {
383                         other_way += 360.0;
384                 }
385         // move to the +l end/center of the runway
386                 //cout << "Runway center is at " << runway._lon << ", " << runway._lat << '\n';
387         Point3D origin = Point3D(runway._lon, runway._lat, aptElev);
388                 Point3D ref = origin;
389         double tshlon, tshlat, tshr;
390                 double tolon, tolat, tor;
391                 rwy.length = runway._length * SG_FEET_TO_METER;
392         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
393                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
394         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway._heading, 
395                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
396                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
397                 // now copy what we need out of runway into rwy
398         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
399                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
400                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
401                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
402                 rwy.hdg = runway._heading;
403                 // Set the projection for the local area based on this active runway
404                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
405                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
406                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
407         } else {
408                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
409                 activeRwy = "NN";
410         }
411 }
412
413 // Return a random gate ID of an unused gate.
414 // Two error values may be returned and must be checked for by the calling function:
415 // -2 signifies that no gates exist at this airport.
416 // -1 signifies that all gates are currently full.
417 int FGGround::GetRandomGateID() {
418         // Check that this airport actually has some gates!!
419         if(!gates.size()) {
420                 return(-2);
421         }
422
423         gate_vec_type gateVec;
424         int num = 0;
425         int thenum;
426         int ID;
427         
428         gatesItr = gates.begin();
429         while(gatesItr != gates.end()) {
430                 if((gatesItr->second)->used == false) {
431                         gateVec.push_back(gatesItr->second);
432                         num++;
433                 }
434                 ++gatesItr;
435         }
436
437         // Check that there are some unused gates!
438         if(!gateVec.size()) {
439                 return(-1);
440         }
441         
442         // Randomly select one from the list
443         sg_srandom_time();
444         thenum = (int)(sg_random() * gateVec.size());
445         ID = gateVec[thenum]->id;
446         
447         return(ID);
448 }
449
450 // Return a pointer to an unused gate node
451 Gate* FGGround::GetGateNode() {
452         int id = GetRandomGateID();
453         if(id < 0) {
454                 return(NULL);
455         } else {
456                 return(gates[id]);
457         }
458 }
459
460
461 node* FGGround::GetHoldShortNode(const string& rwyID) {
462         return(NULL);   // TODO - either implement me or remove me!!!
463 }
464
465
466 // WARNING - This is hardwired to my prototype logical network format
467 // and will almost certainly change when Bernie's stuff comes on-line.
468 // Returns NULL if it can't find a valid node.
469 node* FGGround::GetThresholdNode(const string& rwyID) {
470         // For now go through all the nodes and parse their names
471         // Maybe in the future we'll map threshold nodes by ID
472         //cout << "Size of network is " << network.size() << '\n';
473         for(unsigned int i=0; i<network.size(); ++i) {
474                 //cout << "Name = " << network[i]->name << '\n';
475                 if(network[i]->name.size()) {
476                         string s = network[i]->name;
477                         // Warning - the next bit is fragile and dependent on my current naming scheme
478                         //cout << "substr = " << s.substr(0,3) << '\n';
479                         //cout << "size of s = " << s.size() << '\n'; 
480                         if(s.substr(0,3) == "rwy") {
481                                 //cout << "subsubstr = " << s.substr(4, s.size() - 4) << '\n';
482                                 if(s.substr(4, s.size() - 4) == rwyID) {
483                                         return network[i];
484                                 }
485                         }
486                 }
487         }
488         return NULL;
489 }
490
491
492 // Get a path from a point on a runway to a gate
493 // TODO !!
494
495 // Get a path from a node to another node
496 // Eventually we will need complex algorithms for this taking other traffic,
497 // shortest path and suitable paths into accout.
498 // For now we'll just call the shortest path algorithm.
499 ground_network_path_type FGGround::GetPath(node* A, node* B) {  
500         return(GetShortestPath(A, B));
501 };
502
503 // Get a path from a node to a runway threshold
504 ground_network_path_type FGGround::GetPath(node* A, const string& rwyID) {
505         node* b = GetThresholdNode(rwyID);
506         if(b == NULL) {
507                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - unable to find path to runway theshold in ground.cxx for airport " << ident << '\n');
508                 ground_network_path_type emptyPath;
509                 emptyPath.erase(emptyPath.begin(), emptyPath.end());
510                 return(emptyPath);
511         }
512         return GetShortestPath(A, b);
513 }
514
515 // Get a path from a node to a runway hold short point
516 // Bit of a hack this at the moment!
517 ground_network_path_type FGGround::GetPathToHoldShort(node* A, const string& rwyID) {
518         ground_network_path_type path = GetPath(A, rwyID);
519         path.pop_back();        // That should be the threshold stripped of 
520         path.pop_back();        // and that should be the arc from hold short to threshold
521         // This isn't robust though - TODO - implement properly!
522         return(path);
523 }
524
525 // A shortest path algorithm from memory (ie. I can't find the bl&*dy book again!)
526 // I'm sure there must be enchancements that we can make to this, such as biasing the
527 // order in which the nodes are searched out from in favour of those geographically
528 // closer to the destination.
529 // Note that we are working with the master set of nodes and arcs so we mustn't change
530 // or delete them -  we only delete the paths that we create during the algorithm.
531 ground_network_path_type FGGround::GetShortestPath(node* A, node* B) {
532         a_path* pathPtr;
533         shortest_path_map_type pathMap;
534         node_array_type nodesLeft;
535         
536         // Debugging check
537         int pathsCreated = 0;
538         
539         // Initialise the algorithm
540         nodesLeft.push_back(A);
541         pathPtr = new a_path;
542         pathsCreated++;
543         pathPtr->path.push_back(A);
544         pathPtr->cost = 0;
545         pathMap[A->nodeID] = pathPtr;
546         bool solution_found = false;    // Flag to indicate that at least one candidate path has been found
547         int solution_cost = -1;                 // Cost of current best cost solution.  -1 indicates no solution found yet.
548         a_path solution_path;           
549                                                                                         
550         node* nPtr;     // nPtr is used to point to the node we are currently working with
551         
552         while(nodesLeft.size()) {
553                 //cout << "\n*****nodesLeft*****\n";
554                 //for(unsigned int i=0; i<nodesLeft.size(); ++i) {
555                         //cout << nodesLeft[i]->nodeID << '\n';
556                 //}
557                 //cout << "*******************\n\n";
558                 nPtr = *nodesLeft.begin();              // Thought - definate optimization possibilities here in the choice of which nodes we process first.
559                 nodesLeft.erase(nodesLeft.begin());
560                 //cout << "Walking out from node " << nPtr->nodeID << '\n';
561                 for(unsigned int i=0; i<nPtr->arcs.size(); ++i) {
562                         //cout << "ARC TO " << ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1) << '\n';
563                 }
564                 if((solution_found) && (solution_cost <= pathMap[nPtr->nodeID]->cost)) {
565                         // Do nothing - we've already found a solution and this partial path is already more expensive
566                 } else {
567                         // This path could still be better than the current solution - check it out
568                         for(unsigned int i=0; i<(nPtr->arcs.size()); i++) {
569                                 // Map the new path against the end node, ie. *not* the one we just started with.
570                                 unsigned int end_nodeID = ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1);
571                                 //cout << "end_nodeID = " << end_nodeID << '\n';
572                                 //cout << "pathMap size is " << pathMap.size() << '\n';
573                                 if(end_nodeID == nPtr->nodeID) {
574                                         //cout << "Circular arc!\n";
575                                         // Then its a circular arc - don't bother!!
576                                         //nPtr->arcs.erase(nPtr->arcs.begin() + i);
577                                 } else {
578                                         // see if the end node is already in the map or not
579                                         if(pathMap.find(end_nodeID) == pathMap.end()) {
580                                                 //cout << "Not in the map" << endl;;
581                                                 // Not in the map - easy!
582                                                 pathPtr = new a_path;
583                                                 pathsCreated++;
584                                                 *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
585                                                 pathPtr->path.push_back(nPtr->arcs[i]);
586                                                 pathPtr->path.push_back(network[end_nodeID]);
587                                                 pathPtr->cost += nPtr->arcs[i]->distance;
588                                                 pathMap[end_nodeID] = pathPtr;
589                                                 nodesLeft.push_back(network[end_nodeID]);       // By definition this can't be in the list already, or
590                                                 // it would also have been in the map and hence OR'd with this one.
591                                                 if(end_nodeID == B->nodeID) {
592                                                         //cout << "Solution found!!!" << endl;
593                                                         // Since this node wasn't in the map this is by definition the first solution
594                                                         solution_cost = pathPtr->cost;
595                                                         solution_path = *pathPtr;
596                                                         solution_found = true;
597                                                 }
598                                         } else {
599                                                 //cout << "Already in the map" << endl;
600                                                 // In the map - not so easy - need to get rid of an arc from the higher cost one.
601                                                 //cout << "Current cost of node " << end_nodeID << " is " << pathMap[end_nodeID]->cost << endl;
602                                                 int newCost = pathMap[nPtr->nodeID]->cost + nPtr->arcs[i]->distance;
603                                                 //cout << "New cost is of node " << nPtr->nodeID << " is " << newCost << endl;
604                                                 if(newCost >= pathMap[end_nodeID]->cost) {
605                                                         // No need to do anything.
606                                                         //cout << "Not doing anything!" << endl;
607                                                 } else {
608                                                         delete pathMap[end_nodeID];
609                                                         pathsCreated--;
610                                                         
611                                                         pathPtr = new a_path;
612                                                         pathsCreated++;
613                                                         *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
614                                                         pathPtr->path.push_back(nPtr->arcs[i]);
615                                                         pathPtr->path.push_back(network[end_nodeID]);
616                                                         pathPtr->cost += nPtr->arcs[i]->distance;
617                                                         pathMap[end_nodeID] = pathPtr;
618                                                         
619                                                         // We need to add this node to the list-to-do again to force a recalculation 
620                                                         // onwards from this node with the new lower cost to node cost.
621                                                         nodesLeft.push_back(network[end_nodeID]);
622                                                         
623                                                         if(end_nodeID == B->nodeID) {
624                                                                 //cout << "Solution found!!!" << endl;
625                                                                 // Need to check if there is a previous better solution
626                                                                 if((solution_cost < 0) || (pathPtr->cost < solution_cost)) {
627                                                                         solution_cost = pathPtr->cost;
628                                                                         solution_path = *pathPtr;
629                                                                         solution_found = true;
630                                                                 }
631                                                         }
632                                                 }
633                                         }
634                                 }
635                         }
636                 }
637         }
638         
639         // delete all the paths before returning
640         shortest_path_map_iterator spItr = pathMap.begin();
641         while(spItr != pathMap.end()) {
642                 if(spItr->second != NULL) {
643                         delete spItr->second;
644                         --pathsCreated;
645                 }
646                 ++spItr;
647         }
648         
649         //cout << "pathsCreated = " << pathsCreated << '\n';
650         if(pathsCreated > 0) {
651                 SG_LOG(SG_ATC, SG_ALERT, "WARNING - Possible memory leak in FGGround::GetShortestPath\n\
652                                                                           Please report to flightgear-devel@flightgear.org\n");
653         }
654         
655         //cout << (solution_found ? "Result: solution found\n" : "Result: no solution found\n");
656         return(solution_path.path);             // TODO - we really ought to have a fallback position incase a solution isn't found.
657 }
658                 
659
660
661 // Randomly or otherwise populate some of the gates with parked planes
662 // (might eventually be done by the AIMgr if and when lots of AI traffic is generated)
663
664 // Return a list of exits from a given runway
665 // It is up to the calling function to check for non-zero size of returned array before use
666 node_array_type FGGround::GetExits(const string& rwyID) {
667         // FIXME - get a 07L or similar in here and we're stuffed!!!
668         return(runways[atoi(rwyID.c_str())].exits);
669 }
670
671 void FGGround::RequestDeparture(const PlaneRec& plane, FGAIEntity* requestee) {
672         // For now we'll just automatically clear all planes to the runway hold.
673         // This communication needs to be delayed 20 sec or so from receiving the request.
674         // Even if display=false we still need to start the timer in case display=true when communication starts.
675         // We also need to bear in mind we also might have other outstanding communications, although for now we'll punt that issue!
676         // FIXME - sort the above!
677         
678         // HACK - assume that anything requesting departure is new for now - FIXME LATER
679         GroundRec* g = new GroundRec;
680         g->plane = plane;
681         g->planePtr = requestee;
682         g->taxiRequestOutstanding = true;
683         g->clearanceCounter = 0;
684         g->cleared = false;
685         g->incoming = false;
686         // TODO - need to handle the next 3 as well
687     //Point3D current_pos;
688     //node* destination;
689     //node* last_clearance;
690         
691         ground_traffic.push_back(g);
692 }
693
694 #if 0
695 void FGGround::NewArrival(plane_rec plane) {
696         // What are we going to do here?
697         // We need to start a new ground_rec and add the plane_rec to it
698         // We need to decide what gate we are going to clear it to.
699         // Then we need to add clearing it to that gate to the pending transmissions queue? - or simply transmit?
700         // Probably simply transmit for now and think about a transmission queue later if we need one.
701         // We might need one though in order to add a little delay for response time.
702         ground_rec* g = new ground_rec;
703         g->plane_rec = plane;
704         g->current_pos = ConvertWGS84ToXY(plane.pos);
705         g->node = GetNode(g->current_pos);  // TODO - might need to sort out node/arc here
706         AssignGate(g);
707         g->cleared = false;
708         ground_traffic.push_back(g);
709         NextClearance(g);
710 }
711
712 void FGGround::NewContact(plane_rec plane) {
713         // This is a bit of a convienience function at the moment and is likely to change.
714         if(at a gate or apron)
715                 NewDeparture(plane);
716         else
717                 NewArrival(plane);
718 }
719
720 void FGGround::NextClearance(ground_rec &g) {
721         // Need to work out where we can clear g to.
722         // Assume the pilot doesn't need progressive instructions
723         // We *should* already have a gate or holding point assigned by the time we get here
724         // but it wouldn't do any harm to check.
725         
726         // For now though we will hardwire it to clear to the final destination.
727 }
728
729 void FGGround::AssignGate(ground_rec &g) {
730         // We'll cheat for now - since we only have the user's aircraft and a couple of airports implemented
731         // we'll hardwire the gate!
732         // In the long run the logic of which gate or area to send the plane to could be somewhat non-trivial.
733 }
734 #endif //0
735