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.
25 #include "NasalPositioned.hxx"
27 #include <simgear/scene/material/mat.hxx>
28 #include <simgear/magvar/magvar.hxx>
29 #include <simgear/timing/sg_time.hxx>
31 #include <Airports/runways.hxx>
32 #include <Airports/simple.hxx>
33 #include <Navaids/navlist.hxx>
34 #include <Navaids/procedure.hxx>
35 #include <Main/globals.hxx>
36 #include <Main/fg_props.hxx>
37 #include <Scenery/scenery.hxx>
40 static void ghostDestroy(void* g);
41 naGhostType PositionedGhostType = { ghostDestroy, "positioned" };
43 static FGPositioned* positionedGhost(naRef r)
45 if (naGhost_type(r) == &PositionedGhostType)
46 return (FGPositioned*) naGhost_ptr(r);
51 static void ghostDestroy(void* g)
53 FGPositioned* pos = (FGPositioned*)g;
54 SGReferenced::put(pos); // unref
57 naRef ghostForPositioned(naContext c, const FGPositioned* pos)
63 SGReferenced::get(pos); // take a ref
64 return naNewGhost(c, &PositionedGhostType, (void*) pos);
67 naRef hashForAirport(naContext c, const FGAirport* apt)
69 std::string id = apt->ident();
70 std::string name = apt->name();
73 naRef rwys = naNewHash(c);
74 for(unsigned int r=0; r<apt->numRunways(); ++r) {
75 FGRunway* rwy(apt->getRunwayByIndex(r));
77 naRef rwyid = naStr_fromdata(naNewString(c),
78 const_cast<char *>(rwy->ident().c_str()),
79 rwy->ident().length());
80 naRef rwydata = hashForRunway(c, rwy);
81 naHash_set(rwys, rwyid, rwydata);
84 naRef aptdata = naNewHash(c);
85 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
86 HASHSET("id", 2, naStr_fromdata(naNewString(c),
87 const_cast<char *>(id.c_str()), id.length()));
88 HASHSET("name", 4, naStr_fromdata(naNewString(c),
89 const_cast<char *>(name.c_str()), name.length()));
90 HASHSET("lat", 3, naNum(apt->getLatitude()));
91 HASHSET("lon", 3, naNum(apt->getLongitude()));
92 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
93 HASHSET("has_metar", 9, naNum(apt->getMetar()));
94 HASHSET("runways", 7, rwys);
96 HASHSET("_positioned", 11, ghostForPositioned(c, apt));
102 naRef hashForRunway(naContext c, FGRunway* rwy)
104 naRef rwyid = naStr_fromdata(naNewString(c),
105 const_cast<char *>(rwy->ident().c_str()),
106 rwy->ident().length());
108 naRef rwydata = naNewHash(c);
109 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
110 HASHSET("id", 2, rwyid);
111 HASHSET("lat", 3, naNum(rwy->latitude()));
112 HASHSET("lon", 3, naNum(rwy->longitude()));
113 HASHSET("heading", 7, naNum(rwy->headingDeg()));
114 HASHSET("length", 6, naNum(rwy->lengthM()));
115 HASHSET("width", 5, naNum(rwy->widthM()));
116 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
117 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
120 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
123 std::vector<flightgear::SID*> sids(rwy->getSIDs());
124 naRef sidVec = naNewVector(c);
126 for (unsigned int s=0; s < sids.size(); ++s) {
127 naRef procId = naStr_fromdata(naNewString(c),
128 const_cast<char *>(sids[s]->ident().c_str()),
129 sids[s]->ident().length());
130 naVec_append(sidVec, procId);
132 HASHSET("sids", 4, sidVec);
134 std::vector<flightgear::STAR*> stars(rwy->getSTARs());
135 naRef starVec = naNewVector(c);
137 for (unsigned int s=0; s < stars.size(); ++s) {
138 naRef procId = naStr_fromdata(naNewString(c),
139 const_cast<char *>(stars[s]->ident().c_str()),
140 stars[s]->ident().length());
141 naVec_append(starVec, procId);
143 HASHSET("stars", 5, starVec);
145 HASHSET("_positioned", 11, ghostForPositioned(c, rwy));
150 naRef hashForNavRecord(naContext c, const FGNavRecord* nav, const SGGeod& rel)
152 naRef navdata = naNewHash(c);
153 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
154 HASHSET("id", 2, naStr_fromdata(naNewString(c),
155 const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
156 HASHSET("name", 4, naStr_fromdata(naNewString(c),
157 const_cast<char *>(nav->name().c_str()), nav->name().length()));
158 HASHSET("frequency", 9, naNum(nav->get_freq()));
159 HASHSET("lat", 3, naNum(nav->get_lat()));
160 HASHSET("lon", 3, naNum(nav->get_lon()));
161 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
162 HASHSET("type", 4, naStr_fromdata(naNewString(c),
163 const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
164 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( rel, nav->geod() ) * SG_NM_TO_METER ) );
165 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( rel, nav->geod() ) ) );
167 // record the real object as a ghost for further operations
168 HASHSET("_positioned",11, ghostForPositioned(c, nav));
174 bool geodFromHash(naRef ref, SGGeod& result)
176 if (!naIsHash(ref)) {
180 // first, see if the hash contains a FGPositioned ghost - in which case
181 // we can read off its position directly
182 naRef posGhost = naHash_cget(ref, (char*) "_positioned");
183 if (!naIsNil(posGhost)) {
184 FGPositioned* pos = positionedGhost(posGhost);
185 result = pos->geod();
189 // then check for manual latitude / longitude names
190 naRef lat = naHash_cget(ref, (char*) "lat");
191 naRef lon = naHash_cget(ref, (char*) "lon");
192 if (naIsNum(lat) && naIsNum(lon)) {
193 result = SGGeod::fromDeg(naNumValue(lat).num, naNumValue(lon).num);
197 // check for any synonyms?
198 // latitude + longitude?
203 // Convert a cartesian point to a geodetic lat/lon/altitude.
204 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
206 double lat, lon, alt, xyz[3];
207 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
208 for(int i=0; i<3; i++)
209 xyz[i] = naNumValue(args[i]).num;
210 sgCartToGeod(xyz, &lat, &lon, &alt);
211 lat *= SG_RADIANS_TO_DEGREES;
212 lon *= SG_RADIANS_TO_DEGREES;
213 naRef vec = naNewVector(c);
214 naVec_append(vec, naNum(lat));
215 naVec_append(vec, naNum(lon));
216 naVec_append(vec, naNum(alt));
220 // Convert a geodetic lat/lon/altitude to a cartesian point.
221 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
223 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
224 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
225 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
226 double alt = naNumValue(args[2]).num;
228 sgGeodToCart(lat, lon, alt, xyz);
229 naRef vec = naNewVector(c);
230 naVec_append(vec, naNum(xyz[0]));
231 naVec_append(vec, naNum(xyz[1]));
232 naVec_append(vec, naNum(xyz[2]));
236 // For given geodetic point return array with elevation, and a material data
237 // hash, or nil if there's no information available (tile not loaded). If
238 // information about the material isn't available, then nil is returned instead
240 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
242 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
243 if(argc < 2 || argc > 3)
244 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
245 double lat = naNumValue(args[0]).num;
246 double lon = naNumValue(args[1]).num;
247 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
248 const SGMaterial *mat;
249 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
250 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
252 naRef vec = naNewVector(c);
253 naVec_append(vec, naNum(elev));
254 naRef matdata = naNil();
256 matdata = naNewHash(c);
257 naRef names = naNewVector(c);
258 const std::vector<std::string> n = mat->get_names();
259 for(unsigned int i=0; i<n.size(); i++)
260 naVec_append(names, naStr_fromdata(naNewString(c),
261 const_cast<char*>(n[i].c_str()), n[i].size()));
262 HASHSET("names", 5, names);
263 HASHSET("solid", 5, naNum(mat->get_solid()));
264 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
265 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
266 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
267 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
268 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
270 naVec_append(vec, matdata);
276 class AirportInfoFilter : public FGAirport::AirportFilter
279 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
282 virtual FGPositioned::Type minType() const {
286 virtual FGPositioned::Type maxType() const {
290 FGPositioned::Type type;
293 // Returns data hash for particular or nearest airport of a <type>, or nil
296 // airportinfo(<id>); e.g. "KSFO"
297 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
298 // airportinfo() same as airportinfo("airport")
299 // airportinfo(<lat>, <lon> [, <type>]);
300 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
302 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
303 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
305 FGAirport* apt = NULL;
307 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
308 pos = SGGeod::fromDeg(args[1].num, args[0].num);
312 pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
315 double maxRange = 10000.0; // expose this? or pick a smaller value?
317 AirportInfoFilter filter; // defaults to airports only
320 // fall through and use AIRPORT
321 } else if(argc == 1 && naIsString(args[0])) {
322 const char *s = naStr_data(args[0]);
323 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
324 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
325 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
327 // user provided an <id>, hopefully
328 apt = FGAirport::findByIdent(s);
330 // return nil here, but don't raise a runtime error; this is a
331 // legitamate way to validate an ICAO code, for example in a
332 // dialog box or similar.
337 naRuntimeError(c, "airportinfo() with invalid function arguments");
342 apt = FGAirport::findClosest(pos, maxRange, &filter);
343 if(!apt) return naNil();
346 std::string id = apt->ident();
347 std::string name = apt->name();
350 naRef rwys = naNewHash(c);
351 for(unsigned int r=0; r<apt->numRunways(); ++r) {
352 FGRunway* rwy(apt->getRunwayByIndex(r));
354 naRef rwyid = naStr_fromdata(naNewString(c),
355 const_cast<char *>(rwy->ident().c_str()),
356 rwy->ident().length());
358 naRef rwydata = naNewHash(c);
359 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
360 HASHSET("id", 2, rwyid);
361 HASHSET("lat", 3, naNum(rwy->latitude()));
362 HASHSET("lon", 3, naNum(rwy->longitude()));
363 HASHSET("heading", 7, naNum(rwy->headingDeg()));
364 HASHSET("length", 6, naNum(rwy->lengthM()));
365 HASHSET("width", 5, naNum(rwy->widthM()));
366 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
367 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
370 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
373 std::vector<flightgear::SID*> sids(rwy->getSIDs());
374 naRef sidVec = naNewVector(c);
376 for (unsigned int s=0; s < sids.size(); ++s) {
377 naRef procId = naStr_fromdata(naNewString(c),
378 const_cast<char *>(sids[s]->ident().c_str()),
379 sids[s]->ident().length());
380 naVec_append(sidVec, procId);
382 HASHSET("sids", 4, sidVec);
384 std::vector<flightgear::STAR*> stars(rwy->getSTARs());
385 naRef starVec = naNewVector(c);
387 for (unsigned int s=0; s < stars.size(); ++s) {
388 naRef procId = naStr_fromdata(naNewString(c),
389 const_cast<char *>(stars[s]->ident().c_str()),
390 stars[s]->ident().length());
391 naVec_append(starVec, procId);
393 HASHSET("stars", 5, starVec);
396 naHash_set(rwys, rwyid, rwydata);
400 naRef aptdata = naNewHash(c);
401 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
402 HASHSET("id", 2, naStr_fromdata(naNewString(c),
403 const_cast<char *>(id.c_str()), id.length()));
404 HASHSET("name", 4, naStr_fromdata(naNewString(c),
405 const_cast<char *>(name.c_str()), name.length()));
406 HASHSET("lat", 3, naNum(apt->getLatitude()));
407 HASHSET("lon", 3, naNum(apt->getLongitude()));
408 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
409 HASHSET("has_metar", 9, naNum(apt->getMetar()));
410 HASHSET("runways", 7, rwys);
416 // Returns vector of data hash for navaid of a <type>, nil on error
417 // navaids sorted by ascending distance
418 // navinfo([<lat>,<lon>],[<type>],[<id>])
419 // lat/lon (numeric): use latitude/longitude instead of ac position
420 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
421 // id: (partial) id of the fix
423 // navinfo("vor") returns all vors
424 // navinfo("HAM") return all navaids who's name start with "HAM"
425 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
426 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
427 // sorted by distance relative to lat=34, lon=48
428 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
430 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
431 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
434 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
435 pos = SGGeod::fromDeg(args[1].num, args[0].num);
439 pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
442 FGPositioned::Type type = FGPositioned::INVALID;
443 nav_list_type navlist;
444 const char * id = "";
446 if(argc > 0 && naIsString(args[0])) {
447 const char *s = naStr_data(args[0]);
448 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
449 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
450 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
451 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
452 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
453 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
454 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
455 else id = s; // this is an id
460 if(argc > 0 && naIsString(args[0])) {
462 naRuntimeError(c, "navinfo() called with navaid id");
465 id = naStr_data(args[0]);
471 naRuntimeError(c, "navinfo() called with too many arguments");
475 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
477 naRef reply = naNewVector(c);
478 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
479 const FGNavRecord * nav = *it;
482 naRef navdata = naNewHash(c);
483 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
484 HASHSET("id", 2, naStr_fromdata(naNewString(c),
485 const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
486 HASHSET("name", 4, naStr_fromdata(naNewString(c),
487 const_cast<char *>(nav->name().c_str()), nav->name().length()));
488 HASHSET("frequency", 9, naNum(nav->get_freq()));
489 HASHSET("lat", 3, naNum(nav->get_lat()));
490 HASHSET("lon", 3, naNum(nav->get_lon()));
491 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
492 HASHSET("type", 4, naStr_fromdata(naNewString(c),
493 const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
494 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( pos, nav->geod() ) * SG_NM_TO_METER ) );
495 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( pos, nav->geod() ) ) );
497 naVec_append( reply, navdata );
502 // Convert a cartesian point to a geodetic lat/lon/altitude.
503 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
506 if ((argc == 1) && geodFromHash(args[0], pos)) {
508 } else if (argc == 2) {
509 double lat = naNumValue(args[0]).num,
510 lon = naNumValue(args[1]).num;
511 pos = SGGeod::fromDeg(lon, lat);
513 naRuntimeError(c, "magvar() expects 1 object arugment, or a lat/lon");
516 double jd = globals->get_time_params()->getJD();
517 double magvarDeg = sgGetMagVar(pos, jd);
518 return naNum(magvarDeg);
521 // Table of extension functions. Terminate with zeros.
522 static struct { const char* name; naCFunction func; } funcs[] = {
523 { "carttogeod", f_carttogeod },
524 { "geodtocart", f_geodtocart },
525 { "geodinfo", f_geodinfo },
526 { "airportinfo", f_airportinfo },
527 { "magvar", f_magvar },
531 static void hashset(naContext c, naRef hash, const char* key, naRef val)
533 naRef s = naNewString(c);
534 naStr_fromdata(s, (char*)key, strlen(key));
535 naHash_set(hash, s, val);
538 naRef initNasalPositioned(naRef globals, naContext c)
540 for(int i=0; funcs[i].name; i++) {
541 hashset(c, globals, funcs[i].name,
542 naNewFunc(c, naNewCCode(c, funcs[i].func)));