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 <Navaids/navlist.hxx>
39 #include <Navaids/procedure.hxx>
40 #include <Main/globals.hxx>
41 #include <Main/fg_props.hxx>
42 #include <Scenery/scenery.hxx>
43 #include <ATC/CommStation.hxx>
45 static void ghostDestroy(void* g);
46 naGhostType PositionedGhostType = { ghostDestroy, "positioned" };
48 static void hashset(naContext c, naRef hash, const char* key, naRef val)
50 naRef s = naNewString(c);
51 naStr_fromdata(s, (char*)key, strlen(key));
52 naHash_set(hash, s, val);
55 static naRef stringToNasal(naContext c, const std::string& s)
57 return naStr_fromdata(naNewString(c),
58 const_cast<char *>(s.c_str()),
62 static FGPositioned* positionedGhost(naRef r)
64 if (naGhost_type(r) == &PositionedGhostType)
65 return (FGPositioned*) naGhost_ptr(r);
70 static void ghostDestroy(void* g)
72 FGPositioned* pos = (FGPositioned*)g;
73 SGReferenced::put(pos); // unref
76 static naRef airportPrototype;
78 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
84 SGReferenced::get(pos); // take a ref
85 return naNewGhost(c, &PositionedGhostType, (void*) pos);
88 naRef hashForAirport(naContext c, const FGAirport* apt)
90 std::string id = apt->ident();
91 std::string name = apt->name();
94 naRef rwys = naNewHash(c);
95 for(unsigned int r=0; r<apt->numRunways(); ++r) {
96 FGRunway* rwy(apt->getRunwayByIndex(r));
97 naRef rwyid = stringToNasal(c, rwy->ident());
98 naRef rwydata = hashForRunway(c, rwy);
99 naHash_set(rwys, rwyid, rwydata);
102 naRef aptdata = naNewHash(c);
103 hashset(c, aptdata, "id", stringToNasal(c, id));
104 hashset(c, aptdata, "name", stringToNasal(c, name));
105 hashset(c, aptdata, "lat", naNum(apt->getLatitude()));
106 hashset(c, aptdata, "lon", naNum(apt->getLongitude()));
107 hashset(c, aptdata, "elevation", naNum(apt->getElevation() * SG_FEET_TO_METER));
108 hashset(c, aptdata, "has_metar", naNum(apt->getMetar()));
109 hashset(c, aptdata, "runways", rwys);
110 hashset(c, aptdata, "_positioned", ghostForPositioned(c, apt));
111 naRef parents = naNewVector(c);
112 naVec_append(parents, airportPrototype);
113 hashset(c, aptdata, "parents", parents);
118 naRef hashForRunway(naContext c, FGRunway* rwy)
120 naRef rwyid = stringToNasal(c, rwy->ident());
121 naRef rwydata = naNewHash(c);
122 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
123 HASHSET("id", 2, rwyid);
124 HASHSET("lat", 3, naNum(rwy->latitude()));
125 HASHSET("lon", 3, naNum(rwy->longitude()));
126 HASHSET("heading", 7, naNum(rwy->headingDeg()));
127 HASHSET("length", 6, naNum(rwy->lengthM()));
128 HASHSET("width", 5, naNum(rwy->widthM()));
129 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
130 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
133 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
134 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
137 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
142 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
144 naRef navdata = naNewHash(c);
145 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
146 HASHSET("id", 2, stringToNasal(c, nav->ident()));
147 HASHSET("name", 4, stringToNasal(c, nav->name()));
148 HASHSET("frequency", 9, naNum(nav->get_freq()));
149 HASHSET("lat", 3, naNum(nav->get_lat()));
150 HASHSET("lon", 3, naNum(nav->get_lon()));
151 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
152 HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
154 // FIXME - get rid of these, people should use courseAndDistance instead
155 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
156 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
158 // record the real object as a ghost for further operations
159 HASHSET("_positioned",11, ghostForPositioned(c, nav));
165 bool geodFromHash(naRef ref, SGGeod& result)
167 if (!naIsHash(ref)) {
171 // first, see if the hash contains a FGPositioned ghost - in which case
172 // we can read off its position directly
173 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
174 if (!naIsNil(posGhost)) {
175 FGPositioned* pos = positionedGhost(posGhost);
176 result = pos->geod();
180 // then check for manual latitude / longitude names
181 naRef lat = naHash_cget(ref, (char*) "lat");
182 naRef lon = naHash_cget(ref, (char*) "lon");
183 if (naIsNum(lat) && naIsNum(lon)) {
184 result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
188 // check for geo.Coord type
190 // check for any synonyms?
191 // latitude + longitude?
196 // Convert a cartesian point to a geodetic lat/lon/altitude.
197 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
199 double lat, lon, alt, xyz[3];
200 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
201 for(int i=0; i<3; i++)
202 xyz[i] = naNumValue(args[i]).num;
203 sgCartToGeod(xyz, &lat, &lon, &alt);
204 lat *= SG_RADIANS_TO_DEGREES;
205 lon *= SG_RADIANS_TO_DEGREES;
206 naRef vec = naNewVector(c);
207 naVec_append(vec, naNum(lat));
208 naVec_append(vec, naNum(lon));
209 naVec_append(vec, naNum(alt));
213 // Convert a geodetic lat/lon/altitude to a cartesian point.
214 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
216 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
217 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
218 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
219 double alt = naNumValue(args[2]).num;
221 sgGeodToCart(lat, lon, alt, xyz);
222 naRef vec = naNewVector(c);
223 naVec_append(vec, naNum(xyz[0]));
224 naVec_append(vec, naNum(xyz[1]));
225 naVec_append(vec, naNum(xyz[2]));
229 // For given geodetic point return array with elevation, and a material data
230 // hash, or nil if there's no information available (tile not loaded). If
231 // information about the material isn't available, then nil is returned instead
233 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
235 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
236 if(argc < 2 || argc > 3)
237 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
238 double lat = naNumValue(args[0]).num;
239 double lon = naNumValue(args[1]).num;
240 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
241 const SGMaterial *mat;
242 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
243 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
245 naRef vec = naNewVector(c);
246 naVec_append(vec, naNum(elev));
247 naRef matdata = naNil();
249 matdata = naNewHash(c);
250 naRef names = naNewVector(c);
251 BOOST_FOREACH(const std::string& n, mat->get_names())
252 naVec_append(names, stringToNasal(c, n));
254 HASHSET("names", 5, names);
255 HASHSET("solid", 5, naNum(mat->get_solid()));
256 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
257 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
258 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
259 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
260 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
262 naVec_append(vec, matdata);
268 class AirportInfoFilter : public FGAirport::AirportFilter
271 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
274 virtual FGPositioned::Type minType() const {
278 virtual FGPositioned::Type maxType() const {
282 FGPositioned::Type type;
285 // Returns data hash for particular or nearest airport of a <type>, or nil
288 // airportinfo(<id>); e.g. "KSFO"
289 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
290 // airportinfo() same as airportinfo("airport")
291 // airportinfo(<lat>, <lon> [, <type>]);
292 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
295 FGAirport* apt = NULL;
297 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
298 pos = SGGeod::fromDeg(args[1].num, args[0].num);
302 pos = globals->get_aircraft_position();
305 double maxRange = 10000.0; // expose this? or pick a smaller value?
307 AirportInfoFilter filter; // defaults to airports only
310 // fall through and use AIRPORT
311 } else if(argc == 1 && naIsString(args[0])) {
312 const char *s = naStr_data(args[0]);
313 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
314 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
315 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
317 // user provided an <id>, hopefully
318 apt = FGAirport::findByIdent(s);
320 // return nil here, but don't raise a runtime error; this is a
321 // legitamate way to validate an ICAO code, for example in a
322 // dialog box or similar.
327 naRuntimeError(c, "airportinfo() with invalid function arguments");
332 apt = FGAirport::findClosest(pos, maxRange, &filter);
333 if(!apt) return naNil();
336 return hashForAirport(c, apt);
339 static FGAirport* airportFromMe(naRef me)
341 naRef ghost = naHash_cget(me, (char*) "_positioned");
342 if (naIsNil(ghost)) {
346 FGPositioned* pos = positionedGhost(ghost);
347 if (pos && FGAirport::isAirportType(pos)) {
348 return (FGAirport*) pos;
354 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
356 FGAirport* apt = airportFromMe(me);
358 naRuntimeError(c, "airport.tower called on non-airport object");
361 // build a hash for the tower position
362 SGGeod towerLoc = apt->getTowerLocation();
363 naRef tower = naNewHash(c);
364 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
365 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
366 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
370 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
372 FGAirport* apt = airportFromMe(me);
374 naRuntimeError(c, "airport.comms called on non-airport object");
376 naRef comms = naNewVector(c);
378 // if we have an explicit type, return a simple vector of frequencies
379 if (argc > 0 && naIsScalar(args[0])) {
380 std::string commName = naStr_data(args[0]);
381 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
383 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
384 naVec_append(comms, naNum(comm->freqMHz()));
387 // otherwise return a vector of hashes, one for each comm station.
388 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
389 naRef commHash = naNewHash(c);
390 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
391 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
392 naVec_append(comms, commHash);
399 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
401 FGAirport* apt = airportFromMe(me);
403 naRuntimeError(c, "airport.sids called on non-airport object");
406 naRef sids = naNewVector(c);
408 // if we have an explicit type, return a simple vector of frequencies
409 if (argc > 0 && naIsString(args[0])) {
410 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
414 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
415 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
416 naRef procId = stringToNasal(c, sid->ident());
417 naVec_append(sids, procId);
420 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
421 flightgear::SID* sid = apt->getSIDByIndex(s);
422 naRef procId = stringToNasal(c, sid->ident());
423 naVec_append(sids, procId);
430 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
432 FGAirport* apt = airportFromMe(me);
434 naRuntimeError(c, "airport.stars called on non-airport object");
437 naRef stars = naNewVector(c);
439 // if we have an explicit type, return a simple vector of frequencies
440 if (argc > 0 && naIsString(args[0])) {
441 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
445 FGRunway* rwy = apt->getRunwayByIdent(naStr_data(args[0]));
446 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
447 naRef procId = stringToNasal(c, s->ident());
448 naVec_append(stars, procId);
451 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
452 flightgear::STAR* star = apt->getSTARByIndex(s);
453 naRef procId = stringToNasal(c, star->ident());
454 naVec_append(stars, procId);
461 // Returns vector of data hash for navaid of a <type>, nil on error
462 // navaids sorted by ascending distance
463 // navinfo([<lat>,<lon>],[<type>],[<id>])
464 // lat/lon (numeric): use latitude/longitude instead of ac position
465 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
466 // id: (partial) id of the fix
468 // navinfo("vor") returns all vors
469 // navinfo("HAM") return all navaids who's name start with "HAM"
470 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
471 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
472 // sorted by distance relative to lat=34, lon=48
473 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
477 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
478 pos = SGGeod::fromDeg(args[1].num, args[0].num);
482 pos = globals->get_aircraft_position();
485 FGPositioned::Type type = FGPositioned::INVALID;
486 nav_list_type navlist;
487 const char * id = "";
489 if(argc > 0 && naIsString(args[0])) {
490 const char *s = naStr_data(args[0]);
491 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
492 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
493 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
494 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
495 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
496 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
497 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
498 else id = s; // this is an id
503 if(argc > 0 && naIsString(args[0])) {
505 naRuntimeError(c, "navinfo() called with navaid id");
508 id = naStr_data(args[0]);
514 naRuntimeError(c, "navinfo() called with too many arguments");
518 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
520 naRef reply = naNewVector(c);
521 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
522 naVec_append( reply, hashForNavRecord(c, *it, pos) );
527 // Convert a cartesian point to a geodetic lat/lon/altitude.
528 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
530 SGGeod pos = globals->get_aircraft_position();
532 // fine, use aircraft position
533 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
535 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
536 double lat = naNumValue(args[0]).num,
537 lon = naNumValue(args[1]).num;
538 pos = SGGeod::fromDeg(lon, lat);
540 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
543 double jd = globals->get_time_params()->getJD();
544 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
545 return naNum(magvarDeg);
548 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
550 SGGeod from = globals->get_aircraft_position(), to;
551 if ((argc == 1) && geodFromHash(args[0], to)) {
553 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
554 // two number arguments, from = current pos, to = lat+lon
555 double lat = naNumValue(args[0]).num,
556 lon = naNumValue(args[1]).num;
557 to = SGGeod::fromDeg(lon, lat);
558 } else if ((argc == 2) && geodFromHash(args[0], from) && geodFromHash(args[1], to)) {
560 } else if ((argc == 3) && geodFromHash(args[0], from) && naIsNum(args[1]) && naIsNum(args[2])) {
561 double lat = naNumValue(args[1]).num,
562 lon = naNumValue(args[2]).num;
563 to = SGGeod::fromDeg(lon, lat);
564 } else if ((argc == 3) && naIsNum(args[0]) && naIsNum(args[1]) && geodFromHash(args[2], to)) {
565 double lat = naNumValue(args[0]).num,
566 lon = naNumValue(args[1]).num;
567 from = SGGeod::fromDeg(lon, lat);
568 } else if (argc == 4) {
569 if (!naIsNum(args[0]) || !naIsNum(args[1]) || !naIsNum(args[2]) || !naIsNum(args[3])) {
570 naRuntimeError(c, "invalid arguments to courseAndDistance - expected four numbers");
573 from = SGGeod::fromDeg(naNumValue(args[1]).num, naNumValue(args[0]).num);
574 to = SGGeod::fromDeg(naNumValue(args[3]).num, naNumValue(args[2]).num);
576 naRuntimeError(c, "invalid arguments to courseAndDistance");
579 double course, course2, d;
580 SGGeodesy::inverse(from, to, course, course2, d);
582 naRef result = naNewVector(c);
583 naVec_append(result, naNum(course));
584 naVec_append(result, naNum(d * SG_METER_TO_NM));
588 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
590 SGGeod pos = globals->get_aircraft_position();
592 // fine, use aircraft position
593 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
595 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
596 double lat = naNumValue(args[0]).num,
597 lon = naNumValue(args[1]).num;
598 pos = SGGeod::fromDeg(lon, lat);
600 naRuntimeError(c, "bucketPath() expects no arguments, a positioned hash or lat,lon pair");
604 return stringToNasal(c, b.gen_base_path());
607 // Table of extension functions. Terminate with zeros.
608 static struct { const char* name; naCFunction func; } funcs[] = {
609 { "carttogeod", f_carttogeod },
610 { "geodtocart", f_geodtocart },
611 { "geodinfo", f_geodinfo },
612 { "airportinfo", f_airportinfo },
613 { "navinfo", f_navinfo },
614 { "magvar", f_magvar },
615 { "courseAndDistance", f_courseAndDistance },
616 { "bucketPath", f_tilePath },
621 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
623 airportPrototype = naNewHash(c);
624 hashset(c, gcSave, "airportProto", airportPrototype);
626 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
627 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
628 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
629 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
631 for(int i=0; funcs[i].name; i++) {
632 hashset(c, globals, funcs[i].name,
633 naNewFunc(c, naNewCCode(c, funcs[i].func)));