7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
19 #include <simgear/nasal/nasal.h>
20 #include <simgear/props/props.hxx>
21 #include <simgear/math/sg_random.h>
22 #include <simgear/misc/sg_path.hxx>
23 #include <simgear/misc/interpolator.hxx>
24 #include <simgear/scene/material/mat.hxx>
25 #include <simgear/structure/commands.hxx>
26 #include <simgear/math/sg_geodesy.hxx>
27 #include <simgear/structure/event_mgr.hxx>
29 #include <Airports/runways.hxx>
30 #include <Airports/simple.hxx>
31 #include <Main/globals.hxx>
32 #include <Main/fg_props.hxx>
33 #include <Main/util.hxx>
34 #include <Scenery/scenery.hxx>
35 #include <Navaids/navrecord.hxx>
37 #include "NasalSys.hxx"
39 static FGNasalSys* nasalSys = 0;
42 // Read and return file contents in a single buffer. Note use of
43 // stat() to get the file size. This is a win32 function, believe it
44 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
45 // Text mode brain damage will kill us if we're trying to do bytewise
47 static char* readfile(const char* file, int* lenOut)
50 if(stat(file, &data) != 0) return 0;
51 FILE* f = fopen(file, "rb");
53 char* buf = new char[data.st_size];
54 *lenOut = fread(buf, 1, data.st_size, f);
56 if(*lenOut != data.st_size) {
57 // Shouldn't happen, but warn anyway since it represents a
58 // platform bug and not a typical runtime error (missing file,
60 SG_LOG(SG_NASAL, SG_ALERT,
61 "ERROR in Nasal initialization: " <<
62 "short count returned from fread() of " << file <<
63 ". Check your C library!");
70 FGNasalSys::FGNasalSys()
76 _nextGCKey = 0; // Any value will do
80 // Does a naCall() in a new context. Wrapped here to make lock
81 // tracking easier. Extension functions are called with the lock, but
82 // we have to release it before making a new naCall(). So rather than
83 // drop the lock in every extension function that might call back into
84 // Nasal, we keep a stack depth counter here and only unlock/lock
85 // around the naCall if it isn't the first one.
86 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
88 naContext ctx = naNewContext();
89 if(_callCount) naModUnlock();
91 naRef result = naCall(ctx, code, argc, args, naNil(), locals);
95 if(_callCount) naModLock();
100 FGNasalSys::~FGNasalSys()
103 map<int, FGNasalListener *>::iterator it, end = _listener.end();
104 for(it = _listener.begin(); it != end; ++it)
107 naFreeContext(_context);
111 bool FGNasalSys::parseAndRun(const char* sourceCode)
113 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
117 call(code, 0, 0, naNil());
121 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
123 FGNasalScript* script = new FGNasalScript();
124 script->_gcKey = -1; // important, if we delete it on a parse
125 script->_nas = this; // error, don't clobber a real handle!
129 sprintf(buf, "FGNasalScript@%p", (void *)script);
133 script->_code = parse(name, src, strlen(src));
134 if(naIsNil(script->_code)) {
139 script->_gcKey = gcSave(script->_code);
143 // Utility. Sets a named key in a hash by C string, rather than nasal
145 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
147 naRef s = naNewString(_context);
148 naStr_fromdata(s, (char*)key, strlen(key));
149 naHash_set(hash, s, val);
152 // The get/setprop functions accept a *list* of strings and walk
153 // through the property tree with them to find the appropriate node.
154 // This allows a Nasal object to hold onto a property path and use it
155 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
156 // is the utility function that walks the property tree.
157 // Future enhancement: support integer arguments to specify array
159 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
161 SGPropertyNode* p = globals->get_props();
163 for(int i=0; i<len; i++) {
165 if(!naIsString(a)) return 0;
166 p = p->getNode(naStr_data(a));
169 } catch (const string& err) {
170 naRuntimeError(c, (char *)err.c_str());
176 // getprop() extension function. Concatenates its string arguments as
177 // property names and returns the value of the specified property. Or
178 // nil if it doesn't exist.
179 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
181 using namespace simgear;
182 const SGPropertyNode* p = findnode(c, args, argc);
183 if(!p) return naNil();
185 switch(p->getType()) {
186 case props::BOOL: case props::INT:
187 case props::LONG: case props::FLOAT:
189 return naNum(p->getDoubleValue());
192 case props::UNSPECIFIED:
194 naRef nastr = naNewString(c);
195 const char* val = p->getStringValue();
196 naStr_fromdata(nastr, (char*)val, strlen(val));
199 case props::ALIAS: // <--- FIXME, recurse?
205 // setprop() extension function. Concatenates its string arguments as
206 // property names and sets the value of the specified property to the
208 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
211 char buf[BUFLEN + 1];
215 for(int i=0; i<argc-1; i++) {
216 naRef s = naStringValue(c, args[i]);
217 if(naIsNil(s)) return naNil();
218 strncpy(p, naStr_data(s), buflen);
220 buflen = BUFLEN - (p - buf);
221 if(i < (argc-2) && buflen > 0) {
227 SGPropertyNode* props = globals->get_props();
228 naRef val = args[argc-1];
231 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
233 naRef n = naNumValue(val);
235 naRuntimeError(c, "setprop() value is not string or number");
236 result = props->setDoubleValue(buf, n.num);
238 } catch (const string& err) {
239 naRuntimeError(c, (char *)err.c_str());
241 return naNum(result);
245 // print() extension function. Concatenates and prints its arguments
246 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
247 // make sure it appears. Is there better way to do this?
248 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
252 for(int i=0; i<n; i++) {
253 naRef s = naStringValue(c, args[i]);
254 if(naIsNil(s)) continue;
255 buf += naStr_data(s);
257 SG_LOG(SG_GENERAL, SG_ALERT, buf);
258 return naNum(buf.length());
261 // fgcommand() extension function. Executes a named command via the
262 // FlightGear command manager. Takes a single property node name as
264 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
266 naRef cmd = argc > 0 ? args[0] : naNil();
267 naRef props = argc > 1 ? args[1] : naNil();
268 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
269 naRuntimeError(c, "bad arguments to fgcommand()");
270 SGPropertyNode_ptr tmp, *node;
272 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
274 tmp = new SGPropertyNode();
277 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
280 // settimer(func, dt, simtime) extension function. Falls through to
281 // FGNasalSys::setTimer(). See there for docs.
282 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
284 nasalSys->setTimer(c, argc, args);
288 // setlistener(func, property, bool) extension function. Falls through to
289 // FGNasalSys::setListener(). See there for docs.
290 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
292 return nasalSys->setListener(c, argc, args);
295 // removelistener(int) extension function. Falls through to
296 // FGNasalSys::removeListener(). See there for docs.
297 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
299 return nasalSys->removeListener(c, argc, args);
302 // Returns a ghost handle to the argument to the currently executing
304 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
306 return nasalSys->cmdArgGhost();
309 // Sets up a property interpolation. The first argument is either a
310 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
311 // interpolate. The second argument is a vector of pairs of
312 // value/delta numbers.
313 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
315 SGPropertyNode* node;
316 naRef prop = argc > 0 ? args[0] : naNil();
317 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
318 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
321 naRef curve = argc > 1 ? args[1] : naNil();
322 if(!naIsVector(curve)) return naNil();
323 int nPoints = naVec_size(curve) / 2;
324 double* values = new double[nPoints];
325 double* deltas = new double[nPoints];
326 for(int i=0; i<nPoints; i++) {
327 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
328 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
331 ((SGInterpolator*)globals->get_subsystem_mgr()
332 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
333 ->interpolate(node, nPoints, values, deltas);
340 // This is a better RNG than the one in the default Nasal distribution
341 // (which is based on the C library rand() implementation). It will
343 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
345 return naNum(sg_random());
348 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
354 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
360 // Return an array listing of all files in a directory
361 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
363 if(argc != 1 || !naIsString(args[0]))
364 naRuntimeError(c, "bad arguments to directory()");
365 naRef ldir = args[0];
366 ulDir* dir = ulOpenDir(naStr_data(args[0]));
367 if(!dir) return naNil();
368 naRef result = naNewVector(c);
370 while((dent = ulReadDir(dir)))
371 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
372 strlen(dent->d_name)));
378 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
380 // <path> ... absolute path to an XML file
381 // <start-tag> ... callback function with two args: tag name, attribute hash
382 // <end-tag> ... callback function with one arg: tag name
383 // <data> ... callback function with one arg: data
384 // <pi> ... callback function with two args: target, data
385 // (pi = "processing instruction")
386 // All four callback functions are optional and default to nil.
387 // The function returns nil on error, or the validated file name otherwise.
388 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
390 if(argc < 1 || !naIsString(args[0]))
391 naRuntimeError(c, "parsexml(): path argument missing or not a string");
392 if(argc > 5) argc = 5;
393 for(int i=1; i<argc; i++)
394 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
395 naRuntimeError(c, "parsexml(): callback argument not a function");
397 const char* file = fgValidatePath(naStr_data(args[0]), false);
399 naRuntimeError(c, "parsexml(): reading '%s' denied "
400 "(unauthorized access)", naStr_data(args[0]));
403 std::ifstream input(file);
404 NasalXMLVisitor visitor(c, argc, args);
406 readXML(input, visitor);
407 } catch (const sg_exception& e) {
408 naRuntimeError(c, "parsexml(): file '%s' %s",
409 file, e.getFormattedMessage().c_str());
412 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
415 // Return UNIX epoch time in seconds.
416 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
420 GetSystemTimeAsFileTime(&ft);
421 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
422 // Converts from 100ns units in 1601 epoch to unix epoch in sec
423 return naNum((t * 1e-7) - 11644473600.0);
427 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
428 return naNum(t + 1e-6 * td.tv_usec);
432 // Convert a cartesian point to a geodetic lat/lon/altitude.
433 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
435 double lat, lon, alt, xyz[3];
436 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
437 for(int i=0; i<3; i++)
438 xyz[i] = naNumValue(args[i]).num;
439 sgCartToGeod(xyz, &lat, &lon, &alt);
440 lat *= SG_RADIANS_TO_DEGREES;
441 lon *= SG_RADIANS_TO_DEGREES;
442 naRef vec = naNewVector(c);
443 naVec_append(vec, naNum(lat));
444 naVec_append(vec, naNum(lon));
445 naVec_append(vec, naNum(alt));
449 // Convert a geodetic lat/lon/altitude to a cartesian point.
450 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
452 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
453 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
454 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
455 double alt = naNumValue(args[2]).num;
457 sgGeodToCart(lat, lon, alt, xyz);
458 naRef vec = naNewVector(c);
459 naVec_append(vec, naNum(xyz[0]));
460 naVec_append(vec, naNum(xyz[1]));
461 naVec_append(vec, naNum(xyz[2]));
465 // For given geodetic point return array with elevation, and a material data
466 // hash, or nil if there's no information available (tile not loaded). If
467 // information about the material isn't available, then nil is returned instead
469 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
471 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
472 if(argc < 2 || argc > 3)
473 naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
474 double lat = naNumValue(args[0]).num;
475 double lon = naNumValue(args[1]).num;
476 double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
477 const SGMaterial *mat;
478 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
479 if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
481 naRef vec = naNewVector(c);
482 naVec_append(vec, naNum(elev));
483 naRef matdata = naNil();
485 matdata = naNewHash(c);
486 naRef names = naNewVector(c);
487 const vector<string> n = mat->get_names();
488 for(unsigned int i=0; i<n.size(); i++)
489 naVec_append(names, naStr_fromdata(naNewString(c),
490 const_cast<char*>(n[i].c_str()), n[i].size()));
491 HASHSET("names", 5, names);
492 HASHSET("solid", 5, naNum(mat->get_solid()));
493 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
494 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
495 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
496 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
497 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
499 naVec_append(vec, matdata);
505 class AirportInfoFilter : public FGAirport::AirportFilter
508 AirportInfoFilter() : type(FGPositioned::AIRPORT) {
511 virtual FGPositioned::Type minType() const {
515 virtual FGPositioned::Type maxType() const {
519 FGPositioned::Type type;
522 // Returns data hash for particular or nearest airport of a <type>, or nil
525 // airportinfo(<id>); e.g. "KSFO"
526 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
527 // airportinfo() same as airportinfo("airport")
528 // airportinfo(<lat>, <lon> [, <type>]);
529 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
531 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
532 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
534 FGAirport* apt = NULL;
536 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
537 pos = SGGeod::fromDeg(args[1].num, args[0].num);
541 pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
544 double maxRange = 10000.0; // expose this? or pick a smaller value?
546 AirportInfoFilter filter; // defaults to airports only
549 // fall through and use AIRPORT
550 } else if(argc == 1 && naIsString(args[0])) {
551 const char *s = naStr_data(args[0]);
552 if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
553 else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
554 else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
556 // user provided an <id>, hopefully
557 apt = FGAirport::findByIdent(s);
559 // return nil here, but don't raise a runtime error; this is a
560 // legitamate way to validate an ICAO code, for example in a
561 // dialog box or similar.
566 naRuntimeError(c, "airportinfo() with invalid function arguments");
571 apt = FGAirport::findClosest(pos, maxRange, &filter);
572 if(!apt) return naNil();
575 string id = apt->ident();
576 string name = apt->name();
579 naRef rwys = naNewHash(c);
580 for(unsigned int r=0; r<apt->numRunways(); ++r) {
581 FGRunway* rwy(apt->getRunwayByIndex(r));
583 naRef rwyid = naStr_fromdata(naNewString(c),
584 const_cast<char *>(rwy->ident().c_str()),
585 rwy->ident().length());
587 naRef rwydata = naNewHash(c);
588 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
589 HASHSET("id", 2, rwyid);
590 HASHSET("lat", 3, naNum(rwy->latitude()));
591 HASHSET("lon", 3, naNum(rwy->longitude()));
592 HASHSET("heading", 7, naNum(rwy->headingDeg()));
593 HASHSET("length", 6, naNum(rwy->lengthM()));
594 HASHSET("width", 5, naNum(rwy->widthM()));
595 HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
596 HASHSET("stopway", 7, naNum(rwy->stopwayM()));
599 HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
603 naHash_set(rwys, rwyid, rwydata);
607 naRef aptdata = naNewHash(c);
608 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
609 HASHSET("id", 2, naStr_fromdata(naNewString(c),
610 const_cast<char *>(id.c_str()), id.length()));
611 HASHSET("name", 4, naStr_fromdata(naNewString(c),
612 const_cast<char *>(name.c_str()), name.length()));
613 HASHSET("lat", 3, naNum(apt->getLatitude()));
614 HASHSET("lon", 3, naNum(apt->getLongitude()));
615 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
616 HASHSET("has_metar", 9, naNum(apt->getMetar()));
617 HASHSET("runways", 7, rwys);
623 // Table of extension functions. Terminate with zeros.
624 static struct { const char* name; naCFunction func; } funcs[] = {
625 { "getprop", f_getprop },
626 { "setprop", f_setprop },
627 { "print", f_print },
628 { "_fgcommand", f_fgcommand },
629 { "settimer", f_settimer },
630 { "_setlistener", f_setlistener },
631 { "removelistener", f_removelistener },
632 { "_cmdarg", f_cmdarg },
633 { "_interpolate", f_interpolate },
635 { "srand", f_srand },
636 { "abort", f_abort },
637 { "directory", f_directory },
638 { "parsexml", f_parsexml },
639 { "systime", f_systime },
640 { "carttogeod", f_carttogeod },
641 { "geodtocart", f_geodtocart },
642 { "geodinfo", f_geodinfo },
643 { "airportinfo", f_airportinfo },
647 naRef FGNasalSys::cmdArgGhost()
649 return propNodeGhost(_cmdArg);
652 void FGNasalSys::init()
656 _context = naNewContext();
658 // Start with globals. Add it to itself as a recursive
659 // sub-reference under the name "globals". This gives client-code
660 // write access to the namespace if someone wants to do something
662 _globals = naInit_std(_context);
663 naSave(_context, _globals);
664 hashset(_globals, "globals", _globals);
666 hashset(_globals, "math", naInit_math(_context));
667 hashset(_globals, "bits", naInit_bits(_context));
668 hashset(_globals, "io", naInit_io(_context));
669 hashset(_globals, "thread", naInit_thread(_context));
670 hashset(_globals, "utf8", naInit_utf8(_context));
672 // Add our custom extension functions:
673 for(i=0; funcs[i].name; i++)
674 hashset(_globals, funcs[i].name,
675 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
677 // And our SGPropertyNode wrapper
678 hashset(_globals, "props", genPropsModule());
680 // Make a "__gcsave" hash to hold the naRef objects which get
681 // passed to handles outside the interpreter (to protect them from
682 // begin garbage-collected).
683 _gcHash = naNewHash(_context);
684 hashset(_globals, "__gcsave", _gcHash);
686 // Now load the various source files in the Nasal directory
687 SGPath p(globals->get_fg_root());
690 ulDir* dir = ulOpenDir(p.c_str());
691 while(dir && (dent = ulReadDir(dir)) != 0) {
693 fullpath.append(dent->d_name);
694 SGPath file(dent->d_name);
695 if(file.extension() != "nas") continue;
696 loadModule(fullpath, file.base().c_str());
700 // set signal and remove node to avoid restoring at reinit
701 const char *s = "nasal-dir-initialized";
702 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
703 signal->setBoolValue(s, true);
704 signal->removeChildren(s, false);
706 // Pull scripts out of the property tree, too
707 loadPropertyScripts();
710 void FGNasalSys::update(double)
712 if(!_dead_listener.empty()) {
713 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
714 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
715 _dead_listener.clear();
718 // The global context is a legacy thing. We use dynamically
719 // created contexts for naCall() now, so that we can call them
720 // recursively. But there are still spots that want to use it for
721 // naNew*() calls, which end up leaking memory because the context
722 // only clears out its temporary vector when it's *used*. So just
723 // junk it and fetch a new/reinitialized one every frame. This is
724 // clumsy: the right solution would use the dynamic context in all
725 // cases and eliminate _context entirely. But that's more work,
726 // and this works fine (yes, they say "New" and "Free", but
727 // they're very fast, just trust me). -Andy
728 naFreeContext(_context);
729 _context = naNewContext();
732 // Loads the scripts found under /nasal in the global tree
733 void FGNasalSys::loadPropertyScripts()
735 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
738 for(int i=0; i<nasal->nChildren(); i++) {
739 SGPropertyNode* n = nasal->getChild(i);
741 const char* module = n->getName();
742 if(n->hasChild("module"))
743 module = n->getStringValue("module");
745 // allow multiple files to be specified within a single
749 bool file_specified = false;
750 while((fn = n->getChild("file", j)) != NULL) {
751 file_specified = true;
752 const char* file = fn->getStringValue();
753 SGPath p(globals->get_fg_root());
755 loadModule(p, module);
759 const char* src = n->getStringValue("script");
760 if(!n->hasChild("script")) src = 0; // Hrm...
762 createModule(module, n->getPath(), src, strlen(src));
764 if(!file_specified && !src)
765 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
766 "no <file> or <script> defined in " <<
767 "/nasal/" << module);
771 // Logs a runtime error, with stack trace, to the FlightGear log stream
772 void FGNasalSys::logError(naContext context)
774 SG_LOG(SG_NASAL, SG_ALERT,
775 "Nasal runtime error: " << naGetError(context));
776 SG_LOG(SG_NASAL, SG_ALERT,
777 " at " << naStr_data(naGetSourceFile(context, 0)) <<
778 ", line " << naGetLine(context, 0));
779 for(int i=1; i<naStackDepth(context); i++)
780 SG_LOG(SG_NASAL, SG_ALERT,
781 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
782 ", line " << naGetLine(context, i));
785 // Reads a script file, executes it, and places the resulting
786 // namespace into the global namespace under the specified module
788 void FGNasalSys::loadModule(SGPath file, const char* module)
791 char* buf = readfile(file.c_str(), &len);
793 SG_LOG(SG_NASAL, SG_ALERT,
794 "Nasal error: could not read script file " << file.c_str()
795 << " into module " << module);
799 createModule(module, file.c_str(), buf, len);
803 // Parse and run. Save the local variables namespace, as it will
804 // become a sub-object of globals. The optional "arg" argument can be
805 // used to pass an associated property node to the module, which can then
806 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
807 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
808 const char* src, int len,
809 const SGPropertyNode* cmdarg,
810 int argc, naRef* args)
812 naRef code = parse(fileName, src, len);
816 // See if we already have a module hash to use. This allows the
817 // user to, for example, add functions to the built-in math
818 // module. Make a new one if necessary.
820 naRef modname = naNewString(_context);
821 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
822 if(!naHash_get(_globals, modname, &locals))
823 locals = naNewHash(_context);
825 _cmdArg = (SGPropertyNode*)cmdarg;
827 call(code, argc, args, locals);
828 hashset(_globals, moduleName, locals);
831 void FGNasalSys::deleteModule(const char* moduleName)
833 naRef modname = naNewString(_context);
834 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
835 naHash_delete(_globals, modname);
838 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
841 naRef srcfile = naNewString(_context);
842 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
843 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
845 SG_LOG(SG_NASAL, SG_ALERT,
846 "Nasal parse error: " << naGetError(_context) <<
847 " in "<< filename <<", line " << errLine);
851 // Bind to the global namespace before returning
852 return naBindFunction(_context, code, _globals);
855 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
857 const char* nasal = arg->getStringValue("script");
858 const char* moduleName = arg->getStringValue("module");
859 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
860 if(naIsNil(code)) return false;
862 // Commands can be run "in" a module. Make sure that module
863 // exists, and set it up as the local variables hash for the
865 naRef locals = naNil();
867 naRef modname = naNewString(_context);
868 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
869 if(!naHash_get(_globals, modname, &locals)) {
870 locals = naNewHash(_context);
871 naHash_set(_globals, modname, locals);
875 // Cache this command's argument for inspection via cmdarg(). For
876 // performance reasons, we won't bother with it if the invoked
877 // code doesn't need it.
878 _cmdArg = (SGPropertyNode*)arg;
880 call(code, 0, 0, locals);
884 // settimer(func, dt, simtime) extension function. The first argument
885 // is a Nasal function to call, the second is a delta time (from now),
886 // in seconds. The third, if present, is a boolean value indicating
887 // that "real world" time (rather than simulator time) is to be used.
889 // Implementation note: the FGTimer objects don't live inside the
890 // garbage collector, so the Nasal handler functions have to be
891 // "saved" somehow lest they be inadvertently cleaned. In this case,
892 // they are inserted into a globals.__gcsave hash and removed on
894 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
896 // Extract the handler, delta, and simtime arguments:
897 naRef handler = argc > 0 ? args[0] : naNil();
898 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
899 naRuntimeError(c, "settimer() with invalid function argument");
903 naRef delta = argc > 1 ? args[1] : naNil();
905 naRuntimeError(c, "settimer() with invalid time argument");
909 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
911 // Generate and register a C++ timer handler
912 NasalTimer* t = new NasalTimer;
913 t->handler = handler;
914 t->gcKey = gcSave(handler);
917 globals->get_event_mgr()->addEvent("NasalTimer",
918 t, &NasalTimer::timerExpired,
922 void FGNasalSys::handleTimer(NasalTimer* t)
924 call(t->handler, 0, 0, naNil());
928 int FGNasalSys::gcSave(naRef r)
930 int key = _nextGCKey++;
931 naHash_set(_gcHash, naNum(key), r);
935 void FGNasalSys::gcRelease(int key)
937 naHash_delete(_gcHash, naNum(key));
940 void FGNasalSys::NasalTimer::timerExpired()
942 nasal->handleTimer(this);
946 int FGNasalSys::_listenerId = 0;
948 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
949 // Attaches a callback function to a property (specified as a global
950 // property path string or a SGPropertyNode_ptr* ghost). If the third,
951 // optional argument (default=0) is set to 1, then the function is also
952 // called initially. If the fourth, optional argument is set to 0, then the
953 // function is only called when the property node value actually changes.
954 // Otherwise it's called independent of the value whenever the node is
955 // written to (default). The setlistener() function returns a unique
956 // id number, which is to be used as argument to the removelistener()
958 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
960 SGPropertyNode_ptr node;
961 naRef prop = argc > 0 ? args[0] : naNil();
962 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
963 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
965 naRuntimeError(c, "setlistener() with invalid property argument");
970 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
973 naRef code = argc > 1 ? args[1] : naNil();
974 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
975 naRuntimeError(c, "setlistener() with invalid function argument");
979 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
980 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
981 FGNasalListener *nl = new FGNasalListener(node, code, this,
982 gcSave(code), _listenerId, init, type);
984 node->addChangeListener(nl, init);
986 _listener[_listenerId] = nl;
987 return naNum(_listenerId++);
990 // removelistener(int) extension function. The argument is the id of
991 // a listener as returned by the setlistener() function.
992 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
994 naRef id = argc > 0 ? args[0] : naNil();
995 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
997 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
998 naRuntimeError(c, "removelistener() with invalid listener id");
1002 it->second->_dead = true;
1003 _dead_listener.push_back(it->second);
1004 _listener.erase(it);
1005 return naNum(_listener.size());
1010 // FGNasalListener class.
1012 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1013 FGNasalSys* nasal, int key, int id,
1014 int init, int type) :
1027 if(_type == 0 && !_init)
1031 FGNasalListener::~FGNasalListener()
1033 _node->removeChangeListener(this);
1034 _nas->gcRelease(_gcKey);
1037 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1039 if(_active || _dead) return;
1040 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1043 arg[0] = _nas->propNodeGhost(which);
1044 arg[1] = _nas->propNodeGhost(_node);
1045 arg[2] = mode; // value changed, child added/removed
1046 arg[3] = naNum(_node != which); // child event?
1047 _nas->call(_code, 4, arg, naNil());
1051 void FGNasalListener::valueChanged(SGPropertyNode* node)
1053 if(_type < 2 && node != _node) return; // skip child events
1054 if(_type > 0 || changed(_node) || _init)
1055 call(node, naNum(0));
1060 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1062 if(_type == 2) call(child, naNum(1));
1065 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1067 if(_type == 2) call(child, naNum(-1));
1070 bool FGNasalListener::changed(SGPropertyNode* node)
1072 using namespace simgear;
1073 props::Type type = node->getType();
1074 if(type == props::NONE) return false;
1075 if(type == props::UNSPECIFIED) return true;
1083 long l = node->getLongValue();
1084 result = l != _last_int;
1091 double d = node->getDoubleValue();
1092 result = d != _last_float;
1098 string s = node->getStringValue();
1099 result = s != _last_string;
1108 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1109 // such a class, then it lets modelLoaded() run the <load> script, and the
1110 // destructor the <unload> script. The latter happens when the model branch
1111 // is removed from the scene graph.
1113 unsigned int FGNasalModelData::_module_id = 0;
1115 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1120 SGPropertyNode *nasal = prop->getNode("nasal");
1124 SGPropertyNode *load = nasal->getNode("load");
1125 _unload = nasal->getNode("unload");
1126 if(!load && !_unload)
1129 std::stringstream m;
1130 m << "__model" << _module_id++;
1133 const char *s = load ? load->getStringValue() : "";
1136 arg[0] = nasalSys->propNodeGhost(_root);
1137 arg[1] = nasalSys->propNodeGhost(prop);
1138 nasalSys->createModule(_module.c_str(), path.c_str(), s, strlen(s),
1142 FGNasalModelData::~FGNasalModelData()
1148 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1149 "without Nasal subsystem present.");
1154 const char *s = _unload->getStringValue();
1155 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1157 nasalSys->deleteModule(_module.c_str());
1162 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1164 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1165 _c(naSubContext(c)),
1166 _start_element(argc > 1 ? args[1] : naNil()),
1167 _end_element(argc > 2 ? args[2] : naNil()),
1168 _data(argc > 3 ? args[3] : naNil()),
1169 _pi(argc > 4 ? args[4] : naNil())
1173 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1175 if(naIsNil(_start_element)) return;
1176 naRef attr = naNewHash(_c);
1177 for(int i=0; i<a.size(); i++) {
1178 naRef name = make_string(a.getName(i));
1179 naRef value = make_string(a.getValue(i));
1180 naHash_set(attr, name, value);
1182 call(_start_element, 2, make_string(tag), attr);
1185 void NasalXMLVisitor::endElement(const char* tag)
1187 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1190 void NasalXMLVisitor::data(const char* str, int len)
1192 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1195 void NasalXMLVisitor::pi(const char* target, const char* data)
1197 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1200 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1205 naCall(_c, func, num, args, naNil(), naNil());
1210 naRef NasalXMLVisitor::make_string(const char* s, int n)
1212 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1213 n < 0 ? strlen(s) : n);