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>
45 static void ghostDestroy(void* g);
46 naGhostType PositionedGhostType = { ghostDestroy, "positioned" };
48 static FGPositioned* positionedGhost(naRef r)
50 if (naGhost_type(r) == &PositionedGhostType)
51 return (FGPositioned*) naGhost_ptr(r);
56 static void ghostDestroy(void* g)
58 FGPositioned* pos = (FGPositioned*)g;
59 SGReferenced::put(pos); // unref
62 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
68 SGReferenced::get(pos); // take a ref
69 return naNewGhost(c, &PositionedGhostType, (void*) pos);
72 naRef hashForAirport(naContext c, const FGAirport* apt)
74 std::string id = apt->ident();
75 std::string name = apt->name();
78 naRef rwys = naNewHash(c);
79 for(unsigned int r=0; r<apt->numRunways(); ++r) {
80 FGRunway* rwy(apt->getRunwayByIndex(r));
82 naRef rwyid = naStr_fromdata(naNewString(c),
83 const_cast<char *>(rwy->ident().c_str()),
84 rwy->ident().length());
85 naRef rwydata = hashForRunway(c, rwy);
86 naHash_set(rwys, rwyid, rwydata);
89 naRef aptdata = naNewHash(c);
90 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
91 HASHSET("id", 2, naStr_fromdata(naNewString(c),
92 const_cast<char *>(id.c_str()), id.length()));
93 HASHSET("name", 4, naStr_fromdata(naNewString(c),
94 const_cast<char *>(name.c_str()), name.length()));
95 HASHSET("lat", 3, naNum(apt->getLatitude()));
96 HASHSET("lon", 3, naNum(apt->getLongitude()));
97 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
98 HASHSET("has_metar", 9, naNum(apt->getMetar()));
99 HASHSET("runways", 7, rwys);
101 HASHSET("_positioned", 11, ghostForPositioned(c, apt));
107 naRef hashForRunway(naContext c, FGRunway* rwy)
109 naRef rwyid = naStr_fromdata(naNewString(c),
110 const_cast<char *>(rwy->ident().c_str()),
111 rwy->ident().length());
113 naRef rwydata = naNewHash(c);
114 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
115 HASHSET("id", 2, rwyid);
116 HASHSET("lat", 3, naNum(rwy->latitude()));
117 HASHSET("lon", 3, naNum(rwy->longitude()));
118 HASHSET("heading", 7, naNum(rwy->headingDeg()));
119 HASHSET("length", 6, naNum(rwy->lengthM()));
120 HASHSET("width", 5, naNum(rwy->widthM()));
121 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
122 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
125 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
126 HASHSET("ils", 3, hashForNavRecord(c, rwy->ILS(), SGGeod()));
129 naRef sidVec = naNewVector(c);
131 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
132 naRef procId = naStr_fromdata(naNewString(c),
133 const_cast<char *>(sid->ident().c_str()),
134 sid->ident().length());
135 naVec_append(sidVec, procId);
137 HASHSET("sids", 4, sidVec);
139 naRef starVec = naNewVector(c);
140 BOOST_FOREACH(flightgear::STAR* star, rwy->getSTARs()) {
141 naRef procId = naStr_fromdata(naNewString(c),
142 const_cast<char *>(star->ident().c_str()),
143 star->ident().length());
144 naVec_append(starVec, procId);
146 HASHSET("stars", 5, starVec);
148 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
153 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
155 naRef navdata = naNewHash(c);
156 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
157 HASHSET("id", 2, naStr_fromdata(naNewString(c),
158 const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
159 HASHSET("name", 4, naStr_fromdata(naNewString(c),
160 const_cast<char *>(nav->name().c_str()), nav->name().length()));
161 HASHSET("frequency", 9, naNum(nav->get_freq()));
162 HASHSET("lat", 3, naNum(nav->get_lat()));
163 HASHSET("lon", 3, naNum(nav->get_lon()));
164 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
165 HASHSET("type", 4, naStr_fromdata(naNewString(c),
166 const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
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 const std::vector<std::string> n = mat->get_names();
264 for(unsigned int i=0; i<n.size(); i++)
265 naVec_append(names, naStr_fromdata(naNewString(c),
266 const_cast<char*>(n[i].c_str()), n[i].size()));
267 HASHSET("names", 5, names);
268 HASHSET("solid", 5, naNum(mat->get_solid()));
269 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
270 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
271 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
272 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
273 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
275 naVec_append(vec, matdata);
281 class AirportInfoFilter : public FGAirport::AirportFilter
284 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
287 virtual FGPositioned::Type minType() const {
291 virtual FGPositioned::Type maxType() const {
295 FGPositioned::Type type;
298 // Returns data hash for particular or nearest airport of a <type>, or nil
301 // airportinfo(<id>); e.g. "KSFO"
302 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
303 // airportinfo() same as airportinfo("airport")
304 // airportinfo(<lat>, <lon> [, <type>]);
305 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
308 FGAirport* apt = NULL;
310 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
311 pos = SGGeod::fromDeg(args[1].num, args[0].num);
315 pos = globals->get_aircraft_position();
318 double maxRange = 10000.0; // expose this? or pick a smaller value?
320 AirportInfoFilter filter; // defaults to airports only
323 // fall through and use AIRPORT
324 } else if(argc == 1 && naIsString(args[0])) {
325 const char *s = naStr_data(args[0]);
326 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
327 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
328 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
330 // user provided an <id>, hopefully
331 apt = FGAirport::findByIdent(s);
333 // return nil here, but don't raise a runtime error; this is a
334 // legitamate way to validate an ICAO code, for example in a
335 // dialog box or similar.
340 naRuntimeError(c, "airportinfo() with invalid function arguments");
345 apt = FGAirport::findClosest(pos, maxRange, &filter);
346 if(!apt) return naNil();
349 return hashForAirport(c, apt);
352 static FGAirport* airportFromRef(naRef ref)
354 if (naIsString(ref)) {
355 return FGAirport::findByIdent(naStr_data(ref));
358 FGPositioned* pos = positionedGhost(ref);
359 if (pos && FGAirport::isAirportType(pos)) {
360 return (FGAirport*) pos;
366 static naRef f_airporttower(naContext c, naRef me, int argc, naRef* args)
369 naRuntimeError(c, "airporttower needs an airport object or ID argument");
372 FGAirport* apt = airportFromRef(args[0]);
373 // build a hash for the tower position
374 // include the frequencies ?
376 SGGeod towerLoc = apt->getTowerLocation();
377 naRef tower = naNewHash(c);
378 #define HASHSET(s,l,n) naHash_set(tower, naStr_fromdata(naNewString(c),s,l),n)
379 HASHSET("lat", 3, naNum(towerLoc.getLatitudeDeg()));
380 HASHSET("lon", 3, naNum(towerLoc.getLongitudeDeg()));
381 HASHSET("elevation", 9, naNum(towerLoc.getElevationM()));
386 static naRef f_airportcomms(naContext c, naRef me, int argc, naRef* args)
389 naRuntimeError(c, "airportcomms needs an airport object or ID argument");
392 FGAirport* apt = airportFromRef(args[0]);
393 naRef comms = naNewHash(c);
394 #define HASHSET(s,l,n) naHash_set(comms, naStr_fromdata(naNewString(c),s,l),n)
401 // Returns vector of data hash for navaid of a <type>, nil on error
402 // navaids sorted by ascending distance
403 // navinfo([<lat>,<lon>],[<type>],[<id>])
404 // lat/lon (numeric): use latitude/longitude instead of ac position
405 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
406 // id: (partial) id of the fix
408 // navinfo("vor") returns all vors
409 // navinfo("HAM") return all navaids who's name start with "HAM"
410 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
411 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
412 // sorted by distance relative to lat=34, lon=48
413 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
417 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
418 pos = SGGeod::fromDeg(args[1].num, args[0].num);
422 pos = globals->get_aircraft_position();
425 FGPositioned::Type type = FGPositioned::INVALID;
426 nav_list_type navlist;
427 const char * id = "";
429 if(argc > 0 && naIsString(args[0])) {
430 const char *s = naStr_data(args[0]);
431 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
432 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
433 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
434 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
435 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
436 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
437 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
438 else id = s; // this is an id
443 if(argc > 0 && naIsString(args[0])) {
445 naRuntimeError(c, "navinfo() called with navaid id");
448 id = naStr_data(args[0]);
454 naRuntimeError(c, "navinfo() called with too many arguments");
458 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
460 naRef reply = naNewVector(c);
461 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
462 naVec_append( reply, hashForNavRecord(c, *it, pos) );
467 // Convert a cartesian point to a geodetic lat/lon/altitude.
468 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
470 SGGeod pos = globals->get_aircraft_position();
472 // fine, use aircraft position
473 } else if ((argc == 1) && geodFromHash(args[0], pos)) {
475 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
476 double lat = naNumValue(args[0]).num,
477 lon = naNumValue(args[1]).num;
478 pos = SGGeod::fromDeg(lon, lat);
480 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
483 double jd = globals->get_time_params()->getJD();
484 double magvarDeg = sgGetMagVar(pos, jd);
485 return naNum(magvarDeg);
488 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
490 SGGeod from = globals->get_aircraft_position(), to;
491 if ((argc == 1) && geodFromHash(args[0], to)) {
493 } else if ((argc == 2) && naIsNum(args[0]) && naIsNum(args[1])) {
494 // two number arguments, from = current pos, to = lat+lon
495 double lat = naNumValue(args[0]).num,
496 lon = naNumValue(args[1]).num;
497 to = SGGeod::fromDeg(lon, lat);
498 } else if ((argc == 2) && geodFromHash(args[0], from) && geodFromHash(args[1], to)) {
500 } else if ((argc == 3) && geodFromHash(args[0], from) && naIsNum(args[1]) && naIsNum(args[2])) {
501 double lat = naNumValue(args[1]).num,
502 lon = naNumValue(args[2]).num;
503 to = SGGeod::fromDeg(lon, lat);
504 } else if ((argc == 3) && naIsNum(args[0]) && naIsNum(args[1]) && geodFromHash(args[2], to)) {
505 double lat = naNumValue(args[0]).num,
506 lon = naNumValue(args[1]).num;
507 from = SGGeod::fromDeg(lon, lat);
508 } else if (argc == 4) {
509 if (!naIsNum(args[0]) || !naIsNum(args[1]) || !naIsNum(args[2]) || !naIsNum(args[3])) {
510 naRuntimeError(c, "invalid arguments to courseAndDistance - expected four numbers");
513 from = SGGeod::fromDeg(naNumValue(args[1]).num, naNumValue(args[0]).num);
514 to = SGGeod::fromDeg(naNumValue(args[3]).num, naNumValue(args[2]).num);
516 naRuntimeError(c, "invalid arguments to courseAndDistance");
519 double course, course2, d;
520 SGGeodesy::inverse(from, to, course, course2, d);
522 naRef result = naNewVector(c);
523 naVec_append(result, naNum(course));
524 naVec_append(result, naNum(d));
528 static naRef f_tilePath(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, "bucketPath() expects no arguments, a positioned hash or lat,lon pair");
544 const char* path = b.gen_base_path().c_str();
545 naRef s = naNewString(c);
546 naStr_fromdata(s, (char*)path, strlen(path));
550 // Table of extension functions. Terminate with zeros.
551 static struct { const char* name; naCFunction func; } funcs[] = {
552 { "carttogeod", f_carttogeod },
553 { "geodtocart", f_geodtocart },
554 { "geodinfo", f_geodinfo },
555 { "airportinfo", f_airportinfo },
556 { "airporttower", f_airporttower },
557 { "airportcomms", f_airportcomms },
558 { "navinfo", f_navinfo },
559 { "magvar", f_magvar },
560 { "courseAndDistance", f_courseAndDistance },
561 { "bucketPath", f_tilePath },
565 static void hashset(naContext c, naRef hash, const char* key, naRef val)
567 naRef s = naNewString(c);
568 naStr_fromdata(s, (char*)key, strlen(key));
569 naHash_set(hash, s, val);
572 naRef initNasalPositioned(naRef globals, naContext c)
574 for(int i=0; funcs[i].name; i++) {
575 hashset(c, globals, funcs[i].name,
576 naNewFunc(c, naNewCCode(c, funcs[i].func)));