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/navrecord.hxx>
35 #include <Navaids/procedure.hxx>
37 #include "NasalSys.hxx"
39 static FGNasalSys* nasalSys = 0;
41 // Listener class for loading Nasal modules on demand
42 class FGNasalModuleListener : public SGPropertyChangeListener
45 FGNasalModuleListener(SGPropertyNode* node);
47 virtual void valueChanged(SGPropertyNode* node);
50 SGPropertyNode_ptr _node;
53 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
57 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
59 if (_node->getBoolValue("enabled",false)&&
60 !_node->getBoolValue("loaded",true))
62 nasalSys->loadPropertyScripts(_node);
67 // Read and return file contents in a single buffer. Note use of
68 // stat() to get the file size. This is a win32 function, believe it
69 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
70 // Text mode brain damage will kill us if we're trying to do bytewise
72 static char* readfile(const char* file, int* lenOut)
75 if(stat(file, &data) != 0) return 0;
76 FILE* f = fopen(file, "rb");
78 char* buf = new char[data.st_size];
79 *lenOut = fread(buf, 1, data.st_size, f);
81 if(*lenOut != data.st_size) {
82 // Shouldn't happen, but warn anyway since it represents a
83 // platform bug and not a typical runtime error (missing file,
85 SG_LOG(SG_NASAL, SG_ALERT,
86 "ERROR in Nasal initialization: " <<
87 "short count returned from fread() of " << file <<
88 ". Check your C library!");
95 FGNasalSys::FGNasalSys()
101 _nextGCKey = 0; // Any value will do
105 // Does a naCall() in a new context. Wrapped here to make lock
106 // tracking easier. Extension functions are called with the lock, but
107 // we have to release it before making a new naCall(). So rather than
108 // drop the lock in every extension function that might call back into
109 // Nasal, we keep a stack depth counter here and only unlock/lock
110 // around the naCall if it isn't the first one.
111 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
113 naContext ctx = naNewContext();
114 if(_callCount) naModUnlock();
116 naRef result = naCall(ctx, code, argc, args, naNil(), locals);
120 if(_callCount) naModLock();
125 FGNasalSys::~FGNasalSys()
128 map<int, FGNasalListener *>::iterator it, end = _listener.end();
129 for(it = _listener.begin(); it != end; ++it)
132 naFreeContext(_context);
136 bool FGNasalSys::parseAndRun(const char* sourceCode)
138 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
142 call(code, 0, 0, naNil());
146 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
148 FGNasalScript* script = new FGNasalScript();
149 script->_gcKey = -1; // important, if we delete it on a parse
150 script->_nas = this; // error, don't clobber a real handle!
154 sprintf(buf, "FGNasalScript@%p", (void *)script);
158 script->_code = parse(name, src, strlen(src));
159 if(naIsNil(script->_code)) {
164 script->_gcKey = gcSave(script->_code);
168 // Utility. Sets a named key in a hash by C string, rather than nasal
170 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
172 naRef s = naNewString(_context);
173 naStr_fromdata(s, (char*)key, strlen(key));
174 naHash_set(hash, s, val);
177 // The get/setprop functions accept a *list* of strings and walk
178 // through the property tree with them to find the appropriate node.
179 // This allows a Nasal object to hold onto a property path and use it
180 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
181 // is the utility function that walks the property tree.
182 // Future enhancement: support integer arguments to specify array
184 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
186 SGPropertyNode* p = globals->get_props();
188 for(int i=0; i<len; i++) {
190 if(!naIsString(a)) return 0;
191 p = p->getNode(naStr_data(a));
194 } catch (const string& err) {
195 naRuntimeError(c, (char *)err.c_str());
201 // getprop() extension function. Concatenates its string arguments as
202 // property names and returns the value of the specified property. Or
203 // nil if it doesn't exist.
204 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
206 using namespace simgear;
207 const SGPropertyNode* p = findnode(c, args, argc);
208 if(!p) return naNil();
210 switch(p->getType()) {
211 case props::BOOL: case props::INT:
212 case props::LONG: case props::FLOAT:
215 double dv = p->getDoubleValue();
216 if (osg::isNaN(dv)) {
217 SG_LOG(SG_GENERAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
225 case props::UNSPECIFIED:
227 naRef nastr = naNewString(c);
228 const char* val = p->getStringValue();
229 naStr_fromdata(nastr, (char*)val, strlen(val));
232 case props::ALIAS: // <--- FIXME, recurse?
238 // setprop() extension function. Concatenates its string arguments as
239 // property names and sets the value of the specified property to the
241 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
244 char buf[BUFLEN + 1];
248 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
249 for(int i=0; i<argc-1; i++) {
250 naRef s = naStringValue(c, args[i]);
251 if(naIsNil(s)) return naNil();
252 strncpy(p, naStr_data(s), buflen);
254 buflen = BUFLEN - (p - buf);
255 if(i < (argc-2) && buflen > 0) {
261 SGPropertyNode* props = globals->get_props();
262 naRef val = args[argc-1];
265 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
267 naRef n = naNumValue(val);
269 naRuntimeError(c, "setprop() value is not string or number");
271 if (osg::isNaN(n.num)) {
272 naRuntimeError(c, "setprop() passed a NaN");
275 result = props->setDoubleValue(buf, n.num);
277 } catch (const string& err) {
278 naRuntimeError(c, (char *)err.c_str());
280 return naNum(result);
284 // print() extension function. Concatenates and prints its arguments
285 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
286 // make sure it appears. Is there better way to do this?
287 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
291 for(int i=0; i<n; i++) {
292 naRef s = naStringValue(c, args[i]);
293 if(naIsNil(s)) continue;
294 buf += naStr_data(s);
296 SG_LOG(SG_GENERAL, SG_ALERT, buf);
297 return naNum(buf.length());
300 // fgcommand() extension function. Executes a named command via the
301 // FlightGear command manager. Takes a single property node name as
303 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
305 naRef cmd = argc > 0 ? args[0] : naNil();
306 naRef props = argc > 1 ? args[1] : naNil();
307 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
308 naRuntimeError(c, "bad arguments to fgcommand()");
309 SGPropertyNode_ptr tmp, *node;
311 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
313 tmp = new SGPropertyNode();
316 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
319 // settimer(func, dt, simtime) extension function. Falls through to
320 // FGNasalSys::setTimer(). See there for docs.
321 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
323 nasalSys->setTimer(c, argc, args);
327 // setlistener(func, property, bool) extension function. Falls through to
328 // FGNasalSys::setListener(). See there for docs.
329 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
331 return nasalSys->setListener(c, argc, args);
334 // removelistener(int) extension function. Falls through to
335 // FGNasalSys::removeListener(). See there for docs.
336 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
338 return nasalSys->removeListener(c, argc, args);
341 // Returns a ghost handle to the argument to the currently executing
343 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
345 return nasalSys->cmdArgGhost();
348 // Sets up a property interpolation. The first argument is either a
349 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
350 // interpolate. The second argument is a vector of pairs of
351 // value/delta numbers.
352 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
354 SGPropertyNode* node;
355 naRef prop = argc > 0 ? args[0] : naNil();
356 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
357 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
360 naRef curve = argc > 1 ? args[1] : naNil();
361 if(!naIsVector(curve)) return naNil();
362 int nPoints = naVec_size(curve) / 2;
363 double* values = new double[nPoints];
364 double* deltas = new double[nPoints];
365 for(int i=0; i<nPoints; i++) {
366 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
367 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
370 ((SGInterpolator*)globals->get_subsystem_mgr()
371 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
372 ->interpolate(node, nPoints, values, deltas);
379 // This is a better RNG than the one in the default Nasal distribution
380 // (which is based on the C library rand() implementation). It will
382 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
384 return naNum(sg_random());
387 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
393 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
399 // Return an array listing of all files in a directory
400 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
402 if(argc != 1 || !naIsString(args[0]))
403 naRuntimeError(c, "bad arguments to directory()");
405 simgear::Dir d(SGPath(naStr_data(args[0])));
406 if(!d.exists()) return naNil();
407 naRef result = naNewVector(c);
409 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
410 for (unsigned int i=0; i<paths.size(); ++i) {
411 std::string p = paths[i].file();
412 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
419 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
421 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
423 if(argc != 1 || !naIsString(args[0]))
424 naRuntimeError(c, "bad arguments to resolveDataPath()");
426 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
427 const char* pdata = p.c_str();
428 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
432 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
434 // <path> ... absolute path to an XML file
435 // <start-tag> ... callback function with two args: tag name, attribute hash
436 // <end-tag> ... callback function with one arg: tag name
437 // <data> ... callback function with one arg: data
438 // <pi> ... callback function with two args: target, data
439 // (pi = "processing instruction")
440 // All four callback functions are optional and default to nil.
441 // The function returns nil on error, or the validated file name otherwise.
442 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
444 if(argc < 1 || !naIsString(args[0]))
445 naRuntimeError(c, "parsexml(): path argument missing or not a string");
446 if(argc > 5) argc = 5;
447 for(int i=1; i<argc; i++)
448 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
449 naRuntimeError(c, "parsexml(): callback argument not a function");
451 const char* file = fgValidatePath(naStr_data(args[0]), false);
453 naRuntimeError(c, "parsexml(): reading '%s' denied "
454 "(unauthorized access)", naStr_data(args[0]));
457 std::ifstream input(file);
458 NasalXMLVisitor visitor(c, argc, args);
460 readXML(input, visitor);
461 } catch (const sg_exception& e) {
462 naRuntimeError(c, "parsexml(): file '%s' %s",
463 file, e.getFormattedMessage().c_str());
466 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
469 // Return UNIX epoch time in seconds.
470 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
474 GetSystemTimeAsFileTime(&ft);
475 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
476 // Converts from 100ns units in 1601 epoch to unix epoch in sec
477 return naNum((t * 1e-7) - 11644473600.0);
480 gettimeofday(&td, 0);
481 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
485 // Convert a cartesian point to a geodetic lat/lon/altitude.
486 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
488 double lat, lon, alt, xyz[3];
489 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
490 for(int i=0; i<3; i++)
491 xyz[i] = naNumValue(args[i]).num;
492 sgCartToGeod(xyz, &lat, &lon, &alt);
493 lat *= SG_RADIANS_TO_DEGREES;
494 lon *= SG_RADIANS_TO_DEGREES;
495 naRef vec = naNewVector(c);
496 naVec_append(vec, naNum(lat));
497 naVec_append(vec, naNum(lon));
498 naVec_append(vec, naNum(alt));
502 // Convert a geodetic lat/lon/altitude to a cartesian point.
503 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
505 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
506 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
507 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
508 double alt = naNumValue(args[2]).num;
510 sgGeodToCart(lat, lon, alt, xyz);
511 naRef vec = naNewVector(c);
512 naVec_append(vec, naNum(xyz[0]));
513 naVec_append(vec, naNum(xyz[1]));
514 naVec_append(vec, naNum(xyz[2]));
518 // For given geodetic point return array with elevation, and a material data
519 // hash, or nil if there's no information available (tile not loaded). If
520 // information about the material isn't available, then nil is returned instead
522 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
524 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
525 if(argc < 2 || argc > 3)
526 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
527 double lat = naNumValue(args[0]).num;
528 double lon = naNumValue(args[1]).num;
529 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
530 const SGMaterial *mat;
531 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
532 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
534 naRef vec = naNewVector(c);
535 naVec_append(vec, naNum(elev));
536 naRef matdata = naNil();
538 matdata = naNewHash(c);
539 naRef names = naNewVector(c);
540 const vector<string> n = mat->get_names();
541 for(unsigned int i=0; i<n.size(); i++)
542 naVec_append(names, naStr_fromdata(naNewString(c),
543 const_cast<char*>(n[i].c_str()), n[i].size()));
544 HASHSET("names", 5, names);
545 HASHSET("solid", 5, naNum(mat->get_solid()));
546 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
547 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
548 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
549 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
550 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
552 naVec_append(vec, matdata);
558 class AirportInfoFilter : public FGAirport::AirportFilter
561 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
564 virtual FGPositioned::Type minType() const {
568 virtual FGPositioned::Type maxType() const {
572 FGPositioned::Type type;
575 // Returns data hash for particular or nearest airport of a <type>, or nil
578 // airportinfo(<id>); e.g. "KSFO"
579 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
580 // airportinfo() same as airportinfo("airport")
581 // airportinfo(<lat>, <lon> [, <type>]);
582 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
584 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
585 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
587 FGAirport* apt = NULL;
589 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
590 pos = SGGeod::fromDeg(args[1].num, args[0].num);
594 pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
597 double maxRange = 10000.0; // expose this? or pick a smaller value?
599 AirportInfoFilter filter; // defaults to airports only
602 // fall through and use AIRPORT
603 } else if(argc == 1 && naIsString(args[0])) {
604 const char *s = naStr_data(args[0]);
605 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
606 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
607 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
609 // user provided an <id>, hopefully
610 apt = FGAirport::findByIdent(s);
612 // return nil here, but don't raise a runtime error; this is a
613 // legitamate way to validate an ICAO code, for example in a
614 // dialog box or similar.
619 naRuntimeError(c, "airportinfo() with invalid function arguments");
624 apt = FGAirport::findClosest(pos, maxRange, &filter);
625 if(!apt) return naNil();
628 string id = apt->ident();
629 string name = apt->name();
632 naRef rwys = naNewHash(c);
633 for(unsigned int r=0; r<apt->numRunways(); ++r) {
634 FGRunway* rwy(apt->getRunwayByIndex(r));
636 naRef rwyid = naStr_fromdata(naNewString(c),
637 const_cast<char *>(rwy->ident().c_str()),
638 rwy->ident().length());
640 naRef rwydata = naNewHash(c);
641 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
642 HASHSET("id", 2, rwyid);
643 HASHSET("lat", 3, naNum(rwy->latitude()));
644 HASHSET("lon", 3, naNum(rwy->longitude()));
645 HASHSET("heading", 7, naNum(rwy->headingDeg()));
646 HASHSET("length", 6, naNum(rwy->lengthM()));
647 HASHSET("width", 5, naNum(rwy->widthM()));
648 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
649 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
652 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
655 std::vector<flightgear::SID*> sids(rwy->getSIDs());
656 naRef sidVec = naNewVector(c);
658 for (unsigned int s=0; s < sids.size(); ++s) {
659 naRef procId = naStr_fromdata(naNewString(c),
660 const_cast<char *>(sids[s]->ident().c_str()),
661 sids[s]->ident().length());
662 naVec_append(sidVec, procId);
664 HASHSET("sids", 4, sidVec);
666 std::vector<flightgear::STAR*> stars(rwy->getSTARs());
667 naRef starVec = naNewVector(c);
669 for (unsigned int s=0; s < stars.size(); ++s) {
670 naRef procId = naStr_fromdata(naNewString(c),
671 const_cast<char *>(stars[s]->ident().c_str()),
672 stars[s]->ident().length());
673 naVec_append(starVec, procId);
675 HASHSET("stars", 5, starVec);
678 naHash_set(rwys, rwyid, rwydata);
682 naRef aptdata = naNewHash(c);
683 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
684 HASHSET("id", 2, naStr_fromdata(naNewString(c),
685 const_cast<char *>(id.c_str()), id.length()));
686 HASHSET("name", 4, naStr_fromdata(naNewString(c),
687 const_cast<char *>(name.c_str()), name.length()));
688 HASHSET("lat", 3, naNum(apt->getLatitude()));
689 HASHSET("lon", 3, naNum(apt->getLongitude()));
690 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
691 HASHSET("has_metar", 9, naNum(apt->getMetar()));
692 HASHSET("runways", 7, rwys);
698 // Table of extension functions. Terminate with zeros.
699 static struct { const char* name; naCFunction func; } funcs[] = {
700 { "getprop", f_getprop },
701 { "setprop", f_setprop },
702 { "print", f_print },
703 { "_fgcommand", f_fgcommand },
704 { "settimer", f_settimer },
705 { "_setlistener", f_setlistener },
706 { "removelistener", f_removelistener },
707 { "_cmdarg", f_cmdarg },
708 { "_interpolate", f_interpolate },
710 { "srand", f_srand },
711 { "abort", f_abort },
712 { "directory", f_directory },
713 { "resolvepath", f_resolveDataPath },
714 { "parsexml", f_parsexml },
715 { "systime", f_systime },
716 { "carttogeod", f_carttogeod },
717 { "geodtocart", f_geodtocart },
718 { "geodinfo", f_geodinfo },
719 { "airportinfo", f_airportinfo },
723 naRef FGNasalSys::cmdArgGhost()
725 return propNodeGhost(_cmdArg);
728 void FGNasalSys::init()
732 _context = naNewContext();
734 // Start with globals. Add it to itself as a recursive
735 // sub-reference under the name "globals". This gives client-code
736 // write access to the namespace if someone wants to do something
738 _globals = naInit_std(_context);
739 naSave(_context, _globals);
740 hashset(_globals, "globals", _globals);
742 hashset(_globals, "math", naInit_math(_context));
743 hashset(_globals, "bits", naInit_bits(_context));
744 hashset(_globals, "io", naInit_io(_context));
745 hashset(_globals, "thread", naInit_thread(_context));
746 hashset(_globals, "utf8", naInit_utf8(_context));
748 // Add our custom extension functions:
749 for(i=0; funcs[i].name; i++)
750 hashset(_globals, funcs[i].name,
751 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
753 // And our SGPropertyNode wrapper
754 hashset(_globals, "props", genPropsModule());
756 // Make a "__gcsave" hash to hold the naRef objects which get
757 // passed to handles outside the interpreter (to protect them from
758 // begin garbage-collected).
759 _gcHash = naNewHash(_context);
760 hashset(_globals, "__gcsave", _gcHash);
762 // Now load the various source files in the Nasal directory
763 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
764 loadScriptDirectory(nasalDir);
766 // Add modules in Nasal subdirectories to property tree
767 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
768 simgear::Dir::NO_DOT_OR_DOTDOT, "");
769 for (unsigned int i=0; i<directories.size(); ++i) {
770 simgear::Dir dir(directories[i]);
771 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
772 addModule(directories[i].file(), scripts);
775 // set signal and remove node to avoid restoring at reinit
776 const char *s = "nasal-dir-initialized";
777 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
778 signal->setBoolValue(s, true);
779 signal->removeChildren(s, false);
781 // Pull scripts out of the property tree, too
782 loadPropertyScripts();
785 void FGNasalSys::update(double)
787 if(!_dead_listener.empty()) {
788 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
789 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
790 _dead_listener.clear();
793 // The global context is a legacy thing. We use dynamically
794 // created contexts for naCall() now, so that we can call them
795 // recursively. But there are still spots that want to use it for
796 // naNew*() calls, which end up leaking memory because the context
797 // only clears out its temporary vector when it's *used*. So just
798 // junk it and fetch a new/reinitialized one every frame. This is
799 // clumsy: the right solution would use the dynamic context in all
800 // cases and eliminate _context entirely. But that's more work,
801 // and this works fine (yes, they say "New" and "Free", but
802 // they're very fast, just trust me). -Andy
803 naFreeContext(_context);
804 _context = naNewContext();
807 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
809 return p1.file() < p2.file();
812 // Loads all scripts in given directory
813 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
815 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
816 // sort scripts, avoid loading sequence effects due to file system's
817 // random directory order
818 std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
820 for (unsigned int i=0; i<scripts.size(); ++i) {
821 SGPath fullpath(scripts[i]);
822 SGPath file = fullpath.file();
823 loadModule(fullpath, file.base().c_str());
827 // Create module with list of scripts
828 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
830 if (scripts.size()>0)
832 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
833 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
834 for (unsigned int i=0; i<scripts.size(); ++i) {
835 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
836 pFileNode->setStringValue(scripts[i].c_str());
838 if (!module_node->hasChild("enabled",0))
840 SGPropertyNode* node = module_node->getChild("enabled",0,true);
841 node->setBoolValue(true);
842 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
847 // Loads the scripts found under /nasal in the global tree
848 void FGNasalSys::loadPropertyScripts()
850 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
853 for(int i=0; i<nasal->nChildren(); i++)
855 SGPropertyNode* n = nasal->getChild(i);
856 loadPropertyScripts(n);
860 // Loads the scripts found under /nasal in the global tree
861 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
863 bool is_loaded = false;
865 const char* module = n->getName();
866 if(n->hasChild("module"))
867 module = n->getStringValue("module");
868 if (n->getBoolValue("enabled",true))
870 // allow multiple files to be specified within a single
874 bool file_specified = false;
876 while((fn = n->getChild("file", j)) != NULL) {
877 file_specified = true;
878 const char* file = fn->getStringValue();
880 if (!p.isAbsolute() || !p.exists())
882 p = globals->resolve_maybe_aircraft_path(file);
884 ok &= loadModule(p, module);
888 const char* src = n->getStringValue("script");
889 if(!n->hasChild("script")) src = 0; // Hrm...
891 createModule(module, n->getPath().c_str(), src, strlen(src));
893 if(!file_specified && !src)
895 // module no longer exists - clear the archived "enable" flag
896 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
897 SGPropertyNode* node = n->getChild("enabled",0,false);
899 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
901 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
902 "no <file> or <script> defined in " <<
903 "/nasal/" << module);
910 SGPropertyNode* enable = n->getChild("enabled");
913 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
914 enable->addChangeListener(listener, false);
917 n->setBoolValue("loaded",is_loaded);
920 // Logs a runtime error, with stack trace, to the FlightGear log stream
921 void FGNasalSys::logError(naContext context)
923 SG_LOG(SG_NASAL, SG_ALERT,
924 "Nasal runtime error: " << naGetError(context));
925 SG_LOG(SG_NASAL, SG_ALERT,
926 " at " << naStr_data(naGetSourceFile(context, 0)) <<
927 ", line " << naGetLine(context, 0));
928 for(int i=1; i<naStackDepth(context); i++)
929 SG_LOG(SG_NASAL, SG_ALERT,
930 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
931 ", line " << naGetLine(context, i));
934 // Reads a script file, executes it, and places the resulting
935 // namespace into the global namespace under the specified module
937 bool FGNasalSys::loadModule(SGPath file, const char* module)
940 char* buf = readfile(file.c_str(), &len);
942 SG_LOG(SG_NASAL, SG_ALERT,
943 "Nasal error: could not read script file " << file.c_str()
944 << " into module " << module);
948 bool ok = createModule(module, file.c_str(), buf, len);
953 // Parse and run. Save the local variables namespace, as it will
954 // become a sub-object of globals. The optional "arg" argument can be
955 // used to pass an associated property node to the module, which can then
956 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
957 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
958 const char* src, int len,
959 const SGPropertyNode* cmdarg,
960 int argc, naRef* args)
962 naRef code = parse(fileName, src, len);
966 // See if we already have a module hash to use. This allows the
967 // user to, for example, add functions to the built-in math
968 // module. Make a new one if necessary.
970 naRef modname = naNewString(_context);
971 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
972 if(!naHash_get(_globals, modname, &locals))
973 locals = naNewHash(_context);
975 _cmdArg = (SGPropertyNode*)cmdarg;
977 call(code, argc, args, locals);
978 hashset(_globals, moduleName, locals);
982 void FGNasalSys::deleteModule(const char* moduleName)
984 naRef modname = naNewString(_context);
985 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
986 naHash_delete(_globals, modname);
989 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
992 naRef srcfile = naNewString(_context);
993 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
994 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
996 SG_LOG(SG_NASAL, SG_ALERT,
997 "Nasal parse error: " << naGetError(_context) <<
998 " in "<< filename <<", line " << errLine);
1002 // Bind to the global namespace before returning
1003 return naBindFunction(_context, code, _globals);
1006 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1008 const char* nasal = arg->getStringValue("script");
1009 const char* moduleName = arg->getStringValue("module");
1010 naRef code = parse(arg->getPath(true).c_str(), nasal, strlen(nasal));
1011 if(naIsNil(code)) return false;
1013 // Commands can be run "in" a module. Make sure that module
1014 // exists, and set it up as the local variables hash for the
1016 naRef locals = naNil();
1018 naRef modname = naNewString(_context);
1019 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1020 if(!naHash_get(_globals, modname, &locals)) {
1021 locals = naNewHash(_context);
1022 naHash_set(_globals, modname, locals);
1026 // Cache this command's argument for inspection via cmdarg(). For
1027 // performance reasons, we won't bother with it if the invoked
1028 // code doesn't need it.
1029 _cmdArg = (SGPropertyNode*)arg;
1031 call(code, 0, 0, locals);
1035 // settimer(func, dt, simtime) extension function. The first argument
1036 // is a Nasal function to call, the second is a delta time (from now),
1037 // in seconds. The third, if present, is a boolean value indicating
1038 // that "real world" time (rather than simulator time) is to be used.
1040 // Implementation note: the FGTimer objects don't live inside the
1041 // garbage collector, so the Nasal handler functions have to be
1042 // "saved" somehow lest they be inadvertently cleaned. In this case,
1043 // they are inserted into a globals.__gcsave hash and removed on
1045 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1047 // Extract the handler, delta, and simtime arguments:
1048 naRef handler = argc > 0 ? args[0] : naNil();
1049 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1050 naRuntimeError(c, "settimer() with invalid function argument");
1054 naRef delta = argc > 1 ? args[1] : naNil();
1055 if(naIsNil(delta)) {
1056 naRuntimeError(c, "settimer() with invalid time argument");
1060 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1062 // Generate and register a C++ timer handler
1063 NasalTimer* t = new NasalTimer;
1064 t->handler = handler;
1065 t->gcKey = gcSave(handler);
1068 globals->get_event_mgr()->addEvent("NasalTimer",
1069 t, &NasalTimer::timerExpired,
1070 delta.num, simtime);
1073 void FGNasalSys::handleTimer(NasalTimer* t)
1075 call(t->handler, 0, 0, naNil());
1076 gcRelease(t->gcKey);
1079 int FGNasalSys::gcSave(naRef r)
1081 int key = _nextGCKey++;
1082 naHash_set(_gcHash, naNum(key), r);
1086 void FGNasalSys::gcRelease(int key)
1088 naHash_delete(_gcHash, naNum(key));
1091 void FGNasalSys::NasalTimer::timerExpired()
1093 nasal->handleTimer(this);
1097 int FGNasalSys::_listenerId = 0;
1099 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1100 // Attaches a callback function to a property (specified as a global
1101 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1102 // optional argument (default=0) is set to 1, then the function is also
1103 // called initially. If the fourth, optional argument is set to 0, then the
1104 // function is only called when the property node value actually changes.
1105 // Otherwise it's called independent of the value whenever the node is
1106 // written to (default). The setlistener() function returns a unique
1107 // id number, which is to be used as argument to the removelistener()
1109 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1111 SGPropertyNode_ptr node;
1112 naRef prop = argc > 0 ? args[0] : naNil();
1113 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1114 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1116 naRuntimeError(c, "setlistener() with invalid property argument");
1121 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1124 naRef code = argc > 1 ? args[1] : naNil();
1125 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1126 naRuntimeError(c, "setlistener() with invalid function argument");
1130 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1131 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1132 FGNasalListener *nl = new FGNasalListener(node, code, this,
1133 gcSave(code), _listenerId, init, type);
1135 node->addChangeListener(nl, init);
1137 _listener[_listenerId] = nl;
1138 return naNum(_listenerId++);
1141 // removelistener(int) extension function. The argument is the id of
1142 // a listener as returned by the setlistener() function.
1143 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1145 naRef id = argc > 0 ? args[0] : naNil();
1146 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1148 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1149 naRuntimeError(c, "removelistener() with invalid listener id");
1153 it->second->_dead = true;
1154 _dead_listener.push_back(it->second);
1155 _listener.erase(it);
1156 return naNum(_listener.size());
1161 // FGNasalListener class.
1163 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1164 FGNasalSys* nasal, int key, int id,
1165 int init, int type) :
1178 if(_type == 0 && !_init)
1182 FGNasalListener::~FGNasalListener()
1184 _node->removeChangeListener(this);
1185 _nas->gcRelease(_gcKey);
1188 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1190 if(_active || _dead) return;
1191 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1194 arg[0] = _nas->propNodeGhost(which);
1195 arg[1] = _nas->propNodeGhost(_node);
1196 arg[2] = mode; // value changed, child added/removed
1197 arg[3] = naNum(_node != which); // child event?
1198 _nas->call(_code, 4, arg, naNil());
1202 void FGNasalListener::valueChanged(SGPropertyNode* node)
1204 if(_type < 2 && node != _node) return; // skip child events
1205 if(_type > 0 || changed(_node) || _init)
1206 call(node, naNum(0));
1211 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1213 if(_type == 2) call(child, naNum(1));
1216 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1218 if(_type == 2) call(child, naNum(-1));
1221 bool FGNasalListener::changed(SGPropertyNode* node)
1223 using namespace simgear;
1224 props::Type type = node->getType();
1225 if(type == props::NONE) return false;
1226 if(type == props::UNSPECIFIED) return true;
1234 long l = node->getLongValue();
1235 result = l != _last_int;
1242 double d = node->getDoubleValue();
1243 result = d != _last_float;
1249 string s = node->getStringValue();
1250 result = s != _last_string;
1259 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1260 // such a class, then it lets modelLoaded() run the <load> script, and the
1261 // destructor the <unload> script. The latter happens when the model branch
1262 // is removed from the scene graph.
1264 unsigned int FGNasalModelData::_module_id = 0;
1266 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1271 SGPropertyNode *nasal = prop->getNode("nasal");
1275 SGPropertyNode *load = nasal->getNode("load");
1276 _unload = nasal->getNode("unload");
1277 if(!load && !_unload)
1280 std::stringstream m;
1281 m << "__model" << _module_id++;
1284 const char *s = load ? load->getStringValue() : "";
1287 arg[0] = nasalSys->propNodeGhost(_root);
1288 arg[1] = nasalSys->propNodeGhost(prop);
1289 nasalSys->createModule(_module.c_str(), path.c_str(), s, strlen(s),
1293 FGNasalModelData::~FGNasalModelData()
1299 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1300 "without Nasal subsystem present.");
1305 const char *s = _unload->getStringValue();
1306 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1308 nasalSys->deleteModule(_module.c_str());
1313 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1315 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1316 _c(naSubContext(c)),
1317 _start_element(argc > 1 ? args[1] : naNil()),
1318 _end_element(argc > 2 ? args[2] : naNil()),
1319 _data(argc > 3 ? args[3] : naNil()),
1320 _pi(argc > 4 ? args[4] : naNil())
1324 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1326 if(naIsNil(_start_element)) return;
1327 naRef attr = naNewHash(_c);
1328 for(int i=0; i<a.size(); i++) {
1329 naRef name = make_string(a.getName(i));
1330 naRef value = make_string(a.getValue(i));
1331 naHash_set(attr, name, value);
1333 call(_start_element, 2, make_string(tag), attr);
1336 void NasalXMLVisitor::endElement(const char* tag)
1338 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1341 void NasalXMLVisitor::data(const char* str, int len)
1343 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1346 void NasalXMLVisitor::pi(const char* target, const char* data)
1348 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1351 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1356 naCall(_c, func, num, args, naNil(), naNil());
1361 naRef NasalXMLVisitor::make_string(const char* s, int n)
1363 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1364 n < 0 ? strlen(s) : n);