1 // NasalPositioned.cxx -- expose FGPositioned classes to Nasal
3 // Written by James Turner, started 2012.
5 // Copyright (C) 2012 James Turner
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include "NasalPositioned.hxx"
29 #include <boost/foreach.hpp>
31 #include <simgear/scene/material/mat.hxx>
32 #include <simgear/magvar/magvar.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/bucket/newbucket.hxx>
36 #include <Airports/runways.hxx>
37 #include <Airports/simple.hxx>
38 #include <Airports/dynamics.hxx>
39 #include <Airports/parking.hxx>
40 #include <Navaids/navlist.hxx>
41 #include <Navaids/procedure.hxx>
42 #include <Main/globals.hxx>
43 #include <Main/fg_props.hxx>
44 #include <Scenery/scenery.hxx>
45 #include <ATC/CommStation.hxx>
46 #include <Navaids/route.hxx>
47 #include <Autopilot/route_mgr.hxx>
48 #include <Navaids/procedure.hxx>
50 static void positionedGhostDestroy(void* g);
51 static void wayptGhostDestroy(void* g);
52 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
53 naGhostType WayptGhostType = { wayptGhostDestroy, "waypoint" };
55 static void hashset(naContext c, naRef hash, const char* key, naRef val)
57 naRef s = naNewString(c);
58 naStr_fromdata(s, (char*)key, strlen(key));
59 naHash_set(hash, s, val);
62 static naRef stringToNasal(naContext c, const std::string& s)
64 return naStr_fromdata(naNewString(c),
65 const_cast<char *>(s.c_str()),
69 static FGPositioned* positionedGhost(naRef r)
71 if (naGhost_type(r) == &PositionedGhostType)
72 return (FGPositioned*) naGhost_ptr(r);
76 static void positionedGhostDestroy(void* g)
78 FGPositioned* pos = (FGPositioned*)g;
79 if (!FGPositioned::put(pos)) // unref
83 static flightgear::Waypt* wayptGhost(naRef r)
85 if (naGhost_type(r) == &WayptGhostType)
86 return (flightgear::Waypt*) naGhost_ptr(r);
90 static void wayptGhostDestroy(void* g)
92 flightgear::Waypt* wpt = (flightgear::Waypt*)g;
93 if (!flightgear::Waypt::put(wpt)) // unref
97 static naRef airportPrototype;
98 static naRef routePrototype;
99 static naRef waypointPrototype;
100 static naRef geoCoordClass;
102 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
108 FGPositioned::get(pos); // take a ref
109 return naNewGhost(c, &PositionedGhostType, (void*) pos);
112 naRef ghostForWaypt(naContext c, const flightgear::Waypt* wpt)
118 flightgear::Waypt::get(wpt); // take a ref
119 return naNewGhost(c, &WayptGhostType, (void*) wpt);
122 naRef hashForAirport(naContext c, const FGAirport* apt)
124 std::string id = apt->ident();
125 std::string name = apt->name();
127 // build runways hash
128 naRef rwys = naNewHash(c);
129 for(unsigned int r=0; r<apt->numRunways(); ++r) {
130 FGRunway* rwy(apt->getRunwayByIndex(r));
131 naRef rwyid = stringToNasal(c, rwy->ident());
132 naRef rwydata = hashForRunway(c, rwy);
133 naHash_set(rwys, rwyid, rwydata);
136 naRef aptdata = naNewHash(c);
137 hashset(c, aptdata, "id", stringToNasal(c, id));
138 hashset(c, aptdata, "name", stringToNasal(c, name));
139 hashset(c, aptdata, "lat", naNum(apt->getLatitude()));
140 hashset(c, aptdata, "lon", naNum(apt->getLongitude()));
141 hashset(c, aptdata, "elevation", naNum(apt->getElevation() * SG_FEET_TO_METER));
142 hashset(c, aptdata, "has_metar", naNum(apt->getMetar()));
143 hashset(c, aptdata, "runways", rwys);
144 hashset(c, aptdata, "_positioned", ghostForPositioned(c, apt));
145 naRef parents = naNewVector(c);
146 naVec_append(parents, airportPrototype);
147 hashset(c, aptdata, "parents", parents);
152 naRef hashForWaypoint(naContext c, flightgear::Waypt* wpt, flightgear::Waypt* next)
154 SGGeod pos = wpt->position();
155 naRef h = naNewHash(c);
157 flightgear::Procedure* proc = dynamic_cast<flightgear::Procedure*>(wpt->owner());
159 hashset(c, h, "wp_parent_name", stringToNasal(c, proc->ident()));
160 // set 'wp_parent' route object to query the SID / STAR / airway?
161 // TODO - needs some extensions to flightgear::Route
164 if (wpt->type() == "hold") {
165 hashset(c, h, "fly_type", stringToNasal(c, "Hold"));
166 } else if (wpt->flag(flightgear::WPT_OVERFLIGHT)) {
167 hashset(c, h, "fly_type", stringToNasal(c, "flyOver"));
169 hashset(c, h, "fly_type", stringToNasal(c, "flyBy"));
172 hashset(c, h, "wp_type", stringToNasal(c, wpt->type()));
173 hashset(c, h, "wp_name", stringToNasal(c, wpt->ident()));
174 hashset(c, h, "wp_lat", naNum(pos.getLatitudeDeg()));
175 hashset(c, h, "wp_lon", naNum(pos.getLongitudeDeg()));
176 hashset(c, h, "alt_cstr", naNum(wpt->altitudeFt()));
178 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
179 hashset(c, h, "spd_cstr", naNum(wpt->speedMach()));
181 hashset(c, h, "spd_cstr", naNum(wpt->speedKts()));
185 std::pair<double, double> crsDist =
186 next->courseAndDistanceFrom(pos);
187 hashset(c, h, "leg_distance", naNum(crsDist.second * SG_METER_TO_NM));
188 hashset(c, h, "leg_bearing", naNum(crsDist.first));
189 hashset(c, h, "hdg_radial", naNum(wpt->headingRadialDeg()));
192 // leg bearing, distance, etc
195 // parents and ghost of the C++ object
196 hashset(c, h, "_waypt", ghostForWaypt(c, wpt));
197 naRef parents = naNewVector(c);
198 naVec_append(parents, waypointPrototype);
199 hashset(c, h, "parents", parents);
205 naRef hashForRunway(naContext c, FGRunway* rwy)
207 naRef rwyid = stringToNasal(c, rwy->ident());
208 naRef rwydata = naNewHash(c);
209 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
210 HASHSET("id", 2, rwyid);
211 HASHSET("lat", 3, naNum(rwy->latitude()));
212 HASHSET("lon", 3, naNum(rwy->longitude()));
213 HASHSET("heading", 7, naNum(rwy->headingDeg()));
214 HASHSET("length", 6, naNum(rwy->lengthM()));
215 HASHSET("width", 5, naNum(rwy->widthM()));
216 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
217 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
220 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
221 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
224 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
229 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
231 naRef navdata = naNewHash(c);
232 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
233 HASHSET("id", 2, stringToNasal(c, nav->ident()));
234 HASHSET("name", 4, stringToNasal(c, nav->name()));
235 HASHSET("frequency", 9, naNum(nav->get_freq()));
236 HASHSET("lat", 3, naNum(nav->get_lat()));
237 HASHSET("lon", 3, naNum(nav->get_lon()));
238 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
239 HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
241 // FIXME - get rid of these, people should use courseAndDistance instead
242 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
243 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
245 // record the real object as a ghost for further operations
246 HASHSET("_positioned",11, ghostForPositioned(c, nav));
252 static bool hashIsCoord(naRef h)
254 naRef parents = naHash_cget(h, (char*) "parents");
255 if (!naIsVector(parents)) {
259 return naEqual(naVec_get(parents, 0), geoCoordClass);
262 bool geodFromHash(naRef ref, SGGeod& result)
264 if (!naIsHash(ref)) {
268 // first, see if the hash contains a FGPositioned ghost - in which case
269 // we can read off its position directly
270 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
271 if (!naIsNil(posGhost)) {
272 FGPositioned* pos = positionedGhost(posGhost);
273 result = pos->geod();
277 naRef ghost = naHash_cget(ref, (char*) "_waypt");
278 if (!naIsNil(ghost)) {
279 flightgear::Waypt* w = wayptGhost(ghost);
280 result = w->position();
284 // then check for manual latitude / longitude names
285 naRef lat = naHash_cget(ref, (char*) "lat");
286 naRef lon = naHash_cget(ref, (char*) "lon");
287 if (naIsNum(lat) && naIsNum(lon)) {
288 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
292 if (hashIsCoord(ref)) {
293 naRef lat = naHash_cget(ref, (char*) "_lat");
294 naRef lon = naHash_cget(ref, (char*) "_lon");
295 if (naIsNum(lat) && naIsNum(lon)) {
296 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
301 // check for any synonyms?
302 // latitude + longitude?
307 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
309 if (offset >= argc) {
313 if (geodFromHash(args[offset], result)) {
317 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
318 double lat = naNumValue(args[0]).num,
319 lon = naNumValue(args[1]).num;
320 result = SGGeod::fromDeg(lon, lat);
327 // Convert a cartesian point to a geodetic lat/lon/altitude.
328 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
330 double lat, lon, alt, xyz[3];
331 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
332 for(int i=0; i<3; i++)
333 xyz[i] = naNumValue(args[i]).num;
334 sgCartToGeod(xyz, &lat, &lon, &alt);
335 lat *= SG_RADIANS_TO_DEGREES;
336 lon *= SG_RADIANS_TO_DEGREES;
337 naRef vec = naNewVector(c);
338 naVec_append(vec, naNum(lat));
339 naVec_append(vec, naNum(lon));
340 naVec_append(vec, naNum(alt));
344 // Convert a geodetic lat/lon/altitude to a cartesian point.
345 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
347 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
348 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
349 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
350 double alt = naNumValue(args[2]).num;
352 sgGeodToCart(lat, lon, alt, xyz);
353 naRef vec = naNewVector(c);
354 naVec_append(vec, naNum(xyz[0]));
355 naVec_append(vec, naNum(xyz[1]));
356 naVec_append(vec, naNum(xyz[2]));
360 // For given geodetic point return array with elevation, and a material data
361 // hash, or nil if there's no information available (tile not loaded). If
362 // information about the material isn't available, then nil is returned instead
364 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
366 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
367 if(argc < 2 || argc > 3)
368 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
369 double lat = naNumValue(args[0]).num;
370 double lon = naNumValue(args[1]).num;
371 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
372 const SGMaterial *mat;
373 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
374 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
376 naRef vec = naNewVector(c);
377 naVec_append(vec, naNum(elev));
378 naRef matdata = naNil();
380 matdata = naNewHash(c);
381 naRef names = naNewVector(c);
382 BOOST_FOREACH(const std::string& n, mat->get_names())
383 naVec_append(names, stringToNasal(c, n));
385 HASHSET("names", 5, names);
386 HASHSET("solid", 5, naNum(mat->get_solid()));
387 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
388 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
389 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
390 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
391 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
393 naVec_append(vec, matdata);
399 class AirportInfoFilter : public FGAirport::AirportFilter
402 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
405 bool fromArg(naRef arg)
407 const char *s = naStr_data(arg);
408 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
409 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
410 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
417 virtual FGPositioned::Type minType() const {
421 virtual FGPositioned::Type maxType() const {
425 FGPositioned::Type type;
428 // Returns data hash for particular or nearest airport of a <type>, or nil
431 // airportinfo(<id>); e.g. "KSFO"
432 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
433 // airportinfo() same as airportinfo("airport")
434 // airportinfo(<lat>, <lon> [, <type>]);
435 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
437 SGGeod pos = globals->get_aircraft_position();
438 FGAirport* apt = NULL;
440 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
441 pos = SGGeod::fromDeg(args[1].num, args[0].num);
446 double maxRange = 10000.0; // expose this? or pick a smaller value?
448 AirportInfoFilter filter; // defaults to airports only
451 // fall through and use AIRPORT
452 } else if(argc == 1 && naIsString(args[0])) {
453 if (filter.fromArg(args[0])) {
456 // user provided an <id>, hopefully
457 apt = FGAirport::findByIdent(naStr_data(args[0]));
459 // return nil here, but don't raise a runtime error; this is a
460 // legitamate way to validate an ICAO code, for example in a
461 // dialog box or similar.
466 naRuntimeError(c, "airportinfo() with invalid function arguments");
471 apt = FGAirport::findClosest(pos, maxRange, &filter);
472 if(!apt) return naNil();
475 return hashForAirport(c, apt);
478 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
481 SGGeod pos = globals->get_aircraft_position();
482 argOffset += geodFromArgs(args, 0, argc, pos);
484 if (!naIsNum(args[argOffset])) {
485 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
488 AirportInfoFilter filter; // defaults to airports only
489 double rangeNm = args[argOffset++].num;
490 if (argOffset < argc) {
491 filter.fromArg(args[argOffset++]);
494 naRef r = naNewVector(c);
496 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
497 FGPositioned::sortByRange(apts, pos);
499 BOOST_FOREACH(FGPositionedRef a, apts) {
500 FGAirport* apt = (FGAirport*) a.get();
501 naVec_append(r, hashForAirport(c, apt));
507 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
509 if (!naIsString(args[0])) {
510 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
514 string prefix(naStr_data(args[argOffset++]));
515 AirportInfoFilter filter; // defaults to airports only
516 if (argOffset < argc) {
517 filter.fromArg(args[argOffset++]);
520 naRef r = naNewVector(c);
522 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
524 BOOST_FOREACH(FGPositionedRef a, apts) {
525 FGAirport* apt = (FGAirport*) a.get();
526 naVec_append(r, hashForAirport(c, apt));
532 static FGAirport* airportFromMe(naRef me)
534 naRef ghost = naHash_cget(me, (char*) "_positioned");
535 if (naIsNil(ghost)) {
539 FGPositioned* pos = positionedGhost(ghost);
540 if (pos && FGAirport::isAirportType(pos)) {
541 return (FGAirport*) pos;
547 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
549 FGAirport* apt = airportFromMe(me);
551 naRuntimeError(c, "airport.tower called on non-airport object");
554 // build a hash for the tower position
555 SGGeod towerLoc = apt->getTowerLocation();
556 naRef tower = naNewHash(c);
557 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
558 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
559 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
563 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
565 FGAirport* apt = airportFromMe(me);
567 naRuntimeError(c, "airport.comms called on non-airport object");
569 naRef comms = naNewVector(c);
571 // if we have an explicit type, return a simple vector of frequencies
572 if (argc > 0 && naIsScalar(args[0])) {
573 std::string commName = naStr_data(args[0]);
574 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
576 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
577 naVec_append(comms, naNum(comm->freqMHz()));
580 // otherwise return a vector of hashes, one for each comm station.
581 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
582 naRef commHash = naNewHash(c);
583 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
584 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
585 naVec_append(comms, commHash);
592 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
594 FGAirport* apt = airportFromMe(me);
596 naRuntimeError(c, "airport.sids called on non-airport object");
599 naRef sids = naNewVector(c);
601 if (argc > 0 && naIsString(args[0])) {
602 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
606 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
607 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
608 naRef procId = stringToNasal(c, sid->ident());
609 naVec_append(sids, procId);
612 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
613 flightgear::SID* sid = apt->getSIDByIndex(s);
614 naRef procId = stringToNasal(c, sid->ident());
615 naVec_append(sids, procId);
622 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
624 FGAirport* apt = airportFromMe(me);
626 naRuntimeError(c, "airport.stars called on non-airport object");
629 naRef stars = naNewVector(c);
631 if (argc > 0 && naIsString(args[0])) {
632 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
636 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
637 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
638 naRef procId = stringToNasal(c, s->ident());
639 naVec_append(stars, procId);
642 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
643 flightgear::STAR* star = apt->getSTARByIndex(s);
644 naRef procId = stringToNasal(c, star->ident());
645 naVec_append(stars, procId);
652 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
654 FGAirport* apt = airportFromMe(me);
656 naRuntimeError(c, "airport.parking called on non-airport object");
659 naRef r = naNewVector(c);
661 bool onlyAvailable = false;
663 if (argc > 0 && naIsString(args[0])) {
664 type = naStr_data(args[0]);
667 if ((argc > 1) && naIsNum(args[1])) {
668 onlyAvailable = (args[1].num != 0.0);
671 FGAirportDynamics* dynamics = apt->getDynamics();
672 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
673 FGParking* park = dynamics->getParking(i);
674 // filter out based on availability and type
675 if (onlyAvailable && !park->isAvailable()) {
679 if (!type.empty() && (park->getType() != type)) {
683 naRef nm = stringToNasal(c, park->getName());
690 // Returns vector of data hash for navaid of a <type>, nil on error
691 // navaids sorted by ascending distance
692 // navinfo([<lat>,<lon>],[<type>],[<id>])
693 // lat/lon (numeric): use latitude/longitude instead of ac position
694 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
695 // id: (partial) id of the fix
697 // navinfo("vor") returns all vors
698 // navinfo("HAM") return all navaids who's name start with "HAM"
699 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
700 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
701 // sorted by distance relative to lat=34, lon=48
702 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
706 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
707 pos = SGGeod::fromDeg(args[1].num, args[0].num);
711 pos = globals->get_aircraft_position();
714 FGPositioned::Type type = FGPositioned::INVALID;
715 nav_list_type navlist;
716 const char * id = "";
718 if(argc > 0 && naIsString(args[0])) {
719 const char *s = naStr_data(args[0]);
720 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
721 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
722 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
723 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
724 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
725 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
726 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
727 else id = s; // this is an id
732 if(argc > 0 && naIsString(args[0])) {
734 naRuntimeError(c, "navinfo() called with navaid id");
737 id = naStr_data(args[0]);
743 naRuntimeError(c, "navinfo() called with too many arguments");
747 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
749 naRef reply = naNewVector(c);
750 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
751 naVec_append( reply, hashForNavRecord(c, *it, pos) );
756 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
759 SGGeod pos = globals->get_aircraft_position();
760 argOffset += geodFromArgs(args, 0, argc, pos);
762 if (!naIsNum(args[argOffset])) {
763 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
766 FGPositioned::Type type = FGPositioned::INVALID;
767 double rangeNm = args[argOffset++].num;
768 if (argOffset < argc) {
769 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
772 naRef r = naNewVector(c);
773 FGNavList::TypeFilter filter(type);
774 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
775 FGPositioned::sortByRange(navs, pos);
777 BOOST_FOREACH(FGPositionedRef a, navs) {
778 FGNavRecord* nav = (FGNavRecord*) a.get();
779 naVec_append(r, hashForNavRecord(c, nav, pos));
785 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
788 SGGeod pos = globals->get_aircraft_position();
789 argOffset += geodFromArgs(args, 0, argc, pos);
791 if (!naIsNum(args[argOffset])) {
792 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
795 FGPositioned::Type type = FGPositioned::INVALID;
796 double freqMhz = args[argOffset++].num;
797 if (argOffset < argc) {
798 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
801 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
806 return hashForNavRecord(c, navs.front().ptr(), pos);
809 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
812 SGGeod pos = globals->get_aircraft_position();
813 argOffset += geodFromArgs(args, 0, argc, pos);
815 if (!naIsNum(args[argOffset])) {
816 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
819 FGPositioned::Type type = FGPositioned::INVALID;
820 double freqMhz = args[argOffset++].num;
821 if (argOffset < argc) {
822 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
825 naRef r = naNewVector(c);
826 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
828 BOOST_FOREACH(nav_rec_ptr a, navs) {
829 naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
835 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
838 SGGeod pos = globals->get_aircraft_position();
839 argOffset += geodFromArgs(args, 0, argc, pos);
841 if (!naIsString(args[argOffset])) {
842 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
845 FGPositioned::Type type = FGPositioned::INVALID;
846 string ident = naStr_data(args[argOffset++]);
847 if (argOffset < argc) {
848 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
851 naRef r = naNewVector(c);
852 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
854 BOOST_FOREACH(nav_rec_ptr a, navs) {
855 naVec_append(r, hashForNavRecord(c, a.ptr(), pos));
862 // Convert a cartesian point to a geodetic lat/lon/altitude.
863 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
865 SGGeod pos = globals->get_aircraft_position();
867 // fine, use aircraft position
868 } else if (geodFromArgs(args, 0, argc, pos)) {
871 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
874 double jd = globals->get_time_params()->getJD();
875 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
876 return naNum(magvarDeg);
879 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
881 SGGeod from = globals->get_aircraft_position(), to, p;
882 int argOffset = geodFromArgs(args, 0, argc, p);
883 if (geodFromArgs(args, argOffset, argc, to)) {
884 from = p; // we parsed both FROM and TO args, so first was from
886 to = p; // only parsed one arg, so FROM is current
889 if (argOffset == 0) {
890 naRuntimeError(c, "invalid arguments to courseAndDistance");
893 double course, course2, d;
894 SGGeodesy::inverse(from, to, course, course2, d);
896 naRef result = naNewVector(c);
897 naVec_append(result, naNum(course));
898 naVec_append(result, naNum(d * SG_METER_TO_NM));
902 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
904 SGGeod from = globals->get_aircraft_position(), to;
907 // complication - don't inerpret two doubles (as the only args)
908 // as a lat,lon pair - only do so if we have at least three args.
910 argOffset = geodFromArgs(args, 0, argc, from);
913 if ((argOffset + 1) >= argc) {
914 naRuntimeError(c, "isufficent arguments to greatCircleMove");
917 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
918 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
919 argOffset, argOffset + 1);
922 double course = args[argOffset].num, course2;
923 double distanceNm = args[argOffset + 1].num;
924 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
927 naRef coord = naNewHash(c);
928 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
929 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
933 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
935 SGGeod pos = globals->get_aircraft_position();
936 geodFromArgs(args, 0, argc, pos);
938 return stringToNasal(c, b.gen_base_path());
941 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
943 SGGeod pos = globals->get_aircraft_position();
944 geodFromArgs(args, 0, argc, pos);
946 return naNum(b.gen_index());
949 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
951 naRef route = naNewHash(c);
953 // return active route hash by default,
954 // other routes in the future
956 naRef parents = naNewVector(c);
957 naVec_append(parents, routePrototype);
958 hashset(c, route, "parents", parents);
963 static naRef f_route_getWP(naContext c, naRef me, int argc, naRef* args)
965 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
969 index = rm->currentIndex();
971 index = (int) naNumValue(args[0]).num;
974 if ((index < 0) || (index >= rm->numWaypts())) {
978 flightgear::Waypt* next = NULL;
979 if (index < (rm->numWaypts() - 1)) {
980 next = rm->wayptAtIndex(index + 1);
982 return hashForWaypoint(c, rm->wayptAtIndex(index), next);
985 static naRef f_route_currentWP(naContext c, naRef me, int argc, naRef* args)
987 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
988 flightgear::Waypt* next = NULL;
989 if (rm->currentIndex() < (rm->numWaypts() - 1)) {
990 next = rm->wayptAtIndex(rm->currentIndex() + 1);
992 return hashForWaypoint(c, rm->currentWaypt(), next);
995 static naRef f_route_currentIndex(naContext c, naRef me, int argc, naRef* args)
997 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
998 return naNum(rm->currentIndex());
1001 static naRef f_route_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1003 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1004 return naNum(rm->numWaypts());
1007 static flightgear::Waypt* wayptFromMe(naRef me)
1009 naRef ghost = naHash_cget(me, (char*) "_waypt");
1010 if (naIsNil(ghost)) {
1014 return wayptGhost(ghost);
1017 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
1019 flightgear::Waypt* w = wayptFromMe(me);
1021 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1024 FGPositioned* pos = w->source();
1029 switch (pos->type()) {
1030 case FGPositioned::VOR:
1031 case FGPositioned::NDB:
1032 case FGPositioned::ILS:
1033 case FGPositioned::LOC:
1034 case FGPositioned::GS:
1035 case FGPositioned::DME:
1036 case FGPositioned::TACAN: {
1037 FGNavRecord* nav = (FGNavRecord*) pos;
1038 return hashForNavRecord(c, nav, globals->get_aircraft_position());
1046 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
1048 flightgear::Waypt* w = wayptFromMe(me);
1050 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1053 FGPositioned* pos = w->source();
1054 if (!pos || FGAirport::isAirportType(pos)) {
1058 return hashForAirport(c, (FGAirport*) pos);
1061 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1063 flightgear::Waypt* w = wayptFromMe(me);
1065 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1068 FGPositioned* pos = w->source();
1069 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1073 return hashForRunway(c, (FGRunway*) pos);
1076 // Table of extension functions. Terminate with zeros.
1077 static struct { const char* name; naCFunction func; } funcs[] = {
1078 { "carttogeod", f_carttogeod },
1079 { "geodtocart", f_geodtocart },
1080 { "geodinfo", f_geodinfo },
1081 { "airportinfo", f_airportinfo },
1082 { "findAirportsWithinRange", f_findAirportsWithinRange },
1083 { "findAirportsByICAO", f_findAirportsByICAO },
1084 { "navinfo", f_navinfo },
1085 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
1086 { "findNavaidByFrequency", f_findNavaidByFrequency },
1087 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
1088 { "findNavaidsByID", f_findNavaidsByIdent },
1089 { "route", f_route },
1090 { "magvar", f_magvar },
1091 { "courseAndDistance", f_courseAndDistance },
1092 { "greatCircleMove", f_greatCircleMove },
1093 { "tileIndex", f_tileIndex },
1094 { "tilePath", f_tilePath },
1099 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
1101 airportPrototype = naNewHash(c);
1102 hashset(c, gcSave, "airportProto", airportPrototype);
1104 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
1105 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
1106 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
1107 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
1108 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
1110 routePrototype = naNewHash(c);
1111 hashset(c, gcSave, "routeProto", routePrototype);
1113 hashset(c, routePrototype, "getWP", naNewFunc(c, naNewCCode(c, f_route_getWP)));
1114 hashset(c, routePrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_route_currentWP)));
1115 hashset(c, routePrototype, "currentIndex", naNewFunc(c, naNewCCode(c, f_route_currentIndex)));
1116 hashset(c, routePrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_route_numWaypoints)));
1118 waypointPrototype = naNewHash(c);
1119 hashset(c, gcSave, "wayptProto", waypointPrototype);
1121 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
1122 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
1123 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
1125 for(int i=0; funcs[i].name; i++) {
1126 hashset(c, globals, funcs[i].name,
1127 naNewFunc(c, naNewCCode(c, funcs[i].func)));
1133 void postinitNasalPositioned(naRef globals, naContext c)
1135 naRef geoModule = naHash_cget(globals, (char*) "geo");
1136 if (naIsNil(geoModule)) {
1137 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
1141 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");