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 naRef stringToNasal(naContext c, const std::string& s)
50 return naStr_fromdata(naNewString(c),
51 const_cast<char *>(s.c_str()),
55 static FGPositioned* positionedGhost(naRef r)
57 if (naGhost_type(r) == &PositionedGhostType)
58 return (FGPositioned*) naGhost_ptr(r);
63 static void ghostDestroy(void* g)
65 FGPositioned* pos = (FGPositioned*)g;
66 SGReferenced::put(pos); // unref
69 static naRef airportPrototype;
71 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
77 SGReferenced::get(pos); // take a ref
78 return naNewGhost(c, &PositionedGhostType, (void*) pos);
81 naRef hashForAirport(naContext c, const FGAirport* apt)
83 std::string id = apt->ident();
84 std::string name = apt->name();
87 naRef rwys = naNewHash(c);
88 for(unsigned int r=0; r<apt->numRunways(); ++r) {
89 FGRunway* rwy(apt->getRunwayByIndex(r));
90 naRef rwyid = stringToNasal(c, rwy->ident());
91 naRef rwydata = hashForRunway(c, rwy);
92 naHash_set(rwys, rwyid, rwydata);
95 naRef aptdata = naNewHash(c);
96 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
97 HASHSET("id", 2, stringToNasal(c, id));
98 HASHSET("name", 4, stringToNasal(c, name));
99 HASHSET("lat", 3, naNum(apt->getLatitude()));
100 HASHSET("lon", 3, naNum(apt->getLongitude()));
101 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
102 HASHSET("has_metar", 9, naNum(apt->getMetar()));
103 HASHSET("runways", 7, rwys);
105 HASHSET("_positioned", 11, ghostForPositioned(c, apt));
107 naRef parents = naNewVector(c);
108 naVec_append(parents, airportPrototype);
109 HASHSET("parents", 7, parents);
115 naRef hashForRunway(naContext c, FGRunway* rwy)
117 naRef rwyid = stringToNasal(c, rwy->ident());
118 naRef rwydata = naNewHash(c);
119 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
120 HASHSET("id", 2, rwyid);
121 HASHSET("lat", 3, naNum(rwy->latitude()));
122 HASHSET("lon", 3, naNum(rwy->longitude()));
123 HASHSET("heading", 7, naNum(rwy->headingDeg()));
124 HASHSET("length", 6, naNum(rwy->lengthM()));
125 HASHSET("width", 5, naNum(rwy->widthM()));
126 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
127 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
130 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
131 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
134 naRef sidVec = naNewVector(c);
136 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
137 naRef procId = stringToNasal(c, sid->ident());
138 naVec_append(sidVec, procId);
140 HASHSET("sids", 4, sidVec);
142 naRef starVec = naNewVector(c);
143 BOOST_FOREACH(flightgear::STAR* star, rwy->getSTARs()) {
144 naRef procId = stringToNasal(c, star->ident());
145 naVec_append(starVec, procId);
147 HASHSET("stars", 5, starVec);
149 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
154 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
156 naRef navdata = naNewHash(c);
157 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
158 HASHSET("id", 2, stringToNasal(c, nav->ident()));
159 HASHSET("name", 4, stringToNasal(c, nav->name()));
160 HASHSET("frequency", 9, naNum(nav->get_freq()));
161 HASHSET("lat", 3, naNum(nav->get_lat()));
162 HASHSET("lon", 3, naNum(nav->get_lon()));
163 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
164 HASHSET("type", 4, stringToNasal(c, nav->nameForType(nav->type())));
166 // FIXME - get rid of these, people should use courseAndDistance instead
167 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
168 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
170 // record the real object as a ghost for further operations
171 HASHSET("_positioned",11, ghostForPositioned(c, nav));
177 bool geodFromHash(naRef ref, SGGeod& result)
179 if (!naIsHash(ref)) {
183 // first, see if the hash contains a FGPositioned ghost - in which case
184 // we can read off its position directly
185 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
186 if (!naIsNil(posGhost)) {
187 FGPositioned* pos = positionedGhost(posGhost);
188 result = pos->geod();
192 // then check for manual latitude / longitude names
193 naRef lat = naHash_cget(ref, (char*) "lat");
194 naRef lon = naHash_cget(ref, (char*) "lon");
195 if (naIsNum(lat) && naIsNum(lon)) {
196 result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
200 // check for geo.Coord type
202 // check for any synonyms?
203 // latitude + longitude?
208 // Convert a cartesian point to a geodetic lat/lon/altitude.
209 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
211 double lat, lon, alt, xyz[3];
212 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
213 for(int i=0; i<3; i++)
214 xyz[i] = naNumValue(args[i]).num;
215 sgCartToGeod(xyz, &lat, &lon, &alt);
216 lat *= SG_RADIANS_TO_DEGREES;
217 lon *= SG_RADIANS_TO_DEGREES;
218 naRef vec = naNewVector(c);
219 naVec_append(vec, naNum(lat));
220 naVec_append(vec, naNum(lon));
221 naVec_append(vec, naNum(alt));
225 // Convert a geodetic lat/lon/altitude to a cartesian point.
226 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
228 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
229 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
230 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
231 double alt = naNumValue(args[2]).num;
233 sgGeodToCart(lat, lon, alt, xyz);
234 naRef vec = naNewVector(c);
235 naVec_append(vec, naNum(xyz[0]));
236 naVec_append(vec, naNum(xyz[1]));
237 naVec_append(vec, naNum(xyz[2]));
241 // For given geodetic point return array with elevation, and a material data
242 // hash, or nil if there's no information available (tile not loaded). If
243 // information about the material isn't available, then nil is returned instead
245 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
247 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
248 if(argc < 2 || argc > 3)
249 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
250 double lat = naNumValue(args[0]).num;
251 double lon = naNumValue(args[1]).num;
252 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
253 const SGMaterial *mat;
254 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
255 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
257 naRef vec = naNewVector(c);
258 naVec_append(vec, naNum(elev));
259 naRef matdata = naNil();
261 matdata = naNewHash(c);
262 naRef names = naNewVector(c);
263 BOOST_FOREACH(const std::string& n, mat->get_names())
264 naVec_append(names, stringToNasal(c, n));
266 HASHSET("names", 5, names);
267 HASHSET("solid", 5, naNum(mat->get_solid()));
268 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
269 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
270 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
271 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
272 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
274 naVec_append(vec, matdata);
280 class AirportInfoFilter : public FGAirport::AirportFilter
283 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
286 virtual FGPositioned::Type minType() const {
290 virtual FGPositioned::Type maxType() const {
294 FGPositioned::Type type;
297 // Returns data hash for particular or nearest airport of a <type>, or nil
300 // airportinfo(<id>); e.g. "KSFO"
301 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
302 // airportinfo() same as airportinfo("airport")
303 // airportinfo(<lat>, <lon> [, <type>]);
304 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
307 FGAirport* apt = NULL;
309 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
310 pos = SGGeod::fromDeg(args[1].num, args[0].num);
314 pos = globals->get_aircraft_position();
317 double maxRange = 10000.0; // expose this? or pick a smaller value?
319 AirportInfoFilter filter; // defaults to airports only
322 // fall through and use AIRPORT
323 } else if(argc == 1 && naIsString(args[0])) {
324 const char *s = naStr_data(args[0]);
325 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
326 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
327 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
329 // user provided an <id>, hopefully
330 apt = FGAirport::findByIdent(s);
332 // return nil here, but don't raise a runtime error; this is a
333 // legitamate way to validate an ICAO code, for example in a
334 // dialog box or similar.
339 naRuntimeError(c, "airportinfo() with invalid function arguments");
344 apt = FGAirport::findClosest(pos, maxRange, &filter);
345 if(!apt) return naNil();
348 return hashForAirport(c, apt);
351 static FGAirport* airportFromRef(naRef ref)
353 if (naIsString(ref)) {
354 return FGAirport::findByIdent(naStr_data(ref));
357 FGPositioned* pos = positionedGhost(ref);
358 if (pos && FGAirport::isAirportType(pos)) {
359 return (FGAirport*) pos;
365 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
367 FGPositioned* pos = positionedGhost(me);
368 if (!pos ||! FGAirport::isAirportType(pos)) {
369 naRuntimeError(c, "airport_tower called on non-airport object");
372 FGAirport* apt = (FGAirport*) pos;
374 // build a hash for the tower position
375 SGGeod towerLoc = apt->getTowerLocation();
376 naRef tower = naNewHash(c);
377 #define HASHSET(s,l,n) naHash_set(tower, naStr_fromdata(naNewString(c),s,l),n)
378 HASHSET("lat", 3, naNum(towerLoc.getLatitudeDeg()));
379 HASHSET("lon", 3, naNum(towerLoc.getLongitudeDeg()));
380 HASHSET("elevation", 9, naNum(towerLoc.getElevationM()));
385 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
387 FGPositioned* pos = positionedGhost(me);
388 if (!pos ||! FGAirport::isAirportType(pos)) {
389 naRuntimeError(c, "airport_comms called on non-airport object");
392 FGAirport* apt = (FGAirport*) pos;
395 // if we have an explicit type, return a simple vector of frequencies
396 if (argc > 0 && naIsScalar(args[0])) {
397 std::string commName = naStr_data(args[0]);
398 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
400 naRef comms = naNewVector(c);
401 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
402 naVec_append(comms, naNum(comm->freqMHz()));
405 // otherwise return a vector of hashes, one for each comm station.
406 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
407 naRef commHash = naNewHash(c);
408 #define HASHSET(s,n) naHash_set(commHash, naStr_fromdata(naNewString(c),s,strlen(s)),n)
409 HASHSET("frequency", naNum(comm->freqMHz()));
410 HASHSET("ident", stringToNasal(c, comm->ident()));
413 naVec_append(comms, commHash);
421 // Returns vector of data hash for navaid of a <type>, nil on error
422 // navaids sorted by ascending distance
423 // navinfo([<lat>,<lon>],[<type>],[<id>])
424 // lat/lon (numeric): use latitude/longitude instead of ac position
425 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
426 // id: (partial) id of the fix
428 // navinfo("vor") returns all vors
429 // navinfo("HAM") return all navaids who's name start with "HAM"
430 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
431 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
432 // sorted by distance relative to lat=34, lon=48
433 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
437 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
438 pos = SGGeod::fromDeg(args[1].num, args[0].num);
442 pos = globals->get_aircraft_position();
445 FGPositioned::Type type = FGPositioned::INVALID;
446 nav_list_type navlist;
447 const char * id = "";
449 if(argc > 0 && naIsString(args[0])) {
450 const char *s = naStr_data(args[0]);
451 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
452 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
453 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
454 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
455 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
456 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
457 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
458 else id = s; // this is an id
463 if(argc > 0 && naIsString(args[0])) {
465 naRuntimeError(c, "navinfo() called with navaid id");
468 id = naStr_data(args[0]);
474 naRuntimeError(c, "navinfo() called with too many arguments");
478 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
480 naRef reply = naNewVector(c);
481 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
482 naVec_append( reply, hashForNavRecord(c, *it, pos) );
487 // Convert a cartesian point to a geodetic lat/lon/altitude.
488 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
490 SGGeod pos = globals->get_aircraft_position();
492 // fine, use aircraft position
493 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
495 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
496 double lat = naNumValue(args[0]).num,
497 lon = naNumValue(args[1]).num;
498 pos = SGGeod::fromDeg(lon, lat);
500 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
503 double jd = globals->get_time_params()->getJD();
504 double magvarDeg = sgGetMagVar(pos, jd);
505 return naNum(magvarDeg);
508 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
510 SGGeod from = globals->get_aircraft_position(), to;
511 if ((argc == 1) && geodFromHash(args[0], to)) {
513 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
514 // two number arguments, from = current pos, to = lat+lon
515 double lat = naNumValue(args[0]).num,
516 lon = naNumValue(args[1]).num;
517 to = SGGeod::fromDeg(lon, lat);
518 } else if ((argc == 2) && geodFromHash(args[0], from) && geodFromHash(args[1], to)) {
520 } else if ((argc == 3) && geodFromHash(args[0], from) && naIsNum(args[1]) && naIsNum(args[2])) {
521 double lat = naNumValue(args[1]).num,
522 lon = naNumValue(args[2]).num;
523 to = SGGeod::fromDeg(lon, lat);
524 } else if ((argc == 3) && naIsNum(args[0]) && naIsNum(args[1]) && geodFromHash(args[2], to)) {
525 double lat = naNumValue(args[0]).num,
526 lon = naNumValue(args[1]).num;
527 from = SGGeod::fromDeg(lon, lat);
528 } else if (argc == 4) {
529 if (!naIsNum(args[0]) || !naIsNum(args[1]) || !naIsNum(args[2]) || !naIsNum(args[3])) {
530 naRuntimeError(c, "invalid arguments to courseAndDistance - expected four numbers");
533 from = SGGeod::fromDeg(naNumValue(args[1]).num, naNumValue(args[0]).num);
534 to = SGGeod::fromDeg(naNumValue(args[3]).num, naNumValue(args[2]).num);
536 naRuntimeError(c, "invalid arguments to courseAndDistance");
539 double course, course2, d;
540 SGGeodesy::inverse(from, to, course, course2, d);
542 naRef result = naNewVector(c);
543 naVec_append(result, naNum(course));
544 naVec_append(result, naNum(d));
548 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
550 SGGeod pos = globals->get_aircraft_position();
552 // fine, use aircraft position
553 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
555 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
556 double lat = naNumValue(args[0]).num,
557 lon = naNumValue(args[1]).num;
558 pos = SGGeod::fromDeg(lon, lat);
560 naRuntimeError(c, "bucketPath() expects no arguments, a positioned hash or lat,lon pair");
564 return stringToNasal(c, b.gen_base_path());
567 // Table of extension functions. Terminate with zeros.
568 static struct { const char* name; naCFunction func; } funcs[] = {
569 { "carttogeod", f_carttogeod },
570 { "geodtocart", f_geodtocart },
571 { "geodinfo", f_geodinfo },
572 { "airportinfo", f_airportinfo },
573 { "navinfo", f_navinfo },
574 { "magvar", f_magvar },
575 { "courseAndDistance", f_courseAndDistance },
576 { "bucketPath", f_tilePath },
580 static void hashset(naContext c, naRef hash, const char* key, naRef val)
582 naRef s = naNewString(c);
583 naStr_fromdata(s, (char*)key, strlen(key));
584 naHash_set(hash, s, val);
587 naRef initNasalPositioned(naRef globals, naContext c)
589 airportPrototype = naNewHash(c);
590 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
591 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
593 for(int i=0; funcs[i].name; i++) {
594 hashset(c, globals, funcs[i].name,
595 naNewFunc(c, naNewCCode(c, funcs[i].func)));