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>
30 #include <boost/algorithm/string/case_conv.hpp>
32 #include <simgear/sg_inlines.h>
33 #include <simgear/scene/material/mat.hxx>
34 #include <simgear/magvar/magvar.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/bucket/newbucket.hxx>
38 #include <Airports/runways.hxx>
39 #include <Airports/simple.hxx>
40 #include <Airports/dynamics.hxx>
41 #include <Airports/parking.hxx>
42 #include <Navaids/navlist.hxx>
43 #include <Navaids/procedure.hxx>
44 #include <Main/globals.hxx>
45 #include <Main/fg_props.hxx>
46 #include <Scenery/scenery.hxx>
47 #include <ATC/CommStation.hxx>
48 #include <Navaids/route.hxx>
49 #include <Navaids/waypoint.hxx>
50 #include <Navaids/fix.hxx>
51 #include <Autopilot/route_mgr.hxx>
52 #include <Navaids/procedure.hxx>
53 #include <Navaids/airways.hxx>
55 using namespace flightgear;
57 static void positionedGhostDestroy(void* g);
58 static void wayptGhostDestroy(void* g);
59 static void legGhostDestroy(void* g);
60 static void routeBaseGhostDestroy(void* g);
62 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
64 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
65 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
67 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
68 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
70 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
71 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
73 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
74 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
76 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
77 naGhostType WayptGhostType = { wayptGhostDestroy,
82 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
83 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value);
85 naGhostType FPLegGhostType = { legGhostDestroy,
90 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
91 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
93 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy,
95 flightplanGhostGetMember,
96 flightplanGhostSetMember
99 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
100 naGhostType ProcedureGhostType = { routeBaseGhostDestroy,
102 procedureGhostGetMember,
105 static void hashset(naContext c, naRef hash, const char* key, naRef val)
107 naRef s = naNewString(c);
108 naStr_fromdata(s, (char*)key, strlen(key));
109 naHash_set(hash, s, val);
112 static naRef stringToNasal(naContext c, const std::string& s)
114 return naStr_fromdata(naNewString(c),
115 const_cast<char *>(s.c_str()),
119 static WayptFlag wayptFlagFromString(const char* s)
121 if (!strcmp(s, "sid")) return WPT_DEPARTURE;
122 if (!strcmp(s, "star")) return WPT_ARRIVAL;
123 if (!strcmp(s, "approach")) return WPT_APPROACH;
124 if (!strcmp(s, "missed")) return WPT_MISS;
125 if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
127 return (WayptFlag) 0;
130 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
132 if (flags & WPT_PSEUDO) return stringToNasal(c, "pseudo");
133 if (flags & WPT_DEPARTURE) return stringToNasal(c, "sid");
134 if (flags & WPT_ARRIVAL) return stringToNasal(c, "star");
135 if (flags & WPT_MISS) return stringToNasal(c, "missed");
136 if (flags & WPT_APPROACH) return stringToNasal(c, "approach");
140 static FGPositioned* positionedGhost(naRef r)
142 if ((naGhost_type(r) == &AirportGhostType) ||
143 (naGhost_type(r) == &NavaidGhostType) ||
144 (naGhost_type(r) == &RunwayGhostType) ||
145 (naGhost_type(r) == &FixGhostType))
147 return (FGPositioned*) naGhost_ptr(r);
153 static FGAirport* airportGhost(naRef r)
155 if (naGhost_type(r) == &AirportGhostType)
156 return (FGAirport*) naGhost_ptr(r);
160 static FGNavRecord* navaidGhost(naRef r)
162 if (naGhost_type(r) == &NavaidGhostType)
163 return (FGNavRecord*) naGhost_ptr(r);
167 static FGRunway* runwayGhost(naRef r)
169 if (naGhost_type(r) == &RunwayGhostType)
170 return (FGRunway*) naGhost_ptr(r);
174 static FGFix* fixGhost(naRef r)
176 if (naGhost_type(r) == &FixGhostType)
177 return (FGFix*) naGhost_ptr(r);
182 static void positionedGhostDestroy(void* g)
184 FGPositioned* pos = (FGPositioned*)g;
185 if (!FGPositioned::put(pos)) // unref
189 static Waypt* wayptGhost(naRef r)
191 if (naGhost_type(r) == &WayptGhostType)
192 return (Waypt*) naGhost_ptr(r);
194 if (naGhost_type(r) == &FPLegGhostType) {
195 FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
196 return leg->waypoint();
202 static void wayptGhostDestroy(void* g)
204 Waypt* wpt = (Waypt*)g;
205 if (!Waypt::put(wpt)) // unref
209 static void legGhostDestroy(void* g)
215 static FlightPlan::Leg* fpLegGhost(naRef r)
217 if (naGhost_type(r) == &FPLegGhostType)
218 return (FlightPlan::Leg*) naGhost_ptr(r);
222 static Procedure* procedureGhost(naRef r)
224 if (naGhost_type(r) == &ProcedureGhostType)
225 return (Procedure*) naGhost_ptr(r);
229 static FlightPlan* flightplanGhost(naRef r)
231 if (naGhost_type(r) == &FlightPlanGhostType)
232 return (FlightPlan*) naGhost_ptr(r);
236 static void routeBaseGhostDestroy(void* g)
241 static naRef airportPrototype;
242 static naRef flightplanPrototype;
243 static naRef waypointPrototype;
244 static naRef geoCoordClass;
245 static naRef fpLegPrototype;
246 static naRef procedurePrototype;
248 naRef ghostForAirport(naContext c, const FGAirport* apt)
254 FGPositioned::get(apt); // take a ref
255 return naNewGhost2(c, &AirportGhostType, (void*) apt);
258 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
264 FGPositioned::get(n); // take a ref
265 return naNewGhost2(c, &NavaidGhostType, (void*) n);
268 naRef ghostForRunway(naContext c, const FGRunway* r)
274 FGPositioned::get(r); // take a ref
275 return naNewGhost2(c, &RunwayGhostType, (void*) r);
278 naRef ghostForFix(naContext c, const FGFix* r)
284 FGPositioned::get(r); // take a ref
285 return naNewGhost2(c, &FixGhostType, (void*) r);
289 naRef ghostForWaypt(naContext c, const Waypt* wpt)
295 Waypt::get(wpt); // take a ref
296 return naNewGhost2(c, &WayptGhostType, (void*) wpt);
299 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
305 return naNewGhost2(c, &FPLegGhostType, (void*) leg);
308 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
314 return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
317 naRef ghostForProcedure(naContext c, const Procedure* proc)
323 return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
326 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
328 const char* fieldName = naStr_data(field);
329 FGAirport* apt = (FGAirport*) g;
331 if (!strcmp(fieldName, "parents")) {
332 *out = naNewVector(c);
333 naVec_append(*out, airportPrototype);
334 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
335 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
336 else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
337 else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
338 else if (!strcmp(fieldName, "elevation")) {
339 *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
340 } else if (!strcmp(fieldName, "has_metar")) {
341 *out = naNum(apt->getMetar());
342 } else if (!strcmp(fieldName, "runways")) {
344 for(unsigned int r=0; r<apt->numRunways(); ++r) {
345 FGRunway* rwy(apt->getRunwayByIndex(r));
346 naRef rwyid = stringToNasal(c, rwy->ident());
347 naRef rwydata = ghostForRunway(c, rwy);
348 naHash_set(*out, rwyid, rwydata);
358 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
360 if (!strcmp(fieldName, "wp_name")) *out = stringToNasal(c, wpt->ident());
361 else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
362 else if (!strcmp(fieldName, "wp_role")) *out = wayptFlagToNasal(c, wpt->flags());
363 else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
364 else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
365 else if (!strcmp(fieldName, "wp_parent_name")) {
366 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
367 *out = proc ? stringToNasal(c, proc->ident()) : naNil();
368 } else if (!strcmp(fieldName, "wp_parent")) {
369 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
370 *out = ghostForProcedure(c, proc);
371 } else if (!strcmp(fieldName, "fly_type")) {
372 if (wpt->type() == "hold") {
373 *out = stringToNasal(c, "Hold");
375 *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
378 return NULL; // member not found
384 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
386 const char* fieldName = naStr_data(field);
387 Waypt* wpt = (flightgear::Waypt*) g;
388 return waypointCommonGetMember(c, wpt, fieldName, out);
391 static RouteRestriction routeRestrictionFromString(const char* s)
395 if (u == "computed") return RESTRICT_COMPUTED;
396 if (u == "at") return RESTRICT_AT;
397 if (u == "mach") return SPEED_RESTRICT_MACH;
398 if (u == "computed-mach") return SPEED_COMPUTED_MACH;
399 if (u == "delete") return RESTRICT_DELETE;
400 return RESTRICT_NONE;
403 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
406 case RESTRICT_NONE: return naNil();
407 case RESTRICT_AT: return stringToNasal(c, "at");
408 case RESTRICT_ABOVE: return stringToNasal(c, "above");
409 case RESTRICT_BELOW: return stringToNasal(c, "below");
410 case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
411 case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
412 case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
413 case RESTRICT_DELETE: return stringToNasal(c, "delete");
419 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
421 const char* fieldName = naStr_data(field);
422 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
423 Waypt* wpt = leg->waypoint();
425 if (!strcmp(fieldName, "parents")) {
426 *out = naNewVector(c);
427 naVec_append(*out, fpLegPrototype);
428 } else if (!strcmp(fieldName, "index")) {
429 *out = naNum(leg->index());
430 } else if (!strcmp(fieldName, "alt_cstr")) {
431 *out = naNum(leg->altitudeFt());
432 } else if (!strcmp(fieldName, "alt_cstr_type")) {
433 *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
434 } else if (!strcmp(fieldName, "speed_cstr")) {
435 double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
437 } else if (!strcmp(fieldName, "speed_cstr_type")) {
438 *out = routeRestrictionToNasal(c, leg->speedRestriction());
439 } else if (!strcmp(fieldName, "leg_distance")) {
440 *out = naNum(leg->distanceNm());
441 } else if (!strcmp(fieldName, "leg_bearing")) {
442 *out = naNum(leg->courseDeg());
443 } else if (!strcmp(fieldName, "distance_along_route")) {
444 *out = naNum(leg->distanceAlongRoute());
445 } else { // check for fields defined on the underlying waypoint
446 return waypointCommonGetMember(c, wpt, fieldName, out);
449 return ""; // success
452 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
454 const char* fieldName = naStr_data(field);
455 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
457 if (!strcmp(fieldName, "wp_role")) {
458 if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
459 if (leg->waypoint()->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
460 WayptFlag f = wayptFlagFromString(naStr_data(value));
462 naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
465 leg->waypoint()->setFlag(f, true);
469 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
471 const char* fieldName = naStr_data(field);
472 FlightPlan* fp = (FlightPlan*) g;
474 if (!strcmp(fieldName, "parents")) {
475 *out = naNewVector(c);
476 naVec_append(*out, flightplanPrototype);
477 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
478 else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
479 else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
480 else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
481 else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
482 else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
483 else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
484 else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
485 else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
486 else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
487 else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
495 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
497 const char* fieldName = naStr_data(field);
498 FlightPlan* fp = (FlightPlan*) g;
500 if (!strcmp(fieldName, "id")) {
501 if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
502 fp->setIdent(naStr_data(value));
503 } else if (!strcmp(fieldName, "current")) {
504 int index = value.num;
505 if ((index < 0) || (index >= fp->numLegs())) {
508 fp->setCurrentIndex(index);
509 } else if (!strcmp(fieldName, "departure")) {
510 FGAirport* apt = airportGhost(value);
512 fp->setDeparture(apt);
516 FGRunway* rwy = runwayGhost(value);
518 fp->setDeparture(rwy);
522 naRuntimeError(c, "bad argument type setting departure");
523 } else if (!strcmp(fieldName, "destination")) {
524 FGAirport* apt = airportGhost(value);
526 fp->setDestination(apt);
530 FGRunway* rwy = runwayGhost(value);
532 fp->setDestination(rwy);
536 naRuntimeError(c, "bad argument type setting destination");
537 } else if (!strcmp(fieldName, "departure_runway")) {
538 FGRunway* rwy = runwayGhost(value);
540 fp->setDeparture(rwy);
544 naRuntimeError(c, "bad argument type setting departure");
545 } else if (!strcmp(fieldName, "destination_runway")) {
546 FGRunway* rwy = runwayGhost(value);
548 fp->setDestination(rwy);
552 naRuntimeError(c, "bad argument type setting departure");
553 } else if (!strcmp(fieldName, "sid")) {
554 Procedure* proc = procedureGhost(value);
555 if (proc && (proc->type() == PROCEDURE_SID)) {
556 fp->setSID((flightgear::SID*) proc);
559 // allow a SID transition to be set, implicitly include the SID itself
560 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
561 fp->setSID((Transition*) proc);
565 if (naIsString(value)) {
566 FGAirport* apt = fp->departureAirport();
567 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
571 naRuntimeError(c, "bad argument type setting SID");
572 } else if (!strcmp(fieldName, "star")) {
573 Procedure* proc = procedureGhost(value);
574 if (proc && (proc->type() == PROCEDURE_STAR)) {
575 fp->setSTAR((STAR*) proc);
579 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
580 fp->setSTAR((Transition*) proc);
584 if (naIsString(value)) {
585 FGAirport* apt = fp->destinationAirport();
586 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
590 naRuntimeError(c, "bad argument type setting STAR");
591 } else if (!strcmp(fieldName, "approach")) {
592 Procedure* proc = procedureGhost(value);
593 if (proc && Approach::isApproach(proc->type())) {
594 fp->setApproach((Approach*) proc);
598 if (naIsString(value)) {
599 FGAirport* apt = fp->destinationAirport();
600 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
604 naRuntimeError(c, "bad argument type setting approach");
609 static naRef procedureTpType(naContext c, ProcedureType ty)
612 case PROCEDURE_SID: return stringToNasal(c, "sid");
613 case PROCEDURE_STAR: return stringToNasal(c, "star");
614 case PROCEDURE_APPROACH_VOR:
615 case PROCEDURE_APPROACH_ILS:
616 case PROCEDURE_APPROACH_RNAV:
617 case PROCEDURE_APPROACH_NDB:
618 return stringToNasal(c, "IAP");
624 static naRef procedureRadioType(naContext c, ProcedureType ty)
627 case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
628 case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
629 case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
630 case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
636 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
638 const char* fieldName = naStr_data(field);
639 Procedure* proc = (Procedure*) g;
641 if (!strcmp(fieldName, "parents")) {
642 *out = naNewVector(c);
643 naVec_append(*out, procedurePrototype);
644 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
645 else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
646 else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
647 else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
648 else if (!strcmp(fieldName, "runways")) {
649 *out = naNewVector(c);
650 BOOST_FOREACH(FGRunwayPtr rwy, proc->runways()) {
651 naVec_append(*out, stringToNasal(c, rwy->ident()));
653 } else if (!strcmp(fieldName, "transitions")) {
654 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
659 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
660 *out = naNewVector(c);
661 BOOST_FOREACH(string id, ad->transitionIdents()) {
662 naVec_append(*out, stringToNasal(c, id));
671 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
673 const char* fieldName = naStr_data(field);
674 FGRunway* rwy = (FGRunway*) g;
676 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
677 else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
678 else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
679 else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
680 else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
681 else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
682 else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
683 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
684 else if (!strcmp(fieldName, "ils_frequency_mhz")) {
685 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
686 } else if (!strcmp(fieldName, "ils")) {
687 *out = ghostForNavaid(c, rwy->ILS());
695 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
697 const char* fieldName = naStr_data(field);
698 FGNavRecord* nav = (FGNavRecord*) g;
700 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
701 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
702 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
703 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
704 else if (!strcmp(fieldName, "elevation")) {
705 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
706 } else if (!strcmp(fieldName, "type")) {
707 *out = stringToNasal(c, nav->nameForType(nav->type()));
708 } else if (!strcmp(fieldName, "frequency")) {
709 *out = naNum(nav->get_freq());
710 } else if (!strcmp(fieldName, "range_nm")) {
711 *out = naNum(nav->get_range());
712 } else if (!strcmp(fieldName, "course")) {
713 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
714 double radial = nav->get_multiuse();
715 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
716 *out = naNum(radial);
727 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
729 const char* fieldName = naStr_data(field);
730 FGFix* fix = (FGFix*) g;
732 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
733 else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
734 else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
742 static bool hashIsCoord(naRef h)
744 naRef parents = naHash_cget(h, (char*) "parents");
745 if (!naIsVector(parents)) {
749 return naEqual(naVec_get(parents, 0), geoCoordClass);
752 bool geodFromHash(naRef ref, SGGeod& result)
754 if (!naIsHash(ref)) {
759 // check for manual latitude / longitude names
760 naRef lat = naHash_cget(ref, (char*) "lat");
761 naRef lon = naHash_cget(ref, (char*) "lon");
762 if (naIsNum(lat) && naIsNum(lon)) {
763 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
767 if (hashIsCoord(ref)) {
768 naRef lat = naHash_cget(ref, (char*) "_lat");
769 naRef lon = naHash_cget(ref, (char*) "_lon");
770 if (naIsNum(lat) && naIsNum(lon)) {
771 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
776 // check for any synonyms?
777 // latitude + longitude?
782 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
784 if (offset >= argc) {
788 if (naIsGhost(args[offset])) {
789 naGhostType* gt = naGhost_type(args[offset]);
790 if (gt == &AirportGhostType) {
791 result = airportGhost(args[offset])->geod();
795 if (gt == &NavaidGhostType) {
796 result = navaidGhost(args[offset])->geod();
800 if (gt == &RunwayGhostType) {
801 result = runwayGhost(args[offset])->geod();
805 if (gt == &FixGhostType) {
806 result = fixGhost(args[offset])->geod();
810 if (gt == &WayptGhostType) {
811 result = wayptGhost(args[offset])->position();
816 if (geodFromHash(args[offset], result)) {
820 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
821 double lat = naNumValue(args[0]).num,
822 lon = naNumValue(args[1]).num;
823 result = SGGeod::fromDeg(lon, lat);
830 // Convert a cartesian point to a geodetic lat/lon/altitude.
831 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
833 double lat, lon, alt, xyz[3];
834 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
835 for(int i=0; i<3; i++)
836 xyz[i] = naNumValue(args[i]).num;
837 sgCartToGeod(xyz, &lat, &lon, &alt);
838 lat *= SG_RADIANS_TO_DEGREES;
839 lon *= SG_RADIANS_TO_DEGREES;
840 naRef vec = naNewVector(c);
841 naVec_append(vec, naNum(lat));
842 naVec_append(vec, naNum(lon));
843 naVec_append(vec, naNum(alt));
847 // Convert a geodetic lat/lon/altitude to a cartesian point.
848 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
850 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
851 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
852 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
853 double alt = naNumValue(args[2]).num;
855 sgGeodToCart(lat, lon, alt, xyz);
856 naRef vec = naNewVector(c);
857 naVec_append(vec, naNum(xyz[0]));
858 naVec_append(vec, naNum(xyz[1]));
859 naVec_append(vec, naNum(xyz[2]));
863 // For given geodetic point return array with elevation, and a material data
864 // hash, or nil if there's no information available (tile not loaded). If
865 // information about the material isn't available, then nil is returned instead
867 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
869 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
870 if(argc < 2 || argc > 3)
871 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
872 double lat = naNumValue(args[0]).num;
873 double lon = naNumValue(args[1]).num;
874 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
875 const SGMaterial *mat;
876 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
877 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
879 naRef vec = naNewVector(c);
880 naVec_append(vec, naNum(elev));
881 naRef matdata = naNil();
883 matdata = naNewHash(c);
884 naRef names = naNewVector(c);
885 BOOST_FOREACH(const std::string& n, mat->get_names())
886 naVec_append(names, stringToNasal(c, n));
888 HASHSET("names", 5, names);
889 HASHSET("solid", 5, naNum(mat->get_solid()));
890 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
891 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
892 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
893 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
894 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
896 naVec_append(vec, matdata);
902 class AirportInfoFilter : public FGAirport::AirportFilter
905 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
908 bool fromArg(naRef arg)
910 const char *s = naStr_data(arg);
911 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
912 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
913 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
920 virtual FGPositioned::Type minType() const {
924 virtual FGPositioned::Type maxType() const {
928 FGPositioned::Type type;
931 // Returns data hash for particular or nearest airport of a <type>, or nil
934 // airportinfo(<id>); e.g. "KSFO"
935 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
936 // airportinfo() same as airportinfo("airport")
937 // airportinfo(<lat>, <lon> [, <type>]);
938 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
940 SGGeod pos = globals->get_aircraft_position();
941 FGAirport* apt = NULL;
943 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
944 pos = SGGeod::fromDeg(args[1].num, args[0].num);
949 double maxRange = 10000.0; // expose this? or pick a smaller value?
951 AirportInfoFilter filter; // defaults to airports only
954 // fall through and use AIRPORT
955 } else if(argc == 1 && naIsString(args[0])) {
956 if (filter.fromArg(args[0])) {
959 // user provided an <id>, hopefully
960 apt = FGAirport::findByIdent(naStr_data(args[0]));
962 // return nil here, but don't raise a runtime error; this is a
963 // legitamate way to validate an ICAO code, for example in a
964 // dialog box or similar.
969 naRuntimeError(c, "airportinfo() with invalid function arguments");
974 apt = FGAirport::findClosest(pos, maxRange, &filter);
975 if(!apt) return naNil();
978 return ghostForAirport(c, apt);
981 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
984 SGGeod pos = globals->get_aircraft_position();
985 argOffset += geodFromArgs(args, 0, argc, pos);
987 if (!naIsNum(args[argOffset])) {
988 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
991 AirportInfoFilter filter; // defaults to airports only
992 double rangeNm = args[argOffset++].num;
993 if (argOffset < argc) {
994 filter.fromArg(args[argOffset++]);
997 naRef r = naNewVector(c);
999 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1000 FGPositioned::sortByRange(apts, pos);
1002 BOOST_FOREACH(FGPositionedRef a, apts) {
1003 FGAirport* apt = (FGAirport*) a.get();
1004 naVec_append(r, ghostForAirport(c, apt));
1010 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1012 if (!naIsString(args[0])) {
1013 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1017 string prefix(naStr_data(args[argOffset++]));
1018 AirportInfoFilter filter; // defaults to airports only
1019 if (argOffset < argc) {
1020 filter.fromArg(args[argOffset++]);
1023 naRef r = naNewVector(c);
1025 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1027 BOOST_FOREACH(FGPositionedRef a, apts) {
1028 FGAirport* apt = (FGAirport*) a.get();
1029 naVec_append(r, ghostForAirport(c, apt));
1035 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1037 FGAirport* apt = airportGhost(me);
1039 naRuntimeError(c, "airport.tower called on non-airport object");
1042 // build a hash for the tower position
1043 SGGeod towerLoc = apt->getTowerLocation();
1044 naRef tower = naNewHash(c);
1045 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1046 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1047 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1051 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1053 FGAirport* apt = airportGhost(me);
1055 naRuntimeError(c, "airport.comms called on non-airport object");
1057 naRef comms = naNewVector(c);
1059 // if we have an explicit type, return a simple vector of frequencies
1060 if (argc > 0 && naIsScalar(args[0])) {
1061 std::string commName = naStr_data(args[0]);
1062 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1064 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1065 naVec_append(comms, naNum(comm->freqMHz()));
1068 // otherwise return a vector of hashes, one for each comm station.
1069 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1070 naRef commHash = naNewHash(c);
1071 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1072 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1073 naVec_append(comms, commHash);
1080 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1082 FGAirport* apt = airportGhost(me);
1084 naRuntimeError(c, "airport.runway called on non-airport object");
1087 if ((argc < 1) || !naIsString(args[0])) {
1088 naRuntimeError(c, "airport.runway expects a runway ident argument");
1091 std::string ident(naStr_data(args[0]));
1092 boost::to_upper(ident);
1093 if (!apt->hasRunwayWithIdent(ident)) {
1097 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1100 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1102 FGAirport* apt = airportGhost(me);
1104 naRuntimeError(c, "airport.sids called on non-airport object");
1107 naRef sids = naNewVector(c);
1109 FGRunway* rwy = NULL;
1110 if (argc > 0 && naIsString(args[0])) {
1111 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1115 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1116 } else if (argc > 0) {
1117 rwy = runwayGhost(args[0]);
1121 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1122 naRef procId = stringToNasal(c, sid->ident());
1123 naVec_append(sids, procId);
1126 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1127 flightgear::SID* sid = apt->getSIDByIndex(s);
1128 naRef procId = stringToNasal(c, sid->ident());
1129 naVec_append(sids, procId);
1136 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1138 FGAirport* apt = airportGhost(me);
1140 naRuntimeError(c, "airport.stars called on non-airport object");
1143 naRef stars = naNewVector(c);
1145 FGRunway* rwy = NULL;
1146 if (argc > 0 && naIsString(args[0])) {
1147 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1151 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1152 } else if (argc > 0) {
1153 rwy = runwayGhost(args[0]);
1157 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1158 naRef procId = stringToNasal(c, s->ident());
1159 naVec_append(stars, procId);
1162 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1163 flightgear::STAR* star = apt->getSTARByIndex(s);
1164 naRef procId = stringToNasal(c, star->ident());
1165 naVec_append(stars, procId);
1172 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1174 FGAirport* apt = airportGhost(me);
1176 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1179 naRef approaches = naNewVector(c);
1181 ProcedureType ty = PROCEDURE_INVALID;
1182 if ((argc > 1) && naIsString(args[1])) {
1183 std::string u(naStr_data(args[1]));
1185 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1186 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1187 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1188 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1191 FGRunway* rwy = NULL;
1192 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1194 } else if (argc > 0 && naIsString(args[0])) {
1195 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1199 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1203 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1204 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1208 naRef procId = stringToNasal(c, s->ident());
1209 naVec_append(approaches, procId);
1212 // no runway specified, report them all
1213 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1214 Approach* app = apt->getApproachByIndex(s);
1215 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1219 naRef procId = stringToNasal(c, app->ident());
1220 naVec_append(approaches, procId);
1227 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1229 FGAirport* apt = airportGhost(me);
1231 naRuntimeError(c, "airport.parking called on non-airport object");
1234 naRef r = naNewVector(c);
1236 bool onlyAvailable = false;
1238 if (argc > 0 && naIsString(args[0])) {
1239 type = naStr_data(args[0]);
1242 if ((argc > 1) && naIsNum(args[1])) {
1243 onlyAvailable = (args[1].num != 0.0);
1246 FGAirportDynamics* dynamics = apt->getDynamics();
1247 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
1248 FGParking* park = dynamics->getParking(i);
1249 // filter out based on availability and type
1250 if (onlyAvailable && !park->isAvailable()) {
1254 if (!type.empty() && (park->getType() != type)) {
1258 naRef nm = stringToNasal(c, park->getName());
1259 naVec_append(r, nm);
1265 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1267 FGAirport* apt = airportGhost(me);
1269 naRuntimeError(c, "airport.getSid called on non-airport object");
1272 if ((argc != 1) || !naIsString(args[0])) {
1273 naRuntimeError(c, "airport.getSid passed invalid argument");
1276 string ident = naStr_data(args[0]);
1277 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1280 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1282 FGAirport* apt = airportGhost(me);
1284 naRuntimeError(c, "airport.getStar called on non-airport object");
1287 if ((argc != 1) || !naIsString(args[0])) {
1288 naRuntimeError(c, "airport.getStar passed invalid argument");
1291 string ident = naStr_data(args[0]);
1292 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1295 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1297 FGAirport* apt = airportGhost(me);
1299 naRuntimeError(c, "airport.getIAP called on non-airport object");
1302 if ((argc != 1) || !naIsString(args[0])) {
1303 naRuntimeError(c, "airport.getIAP passed invalid argument");
1306 string ident = naStr_data(args[0]);
1307 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1310 // Returns vector of data hash for navaid of a <type>, nil on error
1311 // navaids sorted by ascending distance
1312 // navinfo([<lat>,<lon>],[<type>],[<id>])
1313 // lat/lon (numeric): use latitude/longitude instead of ac position
1314 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1315 // id: (partial) id of the fix
1317 // navinfo("vor") returns all vors
1318 // navinfo("HAM") return all navaids who's name start with "HAM"
1319 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1320 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1321 // sorted by distance relative to lat=34, lon=48
1322 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1326 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1327 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1331 pos = globals->get_aircraft_position();
1334 FGPositioned::Type type = FGPositioned::INVALID;
1335 nav_list_type navlist;
1336 const char * id = "";
1338 if(argc > 0 && naIsString(args[0])) {
1339 const char *s = naStr_data(args[0]);
1340 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1341 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1342 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1343 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1344 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1345 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1346 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1347 else id = s; // this is an id
1352 if(argc > 0 && naIsString(args[0])) {
1354 naRuntimeError(c, "navinfo() called with navaid id");
1357 id = naStr_data(args[0]);
1363 naRuntimeError(c, "navinfo() called with too many arguments");
1367 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
1369 naRef reply = naNewVector(c);
1370 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1371 naVec_append( reply, ghostForNavaid(c, *it) );
1376 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1379 SGGeod pos = globals->get_aircraft_position();
1380 argOffset += geodFromArgs(args, 0, argc, pos);
1382 if (!naIsNum(args[argOffset])) {
1383 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1386 FGPositioned::Type type = FGPositioned::INVALID;
1387 double rangeNm = args[argOffset++].num;
1388 if (argOffset < argc) {
1389 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1392 naRef r = naNewVector(c);
1393 FGNavList::TypeFilter filter(type);
1394 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1395 FGPositioned::sortByRange(navs, pos);
1397 BOOST_FOREACH(FGPositionedRef a, navs) {
1398 FGNavRecord* nav = (FGNavRecord*) a.get();
1399 naVec_append(r, ghostForNavaid(c, nav));
1405 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1408 SGGeod pos = globals->get_aircraft_position();
1409 argOffset += geodFromArgs(args, 0, argc, pos);
1411 if (!naIsNum(args[argOffset])) {
1412 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1415 FGPositioned::Type type = FGPositioned::INVALID;
1416 double freqMhz = args[argOffset++].num;
1417 if (argOffset < argc) {
1418 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1421 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1426 return ghostForNavaid(c, navs.front().ptr());
1429 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1432 SGGeod pos = globals->get_aircraft_position();
1433 argOffset += geodFromArgs(args, 0, argc, pos);
1435 if (!naIsNum(args[argOffset])) {
1436 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1439 FGPositioned::Type type = FGPositioned::INVALID;
1440 double freqMhz = args[argOffset++].num;
1441 if (argOffset < argc) {
1442 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1445 naRef r = naNewVector(c);
1446 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1448 BOOST_FOREACH(nav_rec_ptr a, navs) {
1449 naVec_append(r, ghostForNavaid(c, a.ptr()));
1455 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1458 SGGeod pos = globals->get_aircraft_position();
1459 argOffset += geodFromArgs(args, 0, argc, pos);
1461 if (!naIsString(args[argOffset])) {
1462 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1465 FGPositioned::Type type = FGPositioned::INVALID;
1466 string ident = naStr_data(args[argOffset++]);
1467 if (argOffset < argc) {
1468 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1471 naRef r = naNewVector(c);
1472 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
1474 BOOST_FOREACH(nav_rec_ptr a, navs) {
1475 naVec_append(r, ghostForNavaid(c, a.ptr()));
1481 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1484 SGGeod pos = globals->get_aircraft_position();
1485 argOffset += geodFromArgs(args, 0, argc, pos);
1487 if (!naIsString(args[argOffset])) {
1488 naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1491 string ident(naStr_data(args[argOffset]));
1492 naRef r = naNewVector(c);
1494 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1495 FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1496 FGPositioned::sortByRange(fixes, pos);
1498 BOOST_FOREACH(FGPositionedRef f, fixes) {
1499 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1505 // Convert a cartesian point to a geodetic lat/lon/altitude.
1506 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1508 SGGeod pos = globals->get_aircraft_position();
1510 // fine, use aircraft position
1511 } else if (geodFromArgs(args, 0, argc, pos)) {
1514 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1517 double jd = globals->get_time_params()->getJD();
1518 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1519 return naNum(magvarDeg);
1522 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1524 SGGeod from = globals->get_aircraft_position(), to, p;
1525 int argOffset = geodFromArgs(args, 0, argc, p);
1526 if (geodFromArgs(args, argOffset, argc, to)) {
1527 from = p; // we parsed both FROM and TO args, so first was from
1529 to = p; // only parsed one arg, so FROM is current
1532 if (argOffset == 0) {
1533 naRuntimeError(c, "invalid arguments to courseAndDistance");
1536 double course, course2, d;
1537 SGGeodesy::inverse(from, to, course, course2, d);
1539 naRef result = naNewVector(c);
1540 naVec_append(result, naNum(course));
1541 naVec_append(result, naNum(d * SG_METER_TO_NM));
1545 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1547 SGGeod from = globals->get_aircraft_position(), to;
1550 // complication - don't inerpret two doubles (as the only args)
1551 // as a lat,lon pair - only do so if we have at least three args.
1553 argOffset = geodFromArgs(args, 0, argc, from);
1556 if ((argOffset + 1) >= argc) {
1557 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1560 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1561 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1562 argOffset, argOffset + 1);
1565 double course = args[argOffset].num, course2;
1566 double distanceNm = args[argOffset + 1].num;
1567 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1570 naRef coord = naNewHash(c);
1571 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1572 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1576 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1578 SGGeod pos = globals->get_aircraft_position();
1579 geodFromArgs(args, 0, argc, pos);
1581 return stringToNasal(c, b.gen_base_path());
1584 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1586 SGGeod pos = globals->get_aircraft_position();
1587 geodFromArgs(args, 0, argc, pos);
1589 return naNum(b.gen_index());
1592 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1595 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1596 return ghostForFlightPlan(c, rm->flightPlan());
1599 if ((argc > 0) && naIsString(args[0])) {
1600 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1601 SGPath path(naStr_data(args[0]));
1602 if (!path.exists()) {
1603 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1606 if (!fp->load(path)) {
1607 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1612 return ghostForFlightPlan(c, fp);
1615 naRuntimeError(c, "bad arguments to flightplan()");
1619 static WayptRef wayptFromArg(naRef arg)
1621 WayptRef r = wayptGhost(arg);
1626 FGPositioned* pos = positionedGhost(arg);
1628 // let's check if the arg is hash, coudl extra a geod and hence build
1629 // a simple waypoint
1634 // special-case for runways
1635 if (pos->type() == FGPositioned::RUNWAY) {
1636 return new RunwayWaypt((FGRunway*) pos, NULL);
1639 return new NavaidWaypoint(pos, NULL);
1642 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1644 naRef result = naNewVector(c);
1645 BOOST_FOREACH(WayptRef wpt, wps) {
1646 naVec_append(result, ghostForWaypt(c, wpt.get()));
1651 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1654 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1657 WayptRef start = wayptFromArg(args[0]),
1658 end = wayptFromArg(args[1]);
1660 if (!start || !end) {
1661 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1665 bool highLevel = true;
1666 if ((argc > 2) && naIsString(args[2])) {
1667 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1674 Airway::highLevel()->route(start, end, route);
1676 Airway::lowLevel()->route(start, end, route);
1679 return convertWayptVecToNasal(c, route);
1682 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1685 int argOffset = geodFromArgs(args, 0, argc, pos);
1687 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1688 naRuntimeError(c, "createWP: no identifier supplied");
1691 string ident = naStr_data(args[argOffset++]);
1692 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1694 // set waypt flags - approach, departure, pseudo, etc
1695 if (argc > argOffset) {
1696 WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1700 return ghostForWaypt(c, wpt);
1703 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1706 naRuntimeError(c, "createWPFrom: need at least one argument");
1709 FGPositioned* positioned = positionedGhost(args[0]);
1711 naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1715 if (positioned->type() == FGPositioned::RUNWAY) {
1716 wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1718 wpt = new NavaidWaypoint(positioned, NULL);
1721 // set waypt flags - approach, departure, pseudo, etc
1723 WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1727 return ghostForWaypt(c, wpt);
1730 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1732 FlightPlan* fp = flightplanGhost(me);
1734 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1739 index = fp->currentIndex();
1741 index = (int) naNumValue(args[0]).num;
1744 if ((index < 0) || (index >= fp->numLegs())) {
1748 return ghostForLeg(c, fp->legAtIndex(index));
1751 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1753 FlightPlan* fp = flightplanGhost(me);
1755 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1757 return ghostForLeg(c, fp->currentLeg());
1760 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1762 FlightPlan* fp = flightplanGhost(me);
1764 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1766 return ghostForLeg(c, fp->nextLeg());
1769 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1771 FlightPlan* fp = flightplanGhost(me);
1773 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1775 return naNum(fp->numLegs());
1778 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
1780 FlightPlan* fp = flightplanGhost(me);
1782 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
1785 WayptRef wp = wayptGhost(args[0]);
1786 int index = fp->numLegs();
1787 fp->insertWayptAtIndex(wp.get(), index);
1788 return naNum(index);
1791 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
1793 FlightPlan* fp = flightplanGhost(me);
1795 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
1798 WayptRef wp = wayptGhost(args[0]);
1799 int index = -1; // append
1800 if ((argc > 1) && naIsNum(args[1])) {
1801 index = (int) args[1].num;
1804 fp->insertWayptAtIndex(wp.get(), index);
1808 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
1810 FlightPlan* fp = flightplanGhost(me);
1812 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
1815 WayptRef wp = wayptGhost(args[0]);
1816 int index = -1; // append
1817 if ((argc > 1) && naIsNum(args[1])) {
1818 index = (int) args[1].num;
1821 fp->insertWayptAtIndex(wp.get(), index + 1);
1825 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
1827 FlightPlan* fp = flightplanGhost(me);
1829 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
1833 if (!naIsVector(args[0])) {
1834 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
1837 int count = naVec_size(args[0]);
1838 for (int i=0; i<count; ++i) {
1839 Waypt* wp = wayptGhost(naVec_get(args[0], i));
1845 int index = -1; // append
1846 if ((argc > 1) && naIsNum(args[1])) {
1847 index = (int) args[1].num;
1850 fp->insertWayptsAtIndex(wps, index);
1854 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
1856 FlightPlan* fp = flightplanGhost(me);
1858 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
1861 if ((argc < 1) || !naIsNum(args[0])) {
1862 naRuntimeError(c, "bad argument to flightplan.deleteWP");
1865 int index = (int) args[0].num;
1866 fp->deleteIndex(index);
1870 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
1872 FlightPlan* fp = flightplanGhost(me);
1874 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
1881 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
1883 FlightPlan* fp = flightplanGhost(me);
1885 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
1889 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
1892 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
1893 fp->clearWayptsWithFlag(flag);
1897 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
1899 FlightPlan* fp = flightplanGhost(me);
1901 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
1904 return ghostForFlightPlan(c, fp->clone());
1907 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
1909 FlightPlan::Leg* leg = fpLegGhost(me);
1911 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
1915 naRuntimeError(c, "bad arguments to leg.setSpeed");
1918 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
1919 leg->setSpeed(rr, args[0].num);
1923 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
1925 FlightPlan::Leg* leg = fpLegGhost(me);
1927 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
1931 naRuntimeError(c, "bad arguments to leg.setAltitude");
1934 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
1935 leg->setAltitude(rr, args[0].num);
1939 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
1941 flightgear::Waypt* w = wayptGhost(me);
1943 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1946 FGPositioned* pos = w->source();
1951 switch (pos->type()) {
1952 case FGPositioned::VOR:
1953 case FGPositioned::NDB:
1954 case FGPositioned::ILS:
1955 case FGPositioned::LOC:
1956 case FGPositioned::GS:
1957 case FGPositioned::DME:
1958 case FGPositioned::TACAN: {
1959 FGNavRecord* nav = (FGNavRecord*) pos;
1960 return ghostForNavaid(c, nav);
1968 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
1970 flightgear::Waypt* w = wayptGhost(me);
1972 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1975 FGPositioned* pos = w->source();
1976 if (!pos || FGAirport::isAirportType(pos)) {
1980 return ghostForAirport(c, (FGAirport*) pos);
1983 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1985 flightgear::Waypt* w = wayptGhost(me);
1987 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1990 FGPositioned* pos = w->source();
1991 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1995 return ghostForRunway(c, (FGRunway*) pos);
1998 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2000 Procedure* proc = procedureGhost(me);
2002 naRuntimeError(c, "procedure.transition called on non-procedure object");
2005 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2006 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2009 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2010 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2012 return ghostForProcedure(c, trans);
2015 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2017 Procedure* proc = procedureGhost(me);
2019 naRuntimeError(c, "procedure.route called on non-procedure object");
2022 // wrapping up tow different routines here - approach routing from the IAF
2023 // to the associated runway, and SID/STAR routing via an enroute transition
2024 // and possibly a runway transition or not.
2025 if (Approach::isApproach(proc->type())) {
2028 iaf = wayptFromArg(args[0]);
2032 Approach* app = (Approach*) proc;
2033 if (!app->route(iaf, r)) {
2034 SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2038 return convertWayptVecToNasal(c, r);
2039 } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2040 naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2044 FGRunway* rwy = runwayGhost(args[0]);
2045 if (rwy) ++argOffset;
2047 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2048 Transition* trans = NULL;
2049 if (argOffset < argc) {
2050 trans = (Transition*) procedureGhost(args[argOffset]);
2053 // note either runway or trans may be NULL - that's ok
2055 if (!ad->route(rwy, trans, r)) {
2056 SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2060 return convertWayptVecToNasal(c, r);
2064 // Table of extension functions. Terminate with zeros.
2065 static struct { const char* name; naCFunction func; } funcs[] = {
2066 { "carttogeod", f_carttogeod },
2067 { "geodtocart", f_geodtocart },
2068 { "geodinfo", f_geodinfo },
2069 { "airportinfo", f_airportinfo },
2070 { "findAirportsWithinRange", f_findAirportsWithinRange },
2071 { "findAirportsByICAO", f_findAirportsByICAO },
2072 { "navinfo", f_navinfo },
2073 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2074 { "findNavaidByFrequency", f_findNavaidByFrequency },
2075 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2076 { "findNavaidsByID", f_findNavaidsByIdent },
2077 { "findFixesByID", f_findFixesByIdent },
2078 { "flightplan", f_route },
2079 { "createWP", f_createWP },
2080 { "createWPFrom", f_createWPFrom },
2081 { "airwaysRoute", f_airwaySearch },
2082 { "magvar", f_magvar },
2083 { "courseAndDistance", f_courseAndDistance },
2084 { "greatCircleMove", f_greatCircleMove },
2085 { "tileIndex", f_tileIndex },
2086 { "tilePath", f_tilePath },
2091 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2093 airportPrototype = naNewHash(c);
2094 hashset(c, gcSave, "airportProto", airportPrototype);
2096 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2097 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2098 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2099 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2100 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2101 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2102 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2103 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2104 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2105 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2107 flightplanPrototype = naNewHash(c);
2108 hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2110 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2111 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
2112 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
2113 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2114 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
2115 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
2116 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
2117 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
2118 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
2119 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
2120 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
2121 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
2123 waypointPrototype = naNewHash(c);
2124 hashset(c, gcSave, "wayptProto", waypointPrototype);
2126 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2127 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2128 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2130 procedurePrototype = naNewHash(c);
2131 hashset(c, gcSave, "procedureProto", procedurePrototype);
2132 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2133 hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2135 fpLegPrototype = naNewHash(c);
2136 hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2137 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2138 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2140 for(int i=0; funcs[i].name; i++) {
2141 hashset(c, globals, funcs[i].name,
2142 naNewFunc(c, naNewCCode(c, funcs[i].func)));
2148 void postinitNasalPositioned(naRef globals, naContext c)
2150 naRef geoModule = naHash_cget(globals, (char*) "geo");
2151 if (naIsNil(geoModule)) {
2152 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2156 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");