]> git.mxchange.org Git - flightgear.git/blob - src/ATC/ground.cxx
Modified slightly whilst developing the shortest-path algorithm in the ground code...
[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 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/math/sg_random.h>
23 #include <simgear/debug/logstream.hxx>
24 #include <simgear/misc/sgstream.hxx>
25 #include <simgear/constants.h>
26 #include <Main/globals.hxx>
27
28 #include <stdlib.h>
29 #include STL_FSTREAM
30
31 #include "ground.hxx"
32 #include "ATCutils.hxx"
33
34 SG_USING_STD(ifstream);
35 SG_USING_STD(cout);
36
37 node::node() {
38 }
39
40 node::~node() {
41         for(unsigned int i=0; i < arcs.size(); ++i) {
42                 delete arcs[i];
43         }
44 }
45
46 // Make sure that a_path.cost += distance is safe from the moment it's created.
47 a_path::a_path() {
48         cost = 0;
49 }
50
51 FGGround::FGGround() {
52         display = false;
53         networkLoadOK = false;
54 }
55
56 FGGround::~FGGround() {
57 }
58
59 void FGGround::ParseRwyExits(node* np, char* es) {
60         char* token;
61         char estr[20];
62         strcpy(estr, es);
63         const char delimiters[] = "-";
64         token = strtok(estr, delimiters);
65         while(token != NULL) {
66                 int i = atoi(token);
67                 //cout << "token = " << token << endl;
68                 //cout << "rwy number = " << i << endl;
69                 //runways[(atoi(token))].exits.push_back(np);
70                 runways[i].exits.push_back(np);
71                 //cout << "token = " << token << '\n';
72                 token = strtok(NULL, delimiters);
73         }
74 }
75         
76
77 // Load the ground logical network of the current instances airport
78 // Return true if successfull.
79 // TODO - currently the file is assumed to reside in the base/ATC directory.
80 // This might change to something more thought out in the future.
81 // NOTE - currently it is assumed that all nodes are loaded before any arcs.
82 // It won't work ATM if this doesn't hold true.
83 bool FGGround::LoadNetwork() {
84         node* np;
85         arc* ap;
86         Gate* gp;
87         
88         int gateCount = 0;      // This is used to allocate gateID's from zero upwards
89         // This may well change in the future - probably to reading in the real-world
90         // gate numbers from file.
91         
92         ifstream fin;
93         SGPath path = globals->get_fg_root();
94         //string taxiPath = "ATC/" + ident + ".taxi";
95         string taxiPath = "ATC/KEMT.taxi";      // FIXME - HARDWIRED FOR TESTING
96         path.append(taxiPath);
97         
98         SG_LOG(SG_GENERAL, SG_INFO, "Trying to read taxiway data for " << ident << "...");
99         //cout << "Trying to read taxiway data for " << ident << "..." << endl;
100         fin.open(path.c_str(), ios::in);
101         if(!fin) {
102                 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to open taxiway data input file " << path.c_str());
103                 //cout << "Unable to open taxiway data input file " << path.c_str() << endl;
104                 return(false);
105         }
106         
107         char ch;
108         char buf[30];
109         while(!fin.eof()) {
110                 fin >> buf;
111                 // Node, arc, or [End]?
112                 //cout << "Read in ground network element type = " << buf << endl;
113                 if(!strcmp(buf, "[End]")) {             // TODO - maybe make this more robust to spelling errors by just looking for '['
114                         SG_LOG(SG_GENERAL, SG_INFO, "Done reading " << path.c_str() << endl);
115                         break;
116                 } else if(!strcmp(buf, "N")) {
117                         // Node
118                         np = new node;
119                         np->struct_type = NODE;
120                         fin >> buf;
121                         np->nodeID = atoi(buf);
122                         fin >> buf;
123                         np->pos.setlon(atof(buf));
124                         fin >> buf;
125                         np->pos.setlat(atof(buf));
126                         fin >> buf;
127                         np->pos.setelev(atof(buf));
128                         fin >> buf;             // node type
129                         if(!strcmp(buf, "J")) {
130                                 np->type = JUNCTION;
131                         } else if(!strcmp(buf, "T")) {
132                                 np->type = TJUNCTION;
133                         } else if(!strcmp(buf, "H")) {
134                                 np->type = HOLD;
135                         } else {
136                                 cout << "**** ERROR ***** Unknown node type in taxi network...\n";
137                                 delete np;
138                                 return(false);
139                         }
140                         fin >> buf;             // rwy exit information - gets parsed later - FRAGILE - will break if buf is reused.
141                         // Now the name
142                         np->name = "";
143                         while(1) {
144                                 fin.unsetf(ios::skipws);
145                                 fin >> ch;
146                                 np->name += ch;
147                                 if((ch == '"') || (ch == 0x0A)) {
148                                         break;
149                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
150                         }
151                         fin.setf(ios::skipws);
152                         network.push_back(np);
153                         // FIXME - fragile - replies on buf not getting modified from exits read to here
154                         // see if we also need to push it onto the runway exit list
155                         cout << "strlen(buf) = " << strlen(buf) << endl;
156                         if(strlen(buf) > 2) {
157                                 cout << "Calling ParseRwyExits for " << buf << endl;
158                                 ParseRwyExits(np, buf);
159                         }
160                 } else if(!strcmp(buf, "A")) {
161                         ap = new arc;
162                         ap->struct_type = ARC;
163                         fin >> buf;
164                         ap->n1 = atoi(buf);
165                         fin >> buf;
166                         ap->n2 = atoi(buf);
167                         fin >> buf;
168                         if(!strcmp(buf, "R")) {
169                                 ap->type = RUNWAY;
170                         } else if(!strcmp(buf, "T")) {
171                                 ap->type = TAXIWAY;
172                         } else {
173                                 cout << "**** ERROR ***** Unknown arc type in taxi network...\n";
174                                 delete ap;
175                                 return(false);
176                         }
177                         // directed?
178                         fin >> buf;
179                         if(!strcmp(buf, "Y")) {
180                                 ap->directed = true;
181                         } else if(!strcmp(buf, "N")) {
182                                 ap->directed = false;
183                         } else {
184                                 cout << "**** ERROR ***** Unknown arc directed value in taxi network - should be Y/N !!!\n";
185                                 delete ap;
186                                 return(false);
187                         }                       
188                         // Now the name
189                         ap->name = "";
190                         while(1) {
191                                 fin.unsetf(ios::skipws);
192                                 fin >> ch;
193                                 ap->name += ch;
194                                 if((ch == '"') || (ch == 0x0A)) {
195                                         break;
196                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
197                         }
198                         fin.setf(ios::skipws);
199                         ap->distance = (int)dclGetHorizontalSeparation(network[ap->n1]->pos, network[ap->n2]->pos);
200                         cout << "Distance  = " << ap->distance << '\n';
201                         network[ap->n1]->arcs.push_back(ap);
202                         network[ap->n2]->arcs.push_back(ap);
203                 } else if(!strcmp(buf, "G")) {
204                         gp = new Gate;
205                         gp->struct_type = NODE;
206                         gp->type = GATE;
207                         fin >> buf;
208                         gp->nodeID = atoi(buf);
209                         fin >> buf;
210                         gp->pos.setlon(atof(buf));
211                         fin >> buf;
212                         gp->pos.setlat(atof(buf));
213                         fin >> buf;
214                         gp->pos.setelev(atof(buf));
215                         fin >> buf;             // gate type - ignore this for now
216                         fin >> buf;             // gate heading
217                         gp->heading = atoi(buf);
218                         // Now the name
219                         gp->name = "";
220                         while(1) {
221                                 fin.unsetf(ios::skipws);
222                                 fin >> ch;
223                                 gp->name += ch;
224                                 if((ch == '"') || (ch == 0x0A)) {
225                                         break;
226                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
227                         }
228                         fin.setf(ios::skipws);
229                         gp->id = gateCount;             // Warning - this will likely change in the future.
230                         gp->used = false;
231                         network.push_back(gp);
232                         gates[gateCount] = gp;
233                         gateCount++;
234                 } else {
235                         // Something has gone seriously pear-shaped
236                         cout << "********* ERROR - unknown ground network element type... aborting read of " << path.c_str() << '\n';
237                         return(false);
238                 }
239                 
240                 fin >> skipeol;         
241         }
242         return(true);
243 }
244
245 void FGGround::Init() {
246         display = false;
247         
248         // For now we'll hardwire the threshold end
249         Point3D P010(-118.037483, 34.081358, 296 * SG_FEET_TO_METER);
250         double hdg = 25.32;
251         ortho.Init(P010, hdg);
252         
253         networkLoadOK = LoadNetwork();
254 }
255
256 void FGGround::Update() {
257         // Each time step, what do we need to do?
258         // We need to go through the list of outstanding requests and acknowedgements
259         // and process at least one of them.
260         // We need to go through the list of planes under our control and check if
261         // any need to be addressed.
262         // We need to check for planes not under our control coming within our 
263         // control area and address if necessary.
264         
265         // Lets take the example of a plane which has just contacted ground
266         // following landing - presumably requesting where to go?
267         // First we need to establish the position of the plane within the logical network.
268         // Next we need to decide where its going. 
269 }
270
271 // Return a random gate ID of an unused gate.
272 // Two error values may be returned and must be checked for by the calling function:
273 // -2 signifies that no gates exist at this airport.
274 // -1 signifies that all gates are currently full.
275 int FGGround::GetRandomGateID() {
276         // Check that this airport actually has some gates!!
277         if(!gates.size()) {
278                 return(-2);
279         }
280
281         gate_vec_type gateVec;
282         int num = 0;
283         int thenum;
284         int ID;
285         
286         gatesItr = gates.begin();
287         while(gatesItr != gates.end()) {
288                 if((gatesItr->second)->used == false) {
289                         gateVec.push_back(gatesItr->second);
290                         num++;
291                 }
292                 ++gatesItr;
293         }
294
295         // Check that there are some unused gates!
296         if(!gateVec.size()) {
297                 return(-1);
298         }
299         
300         // Randomly select one from the list
301         sg_srandom_time();
302         thenum = (int)(sg_random() * gateVec.size());
303         ID = gateVec[thenum]->id;
304         
305         return(ID);
306 }
307
308 // Return a pointer to an unused gate node
309 Gate* FGGround::GetGateNode() {
310         int id = GetRandomGateID();
311         if(id < 0) {
312                 return(NULL);
313         } else {
314                 return(gates[id]);
315         }
316 }
317
318 // Get a path from a point on a runway to a gate
319 // TODO !!
320
321 // Get a path from a node to another node
322 // Eventually we will need complex algorithms for this taking other traffic,
323 // shortest path and suitable paths into accout.
324 // For now we'll just call the shortest path algorithm.
325 ground_network_path_type FGGround::GetPath(node* A, node* B) {  
326         return(GetShortestPath(A, B));
327 };
328
329
330 // A shortest path algorithm from memory (ie. I can't find the bl&*dy book again!)
331 // I'm sure there must be enchancements that we can make to this, such as biasing the
332 // order in which the nodes are searched out from in favour of those geographically
333 // closer to the destination.
334 // Note that we are working with the master set of nodes and arcs so we mustn't change
335 // or delete them -  we only delete the paths that we create during the algorithm.
336 ground_network_path_type FGGround::GetShortestPath(node* A, node* B) {
337         a_path* pathPtr;
338         shortest_path_map_type pathMap;
339         node_array_type nodesLeft;
340         
341         // Debugging check
342         int pathsCreated = 0;
343         
344         // Initialise the algorithm
345         nodesLeft.push_back(A);
346         pathPtr = new a_path;
347         pathsCreated++;
348         pathPtr->path.push_back(A);
349         pathPtr->cost = 0;
350         pathMap[A->nodeID] = pathPtr;
351         bool solution_found = false;    // Flag to indicate that at least one candidate path has been found
352         int solution_cost = -1;                 // Cost of current best cost solution.  -1 indicates no solution found yet.
353         a_path solution_path;           
354                                                                                         
355         node* nPtr;     // nPtr is used to point to the node we are currently working with
356         
357         while(nodesLeft.size()) {
358                 //cout << "\n*****nodesLeft*****\n";
359                 //for(unsigned int i=0; i<nodesLeft.size(); ++i) {
360                         //cout << nodesLeft[i]->nodeID << '\n';
361                 //}
362                 //cout << "*******************\n\n";
363                 nPtr = *nodesLeft.begin();              // Thought - definate optimization possibilities here in the choice of which nodes we process first.
364                 nodesLeft.erase(nodesLeft.begin());
365                 //cout << "Walking out from node " << nPtr->nodeID << '\n';
366                 for(unsigned int i=0; i<nPtr->arcs.size(); ++i) {
367                         //cout << "ARC TO " << ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1) << '\n';
368                 }
369                 if((solution_found) && (solution_cost <= pathMap[nPtr->nodeID]->cost)) {
370                         // Do nothing - we've already found a solution and this partial path is already more expensive
371                 } else {
372                         // This path could still be better than the current solution - check it out
373                         for(unsigned int i=0; i<(nPtr->arcs.size()); i++) {
374                                 // Map the new path against the end node, ie. *not* the one we just started with.
375                                 unsigned int end_nodeID = ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1);
376                                 //cout << "end_nodeID = " << end_nodeID << '\n';
377                                 //cout << "pathMap size is " << pathMap.size() << '\n';
378                                 if(end_nodeID == nPtr->nodeID) {
379                                         //cout << "Circular arc!\n";
380                                         // Then its a circular arc - don't bother!!
381                                         //nPtr->arcs.erase(nPtr->arcs.begin() + i);
382                                 } else {
383                                         // see if the end node is already in the map or not
384                                         if(pathMap.find(end_nodeID) == pathMap.end()) {
385                                                 //cout << "Not in the map" << endl;;
386                                                 // Not in the map - easy!
387                                                 pathPtr = new a_path;
388                                                 pathsCreated++;
389                                                 *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
390                                                 pathPtr->path.push_back(nPtr->arcs[i]);
391                                                 pathPtr->path.push_back(network[end_nodeID]);
392                                                 pathPtr->cost += nPtr->arcs[i]->distance;
393                                                 pathMap[end_nodeID] = pathPtr;
394                                                 nodesLeft.push_back(network[end_nodeID]);       // By definition this can't be in the list already, or
395                                                 // it would also have been in the map and hence OR'd with this one.
396                                                 if(end_nodeID == B->nodeID) {
397                                                         //cout << "Solution found!!!" << endl;
398                                                         // Since this node wasn't in the map this is by definition the first solution
399                                                         solution_cost = pathPtr->cost;
400                                                         solution_path = *pathPtr;
401                                                         solution_found = true;
402                                                 }
403                                         } else {
404                                                 //cout << "Already in the map" << endl;
405                                                 // In the map - not so easy - need to get rid of an arc from the higher cost one.
406                                                 //cout << "Current cost of node " << end_nodeID << " is " << pathMap[end_nodeID]->cost << endl;
407                                                 int newCost = pathMap[nPtr->nodeID]->cost + nPtr->arcs[i]->distance;
408                                                 //cout << "New cost is of node " << nPtr->nodeID << " is " << newCost << endl;
409                                                 if(newCost >= pathMap[end_nodeID]->cost) {
410                                                         // No need to do anything.
411                                                         //cout << "Not doing anything!" << endl;
412                                                 } else {
413                                                         delete pathMap[end_nodeID];
414                                                         pathsCreated--;
415                                                         
416                                                         pathPtr = new a_path;
417                                                         pathsCreated++;
418                                                         *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
419                                                         pathPtr->path.push_back(nPtr->arcs[i]);
420                                                         pathPtr->path.push_back(network[end_nodeID]);
421                                                         pathPtr->cost += nPtr->arcs[i]->distance;
422                                                         pathMap[end_nodeID] = pathPtr;
423                                                         
424                                                         // We need to add this node to the list-to-do again to force a recalculation 
425                                                         // onwards from this node with the new lower cost to node cost.
426                                                         nodesLeft.push_back(network[end_nodeID]);
427                                                         
428                                                         if(end_nodeID == B->nodeID) {
429                                                                 //cout << "Solution found!!!" << endl;
430                                                                 // Need to check if there is a previous better solution
431                                                                 if((solution_cost < 0) || (pathPtr->cost < solution_cost)) {
432                                                                         solution_cost = pathPtr->cost;
433                                                                         solution_path = *pathPtr;
434                                                                         solution_found = true;
435                                                                 }
436                                                         }
437                                                 }
438                                         }
439                                 }
440                         }
441                 }
442         }
443         
444         // delete all the paths before returning
445         shortest_path_map_iterator spItr = pathMap.begin();
446         while(spItr != pathMap.end()) {
447                 if(spItr->second != NULL) {
448                         delete spItr->second;
449                         --pathsCreated;
450                 }
451                 ++spItr;
452         }
453         
454         //cout << "pathsCreated = " << pathsCreated << '\n';
455         if(pathsCreated > 0) {
456                 SG_LOG(SG_GENERAL, SG_ALERT, "WARNING - Possible memory leak in FGGround::GetShortestPath\n\
457                                                                           Please report to flightgear-devel@flightgear.org\n");
458         }
459         
460         //cout << (solution_found ? "Result: solution found\n" : "Result: no solution found\n");
461         return(solution_path.path);             // TODO - we really ought to have a fallback position incase a solution isn't found.
462 }
463                 
464
465
466 // Randomly or otherwise populate some of the gates with parked planes
467 // (might eventually be done by the AIMgr if and when lots of AI traffic is generated)
468
469 // Return a list of exits from a given runway
470 // It is up to the calling function to check for non-zero size of returned array before use
471 node_array_type FGGround::GetExits(int rwyID) {
472         return(runways[rwyID].exits);
473 }
474
475 #if 0
476 void FGGround::NewArrival(plane_rec plane) {
477         // What are we going to do here?
478         // We need to start a new ground_rec and add the plane_rec to it
479         // We need to decide what gate we are going to clear it to.
480         // Then we need to add clearing it to that gate to the pending transmissions queue? - or simply transmit?
481         // Probably simply transmit for now and think about a transmission queue later if we need one.
482         // We might need one though in order to add a little delay for response time.
483         ground_rec* g = new ground_rec;
484         g->plane_rec = plane;
485         g->current_pos = ConvertWGS84ToXY(plane.pos);
486         g->node = GetNode(g->current_pos);  // TODO - might need to sort out node/arc here
487         AssignGate(g);
488         g->cleared = false;
489         ground_traffic.push_back(g);
490         NextClearance(g);
491 }
492
493 void FGGround::NewContact(plane_rec plane) {
494         // This is a bit of a convienience function at the moment and is likely to change.
495         if(at a gate or apron)
496                 NewDeparture(plane);
497         else
498                 NewArrival(plane);
499 }
500
501 void FGGround::NextClearance(ground_rec &g) {
502         // Need to work out where we can clear g to.
503         // Assume the pilot doesn't need progressive instructions
504         // We *should* already have a gate or holding point assigned by the time we get here
505         // but it wouldn't do any harm to check.
506         
507         // For now though we will hardwire it to clear to the final destination.
508 }
509
510 void FGGround::AssignGate(ground_rec &g) {
511         // We'll cheat for now - since we only have the user's aircraft and a couple of airports implemented
512         // we'll hardwire the gate!
513         // In the long run the logic of which gate or area to send the plane to could be somewhat non-trivial.
514 }
515 #endif //0
516