1 // NasalPositioned_cppbind.cxx -- expose FGPositioned classes to Nasal
3 // Port of NasalPositioned.cpp to the new nasal/cppbind helpers. Will replace
4 // old NasalPositioned.cpp once finished.
6 // Copyright (C) 2013 Thomas Geymayer <tomgey@gmail.com>
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 #include "NasalPositioned.hxx"
31 #include <boost/foreach.hpp>
32 #include <boost/algorithm/string/case_conv.hpp>
34 #include <simgear/nasal/cppbind/from_nasal.hxx>
35 #include <simgear/nasal/cppbind/to_nasal.hxx>
36 #include <simgear/nasal/cppbind/NasalHash.hxx>
37 #include <simgear/nasal/cppbind/Ghost.hxx>
39 #include <Airports/airport.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/pavement.hxx>
42 #include <ATC/CommStation.hxx>
43 #include <Main/globals.hxx>
44 #include <Navaids/NavDataCache.hxx>
45 #include <Navaids/navlist.hxx>
46 #include <Navaids/navrecord.hxx>
47 #include <Navaids/fix.hxx>
49 typedef nasal::Ghost<FGPositionedRef> NasalPositioned;
50 typedef nasal::Ghost<FGRunwayRef> NasalRunway;
51 typedef nasal::Ghost<FGParkingRef> NasalParking;
52 typedef nasal::Ghost<FGAirportRef> NasalAirport;
53 typedef nasal::Ghost<flightgear::CommStationRef> NasalCommStation;
54 typedef nasal::Ghost<FGNavRecordRef> NasalNavRecord;
55 typedef nasal::Ghost<FGRunwayRef> NasalRunway;
56 typedef nasal::Ghost<FGFixRef> NasalFix;
58 //------------------------------------------------------------------------------
59 naRef to_nasal_helper(naContext c, flightgear::SID* sid)
62 return nasal::to_nasal(c, sid->ident());
65 //------------------------------------------------------------------------------
66 naRef to_nasal_helper(naContext c, flightgear::STAR* star)
69 return nasal::to_nasal(c, star->ident());
72 //------------------------------------------------------------------------------
73 naRef to_nasal_helper(naContext c, flightgear::Approach* iap)
75 // TODO Approach ghost
76 return nasal::to_nasal(c, iap->ident());
79 //------------------------------------------------------------------------------
80 static naRef f_navaid_course(naContext, FGNavRecord& nav)
82 if( !( nav.type() == FGPositioned::ILS
83 || nav.type() == FGPositioned::LOC
87 double radial = nav.get_multiuse();
88 return naNum(SGMiscd::normalizePeriodic(0.5, 360.5, radial));
91 //------------------------------------------------------------------------------
92 static FGRunwayBaseRef f_airport_runway(FGAirport& apt, std::string ident)
94 boost::to_upper(ident);
96 if( apt.hasRunwayWithIdent(ident) )
97 return apt.getRunwayByIdent(ident);
98 else if( apt.hasHelipadWithIdent(ident) )
99 return apt.getHelipadByIdent(ident);
104 //------------------------------------------------------------------------------
105 template<class T, class C1, class C2>
106 std::vector<T> extract( const std::vector<C1>& in,
107 T (C2::*getter)() const )
109 std::vector<T> ret(in.size());
110 std::transform(in.begin(), in.end(), ret.begin(), std::mem_fun(getter));
114 //------------------------------------------------------------------------------
115 static naRef f_airport_comms(FGAirport& apt, const nasal::CallContext& ctx)
117 FGPositioned::Type comm_type =
118 FGPositioned::typeFromName( ctx.getArg<std::string>(0) );
120 // if we have an explicit type, return a simple vector of frequencies
121 if( comm_type != FGPositioned::INVALID )
124 extract( apt.commStationsOfType(comm_type),
125 &flightgear::CommStation::freqMHz )
128 // otherwise return a vector of ghosts, one for each comm station.
129 return ctx.to_nasal(apt.commStations());
132 //------------------------------------------------------------------------------
133 FGRunway* runwayFromNasalArg( const FGAirport& apt,
134 const nasal::CallContext& ctx,
137 if( index >= ctx.argc )
142 std::string ident = ctx.getArg<std::string>(index);
145 if( !apt.hasRunwayWithIdent(ident) )
146 // TODO warning/exception?
149 return apt.getRunwayByIdent(ident);
155 // TODO warn/error if no runway?
156 return NasalRunway::fromNasal(ctx.c, ctx.args[index]);
159 //------------------------------------------------------------------------------
160 static naRef f_airport_sids(FGAirport& apt, const nasal::CallContext& ctx)
162 FGRunway* rwy = runwayFromNasalArg(apt, ctx);
165 extract(rwy ? rwy->getSIDs() : apt.getSIDs(), &flightgear::SID::ident)
169 //------------------------------------------------------------------------------
170 static naRef f_airport_stars(FGAirport& apt, const nasal::CallContext& ctx)
172 FGRunway* rwy = runwayFromNasalArg(apt, ctx);
175 extract(rwy ? rwy->getSTARs() : apt.getSTARs(), &flightgear::STAR::ident)
179 //------------------------------------------------------------------------------
180 static naRef f_airport_approaches(FGAirport& apt, const nasal::CallContext& ctx)
182 FGRunway* rwy = runwayFromNasalArg(apt, ctx);
184 flightgear::ProcedureType type = flightgear::PROCEDURE_INVALID;
185 std::string type_str = ctx.getArg<std::string>(1);
186 if( !type_str.empty() )
188 boost::to_upper(type_str);
189 if( type_str == "NDB" ) type = flightgear::PROCEDURE_APPROACH_NDB;
190 else if( type_str == "VOR" ) type = flightgear::PROCEDURE_APPROACH_VOR;
191 else if( type_str == "ILS" ) type = flightgear::PROCEDURE_APPROACH_ILS;
192 else if( type_str == "RNAV") type = flightgear::PROCEDURE_APPROACH_RNAV;
197 extract( rwy ? rwy->getApproaches(type)
198 // no runway specified, report them all
199 : apt.getApproaches(type),
200 &flightgear::Approach::ident )
204 //------------------------------------------------------------------------------
206 f_airport_parking(FGAirport& apt, nasal::CallContext ctx)
208 std::string type = ctx.getArg<std::string>(0);
209 bool only_available = ctx.getArg<bool>(1);
211 FGAirportDynamics* dynamics = apt.getDynamics();
212 PositionedIDVec parkings =
213 flightgear::NavDataCache::instance()
214 ->airportItemsOfType(apt.guid(), FGPositioned::PARKING);
217 BOOST_FOREACH(PositionedID parking, parkings)
219 // filter out based on availability and type
220 if( only_available && !dynamics->isParkingAvailable(parking) )
223 FGParking* park = dynamics->getParking(parking);
224 if( !type.empty() && (park->getType() != type) )
234 * Extract a SGGeod from a nasal function argument list.
237 * {"lat": <lat-deg>, "lon": <lon-deg>}
238 * geo.Coord.new() (aka. {"_lat": <lat-rad>, "_lon": <lon-rad>})
240 static bool extractGeod(nasal::CallContext& ctx, SGGeod& result)
248 NasalPositioned::fromNasal(ctx.c, ctx.requireArg<naRef>(0));
252 result = pos->geod();
257 else if( ctx.isHash(0) )
259 nasal::Hash pos_hash = ctx.requireArg<nasal::Hash>(0);
261 // check for manual latitude / longitude names
262 naRef lat = pos_hash.get("lat"),
263 lon = pos_hash.get("lon");
264 if( naIsNum(lat) && naIsNum(lon) )
266 result = SGGeod::fromDeg( ctx.from_nasal<double>(lon),
267 ctx.from_nasal<double>(lat) );
272 // geo.Coord uses _lat/_lon in radians
273 // TODO should we check if its really a geo.Coord?
274 lat = pos_hash.get("_lat");
275 lon = pos_hash.get("_lon");
276 if( naIsNum(lat) && naIsNum(lon) )
278 result = SGGeod::fromRad( ctx.from_nasal<double>(lon),
279 ctx.from_nasal<double>(lat) );
284 else if( ctx.isNumeric(0) && ctx.isNumeric(1) )
287 result = SGGeod::fromDeg( ctx.requireArg<double>(1),
288 ctx.requireArg<double>(0) );
297 * Extract position from ctx or return current aircraft position if not given.
299 static SGGeod getPosition(nasal::CallContext& ctx)
302 if( !extractGeod(ctx, pos) )
303 pos = globals->get_aircraft_position();
308 //------------------------------------------------------------------------------
309 // Returns Nasal ghost for particular or nearest airport of a <type>, or nil
312 // airportinfo(<id>); e.g. "KSFO"
313 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
314 // airportinfo() same as airportinfo("airport")
315 // airportinfo(<lat>, <lon> [, <type>]);
316 static naRef f_airportinfo(nasal::CallContext ctx)
318 SGGeod pos = getPosition(ctx);
321 naRuntimeError(ctx.c, "airportinfo() with invalid function arguments");
323 // optional type/ident
324 std::string ident("airport");
325 if( ctx.isString(0) )
326 ident = ctx.requireArg<std::string>(0);
328 FGAirport::TypeRunwayFilter filter;
329 if( !filter.fromTypeString(ident) )
330 // user provided an <id>, hopefully
331 return ctx.to_nasal(FGAirport::findByIdent(ident));
333 double maxRange = 10000.0; // expose this? or pick a smaller value?
334 return ctx.to_nasal( FGAirport::findClosest(pos, maxRange, &filter) );
338 * findAirportsWithinRange([<position>,] <range-nm> [, type])
340 static naRef f_findAirportsWithinRange(nasal::CallContext ctx)
342 SGGeod pos = getPosition(ctx);
343 double range_nm = ctx.requireArg<double>(0);
345 FGAirport::TypeRunwayFilter filter; // defaults to airports only
346 filter.fromTypeString( ctx.getArg<std::string>(1) );
348 FGPositionedList apts = FGPositioned::findWithinRange(pos, range_nm, &filter);
349 FGPositioned::sortByRange(apts, pos);
351 return ctx.to_nasal(apts);
355 * findAirportsByICAO(<ident/prefix> [, type])
357 static naRef f_findAirportsByICAO(nasal::CallContext ctx)
359 std::string prefix = ctx.requireArg<std::string>(0);
361 FGAirport::TypeRunwayFilter filter; // defaults to airports only
362 filter.fromTypeString( ctx.getArg<std::string>(1) );
364 return ctx.to_nasal( FGPositioned::findAllWithIdent(prefix, &filter, false) );
367 // Returns vector of data hash for navaid of a <type>, nil on error
368 // navaids sorted by ascending distance
369 // navinfo([<lat>,<lon>],[<type>],[<id>])
370 // lat/lon (numeric): use latitude/longitude instead of ac position
371 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
372 // id: (partial) id of the fix
374 // navinfo("vor") returns all vors
375 // navinfo("HAM") return all navaids who's name start with "HAM"
376 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
377 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
378 // sorted by distance relative to lat=34, lon=48
379 static naRef f_navinfo(nasal::CallContext ctx)
381 SGGeod pos = getPosition(ctx);
382 std::string id = ctx.getArg<std::string>(0);
384 FGNavList::TypeFilter filter;
385 if( filter.fromTypeString(id) )
386 id = ctx.getArg<std::string>(1);
387 else if( ctx.argc > 1 )
388 naRuntimeError(ctx.c, "navinfo() already got an ident");
390 return ctx.to_nasal( FGNavList::findByIdentAndFreq(pos, id, 0.0, &filter) );
393 //------------------------------------------------------------------------------
394 static naRef f_findWithinRange(nasal::CallContext ctx)
396 SGGeod pos = getPosition(ctx);
397 double range_nm = ctx.requireArg<double>(0);
399 FGPositioned::TypeFilter filter(FGPositioned::typeFromName(ctx.getArg<std::string>(1)));
401 FGPositionedList items = FGPositioned::findWithinRange(pos, range_nm, &filter);
402 FGPositioned::sortByRange(items, pos);
403 return ctx.to_nasal(items);
406 static naRef f_findByIdent(nasal::CallContext ctx)
408 std::string prefix = ctx.requireArg<std::string>(0);
409 std::string typeSpec = ctx.getArg<std::string>(1);
410 FGPositioned::TypeFilter filter(FGPositioned::TypeFilter::fromString(typeSpec));
411 bool exact = ctx.getArg<bool>(2, false);
413 return ctx.to_nasal( FGPositioned::findAllWithIdent(prefix, &filter, exact) );
416 static naRef f_findByName(nasal::CallContext ctx)
418 std::string prefix = ctx.requireArg<std::string>(0);
419 std::string typeSpec = ctx.getArg<std::string>(1);
420 FGPositioned::TypeFilter filter(FGPositioned::TypeFilter::fromString(typeSpec));
422 return ctx.to_nasal( FGPositioned::findAllWithName(prefix, &filter, false) );
425 //------------------------------------------------------------------------------
427 static naRef f_courseAndDistance(nasal::CallContext ctx)
429 SGGeod from = globals->get_aircraft_position(), to, pos;
430 bool ok = extractGeod(ctx, pos);
432 naRuntimeError(ctx.c, "invalid arguments to courseAndDistance");
435 if (extractGeod(ctx, to)) {
436 from = pos; // we parsed both FROM and TO args, so first was FROM
438 to = pos; // only parsed one arg, so FROM is current
441 double course, course2, d;
442 SGGeodesy::inverse(from, to, course, course2, d);
444 naRef result = naNewVector(ctx.c);
445 naVec_append(result, naNum(course));
446 naVec_append(result, naNum(d * SG_METER_TO_NM));
450 static naRef f_sortByRange(nasal::CallContext ctx)
452 FGPositionedList items = ctx.requireArg<FGPositionedList>(0);
454 FGPositioned::sortByRange(items, getPosition(ctx));
455 return ctx.to_nasal(items);
458 //------------------------------------------------------------------------------
459 naRef initNasalPositioned_cppbind(naRef globalsRef, naContext c, naRef gcSave)
461 NasalPositioned::init("Positioned")
462 .member("id", &FGPositioned::ident)
463 .member("ident", &FGPositioned::ident) // TODO to we really need id and ident?
464 .member("name", &FGPositioned::name)
465 .member("type", &FGPositioned::typeString)
466 .member("lat", &FGPositioned::latitude)
467 .member("lon", &FGPositioned::longitude)
468 .member("elevation", &FGPositioned::elevationM);
469 NasalRunway::init("Runway")
470 .bases<NasalPositioned>();
471 NasalParking::init("Parking")
472 .bases<NasalPositioned>();
473 NasalCommStation::init("CommStation")
474 .bases<NasalPositioned>()
475 .member("frequency", &flightgear::CommStation::freqMHz);
476 NasalNavRecord::init("Navaid")
477 .bases<NasalPositioned>()
478 .member("frequency", &FGNavRecord::get_freq)
479 .member("range_nm", &FGNavRecord::get_range)
480 .member("course", &f_navaid_course);
482 NasalFix::init("Fix")
483 .bases<NasalPositioned>();
485 NasalAirport::init("FGAirport")
486 .bases<NasalPositioned>()
487 .member("has_metar", &FGAirport::getMetar)
488 .member("runways", &FGAirport::getRunwayMap)
489 .member("helipads", &FGAirport::getHelipadMap)
490 .member("taxiways", &FGAirport::getTaxiways)
491 .member("pavements", &FGAirport::getPavements)
492 .method("runway", &f_airport_runway)
493 .method("helipad", &f_airport_runway)
494 .method("tower", &FGAirport::getTowerLocation)
495 .method("comms", &f_airport_comms)
496 .method("sids", &f_airport_sids)
497 .method("stars", &f_airport_stars)
498 .method("getApproachList", f_airport_approaches)
499 .method("parking", &f_airport_parking)
500 .method("getSid", &FGAirport::findSIDWithIdent)
501 .method("getStar", &FGAirport::findSTARWithIdent)
502 .method("getIAP", &FGAirport::findApproachWithIdent)
503 .method("tostring", &FGAirport::toString);
505 nasal::Hash globals(globalsRef, c),
506 positioned( globals.createHash("positioned") );
508 positioned.set("airportinfo", &f_airportinfo);
509 positioned.set("findAirportsWithinRange", f_findAirportsWithinRange);
510 positioned.set("findAirportsByICAO", &f_findAirportsByICAO);
511 positioned.set("navinfo", &f_navinfo);
513 positioned.set("findWithinRange", &f_findWithinRange);
514 positioned.set("findByIdent", &f_findByIdent);
515 positioned.set("findByName", &f_findByName);
516 positioned.set("courseAndDistance", &f_courseAndDistance);
517 positioned.set("sortByRange", &f_sortByRange);