7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
17 #include <simgear/nasal/nasal.h>
18 #include <simgear/props/props.hxx>
19 #include <simgear/math/sg_random.h>
20 #include <simgear/misc/sg_path.hxx>
21 #include <simgear/misc/sg_dir.hxx>
22 #include <simgear/misc/interpolator.hxx>
23 #include <simgear/scene/material/mat.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/structure/event_mgr.hxx>
28 #include <Airports/runways.hxx>
29 #include <Airports/simple.hxx>
30 #include <Main/globals.hxx>
31 #include <Main/fg_props.hxx>
32 #include <Main/util.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Navaids/navlist.hxx>
35 #include <Navaids/procedure.hxx>
37 #include "NasalSys.hxx"
41 static FGNasalSys* nasalSys = 0;
43 // Listener class for loading Nasal modules on demand
44 class FGNasalModuleListener : public SGPropertyChangeListener
47 FGNasalModuleListener(SGPropertyNode* node);
49 virtual void valueChanged(SGPropertyNode* node);
52 SGPropertyNode_ptr _node;
55 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
59 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
61 if (_node->getBoolValue("enabled",false)&&
62 !_node->getBoolValue("loaded",true))
64 nasalSys->loadPropertyScripts(_node);
69 // Read and return file contents in a single buffer. Note use of
70 // stat() to get the file size. This is a win32 function, believe it
71 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
72 // Text mode brain damage will kill us if we're trying to do bytewise
74 static char* readfile(const char* file, int* lenOut)
77 if(stat(file, &data) != 0) return 0;
78 FILE* f = fopen(file, "rb");
80 char* buf = new char[data.st_size];
81 *lenOut = fread(buf, 1, data.st_size, f);
83 if(*lenOut != data.st_size) {
84 // Shouldn't happen, but warn anyway since it represents a
85 // platform bug and not a typical runtime error (missing file,
87 SG_LOG(SG_NASAL, SG_ALERT,
88 "ERROR in Nasal initialization: " <<
89 "short count returned from fread() of " << file <<
90 ". Check your C library!");
97 FGNasalSys::FGNasalSys()
103 _nextGCKey = 0; // Any value will do
107 // Does a naCall() in a new context. Wrapped here to make lock
108 // tracking easier. Extension functions are called with the lock, but
109 // we have to release it before making a new naCall(). So rather than
110 // drop the lock in every extension function that might call back into
111 // Nasal, we keep a stack depth counter here and only unlock/lock
112 // around the naCall if it isn't the first one.
113 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
115 naContext ctx = naNewContext();
116 if(_callCount) naModUnlock();
118 naRef result = naCall(ctx, code, argc, args, naNil(), locals);
122 if(_callCount) naModLock();
127 FGNasalSys::~FGNasalSys()
130 map<int, FGNasalListener *>::iterator it, end = _listener.end();
131 for(it = _listener.begin(); it != end; ++it)
134 naFreeContext(_context);
138 bool FGNasalSys::parseAndRun(const char* sourceCode)
140 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
144 call(code, 0, 0, naNil());
148 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
150 FGNasalScript* script = new FGNasalScript();
151 script->_gcKey = -1; // important, if we delete it on a parse
152 script->_nas = this; // error, don't clobber a real handle!
156 sprintf(buf, "FGNasalScript@%p", (void *)script);
160 script->_code = parse(name, src, strlen(src));
161 if(naIsNil(script->_code)) {
166 script->_gcKey = gcSave(script->_code);
170 // Utility. Sets a named key in a hash by C string, rather than nasal
172 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
174 naRef s = naNewString(_context);
175 naStr_fromdata(s, (char*)key, strlen(key));
176 naHash_set(hash, s, val);
179 // The get/setprop functions accept a *list* of strings and walk
180 // through the property tree with them to find the appropriate node.
181 // This allows a Nasal object to hold onto a property path and use it
182 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
183 // is the utility function that walks the property tree.
184 // Future enhancement: support integer arguments to specify array
186 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
188 SGPropertyNode* p = globals->get_props();
190 for(int i=0; i<len; i++) {
192 if(!naIsString(a)) return 0;
193 p = p->getNode(naStr_data(a));
196 } catch (const string& err) {
197 naRuntimeError(c, (char *)err.c_str());
203 // getprop() extension function. Concatenates its string arguments as
204 // property names and returns the value of the specified property. Or
205 // nil if it doesn't exist.
206 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
208 using namespace simgear;
209 const SGPropertyNode* p = findnode(c, args, argc);
210 if(!p) return naNil();
212 switch(p->getType()) {
213 case props::BOOL: case props::INT:
214 case props::LONG: case props::FLOAT:
217 double dv = p->getDoubleValue();
218 if (osg::isNaN(dv)) {
219 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
227 case props::UNSPECIFIED:
229 naRef nastr = naNewString(c);
230 const char* val = p->getStringValue();
231 naStr_fromdata(nastr, (char*)val, strlen(val));
234 case props::ALIAS: // <--- FIXME, recurse?
240 // setprop() extension function. Concatenates its string arguments as
241 // property names and sets the value of the specified property to the
243 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
246 char buf[BUFLEN + 1];
250 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
251 for(int i=0; i<argc-1; i++) {
252 naRef s = naStringValue(c, args[i]);
253 if(naIsNil(s)) return naNil();
254 strncpy(p, naStr_data(s), buflen);
256 buflen = BUFLEN - (p - buf);
257 if(i < (argc-2) && buflen > 0) {
263 SGPropertyNode* props = globals->get_props();
264 naRef val = args[argc-1];
267 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
269 naRef n = naNumValue(val);
271 naRuntimeError(c, "setprop() value is not string or number");
273 if (osg::isNaN(n.num)) {
274 naRuntimeError(c, "setprop() passed a NaN");
277 result = props->setDoubleValue(buf, n.num);
279 } catch (const string& err) {
280 naRuntimeError(c, (char *)err.c_str());
282 return naNum(result);
286 // print() extension function. Concatenates and prints its arguments
287 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
288 // make sure it appears. Is there better way to do this?
289 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
293 for(int i=0; i<n; i++) {
294 naRef s = naStringValue(c, args[i]);
295 if(naIsNil(s)) continue;
296 buf += naStr_data(s);
298 SG_LOG(SG_NASAL, SG_ALERT, buf);
299 return naNum(buf.length());
302 // fgcommand() extension function. Executes a named command via the
303 // FlightGear command manager. Takes a single property node name as
305 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
307 naRef cmd = argc > 0 ? args[0] : naNil();
308 naRef props = argc > 1 ? args[1] : naNil();
309 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
310 naRuntimeError(c, "bad arguments to fgcommand()");
311 SGPropertyNode_ptr tmp, *node;
313 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
315 tmp = new SGPropertyNode();
318 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
321 // settimer(func, dt, simtime) extension function. Falls through to
322 // FGNasalSys::setTimer(). See there for docs.
323 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
325 nasalSys->setTimer(c, argc, args);
329 // setlistener(func, property, bool) extension function. Falls through to
330 // FGNasalSys::setListener(). See there for docs.
331 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
333 return nasalSys->setListener(c, argc, args);
336 // removelistener(int) extension function. Falls through to
337 // FGNasalSys::removeListener(). See there for docs.
338 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
340 return nasalSys->removeListener(c, argc, args);
343 // Returns a ghost handle to the argument to the currently executing
345 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
347 return nasalSys->cmdArgGhost();
350 // Sets up a property interpolation. The first argument is either a
351 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
352 // interpolate. The second argument is a vector of pairs of
353 // value/delta numbers.
354 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
356 SGPropertyNode* node;
357 naRef prop = argc > 0 ? args[0] : naNil();
358 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
359 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
362 naRef curve = argc > 1 ? args[1] : naNil();
363 if(!naIsVector(curve)) return naNil();
364 int nPoints = naVec_size(curve) / 2;
365 double* values = new double[nPoints];
366 double* deltas = new double[nPoints];
367 for(int i=0; i<nPoints; i++) {
368 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
369 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
372 ((SGInterpolator*)globals->get_subsystem_mgr()
373 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
374 ->interpolate(node, nPoints, values, deltas);
381 // This is a better RNG than the one in the default Nasal distribution
382 // (which is based on the C library rand() implementation). It will
384 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
386 return naNum(sg_random());
389 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
395 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
401 // Return an array listing of all files in a directory
402 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
404 if(argc != 1 || !naIsString(args[0]))
405 naRuntimeError(c, "bad arguments to directory()");
407 simgear::Dir d(SGPath(naStr_data(args[0])));
408 if(!d.exists()) return naNil();
409 naRef result = naNewVector(c);
411 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
412 for (unsigned int i=0; i<paths.size(); ++i) {
413 std::string p = paths[i].file();
414 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
421 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
423 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
425 if(argc != 1 || !naIsString(args[0]))
426 naRuntimeError(c, "bad arguments to resolveDataPath()");
428 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
429 const char* pdata = p.c_str();
430 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
434 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
436 // <path> ... absolute path to an XML file
437 // <start-tag> ... callback function with two args: tag name, attribute hash
438 // <end-tag> ... callback function with one arg: tag name
439 // <data> ... callback function with one arg: data
440 // <pi> ... callback function with two args: target, data
441 // (pi = "processing instruction")
442 // All four callback functions are optional and default to nil.
443 // The function returns nil on error, or the validated file name otherwise.
444 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
446 if(argc < 1 || !naIsString(args[0]))
447 naRuntimeError(c, "parsexml(): path argument missing or not a string");
448 if(argc > 5) argc = 5;
449 for(int i=1; i<argc; i++)
450 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
451 naRuntimeError(c, "parsexml(): callback argument not a function");
453 const char* file = fgValidatePath(naStr_data(args[0]), false);
455 naRuntimeError(c, "parsexml(): reading '%s' denied "
456 "(unauthorized access)", naStr_data(args[0]));
459 std::ifstream input(file);
460 NasalXMLVisitor visitor(c, argc, args);
462 readXML(input, visitor);
463 } catch (const sg_exception& e) {
464 naRuntimeError(c, "parsexml(): file '%s' %s",
465 file, e.getFormattedMessage().c_str());
468 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
471 // Return UNIX epoch time in seconds.
472 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
476 GetSystemTimeAsFileTime(&ft);
477 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
478 // Converts from 100ns units in 1601 epoch to unix epoch in sec
479 return naNum((t * 1e-7) - 11644473600.0);
482 gettimeofday(&td, 0);
483 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
487 // Convert a cartesian point to a geodetic lat/lon/altitude.
488 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
490 double lat, lon, alt, xyz[3];
491 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
492 for(int i=0; i<3; i++)
493 xyz[i] = naNumValue(args[i]).num;
494 sgCartToGeod(xyz, &lat, &lon, &alt);
495 lat *= SG_RADIANS_TO_DEGREES;
496 lon *= SG_RADIANS_TO_DEGREES;
497 naRef vec = naNewVector(c);
498 naVec_append(vec, naNum(lat));
499 naVec_append(vec, naNum(lon));
500 naVec_append(vec, naNum(alt));
504 // Convert a geodetic lat/lon/altitude to a cartesian point.
505 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
507 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
508 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
509 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
510 double alt = naNumValue(args[2]).num;
512 sgGeodToCart(lat, lon, alt, xyz);
513 naRef vec = naNewVector(c);
514 naVec_append(vec, naNum(xyz[0]));
515 naVec_append(vec, naNum(xyz[1]));
516 naVec_append(vec, naNum(xyz[2]));
520 // For given geodetic point return array with elevation, and a material data
521 // hash, or nil if there's no information available (tile not loaded). If
522 // information about the material isn't available, then nil is returned instead
524 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
526 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
527 if(argc < 2 || argc > 3)
528 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
529 double lat = naNumValue(args[0]).num;
530 double lon = naNumValue(args[1]).num;
531 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
532 const SGMaterial *mat;
533 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
534 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
536 naRef vec = naNewVector(c);
537 naVec_append(vec, naNum(elev));
538 naRef matdata = naNil();
540 matdata = naNewHash(c);
541 naRef names = naNewVector(c);
542 const vector<string> n = mat->get_names();
543 for(unsigned int i=0; i<n.size(); i++)
544 naVec_append(names, naStr_fromdata(naNewString(c),
545 const_cast<char*>(n[i].c_str()), n[i].size()));
546 HASHSET("names", 5, names);
547 HASHSET("solid", 5, naNum(mat->get_solid()));
548 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
549 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
550 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
551 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
552 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
554 naVec_append(vec, matdata);
560 class AirportInfoFilter : public FGAirport::AirportFilter
563 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
566 virtual FGPositioned::Type minType() const {
570 virtual FGPositioned::Type maxType() const {
574 FGPositioned::Type type;
577 // Returns data hash for particular or nearest airport of a <type>, or nil
580 // airportinfo(<id>); e.g. "KSFO"
581 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
582 // airportinfo() same as airportinfo("airport")
583 // airportinfo(<lat>, <lon> [, <type>]);
584 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
586 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
587 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
589 FGAirport* apt = NULL;
591 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
592 pos = SGGeod::fromDeg(args[1].num, args[0].num);
596 pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
599 double maxRange = 10000.0; // expose this? or pick a smaller value?
601 AirportInfoFilter filter; // defaults to airports only
604 // fall through and use AIRPORT
605 } else if(argc == 1 && naIsString(args[0])) {
606 const char *s = naStr_data(args[0]);
607 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
608 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
609 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
611 // user provided an <id>, hopefully
612 apt = FGAirport::findByIdent(s);
614 // return nil here, but don't raise a runtime error; this is a
615 // legitamate way to validate an ICAO code, for example in a
616 // dialog box or similar.
621 naRuntimeError(c, "airportinfo() with invalid function arguments");
626 apt = FGAirport::findClosest(pos, maxRange, &filter);
627 if(!apt) return naNil();
630 string id = apt->ident();
631 string name = apt->name();
634 naRef rwys = naNewHash(c);
635 for(unsigned int r=0; r<apt->numRunways(); ++r) {
636 FGRunway* rwy(apt->getRunwayByIndex(r));
638 naRef rwyid = naStr_fromdata(naNewString(c),
639 const_cast<char *>(rwy->ident().c_str()),
640 rwy->ident().length());
642 naRef rwydata = naNewHash(c);
643 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
644 HASHSET("id", 2, rwyid);
645 HASHSET("lat", 3, naNum(rwy->latitude()));
646 HASHSET("lon", 3, naNum(rwy->longitude()));
647 HASHSET("heading", 7, naNum(rwy->headingDeg()));
648 HASHSET("length", 6, naNum(rwy->lengthM()));
649 HASHSET("width", 5, naNum(rwy->widthM()));
650 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
651 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
654 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
657 std::vector<flightgear::SID*> sids(rwy->getSIDs());
658 naRef sidVec = naNewVector(c);
660 for (unsigned int s=0; s < sids.size(); ++s) {
661 naRef procId = naStr_fromdata(naNewString(c),
662 const_cast<char *>(sids[s]->ident().c_str()),
663 sids[s]->ident().length());
664 naVec_append(sidVec, procId);
666 HASHSET("sids", 4, sidVec);
668 std::vector<flightgear::STAR*> stars(rwy->getSTARs());
669 naRef starVec = naNewVector(c);
671 for (unsigned int s=0; s < stars.size(); ++s) {
672 naRef procId = naStr_fromdata(naNewString(c),
673 const_cast<char *>(stars[s]->ident().c_str()),
674 stars[s]->ident().length());
675 naVec_append(starVec, procId);
677 HASHSET("stars", 5, starVec);
680 naHash_set(rwys, rwyid, rwydata);
684 naRef aptdata = naNewHash(c);
685 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
686 HASHSET("id", 2, naStr_fromdata(naNewString(c),
687 const_cast<char *>(id.c_str()), id.length()));
688 HASHSET("name", 4, naStr_fromdata(naNewString(c),
689 const_cast<char *>(name.c_str()), name.length()));
690 HASHSET("lat", 3, naNum(apt->getLatitude()));
691 HASHSET("lon", 3, naNum(apt->getLongitude()));
692 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
693 HASHSET("has_metar", 9, naNum(apt->getMetar()));
694 HASHSET("runways", 7, rwys);
700 // Returns vector of data hash for navaid of a <type>, nil on error
701 // navaids sorted by ascending distance
702 // navinfo([<lat>,<lon>],[<type>],[<id>])
703 // lat/lon (numeric): use latitude/longitude instead of ac position
704 // type: ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
705 // id: (partial) id of the fix
707 // navinfo("vor") returns all vors
708 // navinfo("HAM") return all navaids who's name start with "HAM"
709 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
710 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM"
711 // sorted by distance relative to lat=34, lon=48
712 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
714 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
715 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
718 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
719 pos = SGGeod::fromDeg(args[1].num, args[0].num);
723 pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
726 FGPositioned::Type type = FGPositioned::INVALID;
727 nav_list_type navlist;
728 const char * id = "";
730 if(argc > 0 && naIsString(args[0])) {
731 const char *s = naStr_data(args[0]);
732 if(!strcmp(s, "any")) type = FGPositioned::INVALID;
733 else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
734 else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
735 else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
736 else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
737 else if(!strcmp(s, "dme")) type = FGPositioned::DME;
738 else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
739 else id = s; // this is an id
744 if(argc > 0 && naIsString(args[0])) {
746 naRuntimeError(c, "navinfo() called with navaid id");
749 id = naStr_data(args[0]);
755 naRuntimeError(c, "navinfo() called with too many arguments");
759 navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
761 naRef reply = naNewVector(c);
762 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
763 const FGNavRecord * nav = *it;
766 naRef navdata = naNewHash(c);
767 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
768 HASHSET("id", 2, naStr_fromdata(naNewString(c),
769 const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
770 HASHSET("name", 4, naStr_fromdata(naNewString(c),
771 const_cast<char *>(nav->name().c_str()), nav->name().length()));
772 HASHSET("frequency", 9, naNum(nav->get_freq()));
773 HASHSET("lat", 3, naNum(nav->get_lat()));
774 HASHSET("lon", 3, naNum(nav->get_lon()));
775 HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
776 HASHSET("type", 4, naStr_fromdata(naNewString(c),
777 const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
778 HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( pos, nav->geod() ) * SG_NM_TO_METER ) );
779 HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( pos, nav->geod() ) ) );
781 naVec_append( reply, navdata );
786 // Table of extension functions. Terminate with zeros.
787 static struct { const char* name; naCFunction func; } funcs[] = {
788 { "getprop", f_getprop },
789 { "setprop", f_setprop },
790 { "print", f_print },
791 { "_fgcommand", f_fgcommand },
792 { "settimer", f_settimer },
793 { "_setlistener", f_setlistener },
794 { "removelistener", f_removelistener },
795 { "_cmdarg", f_cmdarg },
796 { "_interpolate", f_interpolate },
798 { "srand", f_srand },
799 { "abort", f_abort },
800 { "directory", f_directory },
801 { "resolvepath", f_resolveDataPath },
802 { "parsexml", f_parsexml },
803 { "systime", f_systime },
804 { "carttogeod", f_carttogeod },
805 { "geodtocart", f_geodtocart },
806 { "geodinfo", f_geodinfo },
807 { "airportinfo", f_airportinfo },
808 { "navinfo", f_navinfo },
812 naRef FGNasalSys::cmdArgGhost()
814 return propNodeGhost(_cmdArg);
817 void FGNasalSys::init()
821 _context = naNewContext();
823 // Start with globals. Add it to itself as a recursive
824 // sub-reference under the name "globals". This gives client-code
825 // write access to the namespace if someone wants to do something
827 _globals = naInit_std(_context);
828 naSave(_context, _globals);
829 hashset(_globals, "globals", _globals);
831 hashset(_globals, "math", naInit_math(_context));
832 hashset(_globals, "bits", naInit_bits(_context));
833 hashset(_globals, "io", naInit_io(_context));
834 hashset(_globals, "thread", naInit_thread(_context));
835 hashset(_globals, "utf8", naInit_utf8(_context));
837 // Add our custom extension functions:
838 for(i=0; funcs[i].name; i++)
839 hashset(_globals, funcs[i].name,
840 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
842 // And our SGPropertyNode wrapper
843 hashset(_globals, "props", genPropsModule());
845 // Make a "__gcsave" hash to hold the naRef objects which get
846 // passed to handles outside the interpreter (to protect them from
847 // begin garbage-collected).
848 _gcHash = naNewHash(_context);
849 hashset(_globals, "__gcsave", _gcHash);
851 // Now load the various source files in the Nasal directory
852 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
853 loadScriptDirectory(nasalDir);
855 // Add modules in Nasal subdirectories to property tree
856 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
857 simgear::Dir::NO_DOT_OR_DOTDOT, "");
858 for (unsigned int i=0; i<directories.size(); ++i) {
859 simgear::Dir dir(directories[i]);
860 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
861 addModule(directories[i].file(), scripts);
864 // set signal and remove node to avoid restoring at reinit
865 const char *s = "nasal-dir-initialized";
866 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
867 signal->setBoolValue(s, true);
868 signal->removeChildren(s, false);
870 // Pull scripts out of the property tree, too
871 loadPropertyScripts();
874 void FGNasalSys::update(double)
876 if(!_dead_listener.empty()) {
877 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
878 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
879 _dead_listener.clear();
882 if (!_loadList.empty())
884 // process Nasal load hook (only one per update loop to avoid excessive lags)
885 _loadList.pop()->load();
888 if (!_unloadList.empty())
890 // process pending Nasal unload hooks after _all_ load hooks were processed
891 // (only unload one per update loop to avoid excessive lags)
892 _unloadList.pop()->unload();
895 // The global context is a legacy thing. We use dynamically
896 // created contexts for naCall() now, so that we can call them
897 // recursively. But there are still spots that want to use it for
898 // naNew*() calls, which end up leaking memory because the context
899 // only clears out its temporary vector when it's *used*. So just
900 // junk it and fetch a new/reinitialized one every frame. This is
901 // clumsy: the right solution would use the dynamic context in all
902 // cases and eliminate _context entirely. But that's more work,
903 // and this works fine (yes, they say "New" and "Free", but
904 // they're very fast, just trust me). -Andy
905 naFreeContext(_context);
906 _context = naNewContext();
909 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
911 return p1.file() < p2.file();
914 // Loads all scripts in given directory
915 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
917 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
918 // sort scripts, avoid loading sequence effects due to file system's
919 // random directory order
920 std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
922 for (unsigned int i=0; i<scripts.size(); ++i) {
923 SGPath fullpath(scripts[i]);
924 SGPath file = fullpath.file();
925 loadModule(fullpath, file.base().c_str());
929 // Create module with list of scripts
930 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
932 if (scripts.size()>0)
934 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
935 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
936 for (unsigned int i=0; i<scripts.size(); ++i) {
937 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
938 pFileNode->setStringValue(scripts[i].c_str());
940 if (!module_node->hasChild("enabled",0))
942 SGPropertyNode* node = module_node->getChild("enabled",0,true);
943 node->setBoolValue(true);
944 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
949 // Loads the scripts found under /nasal in the global tree
950 void FGNasalSys::loadPropertyScripts()
952 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
955 for(int i=0; i<nasal->nChildren(); i++)
957 SGPropertyNode* n = nasal->getChild(i);
958 loadPropertyScripts(n);
962 // Loads the scripts found under /nasal in the global tree
963 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
965 bool is_loaded = false;
967 const char* module = n->getName();
968 if(n->hasChild("module"))
969 module = n->getStringValue("module");
970 if (n->getBoolValue("enabled",true))
972 // allow multiple files to be specified within a single
976 bool file_specified = false;
978 while((fn = n->getChild("file", j)) != NULL) {
979 file_specified = true;
980 const char* file = fn->getStringValue();
982 if (!p.isAbsolute() || !p.exists())
984 p = globals->resolve_maybe_aircraft_path(file);
987 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
988 file << "' for module '" << module << "'.");
991 ok &= p.isNull() ? false : loadModule(p, module);
995 const char* src = n->getStringValue("script");
996 if(!n->hasChild("script")) src = 0; // Hrm...
998 createModule(module, n->getPath().c_str(), src, strlen(src));
1000 if(!file_specified && !src)
1002 // module no longer exists - clear the archived "enable" flag
1003 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1004 SGPropertyNode* node = n->getChild("enabled",0,false);
1006 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1008 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1009 "no <file> or <script> defined in " <<
1010 "/nasal/" << module);
1017 SGPropertyNode* enable = n->getChild("enabled");
1020 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1021 enable->addChangeListener(listener, false);
1024 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1025 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1026 loaded->setBoolValue(is_loaded);
1029 // Logs a runtime error, with stack trace, to the FlightGear log stream
1030 void FGNasalSys::logError(naContext context)
1032 SG_LOG(SG_NASAL, SG_ALERT,
1033 "Nasal runtime error: " << naGetError(context));
1034 SG_LOG(SG_NASAL, SG_ALERT,
1035 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1036 ", line " << naGetLine(context, 0));
1037 for(int i=1; i<naStackDepth(context); i++)
1038 SG_LOG(SG_NASAL, SG_ALERT,
1039 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1040 ", line " << naGetLine(context, i));
1043 // Reads a script file, executes it, and places the resulting
1044 // namespace into the global namespace under the specified module
1046 bool FGNasalSys::loadModule(SGPath file, const char* module)
1049 char* buf = readfile(file.c_str(), &len);
1051 SG_LOG(SG_NASAL, SG_ALERT,
1052 "Nasal error: could not read script file " << file.c_str()
1053 << " into module " << module);
1057 bool ok = createModule(module, file.c_str(), buf, len);
1062 // Parse and run. Save the local variables namespace, as it will
1063 // become a sub-object of globals. The optional "arg" argument can be
1064 // used to pass an associated property node to the module, which can then
1065 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1066 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1067 const char* src, int len,
1068 const SGPropertyNode* cmdarg,
1069 int argc, naRef* args)
1071 naRef code = parse(fileName, src, len);
1075 // See if we already have a module hash to use. This allows the
1076 // user to, for example, add functions to the built-in math
1077 // module. Make a new one if necessary.
1079 naRef modname = naNewString(_context);
1080 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1081 if(!naHash_get(_globals, modname, &locals))
1082 locals = naNewHash(_context);
1084 _cmdArg = (SGPropertyNode*)cmdarg;
1086 call(code, argc, args, locals);
1087 hashset(_globals, moduleName, locals);
1091 void FGNasalSys::deleteModule(const char* moduleName)
1093 naRef modname = naNewString(_context);
1094 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1095 naHash_delete(_globals, modname);
1098 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1101 naRef srcfile = naNewString(_context);
1102 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1103 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1105 SG_LOG(SG_NASAL, SG_ALERT,
1106 "Nasal parse error: " << naGetError(_context) <<
1107 " in "<< filename <<", line " << errLine);
1111 // Bind to the global namespace before returning
1112 return naBindFunction(_context, code, _globals);
1115 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1117 const char* nasal = arg->getStringValue("script");
1118 const char* moduleName = arg->getStringValue("module");
1119 naRef code = parse(arg->getPath(true).c_str(), nasal, strlen(nasal));
1120 if(naIsNil(code)) return false;
1122 // Commands can be run "in" a module. Make sure that module
1123 // exists, and set it up as the local variables hash for the
1125 naRef locals = naNil();
1127 naRef modname = naNewString(_context);
1128 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1129 if(!naHash_get(_globals, modname, &locals)) {
1130 locals = naNewHash(_context);
1131 naHash_set(_globals, modname, locals);
1135 // Cache this command's argument for inspection via cmdarg(). For
1136 // performance reasons, we won't bother with it if the invoked
1137 // code doesn't need it.
1138 _cmdArg = (SGPropertyNode*)arg;
1140 call(code, 0, 0, locals);
1144 // settimer(func, dt, simtime) extension function. The first argument
1145 // is a Nasal function to call, the second is a delta time (from now),
1146 // in seconds. The third, if present, is a boolean value indicating
1147 // that "real world" time (rather than simulator time) is to be used.
1149 // Implementation note: the FGTimer objects don't live inside the
1150 // garbage collector, so the Nasal handler functions have to be
1151 // "saved" somehow lest they be inadvertently cleaned. In this case,
1152 // they are inserted into a globals.__gcsave hash and removed on
1154 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1156 // Extract the handler, delta, and simtime arguments:
1157 naRef handler = argc > 0 ? args[0] : naNil();
1158 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1159 naRuntimeError(c, "settimer() with invalid function argument");
1163 naRef delta = argc > 1 ? args[1] : naNil();
1164 if(naIsNil(delta)) {
1165 naRuntimeError(c, "settimer() with invalid time argument");
1169 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1171 // Generate and register a C++ timer handler
1172 NasalTimer* t = new NasalTimer;
1173 t->handler = handler;
1174 t->gcKey = gcSave(handler);
1177 globals->get_event_mgr()->addEvent("NasalTimer",
1178 t, &NasalTimer::timerExpired,
1179 delta.num, simtime);
1182 void FGNasalSys::handleTimer(NasalTimer* t)
1184 call(t->handler, 0, 0, naNil());
1185 gcRelease(t->gcKey);
1188 int FGNasalSys::gcSave(naRef r)
1190 int key = _nextGCKey++;
1191 naHash_set(_gcHash, naNum(key), r);
1195 void FGNasalSys::gcRelease(int key)
1197 naHash_delete(_gcHash, naNum(key));
1200 void FGNasalSys::NasalTimer::timerExpired()
1202 nasal->handleTimer(this);
1206 int FGNasalSys::_listenerId = 0;
1208 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1209 // Attaches a callback function to a property (specified as a global
1210 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1211 // optional argument (default=0) is set to 1, then the function is also
1212 // called initially. If the fourth, optional argument is set to 0, then the
1213 // function is only called when the property node value actually changes.
1214 // Otherwise it's called independent of the value whenever the node is
1215 // written to (default). The setlistener() function returns a unique
1216 // id number, which is to be used as argument to the removelistener()
1218 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1220 SGPropertyNode_ptr node;
1221 naRef prop = argc > 0 ? args[0] : naNil();
1222 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1223 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1225 naRuntimeError(c, "setlistener() with invalid property argument");
1230 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1233 naRef code = argc > 1 ? args[1] : naNil();
1234 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1235 naRuntimeError(c, "setlistener() with invalid function argument");
1239 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1240 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1241 FGNasalListener *nl = new FGNasalListener(node, code, this,
1242 gcSave(code), _listenerId, init, type);
1244 node->addChangeListener(nl, init != 0);
1246 _listener[_listenerId] = nl;
1247 return naNum(_listenerId++);
1250 // removelistener(int) extension function. The argument is the id of
1251 // a listener as returned by the setlistener() function.
1252 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1254 naRef id = argc > 0 ? args[0] : naNil();
1255 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1257 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1258 naRuntimeError(c, "removelistener() with invalid listener id");
1262 it->second->_dead = true;
1263 _dead_listener.push_back(it->second);
1264 _listener.erase(it);
1265 return naNum(_listener.size());
1270 // FGNasalListener class.
1272 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1273 FGNasalSys* nasal, int key, int id,
1274 int init, int type) :
1287 if(_type == 0 && !_init)
1291 FGNasalListener::~FGNasalListener()
1293 _node->removeChangeListener(this);
1294 _nas->gcRelease(_gcKey);
1297 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1299 if(_active || _dead) return;
1300 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1303 arg[0] = _nas->propNodeGhost(which);
1304 arg[1] = _nas->propNodeGhost(_node);
1305 arg[2] = mode; // value changed, child added/removed
1306 arg[3] = naNum(_node != which); // child event?
1307 _nas->call(_code, 4, arg, naNil());
1311 void FGNasalListener::valueChanged(SGPropertyNode* node)
1313 if(_type < 2 && node != _node) return; // skip child events
1314 if(_type > 0 || changed(_node) || _init)
1315 call(node, naNum(0));
1320 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1322 if(_type == 2) call(child, naNum(1));
1325 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1327 if(_type == 2) call(child, naNum(-1));
1330 bool FGNasalListener::changed(SGPropertyNode* node)
1332 using namespace simgear;
1333 props::Type type = node->getType();
1334 if(type == props::NONE) return false;
1335 if(type == props::UNSPECIFIED) return true;
1343 long l = node->getLongValue();
1344 result = l != _last_int;
1351 double d = node->getDoubleValue();
1352 result = d != _last_float;
1358 string s = node->getStringValue();
1359 result = s != _last_string;
1368 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1369 // such a class, then it lets modelLoaded() run the <load> script, and the
1370 // destructor the <unload> script. The latter happens when the model branch
1371 // is removed from the scene graph.
1373 unsigned int FGNasalModelData::_module_id = 0;
1375 void FGNasalModelData::load()
1377 std::stringstream m;
1378 m << "__model" << _module_id++;
1381 SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1383 const char *s = _load ? _load->getStringValue() : "";
1386 arg[0] = nasalSys->propNodeGhost(_root);
1387 arg[1] = nasalSys->propNodeGhost(_prop);
1388 nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1392 void FGNasalModelData::unload()
1394 if (_module.empty())
1398 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1399 "without Nasal subsystem present.");
1403 SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1407 const char *s = _unload->getStringValue();
1408 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1411 nasalSys->deleteModule(_module.c_str());
1414 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1418 SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1419 "without Nasal subsystem present.");
1426 SGPropertyNode *nasal = prop->getNode("nasal");
1430 SGPropertyNode* load = nasal->getNode("load");
1431 SGPropertyNode* unload = nasal->getNode("unload");
1433 if ((!load) && (!unload))
1436 _data = new FGNasalModelData(_root, path, prop, load, unload);
1438 // register Nasal module to be created and loaded in the main thread.
1439 nasalSys->registerToLoad(_data);
1442 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1444 // when necessary, register Nasal module to be destroyed/unloaded
1445 // in the main thread.
1446 if ((_data.valid())&&(nasalSys))
1447 nasalSys->registerToUnload(_data);
1450 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1452 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1453 _c(naSubContext(c)),
1454 _start_element(argc > 1 ? args[1] : naNil()),
1455 _end_element(argc > 2 ? args[2] : naNil()),
1456 _data(argc > 3 ? args[3] : naNil()),
1457 _pi(argc > 4 ? args[4] : naNil())
1461 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1463 if(naIsNil(_start_element)) return;
1464 naRef attr = naNewHash(_c);
1465 for(int i=0; i<a.size(); i++) {
1466 naRef name = make_string(a.getName(i));
1467 naRef value = make_string(a.getValue(i));
1468 naHash_set(attr, name, value);
1470 call(_start_element, 2, make_string(tag), attr);
1473 void NasalXMLVisitor::endElement(const char* tag)
1475 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1478 void NasalXMLVisitor::data(const char* str, int len)
1480 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1483 void NasalXMLVisitor::pi(const char* target, const char* data)
1485 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1488 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1493 naCall(_c, func, num, args, naNil(), naNil());
1498 naRef NasalXMLVisitor::make_string(const char* s, int n)
1500 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1501 n < 0 ? strlen(s) : n);