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 <Scripting/NasalSys.hxx>
43 #include <Navaids/navlist.hxx>
44 #include <Navaids/procedure.hxx>
45 #include <Main/globals.hxx>
46 #include <Main/fg_props.hxx>
47 #include <Scenery/scenery.hxx>
48 #include <ATC/CommStation.hxx>
49 #include <Navaids/FlightPlan.hxx>
50 #include <Navaids/waypoint.hxx>
51 #include <Navaids/fix.hxx>
52 #include <Autopilot/route_mgr.hxx>
53 #include <Navaids/procedure.hxx>
54 #include <Navaids/airways.hxx>
56 using namespace flightgear;
58 static void positionedGhostDestroy(void* g);
59 static void wayptGhostDestroy(void* g);
60 static void legGhostDestroy(void* g);
61 static void routeBaseGhostDestroy(void* g);
63 naGhostType PositionedGhostType = { positionedGhostDestroy, "positioned" };
65 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out);
66 naGhostType AirportGhostType = { positionedGhostDestroy, "airport", airportGhostGetMember, 0 };
68 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out);
69 naGhostType NavaidGhostType = { positionedGhostDestroy, "navaid", navaidGhostGetMember, 0 };
71 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out);
72 naGhostType RunwayGhostType = { positionedGhostDestroy, "runway", runwayGhostGetMember, 0 };
74 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out);
75 naGhostType FixGhostType = { positionedGhostDestroy, "fix", fixGhostGetMember, 0 };
77 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out);
78 naGhostType WayptGhostType = { wayptGhostDestroy,
83 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out);
84 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value);
86 naGhostType FPLegGhostType = { legGhostDestroy,
91 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out);
92 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value);
94 naGhostType FlightPlanGhostType = { routeBaseGhostDestroy,
96 flightplanGhostGetMember,
97 flightplanGhostSetMember
100 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out);
101 naGhostType ProcedureGhostType = { routeBaseGhostDestroy,
103 procedureGhostGetMember,
106 static void hashset(naContext c, naRef hash, const char* key, naRef val)
108 naRef s = naNewString(c);
109 naStr_fromdata(s, (char*)key, strlen(key));
110 naHash_set(hash, s, val);
113 static naRef stringToNasal(naContext c, const std::string& s)
115 return naStr_fromdata(naNewString(c),
116 const_cast<char *>(s.c_str()),
120 static WayptFlag wayptFlagFromString(const char* s)
122 if (!strcmp(s, "sid")) return WPT_DEPARTURE;
123 if (!strcmp(s, "star")) return WPT_ARRIVAL;
124 if (!strcmp(s, "approach")) return WPT_APPROACH;
125 if (!strcmp(s, "missed")) return WPT_MISS;
126 if (!strcmp(s, "pseudo")) return WPT_PSEUDO;
128 return (WayptFlag) 0;
131 static naRef wayptFlagToNasal(naContext c, unsigned int flags)
133 if (flags & WPT_PSEUDO) return stringToNasal(c, "pseudo");
134 if (flags & WPT_DEPARTURE) return stringToNasal(c, "sid");
135 if (flags & WPT_ARRIVAL) return stringToNasal(c, "star");
136 if (flags & WPT_MISS) return stringToNasal(c, "missed");
137 if (flags & WPT_APPROACH) return stringToNasal(c, "approach");
141 static FGPositioned* positionedGhost(naRef r)
143 if ((naGhost_type(r) == &AirportGhostType) ||
144 (naGhost_type(r) == &NavaidGhostType) ||
145 (naGhost_type(r) == &RunwayGhostType) ||
146 (naGhost_type(r) == &FixGhostType))
148 return (FGPositioned*) naGhost_ptr(r);
154 static FGAirport* airportGhost(naRef r)
156 if (naGhost_type(r) == &AirportGhostType)
157 return (FGAirport*) naGhost_ptr(r);
161 static FGNavRecord* navaidGhost(naRef r)
163 if (naGhost_type(r) == &NavaidGhostType)
164 return (FGNavRecord*) naGhost_ptr(r);
168 static FGRunway* runwayGhost(naRef r)
170 if (naGhost_type(r) == &RunwayGhostType)
171 return (FGRunway*) naGhost_ptr(r);
175 static FGFix* fixGhost(naRef r)
177 if (naGhost_type(r) == &FixGhostType)
178 return (FGFix*) naGhost_ptr(r);
183 static void positionedGhostDestroy(void* g)
185 FGPositioned* pos = (FGPositioned*)g;
186 if (!FGPositioned::put(pos)) // unref
190 static Waypt* wayptGhost(naRef r)
192 if (naGhost_type(r) == &WayptGhostType)
193 return (Waypt*) naGhost_ptr(r);
195 if (naGhost_type(r) == &FPLegGhostType) {
196 FlightPlan::Leg* leg = (FlightPlan::Leg*) naGhost_ptr(r);
197 return leg->waypoint();
203 static void wayptGhostDestroy(void* g)
205 Waypt* wpt = (Waypt*)g;
206 if (!Waypt::put(wpt)) // unref
210 static void legGhostDestroy(void* g)
216 static FlightPlan::Leg* fpLegGhost(naRef r)
218 if (naGhost_type(r) == &FPLegGhostType)
219 return (FlightPlan::Leg*) naGhost_ptr(r);
223 static Procedure* procedureGhost(naRef r)
225 if (naGhost_type(r) == &ProcedureGhostType)
226 return (Procedure*) naGhost_ptr(r);
230 static FlightPlan* flightplanGhost(naRef r)
232 if (naGhost_type(r) == &FlightPlanGhostType)
233 return (FlightPlan*) naGhost_ptr(r);
237 static void routeBaseGhostDestroy(void* g)
242 static naRef airportPrototype;
243 static naRef flightplanPrototype;
244 static naRef waypointPrototype;
245 static naRef geoCoordClass;
246 static naRef fpLegPrototype;
247 static naRef procedurePrototype;
249 naRef ghostForAirport(naContext c, const FGAirport* apt)
255 FGPositioned::get(apt); // take a ref
256 return naNewGhost2(c, &AirportGhostType, (void*) apt);
259 naRef ghostForNavaid(naContext c, const FGNavRecord* n)
265 FGPositioned::get(n); // take a ref
266 return naNewGhost2(c, &NavaidGhostType, (void*) n);
269 naRef ghostForRunway(naContext c, const FGRunway* r)
275 FGPositioned::get(r); // take a ref
276 return naNewGhost2(c, &RunwayGhostType, (void*) r);
279 naRef ghostForFix(naContext c, const FGFix* r)
285 FGPositioned::get(r); // take a ref
286 return naNewGhost2(c, &FixGhostType, (void*) r);
290 naRef ghostForWaypt(naContext c, const Waypt* wpt)
296 Waypt::get(wpt); // take a ref
297 return naNewGhost2(c, &WayptGhostType, (void*) wpt);
300 naRef ghostForLeg(naContext c, const FlightPlan::Leg* leg)
306 return naNewGhost2(c, &FPLegGhostType, (void*) leg);
309 naRef ghostForFlightPlan(naContext c, const FlightPlan* fp)
315 return naNewGhost2(c, &FlightPlanGhostType, (void*) fp);
318 naRef ghostForProcedure(naContext c, const Procedure* proc)
324 return naNewGhost2(c, &ProcedureGhostType, (void*) proc);
327 static const char* airportGhostGetMember(naContext c, void* g, naRef field, naRef* out)
329 const char* fieldName = naStr_data(field);
330 FGAirport* apt = (FGAirport*) g;
332 if (!strcmp(fieldName, "parents")) {
333 *out = naNewVector(c);
334 naVec_append(*out, airportPrototype);
335 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, apt->ident());
336 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, apt->name());
337 else if (!strcmp(fieldName, "lat")) *out = naNum(apt->getLatitude());
338 else if (!strcmp(fieldName, "lon")) *out = naNum(apt->getLongitude());
339 else if (!strcmp(fieldName, "elevation")) {
340 *out = naNum(apt->getElevation() * SG_FEET_TO_METER);
341 } else if (!strcmp(fieldName, "has_metar")) {
342 *out = naNum(apt->getMetar());
343 } else if (!strcmp(fieldName, "runways")) {
345 for(unsigned int r=0; r<apt->numRunways(); ++r) {
346 FGRunway* rwy(apt->getRunwayByIndex(r));
347 naRef rwyid = stringToNasal(c, rwy->ident());
348 naRef rwydata = ghostForRunway(c, rwy);
349 naHash_set(*out, rwyid, rwydata);
359 static const char* waypointCommonGetMember(naContext c, Waypt* wpt, const char* fieldName, naRef* out)
361 if (!strcmp(fieldName, "wp_name")) *out = stringToNasal(c, wpt->ident());
362 else if (!strcmp(fieldName, "wp_type")) *out = stringToNasal(c, wpt->type());
363 else if (!strcmp(fieldName, "wp_role")) *out = wayptFlagToNasal(c, wpt->flags());
364 else if (!strcmp(fieldName, "wp_lat")) *out = naNum(wpt->position().getLatitudeDeg());
365 else if (!strcmp(fieldName, "wp_lon")) *out = naNum(wpt->position().getLongitudeDeg());
366 else if (!strcmp(fieldName, "wp_parent_name")) {
367 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
368 *out = proc ? stringToNasal(c, proc->ident()) : naNil();
369 } else if (!strcmp(fieldName, "wp_parent")) {
370 Procedure* proc = dynamic_cast<Procedure*>(wpt->owner());
371 *out = ghostForProcedure(c, proc);
372 } else if (!strcmp(fieldName, "fly_type")) {
373 if (wpt->type() == "hold") {
374 *out = stringToNasal(c, "Hold");
376 *out = stringToNasal(c, wpt->flag(WPT_OVERFLIGHT) ? "flyOver" : "flyBy");
379 return NULL; // member not found
385 static const char* wayptGhostGetMember(naContext c, void* g, naRef field, naRef* out)
387 const char* fieldName = naStr_data(field);
388 Waypt* wpt = (flightgear::Waypt*) g;
389 return waypointCommonGetMember(c, wpt, fieldName, out);
392 static RouteRestriction routeRestrictionFromString(const char* s)
396 if (u == "computed") return RESTRICT_COMPUTED;
397 if (u == "at") return RESTRICT_AT;
398 if (u == "mach") return SPEED_RESTRICT_MACH;
399 if (u == "computed-mach") return SPEED_COMPUTED_MACH;
400 if (u == "delete") return RESTRICT_DELETE;
401 return RESTRICT_NONE;
404 naRef routeRestrictionToNasal(naContext c, RouteRestriction rr)
407 case RESTRICT_NONE: return naNil();
408 case RESTRICT_AT: return stringToNasal(c, "at");
409 case RESTRICT_ABOVE: return stringToNasal(c, "above");
410 case RESTRICT_BELOW: return stringToNasal(c, "below");
411 case SPEED_RESTRICT_MACH: return stringToNasal(c, "mach");
412 case RESTRICT_COMPUTED: return stringToNasal(c, "computed");
413 case SPEED_COMPUTED_MACH: return stringToNasal(c, "computed-mach");
414 case RESTRICT_DELETE: return stringToNasal(c, "delete");
420 static const char* legGhostGetMember(naContext c, void* g, naRef field, naRef* out)
422 const char* fieldName = naStr_data(field);
423 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
424 Waypt* wpt = leg->waypoint();
426 if (!strcmp(fieldName, "parents")) {
427 *out = naNewVector(c);
428 naVec_append(*out, fpLegPrototype);
429 } else if (!strcmp(fieldName, "index")) {
430 *out = naNum(leg->index());
431 } else if (!strcmp(fieldName, "alt_cstr")) {
432 *out = naNum(leg->altitudeFt());
433 } else if (!strcmp(fieldName, "alt_cstr_type")) {
434 *out = routeRestrictionToNasal(c, leg->altitudeRestriction());
435 } else if (!strcmp(fieldName, "speed_cstr")) {
436 double s = isMachRestrict(leg->speedRestriction()) ? leg->speedMach() : leg->speedKts();
438 } else if (!strcmp(fieldName, "speed_cstr_type")) {
439 *out = routeRestrictionToNasal(c, leg->speedRestriction());
440 } else if (!strcmp(fieldName, "leg_distance")) {
441 *out = naNum(leg->distanceNm());
442 } else if (!strcmp(fieldName, "leg_bearing")) {
443 *out = naNum(leg->courseDeg());
444 } else if (!strcmp(fieldName, "distance_along_route")) {
445 *out = naNum(leg->distanceAlongRoute());
446 } else { // check for fields defined on the underlying waypoint
447 return waypointCommonGetMember(c, wpt, fieldName, out);
450 return ""; // success
453 static void legGhostSetMember(naContext c, void* g, naRef field, naRef value)
455 const char* fieldName = naStr_data(field);
456 FlightPlan::Leg* leg = (FlightPlan::Leg*) g;
458 if (!strcmp(fieldName, "wp_role")) {
459 if (!naIsString(value)) naRuntimeError(c, "wp_role must be a string");
460 if (leg->waypoint()->owner() != NULL) naRuntimeError(c, "cannot override wp_role on waypoint with parent");
461 WayptFlag f = wayptFlagFromString(naStr_data(value));
463 naRuntimeError(c, "unrecognized wp_role value %s", naStr_data(value));
466 leg->waypoint()->setFlag(f, true);
470 static const char* flightplanGhostGetMember(naContext c, void* g, naRef field, naRef* out)
472 const char* fieldName = naStr_data(field);
473 FlightPlan* fp = (FlightPlan*) g;
475 if (!strcmp(fieldName, "parents")) {
476 *out = naNewVector(c);
477 naVec_append(*out, flightplanPrototype);
478 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fp->ident());
479 else if (!strcmp(fieldName, "departure")) *out = ghostForAirport(c, fp->departureAirport());
480 else if (!strcmp(fieldName, "destination")) *out = ghostForAirport(c, fp->destinationAirport());
481 else if (!strcmp(fieldName, "departure_runway")) *out = ghostForRunway(c, fp->departureRunway());
482 else if (!strcmp(fieldName, "destination_runway")) *out = ghostForRunway(c, fp->destinationRunway());
483 else if (!strcmp(fieldName, "sid")) *out = ghostForProcedure(c, fp->sid());
484 else if (!strcmp(fieldName, "sid_trans")) *out = ghostForProcedure(c, fp->sidTransition());
485 else if (!strcmp(fieldName, "star")) *out = ghostForProcedure(c, fp->star());
486 else if (!strcmp(fieldName, "star_trans")) *out = ghostForProcedure(c, fp->starTransition());
487 else if (!strcmp(fieldName, "approach")) *out = ghostForProcedure(c, fp->approach());
488 else if (!strcmp(fieldName, "current")) *out = naNum(fp->currentIndex());
496 static void flightplanGhostSetMember(naContext c, void* g, naRef field, naRef value)
498 const char* fieldName = naStr_data(field);
499 FlightPlan* fp = (FlightPlan*) g;
501 if (!strcmp(fieldName, "id")) {
502 if (!naIsString(value)) naRuntimeError(c, "flightplan.id must be a string");
503 fp->setIdent(naStr_data(value));
504 } else if (!strcmp(fieldName, "current")) {
505 int index = value.num;
506 if ((index < 0) || (index >= fp->numLegs())) {
509 fp->setCurrentIndex(index);
510 } else if (!strcmp(fieldName, "departure")) {
511 FGAirport* apt = airportGhost(value);
513 fp->setDeparture(apt);
517 FGRunway* rwy = runwayGhost(value);
519 fp->setDeparture(rwy);
523 naRuntimeError(c, "bad argument type setting departure");
524 } else if (!strcmp(fieldName, "destination")) {
525 FGAirport* apt = airportGhost(value);
527 fp->setDestination(apt);
531 FGRunway* rwy = runwayGhost(value);
533 fp->setDestination(rwy);
537 naRuntimeError(c, "bad argument type setting destination");
538 } else if (!strcmp(fieldName, "departure_runway")) {
539 FGRunway* rwy = runwayGhost(value);
541 fp->setDeparture(rwy);
545 naRuntimeError(c, "bad argument type setting departure");
546 } else if (!strcmp(fieldName, "destination_runway")) {
547 FGRunway* rwy = runwayGhost(value);
549 fp->setDestination(rwy);
553 naRuntimeError(c, "bad argument type setting departure");
554 } else if (!strcmp(fieldName, "sid")) {
555 Procedure* proc = procedureGhost(value);
556 if (proc && (proc->type() == PROCEDURE_SID)) {
557 fp->setSID((flightgear::SID*) proc);
560 // allow a SID transition to be set, implicitly include the SID itself
561 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
562 fp->setSID((Transition*) proc);
566 if (naIsString(value)) {
567 FGAirport* apt = fp->departureAirport();
568 fp->setSID(apt->findSIDWithIdent(naStr_data(value)));
572 naRuntimeError(c, "bad argument type setting SID");
573 } else if (!strcmp(fieldName, "star")) {
574 Procedure* proc = procedureGhost(value);
575 if (proc && (proc->type() == PROCEDURE_STAR)) {
576 fp->setSTAR((STAR*) proc);
580 if (proc && (proc->type() == PROCEDURE_TRANSITION)) {
581 fp->setSTAR((Transition*) proc);
585 if (naIsString(value)) {
586 FGAirport* apt = fp->destinationAirport();
587 fp->setSTAR(apt->findSTARWithIdent(naStr_data(value)));
591 naRuntimeError(c, "bad argument type setting STAR");
592 } else if (!strcmp(fieldName, "approach")) {
593 Procedure* proc = procedureGhost(value);
594 if (proc && Approach::isApproach(proc->type())) {
595 fp->setApproach((Approach*) proc);
599 if (naIsString(value)) {
600 FGAirport* apt = fp->destinationAirport();
601 fp->setApproach(apt->findApproachWithIdent(naStr_data(value)));
605 naRuntimeError(c, "bad argument type setting approach");
610 static naRef procedureTpType(naContext c, ProcedureType ty)
613 case PROCEDURE_SID: return stringToNasal(c, "sid");
614 case PROCEDURE_STAR: return stringToNasal(c, "star");
615 case PROCEDURE_APPROACH_VOR:
616 case PROCEDURE_APPROACH_ILS:
617 case PROCEDURE_APPROACH_RNAV:
618 case PROCEDURE_APPROACH_NDB:
619 return stringToNasal(c, "IAP");
625 static naRef procedureRadioType(naContext c, ProcedureType ty)
628 case PROCEDURE_APPROACH_VOR: return stringToNasal(c, "VOR");
629 case PROCEDURE_APPROACH_ILS: return stringToNasal(c, "ILS");
630 case PROCEDURE_APPROACH_RNAV: return stringToNasal(c, "RNAV");
631 case PROCEDURE_APPROACH_NDB: return stringToNasal(c, "NDB");
637 static const char* procedureGhostGetMember(naContext c, void* g, naRef field, naRef* out)
639 const char* fieldName = naStr_data(field);
640 Procedure* proc = (Procedure*) g;
642 if (!strcmp(fieldName, "parents")) {
643 *out = naNewVector(c);
644 naVec_append(*out, procedurePrototype);
645 } else if (!strcmp(fieldName, "id")) *out = stringToNasal(c, proc->ident());
646 else if (!strcmp(fieldName, "airport")) *out = ghostForAirport(c, proc->airport());
647 else if (!strcmp(fieldName, "tp_type")) *out = procedureTpType(c, proc->type());
648 else if (!strcmp(fieldName, "radio")) *out = procedureRadioType(c, proc->type());
649 else if (!strcmp(fieldName, "runways")) {
650 *out = naNewVector(c);
651 BOOST_FOREACH(FGRunwayPtr rwy, proc->runways()) {
652 naVec_append(*out, stringToNasal(c, rwy->ident()));
654 } else if (!strcmp(fieldName, "transitions")) {
655 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
660 ArrivalDeparture* ad = static_cast<ArrivalDeparture*>(proc);
661 *out = naNewVector(c);
662 BOOST_FOREACH(string id, ad->transitionIdents()) {
663 naVec_append(*out, stringToNasal(c, id));
672 static const char* runwayGhostGetMember(naContext c, void* g, naRef field, naRef* out)
674 const char* fieldName = naStr_data(field);
675 FGRunway* rwy = (FGRunway*) g;
677 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, rwy->ident());
678 else if (!strcmp(fieldName, "lat")) *out = naNum(rwy->latitude());
679 else if (!strcmp(fieldName, "lon")) *out = naNum(rwy->longitude());
680 else if (!strcmp(fieldName, "heading")) *out = naNum(rwy->headingDeg());
681 else if (!strcmp(fieldName, "length")) *out = naNum(rwy->lengthM());
682 else if (!strcmp(fieldName, "width")) *out = naNum(rwy->widthM());
683 else if (!strcmp(fieldName, "threshold")) *out = naNum(rwy->displacedThresholdM());
684 else if (!strcmp(fieldName, "stopway")) *out = naNum(rwy->stopwayM());
685 else if (!strcmp(fieldName, "ils_frequency_mhz")) {
686 *out = rwy->ILS() ? naNum(rwy->ILS()->get_freq() / 100.0) : naNil();
687 } else if (!strcmp(fieldName, "ils")) {
688 *out = ghostForNavaid(c, rwy->ILS());
696 static const char* navaidGhostGetMember(naContext c, void* g, naRef field, naRef* out)
698 const char* fieldName = naStr_data(field);
699 FGNavRecord* nav = (FGNavRecord*) g;
701 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, nav->ident());
702 else if (!strcmp(fieldName, "name")) *out = stringToNasal(c, nav->name());
703 else if (!strcmp(fieldName, "lat")) *out = naNum(nav->get_lat());
704 else if (!strcmp(fieldName, "lon")) *out = naNum(nav->get_lon());
705 else if (!strcmp(fieldName, "elevation")) {
706 *out = naNum(nav->get_elev_ft() * SG_FEET_TO_METER);
707 } else if (!strcmp(fieldName, "type")) {
708 *out = stringToNasal(c, nav->nameForType(nav->type()));
709 } else if (!strcmp(fieldName, "frequency")) {
710 *out = naNum(nav->get_freq());
711 } else if (!strcmp(fieldName, "range_nm")) {
712 *out = naNum(nav->get_range());
713 } else if (!strcmp(fieldName, "course")) {
714 if ((nav->type() == FGPositioned::ILS) || (nav->type() == FGPositioned::LOC)) {
715 double radial = nav->get_multiuse();
716 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
717 *out = naNum(radial);
728 static const char* fixGhostGetMember(naContext c, void* g, naRef field, naRef* out)
730 const char* fieldName = naStr_data(field);
731 FGFix* fix = (FGFix*) g;
733 if (!strcmp(fieldName, "id")) *out = stringToNasal(c, fix->ident());
734 else if (!strcmp(fieldName, "lat")) *out = naNum(fix->get_lat());
735 else if (!strcmp(fieldName, "lon")) *out = naNum(fix->get_lon());
743 static bool hashIsCoord(naRef h)
745 naRef parents = naHash_cget(h, (char*) "parents");
746 if (!naIsVector(parents)) {
750 return naEqual(naVec_get(parents, 0), geoCoordClass);
753 bool geodFromHash(naRef ref, SGGeod& result)
755 if (!naIsHash(ref)) {
760 // check for manual latitude / longitude names
761 naRef lat = naHash_cget(ref, (char*) "lat");
762 naRef lon = naHash_cget(ref, (char*) "lon");
763 if (naIsNum(lat) && naIsNum(lon)) {
764 result = SGGeod::fromDeg(naNumValue(lon).num, naNumValue(lat).num);
768 if (hashIsCoord(ref)) {
769 naRef lat = naHash_cget(ref, (char*) "_lat");
770 naRef lon = naHash_cget(ref, (char*) "_lon");
771 if (naIsNum(lat) && naIsNum(lon)) {
772 result = SGGeod::fromRad(naNumValue(lon).num, naNumValue(lat).num);
777 // check for any synonyms?
778 // latitude + longitude?
783 static int geodFromArgs(naRef* args, int offset, int argc, SGGeod& result)
785 if (offset >= argc) {
789 if (naIsGhost(args[offset])) {
790 naGhostType* gt = naGhost_type(args[offset]);
791 if (gt == &AirportGhostType) {
792 result = airportGhost(args[offset])->geod();
796 if (gt == &NavaidGhostType) {
797 result = navaidGhost(args[offset])->geod();
801 if (gt == &RunwayGhostType) {
802 result = runwayGhost(args[offset])->geod();
806 if (gt == &FixGhostType) {
807 result = fixGhost(args[offset])->geod();
811 if (gt == &WayptGhostType) {
812 result = wayptGhost(args[offset])->position();
817 if (geodFromHash(args[offset], result)) {
821 if (((argc - offset) >= 2) && naIsNum(args[offset]) && naIsNum(args[offset + 1])) {
822 double lat = naNumValue(args[0]).num,
823 lon = naNumValue(args[1]).num;
824 result = SGGeod::fromDeg(lon, lat);
831 // Convert a cartesian point to a geodetic lat/lon/altitude.
832 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
834 double lat, lon, alt, xyz[3];
835 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
836 for(int i=0; i<3; i++)
837 xyz[i] = naNumValue(args[i]).num;
838 sgCartToGeod(xyz, &lat, &lon, &alt);
839 lat *= SG_RADIANS_TO_DEGREES;
840 lon *= SG_RADIANS_TO_DEGREES;
841 naRef vec = naNewVector(c);
842 naVec_append(vec, naNum(lat));
843 naVec_append(vec, naNum(lon));
844 naVec_append(vec, naNum(alt));
848 // Convert a geodetic lat/lon/altitude to a cartesian point.
849 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
851 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
852 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
853 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
854 double alt = naNumValue(args[2]).num;
856 sgGeodToCart(lat, lon, alt, xyz);
857 naRef vec = naNewVector(c);
858 naVec_append(vec, naNum(xyz[0]));
859 naVec_append(vec, naNum(xyz[1]));
860 naVec_append(vec, naNum(xyz[2]));
864 // For given geodetic point return array with elevation, and a material data
865 // hash, or nil if there's no information available (tile not loaded). If
866 // information about the material isn't available, then nil is returned instead
868 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
870 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
871 if(argc < 2 || argc > 3)
872 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
873 double lat = naNumValue(args[0]).num;
874 double lon = naNumValue(args[1]).num;
875 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
876 const SGMaterial *mat;
877 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
878 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
880 naRef vec = naNewVector(c);
881 naVec_append(vec, naNum(elev));
882 naRef matdata = naNil();
884 matdata = naNewHash(c);
885 naRef names = naNewVector(c);
886 BOOST_FOREACH(const std::string& n, mat->get_names())
887 naVec_append(names, stringToNasal(c, n));
889 HASHSET("names", 5, names);
890 HASHSET("solid", 5, naNum(mat->get_solid()));
891 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
892 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
893 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
894 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
895 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
897 naVec_append(vec, matdata);
903 class AirportInfoFilter : public FGAirport::AirportFilter
906 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
909 bool fromArg(naRef arg)
911 const char *s = naStr_data(arg);
912 if(!strcmp(s, "airport")) type = FGPositioned::AIRPORT;
913 else if(!strcmp(s, "seaport")) type = FGPositioned::SEAPORT;
914 else if(!strcmp(s, "heliport")) type = FGPositioned::HELIPORT;
921 virtual FGPositioned::Type minType() const {
925 virtual FGPositioned::Type maxType() const {
929 FGPositioned::Type type;
932 // Returns data hash for particular or nearest airport of a <type>, or nil
935 // airportinfo(<id>); e.g. "KSFO"
936 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
937 // airportinfo() same as airportinfo("airport")
938 // airportinfo(<lat>, <lon> [, <type>]);
939 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
941 SGGeod pos = globals->get_aircraft_position();
942 FGAirport* apt = NULL;
944 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
945 pos = SGGeod::fromDeg(args[1].num, args[0].num);
950 double maxRange = 10000.0; // expose this? or pick a smaller value?
952 AirportInfoFilter filter; // defaults to airports only
955 // fall through and use AIRPORT
956 } else if(argc == 1 && naIsString(args[0])) {
957 if (filter.fromArg(args[0])) {
960 // user provided an <id>, hopefully
961 apt = FGAirport::findByIdent(naStr_data(args[0]));
963 // return nil here, but don't raise a runtime error; this is a
964 // legitamate way to validate an ICAO code, for example in a
965 // dialog box or similar.
970 naRuntimeError(c, "airportinfo() with invalid function arguments");
975 apt = FGAirport::findClosest(pos, maxRange, &filter);
976 if(!apt) return naNil();
979 return ghostForAirport(c, apt);
982 static naRef f_findAirportsWithinRange(naContext c, naRef me, int argc, naRef* args)
985 SGGeod pos = globals->get_aircraft_position();
986 argOffset += geodFromArgs(args, 0, argc, pos);
988 if (!naIsNum(args[argOffset])) {
989 naRuntimeError(c, "findAirportsWithinRange expected range (in nm) as arg %d", argOffset);
992 AirportInfoFilter filter; // defaults to airports only
993 double rangeNm = args[argOffset++].num;
994 if (argOffset < argc) {
995 filter.fromArg(args[argOffset++]);
998 naRef r = naNewVector(c);
1000 FGPositioned::List apts = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1001 FGPositioned::sortByRange(apts, pos);
1003 BOOST_FOREACH(FGPositionedRef a, apts) {
1004 FGAirport* apt = (FGAirport*) a.get();
1005 naVec_append(r, ghostForAirport(c, apt));
1011 static naRef f_findAirportsByICAO(naContext c, naRef me, int argc, naRef* args)
1013 if (!naIsString(args[0])) {
1014 naRuntimeError(c, "findAirportsByICAO expects string as arg 0");
1018 string prefix(naStr_data(args[argOffset++]));
1019 AirportInfoFilter filter; // defaults to airports only
1020 if (argOffset < argc) {
1021 filter.fromArg(args[argOffset++]);
1024 naRef r = naNewVector(c);
1026 FGPositioned::List apts = FGPositioned::findAllWithIdent(prefix, &filter, false);
1028 BOOST_FOREACH(FGPositionedRef a, apts) {
1029 FGAirport* apt = (FGAirport*) a.get();
1030 naVec_append(r, ghostForAirport(c, apt));
1036 static naRef f_airport_tower(naContext c, naRef me, int argc, naRef* args)
1038 FGAirport* apt = airportGhost(me);
1040 naRuntimeError(c, "airport.tower called on non-airport object");
1043 // build a hash for the tower position
1044 SGGeod towerLoc = apt->getTowerLocation();
1045 naRef tower = naNewHash(c);
1046 hashset(c, tower, "lat", naNum(towerLoc.getLatitudeDeg()));
1047 hashset(c, tower, "lon", naNum(towerLoc.getLongitudeDeg()));
1048 hashset(c, tower, "elevation", naNum(towerLoc.getElevationM()));
1052 static naRef f_airport_comms(naContext c, naRef me, int argc, naRef* args)
1054 FGAirport* apt = airportGhost(me);
1056 naRuntimeError(c, "airport.comms called on non-airport object");
1058 naRef comms = naNewVector(c);
1060 // if we have an explicit type, return a simple vector of frequencies
1061 if (argc > 0 && naIsScalar(args[0])) {
1062 std::string commName = naStr_data(args[0]);
1063 FGPositioned::Type commType = FGPositioned::typeFromName(commName);
1065 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStationsOfType(commType)) {
1066 naVec_append(comms, naNum(comm->freqMHz()));
1069 // otherwise return a vector of hashes, one for each comm station.
1070 BOOST_FOREACH(flightgear::CommStation* comm, apt->commStations()) {
1071 naRef commHash = naNewHash(c);
1072 hashset(c, commHash, "frequency", naNum(comm->freqMHz()));
1073 hashset(c, commHash, "ident", stringToNasal(c, comm->ident()));
1074 naVec_append(comms, commHash);
1081 static naRef f_airport_runway(naContext c, naRef me, int argc, naRef* args)
1083 FGAirport* apt = airportGhost(me);
1085 naRuntimeError(c, "airport.runway called on non-airport object");
1088 if ((argc < 1) || !naIsString(args[0])) {
1089 naRuntimeError(c, "airport.runway expects a runway ident argument");
1092 std::string ident(naStr_data(args[0]));
1093 boost::to_upper(ident);
1094 if (!apt->hasRunwayWithIdent(ident)) {
1098 return ghostForRunway(c, apt->getRunwayByIdent(ident));
1101 static naRef f_airport_sids(naContext c, naRef me, int argc, naRef* args)
1103 FGAirport* apt = airportGhost(me);
1105 naRuntimeError(c, "airport.sids called on non-airport object");
1108 naRef sids = naNewVector(c);
1110 FGRunway* rwy = NULL;
1111 if (argc > 0 && naIsString(args[0])) {
1112 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1116 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1117 } else if (argc > 0) {
1118 rwy = runwayGhost(args[0]);
1122 BOOST_FOREACH(flightgear::SID* sid, rwy->getSIDs()) {
1123 naRef procId = stringToNasal(c, sid->ident());
1124 naVec_append(sids, procId);
1127 for (unsigned int s=0; s<apt->numSIDs(); ++s) {
1128 flightgear::SID* sid = apt->getSIDByIndex(s);
1129 naRef procId = stringToNasal(c, sid->ident());
1130 naVec_append(sids, procId);
1137 static naRef f_airport_stars(naContext c, naRef me, int argc, naRef* args)
1139 FGAirport* apt = airportGhost(me);
1141 naRuntimeError(c, "airport.stars called on non-airport object");
1144 naRef stars = naNewVector(c);
1146 FGRunway* rwy = NULL;
1147 if (argc > 0 && naIsString(args[0])) {
1148 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1152 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1153 } else if (argc > 0) {
1154 rwy = runwayGhost(args[0]);
1158 BOOST_FOREACH(flightgear::STAR* s, rwy->getSTARs()) {
1159 naRef procId = stringToNasal(c, s->ident());
1160 naVec_append(stars, procId);
1163 for (unsigned int s=0; s<apt->numSTARs(); ++s) {
1164 flightgear::STAR* star = apt->getSTARByIndex(s);
1165 naRef procId = stringToNasal(c, star->ident());
1166 naVec_append(stars, procId);
1173 static naRef f_airport_approaches(naContext c, naRef me, int argc, naRef* args)
1175 FGAirport* apt = airportGhost(me);
1177 naRuntimeError(c, "airport.getApproachList called on non-airport object");
1180 naRef approaches = naNewVector(c);
1182 ProcedureType ty = PROCEDURE_INVALID;
1183 if ((argc > 1) && naIsString(args[1])) {
1184 std::string u(naStr_data(args[1]));
1186 if (u == "NDB") ty = PROCEDURE_APPROACH_NDB;
1187 if (u == "VOR") ty = PROCEDURE_APPROACH_VOR;
1188 if (u == "ILS") ty = PROCEDURE_APPROACH_ILS;
1189 if (u == "RNAV") ty = PROCEDURE_APPROACH_RNAV;
1192 FGRunway* rwy = NULL;
1193 if (argc > 0 && (rwy = runwayGhost(args[0]))) {
1195 } else if (argc > 0 && naIsString(args[0])) {
1196 if (!apt->hasRunwayWithIdent(naStr_data(args[0]))) {
1200 rwy = apt->getRunwayByIdent(naStr_data(args[0]));
1204 BOOST_FOREACH(Approach* s, rwy->getApproaches()) {
1205 if ((ty != PROCEDURE_INVALID) && (s->type() != ty)) {
1209 naRef procId = stringToNasal(c, s->ident());
1210 naVec_append(approaches, procId);
1213 // no runway specified, report them all
1214 for (unsigned int s=0; s<apt->numApproaches(); ++s) {
1215 Approach* app = apt->getApproachByIndex(s);
1216 if ((ty != PROCEDURE_INVALID) && (app->type() != ty)) {
1220 naRef procId = stringToNasal(c, app->ident());
1221 naVec_append(approaches, procId);
1228 static naRef f_airport_parking(naContext c, naRef me, int argc, naRef* args)
1230 FGAirport* apt = airportGhost(me);
1232 naRuntimeError(c, "airport.parking called on non-airport object");
1235 naRef r = naNewVector(c);
1237 bool onlyAvailable = false;
1239 if (argc > 0 && naIsString(args[0])) {
1240 type = naStr_data(args[0]);
1243 if ((argc > 1) && naIsNum(args[1])) {
1244 onlyAvailable = (args[1].num != 0.0);
1247 FGAirportDynamics* dynamics = apt->getDynamics();
1248 for (int i=0; i<dynamics->getNrOfParkings(); ++i) {
1249 FGParking* park = dynamics->getParking(i);
1250 // filter out based on availability and type
1251 if (onlyAvailable && !park->isAvailable()) {
1255 if (!type.empty() && (park->getType() != type)) {
1259 naRef nm = stringToNasal(c, park->getName());
1260 naVec_append(r, nm);
1266 static naRef f_airport_getSid(naContext c, naRef me, int argc, naRef* args)
1268 FGAirport* apt = airportGhost(me);
1270 naRuntimeError(c, "airport.getSid called on non-airport object");
1273 if ((argc != 1) || !naIsString(args[0])) {
1274 naRuntimeError(c, "airport.getSid passed invalid argument");
1277 string ident = naStr_data(args[0]);
1278 return ghostForProcedure(c, apt->findSIDWithIdent(ident));
1281 static naRef f_airport_getStar(naContext c, naRef me, int argc, naRef* args)
1283 FGAirport* apt = airportGhost(me);
1285 naRuntimeError(c, "airport.getStar called on non-airport object");
1288 if ((argc != 1) || !naIsString(args[0])) {
1289 naRuntimeError(c, "airport.getStar passed invalid argument");
1292 string ident = naStr_data(args[0]);
1293 return ghostForProcedure(c, apt->findSTARWithIdent(ident));
1296 static naRef f_airport_getApproach(naContext c, naRef me, int argc, naRef* args)
1298 FGAirport* apt = airportGhost(me);
1300 naRuntimeError(c, "airport.getIAP called on non-airport object");
1303 if ((argc != 1) || !naIsString(args[0])) {
1304 naRuntimeError(c, "airport.getIAP passed invalid argument");
1307 string ident = naStr_data(args[0]);
1308 return ghostForProcedure(c, apt->findApproachWithIdent(ident));
1311 // Returns vector of data hash for navaid of a <type>, nil on error
1312 // navaids sorted by ascending distance
1313 // navinfo([<lat>,<lon>],[<type>],[<id>])
1314 // lat/lon (numeric): use latitude/longitude instead of ac position
1315 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
1316 // id: (partial) id of the fix
1318 // navinfo("vor") returns all vors
1319 // navinfo("HAM") return all navaids who's name start with "HAM"
1320 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
1321 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
1322 // sorted by distance relative to lat=34, lon=48
1323 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
1327 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
1328 pos = SGGeod::fromDeg(args[1].num, args[0].num);
1332 pos = globals->get_aircraft_position();
1335 FGPositioned::Type type = FGPositioned::INVALID;
1336 nav_list_type navlist;
1337 const char * id = "";
1339 if(argc > 0 && naIsString(args[0])) {
1340 const char *s = naStr_data(args[0]);
1341 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
1342 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
1343 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
1344 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
1345 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
1346 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
1347 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
1348 else id = s; // this is an id
1353 if(argc > 0 && naIsString(args[0])) {
1355 naRuntimeError(c, "navinfo() called with navaid id");
1358 id = naStr_data(args[0]);
1364 naRuntimeError(c, "navinfo() called with too many arguments");
1368 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
1370 naRef reply = naNewVector(c);
1371 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1372 naVec_append( reply, ghostForNavaid(c, *it) );
1377 static naRef f_findNavaidsWithinRange(naContext c, naRef me, int argc, naRef* args)
1380 SGGeod pos = globals->get_aircraft_position();
1381 argOffset += geodFromArgs(args, 0, argc, pos);
1383 if (!naIsNum(args[argOffset])) {
1384 naRuntimeError(c, "findNavaidsWithinRange expected range (in nm) as arg %d", argOffset);
1387 FGPositioned::Type type = FGPositioned::INVALID;
1388 double rangeNm = args[argOffset++].num;
1389 if (argOffset < argc) {
1390 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1393 naRef r = naNewVector(c);
1394 FGNavList::TypeFilter filter(type);
1395 FGPositioned::List navs = FGPositioned::findWithinRange(pos, rangeNm, &filter);
1396 FGPositioned::sortByRange(navs, pos);
1398 BOOST_FOREACH(FGPositionedRef a, navs) {
1399 FGNavRecord* nav = (FGNavRecord*) a.get();
1400 naVec_append(r, ghostForNavaid(c, nav));
1406 static naRef f_findNavaidByFrequency(naContext c, naRef me, int argc, naRef* args)
1409 SGGeod pos = globals->get_aircraft_position();
1410 argOffset += geodFromArgs(args, 0, argc, pos);
1412 if (!naIsNum(args[argOffset])) {
1413 naRuntimeError(c, "findNavaidByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1416 FGPositioned::Type type = FGPositioned::INVALID;
1417 double freqMhz = args[argOffset++].num;
1418 if (argOffset < argc) {
1419 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1422 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1427 return ghostForNavaid(c, navs.front().ptr());
1430 static naRef f_findNavaidsByFrequency(naContext c, naRef me, int argc, naRef* args)
1433 SGGeod pos = globals->get_aircraft_position();
1434 argOffset += geodFromArgs(args, 0, argc, pos);
1436 if (!naIsNum(args[argOffset])) {
1437 naRuntimeError(c, "findNavaidsByFrequency expectes frequency (in Mhz) as arg %d", argOffset);
1440 FGPositioned::Type type = FGPositioned::INVALID;
1441 double freqMhz = args[argOffset++].num;
1442 if (argOffset < argc) {
1443 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1446 naRef r = naNewVector(c);
1447 nav_list_type navs = globals->get_navlist()->findAllByFreq(freqMhz, pos, type);
1449 BOOST_FOREACH(nav_rec_ptr a, navs) {
1450 naVec_append(r, ghostForNavaid(c, a.ptr()));
1456 static naRef f_findNavaidsByIdent(naContext c, naRef me, int argc, naRef* args)
1459 SGGeod pos = globals->get_aircraft_position();
1460 argOffset += geodFromArgs(args, 0, argc, pos);
1462 if (!naIsString(args[argOffset])) {
1463 naRuntimeError(c, "findNavaidsByIdent expectes ident string as arg %d", argOffset);
1466 FGPositioned::Type type = FGPositioned::INVALID;
1467 string ident = naStr_data(args[argOffset++]);
1468 if (argOffset < argc) {
1469 type = FGPositioned::typeFromName(naStr_data(args[argOffset]));
1472 naRef r = naNewVector(c);
1473 nav_list_type navs = globals->get_navlist()->findByIdentAndFreq(pos, ident, 0.0, type);
1475 BOOST_FOREACH(nav_rec_ptr a, navs) {
1476 naVec_append(r, ghostForNavaid(c, a.ptr()));
1482 static naRef f_findFixesByIdent(naContext c, naRef me, int argc, naRef* args)
1485 SGGeod pos = globals->get_aircraft_position();
1486 argOffset += geodFromArgs(args, 0, argc, pos);
1488 if (!naIsString(args[argOffset])) {
1489 naRuntimeError(c, "findFixesByIdent expectes ident string as arg %d", argOffset);
1492 string ident(naStr_data(args[argOffset]));
1493 naRef r = naNewVector(c);
1495 FGPositioned::TypeFilter filter(FGPositioned::FIX);
1496 FGPositioned::List fixes = FGPositioned::findAllWithIdent(ident, &filter);
1497 FGPositioned::sortByRange(fixes, pos);
1499 BOOST_FOREACH(FGPositionedRef f, fixes) {
1500 naVec_append(r, ghostForFix(c, (FGFix*) f.ptr()));
1506 // Convert a cartesian point to a geodetic lat/lon/altitude.
1507 static naRef f_magvar(naContext c, naRef me, int argc, naRef* args)
1509 SGGeod pos = globals->get_aircraft_position();
1511 // fine, use aircraft position
1512 } else if (geodFromArgs(args, 0, argc, pos)) {
1515 naRuntimeError(c, "magvar() expects no arguments, a positioned hash or lat,lon pair");
1518 double jd = globals->get_time_params()->getJD();
1519 double magvarDeg = sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
1520 return naNum(magvarDeg);
1523 static naRef f_courseAndDistance(naContext c, naRef me, int argc, naRef* args)
1525 SGGeod from = globals->get_aircraft_position(), to, p;
1526 int argOffset = geodFromArgs(args, 0, argc, p);
1527 if (geodFromArgs(args, argOffset, argc, to)) {
1528 from = p; // we parsed both FROM and TO args, so first was from
1530 to = p; // only parsed one arg, so FROM is current
1533 if (argOffset == 0) {
1534 naRuntimeError(c, "invalid arguments to courseAndDistance");
1537 double course, course2, d;
1538 SGGeodesy::inverse(from, to, course, course2, d);
1540 naRef result = naNewVector(c);
1541 naVec_append(result, naNum(course));
1542 naVec_append(result, naNum(d * SG_METER_TO_NM));
1546 static naRef f_greatCircleMove(naContext c, naRef me, int argc, naRef* args)
1548 SGGeod from = globals->get_aircraft_position(), to;
1551 // complication - don't inerpret two doubles (as the only args)
1552 // as a lat,lon pair - only do so if we have at least three args.
1554 argOffset = geodFromArgs(args, 0, argc, from);
1557 if ((argOffset + 1) >= argc) {
1558 naRuntimeError(c, "isufficent arguments to greatCircleMove");
1561 if (!naIsNum(args[argOffset]) || !naIsNum(args[argOffset+1])) {
1562 naRuntimeError(c, "invalid arguments %d and %d to greatCircleMove",
1563 argOffset, argOffset + 1);
1566 double course = args[argOffset].num, course2;
1567 double distanceNm = args[argOffset + 1].num;
1568 SGGeodesy::direct(from, course, distanceNm * SG_NM_TO_METER, to, course2);
1571 naRef coord = naNewHash(c);
1572 hashset(c, coord, "lat", naNum(to.getLatitudeDeg()));
1573 hashset(c, coord, "lon", naNum(to.getLongitudeDeg()));
1577 static naRef f_tilePath(naContext c, naRef me, int argc, naRef* args)
1579 SGGeod pos = globals->get_aircraft_position();
1580 geodFromArgs(args, 0, argc, pos);
1582 return stringToNasal(c, b.gen_base_path());
1585 static naRef f_tileIndex(naContext c, naRef me, int argc, naRef* args)
1587 SGGeod pos = globals->get_aircraft_position();
1588 geodFromArgs(args, 0, argc, pos);
1590 return naNum(b.gen_index());
1593 static naRef f_route(naContext c, naRef me, int argc, naRef* args)
1596 FGRouteMgr* rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
1597 return ghostForFlightPlan(c, rm->flightPlan());
1600 if ((argc > 0) && naIsString(args[0])) {
1601 flightgear::FlightPlan* fp = new flightgear::FlightPlan;
1602 SGPath path(naStr_data(args[0]));
1603 if (!path.exists()) {
1604 naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
1607 if (!fp->load(path)) {
1608 SG_LOG(SG_NASAL, SG_WARN, "failed to load flight-plan from " << path);
1613 return ghostForFlightPlan(c, fp);
1616 naRuntimeError(c, "bad arguments to flightplan()");
1620 static WayptRef wayptFromArg(naRef arg)
1622 WayptRef r = wayptGhost(arg);
1627 FGPositioned* pos = positionedGhost(arg);
1629 // let's check if the arg is hash, coudl extra a geod and hence build
1630 // a simple waypoint
1635 // special-case for runways
1636 if (pos->type() == FGPositioned::RUNWAY) {
1637 return new RunwayWaypt((FGRunway*) pos, NULL);
1640 return new NavaidWaypoint(pos, NULL);
1643 static naRef convertWayptVecToNasal(naContext c, const WayptVec& wps)
1645 naRef result = naNewVector(c);
1646 BOOST_FOREACH(WayptRef wpt, wps) {
1647 naVec_append(result, ghostForWaypt(c, wpt.get()));
1652 static naRef f_airwaySearch(naContext c, naRef me, int argc, naRef* args)
1655 naRuntimeError(c, "airwaysSearch needs at least two arguments");
1658 WayptRef start = wayptFromArg(args[0]),
1659 end = wayptFromArg(args[1]);
1661 if (!start || !end) {
1662 SG_LOG(SG_NASAL, SG_WARN, "airwaysSearch: start or end points are invalid");
1666 bool highLevel = true;
1667 if ((argc > 2) && naIsString(args[2])) {
1668 if (!strcmp(naStr_data(args[2]), "lowlevel")) {
1675 Airway::highLevel()->route(start, end, route);
1677 Airway::lowLevel()->route(start, end, route);
1680 return convertWayptVecToNasal(c, route);
1683 static naRef f_createWP(naContext c, naRef me, int argc, naRef* args)
1686 int argOffset = geodFromArgs(args, 0, argc, pos);
1688 if (((argc - argOffset) < 1) || !naIsString(args[argOffset])) {
1689 naRuntimeError(c, "createWP: no identifier supplied");
1692 string ident = naStr_data(args[argOffset++]);
1693 WayptRef wpt = new BasicWaypt(pos, ident, NULL);
1695 // set waypt flags - approach, departure, pseudo, etc
1696 if (argc > argOffset) {
1697 WayptFlag f = wayptFlagFromString(naStr_data(args[argOffset++]));
1701 return ghostForWaypt(c, wpt);
1704 static naRef f_createWPFrom(naContext c, naRef me, int argc, naRef* args)
1707 naRuntimeError(c, "createWPFrom: need at least one argument");
1710 FGPositioned* positioned = positionedGhost(args[0]);
1712 naRuntimeError(c, "createWPFrom: couldn;t convert arg[0] to FGPositioned");
1716 if (positioned->type() == FGPositioned::RUNWAY) {
1717 wpt = new RunwayWaypt((FGRunway*) positioned, NULL);
1719 wpt = new NavaidWaypoint(positioned, NULL);
1722 // set waypt flags - approach, departure, pseudo, etc
1724 WayptFlag f = wayptFlagFromString(naStr_data(args[1]));
1728 return ghostForWaypt(c, wpt);
1731 static naRef f_flightplan_getWP(naContext c, naRef me, int argc, naRef* args)
1733 FlightPlan* fp = flightplanGhost(me);
1735 naRuntimeError(c, "flightplan.getWP called on non-flightplan object");
1740 index = fp->currentIndex();
1742 index = (int) naNumValue(args[0]).num;
1745 if ((index < 0) || (index >= fp->numLegs())) {
1749 return ghostForLeg(c, fp->legAtIndex(index));
1752 static naRef f_flightplan_currentWP(naContext c, naRef me, int argc, naRef* args)
1754 FlightPlan* fp = flightplanGhost(me);
1756 naRuntimeError(c, "flightplan.currentWP called on non-flightplan object");
1758 return ghostForLeg(c, fp->currentLeg());
1761 static naRef f_flightplan_nextWP(naContext c, naRef me, int argc, naRef* args)
1763 FlightPlan* fp = flightplanGhost(me);
1765 naRuntimeError(c, "flightplan.nextWP called on non-flightplan object");
1767 return ghostForLeg(c, fp->nextLeg());
1770 static naRef f_flightplan_numWaypoints(naContext c, naRef me, int argc, naRef* args)
1772 FlightPlan* fp = flightplanGhost(me);
1774 naRuntimeError(c, "flightplan.numWaypoints called on non-flightplan object");
1776 return naNum(fp->numLegs());
1779 static naRef f_flightplan_appendWP(naContext c, naRef me, int argc, naRef* args)
1781 FlightPlan* fp = flightplanGhost(me);
1783 naRuntimeError(c, "flightplan.appendWP called on non-flightplan object");
1786 WayptRef wp = wayptGhost(args[0]);
1787 int index = fp->numLegs();
1788 fp->insertWayptAtIndex(wp.get(), index);
1789 return naNum(index);
1792 static naRef f_flightplan_insertWP(naContext c, naRef me, int argc, naRef* args)
1794 FlightPlan* fp = flightplanGhost(me);
1796 naRuntimeError(c, "flightplan.insertWP called on non-flightplan object");
1799 WayptRef wp = wayptGhost(args[0]);
1800 int index = -1; // append
1801 if ((argc > 1) && naIsNum(args[1])) {
1802 index = (int) args[1].num;
1805 fp->insertWayptAtIndex(wp.get(), index);
1809 static naRef f_flightplan_insertWPAfter(naContext c, naRef me, int argc, naRef* args)
1811 FlightPlan* fp = flightplanGhost(me);
1813 naRuntimeError(c, "flightplan.insertWPAfter called on non-flightplan object");
1816 WayptRef wp = wayptGhost(args[0]);
1817 int index = -1; // append
1818 if ((argc > 1) && naIsNum(args[1])) {
1819 index = (int) args[1].num;
1822 fp->insertWayptAtIndex(wp.get(), index + 1);
1826 static naRef f_flightplan_insertWaypoints(naContext c, naRef me, int argc, naRef* args)
1828 FlightPlan* fp = flightplanGhost(me);
1830 naRuntimeError(c, "flightplan.insertWaypoints called on non-flightplan object");
1834 if (!naIsVector(args[0])) {
1835 naRuntimeError(c, "flightplan.insertWaypoints expects vector as first arg");
1838 int count = naVec_size(args[0]);
1839 for (int i=0; i<count; ++i) {
1840 Waypt* wp = wayptGhost(naVec_get(args[0], i));
1846 int index = -1; // append
1847 if ((argc > 1) && naIsNum(args[1])) {
1848 index = (int) args[1].num;
1851 fp->insertWayptsAtIndex(wps, index);
1855 static naRef f_flightplan_deleteWP(naContext c, naRef me, int argc, naRef* args)
1857 FlightPlan* fp = flightplanGhost(me);
1859 naRuntimeError(c, "flightplan.deleteWP called on non-flightplan object");
1862 if ((argc < 1) || !naIsNum(args[0])) {
1863 naRuntimeError(c, "bad argument to flightplan.deleteWP");
1866 int index = (int) args[0].num;
1867 fp->deleteIndex(index);
1871 static naRef f_flightplan_clearPlan(naContext c, naRef me, int argc, naRef* args)
1873 FlightPlan* fp = flightplanGhost(me);
1875 naRuntimeError(c, "flightplan.clearPlan called on non-flightplan object");
1882 static naRef f_flightplan_clearWPType(naContext c, naRef me, int argc, naRef* args)
1884 FlightPlan* fp = flightplanGhost(me);
1886 naRuntimeError(c, "flightplan.clearWPType called on non-flightplan object");
1890 naRuntimeError(c, "insufficent args to flightplan.clearWPType");
1893 WayptFlag flag = wayptFlagFromString(naStr_data(args[0]));
1894 fp->clearWayptsWithFlag(flag);
1898 static naRef f_flightplan_clone(naContext c, naRef me, int argc, naRef* args)
1900 FlightPlan* fp = flightplanGhost(me);
1902 naRuntimeError(c, "flightplan.clone called on non-flightplan object");
1905 return ghostForFlightPlan(c, fp->clone());
1908 static naRef f_leg_setSpeed(naContext c, naRef me, int argc, naRef* args)
1910 FlightPlan::Leg* leg = fpLegGhost(me);
1912 naRuntimeError(c, "leg.setSpeed called on non-flightplan-leg object");
1916 naRuntimeError(c, "bad arguments to leg.setSpeed");
1919 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
1920 leg->setSpeed(rr, args[0].num);
1924 static naRef f_leg_setAltitude(naContext c, naRef me, int argc, naRef* args)
1926 FlightPlan::Leg* leg = fpLegGhost(me);
1928 naRuntimeError(c, "leg.setAltitude called on non-flightplan-leg object");
1932 naRuntimeError(c, "bad arguments to leg.setAltitude");
1935 RouteRestriction rr = routeRestrictionFromString(naStr_data(args[1]));
1936 leg->setAltitude(rr, args[0].num);
1940 static naRef f_waypoint_navaid(naContext c, naRef me, int argc, naRef* args)
1942 flightgear::Waypt* w = wayptGhost(me);
1944 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1947 FGPositioned* pos = w->source();
1952 switch (pos->type()) {
1953 case FGPositioned::VOR:
1954 case FGPositioned::NDB:
1955 case FGPositioned::ILS:
1956 case FGPositioned::LOC:
1957 case FGPositioned::GS:
1958 case FGPositioned::DME:
1959 case FGPositioned::TACAN: {
1960 FGNavRecord* nav = (FGNavRecord*) pos;
1961 return ghostForNavaid(c, nav);
1969 static naRef f_waypoint_airport(naContext c, naRef me, int argc, naRef* args)
1971 flightgear::Waypt* w = wayptGhost(me);
1973 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1976 FGPositioned* pos = w->source();
1977 if (!pos || FGAirport::isAirportType(pos)) {
1981 return ghostForAirport(c, (FGAirport*) pos);
1984 static naRef f_waypoint_runway(naContext c, naRef me, int argc, naRef* args)
1986 flightgear::Waypt* w = wayptGhost(me);
1988 naRuntimeError(c, "waypoint.navaid called on non-waypoint object");
1991 FGPositioned* pos = w->source();
1992 if (!pos || (pos->type() != FGPositioned::RUNWAY)) {
1996 return ghostForRunway(c, (FGRunway*) pos);
1999 static naRef f_procedure_transition(naContext c, naRef me, int argc, naRef* args)
2001 Procedure* proc = procedureGhost(me);
2003 naRuntimeError(c, "procedure.transition called on non-procedure object");
2006 if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2007 naRuntimeError(c, "procedure.transition called on non-SID or -STAR");
2010 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2011 Transition* trans = ad->findTransitionByName(naStr_data(args[0]));
2013 return ghostForProcedure(c, trans);
2016 static naRef f_procedure_route(naContext c, naRef me, int argc, naRef* args)
2018 Procedure* proc = procedureGhost(me);
2020 naRuntimeError(c, "procedure.route called on non-procedure object");
2023 // wrapping up tow different routines here - approach routing from the IAF
2024 // to the associated runway, and SID/STAR routing via an enroute transition
2025 // and possibly a runway transition or not.
2026 if (Approach::isApproach(proc->type())) {
2029 iaf = wayptFromArg(args[0]);
2033 Approach* app = (Approach*) proc;
2034 if (!app->route(iaf, r)) {
2035 SG_LOG(SG_NASAL, SG_WARN, "procedure.route failed for Approach somehow");
2039 return convertWayptVecToNasal(c, r);
2040 } else if ((proc->type() != PROCEDURE_SID) && (proc->type() != PROCEDURE_STAR)) {
2041 naRuntimeError(c, "procedure.route called on unsuitable procedure type");
2045 FGRunway* rwy = runwayGhost(args[0]);
2046 if (rwy) ++argOffset;
2048 ArrivalDeparture* ad = (ArrivalDeparture*) proc;
2049 Transition* trans = NULL;
2050 if (argOffset < argc) {
2051 trans = (Transition*) procedureGhost(args[argOffset]);
2054 // note either runway or trans may be NULL - that's ok
2056 if (!ad->route(rwy, trans, r)) {
2057 SG_LOG(SG_NASAL, SG_WARN, "prcoedure.route failed for ArrvialDeparture somehow");
2061 return convertWayptVecToNasal(c, r);
2065 // Table of extension functions. Terminate with zeros.
2066 static struct { const char* name; naCFunction func; } funcs[] = {
2067 { "carttogeod", f_carttogeod },
2068 { "geodtocart", f_geodtocart },
2069 { "geodinfo", f_geodinfo },
2070 { "airportinfo", f_airportinfo },
2071 { "findAirportsWithinRange", f_findAirportsWithinRange },
2072 { "findAirportsByICAO", f_findAirportsByICAO },
2073 { "navinfo", f_navinfo },
2074 { "findNavaidsWithinRange", f_findNavaidsWithinRange },
2075 { "findNavaidByFrequency", f_findNavaidByFrequency },
2076 { "findNavaidsByFrequency", f_findNavaidsByFrequency },
2077 { "findNavaidsByID", f_findNavaidsByIdent },
2078 { "findFixesByID", f_findFixesByIdent },
2079 { "flightplan", f_route },
2080 { "createWP", f_createWP },
2081 { "createWPFrom", f_createWPFrom },
2082 { "airwaysRoute", f_airwaySearch },
2083 { "magvar", f_magvar },
2084 { "courseAndDistance", f_courseAndDistance },
2085 { "greatCircleMove", f_greatCircleMove },
2086 { "tileIndex", f_tileIndex },
2087 { "tilePath", f_tilePath },
2092 naRef initNasalPositioned(naRef globals, naContext c, naRef gcSave)
2094 airportPrototype = naNewHash(c);
2095 hashset(c, gcSave, "airportProto", airportPrototype);
2097 hashset(c, airportPrototype, "runway", naNewFunc(c, naNewCCode(c, f_airport_runway)));
2098 hashset(c, airportPrototype, "tower", naNewFunc(c, naNewCCode(c, f_airport_tower)));
2099 hashset(c, airportPrototype, "comms", naNewFunc(c, naNewCCode(c, f_airport_comms)));
2100 hashset(c, airportPrototype, "sids", naNewFunc(c, naNewCCode(c, f_airport_sids)));
2101 hashset(c, airportPrototype, "stars", naNewFunc(c, naNewCCode(c, f_airport_stars)));
2102 hashset(c, airportPrototype, "getApproachList", naNewFunc(c, naNewCCode(c, f_airport_approaches)));
2103 hashset(c, airportPrototype, "parking", naNewFunc(c, naNewCCode(c, f_airport_parking)));
2104 hashset(c, airportPrototype, "getSid", naNewFunc(c, naNewCCode(c, f_airport_getSid)));
2105 hashset(c, airportPrototype, "getStar", naNewFunc(c, naNewCCode(c, f_airport_getStar)));
2106 hashset(c, airportPrototype, "getIAP", naNewFunc(c, naNewCCode(c, f_airport_getApproach)));
2108 flightplanPrototype = naNewHash(c);
2109 hashset(c, gcSave, "flightplanProto", flightplanPrototype);
2111 hashset(c, flightplanPrototype, "getWP", naNewFunc(c, naNewCCode(c, f_flightplan_getWP)));
2112 hashset(c, flightplanPrototype, "currentWP", naNewFunc(c, naNewCCode(c, f_flightplan_currentWP)));
2113 hashset(c, flightplanPrototype, "nextWP", naNewFunc(c, naNewCCode(c, f_flightplan_nextWP)));
2114 hashset(c, flightplanPrototype, "getPlanSize", naNewFunc(c, naNewCCode(c, f_flightplan_numWaypoints)));
2115 hashset(c, flightplanPrototype, "appendWP", naNewFunc(c, naNewCCode(c, f_flightplan_appendWP)));
2116 hashset(c, flightplanPrototype, "insertWP", naNewFunc(c, naNewCCode(c, f_flightplan_insertWP)));
2117 hashset(c, flightplanPrototype, "deleteWP", naNewFunc(c, naNewCCode(c, f_flightplan_deleteWP)));
2118 hashset(c, flightplanPrototype, "insertWPAfter", naNewFunc(c, naNewCCode(c, f_flightplan_insertWPAfter)));
2119 hashset(c, flightplanPrototype, "insertWaypoints", naNewFunc(c, naNewCCode(c, f_flightplan_insertWaypoints)));
2120 hashset(c, flightplanPrototype, "cleanPlan", naNewFunc(c, naNewCCode(c, f_flightplan_clearPlan)));
2121 hashset(c, flightplanPrototype, "clearWPType", naNewFunc(c, naNewCCode(c, f_flightplan_clearWPType)));
2122 hashset(c, flightplanPrototype, "clone", naNewFunc(c, naNewCCode(c, f_flightplan_clone)));
2124 waypointPrototype = naNewHash(c);
2125 hashset(c, gcSave, "wayptProto", waypointPrototype);
2127 hashset(c, waypointPrototype, "navaid", naNewFunc(c, naNewCCode(c, f_waypoint_navaid)));
2128 hashset(c, waypointPrototype, "runway", naNewFunc(c, naNewCCode(c, f_waypoint_runway)));
2129 hashset(c, waypointPrototype, "airport", naNewFunc(c, naNewCCode(c, f_waypoint_airport)));
2131 procedurePrototype = naNewHash(c);
2132 hashset(c, gcSave, "procedureProto", procedurePrototype);
2133 hashset(c, procedurePrototype, "transition", naNewFunc(c, naNewCCode(c, f_procedure_transition)));
2134 hashset(c, procedurePrototype, "route", naNewFunc(c, naNewCCode(c, f_procedure_route)));
2136 fpLegPrototype = naNewHash(c);
2137 hashset(c, gcSave, "fpLegProto", fpLegPrototype);
2138 hashset(c, fpLegPrototype, "setSpeed", naNewFunc(c, naNewCCode(c, f_leg_setSpeed)));
2139 hashset(c, fpLegPrototype, "setAltitude", naNewFunc(c, naNewCCode(c, f_leg_setAltitude)));
2141 for(int i=0; funcs[i].name; i++) {
2142 hashset(c, globals, funcs[i].name,
2143 naNewFunc(c, naNewCCode(c, funcs[i].func)));
2149 void postinitNasalPositioned(naRef globals, naContext c)
2151 naRef geoModule = naHash_cget(globals, (char*) "geo");
2152 if (naIsNil(geoModule)) {
2153 SG_LOG(SG_GENERAL, SG_WARN, "postinitNasalPositioned: geo.nas not loaded");
2157 geoCoordClass = naHash_cget(geoModule, (char*) "Coord");