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/interpolator.hxx>
22 #include <simgear/scene/material/mat.hxx>
23 #include <simgear/structure/commands.hxx>
24 #include <simgear/math/sg_geodesy.hxx>
26 #include <Main/globals.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Scenery/scenery.hxx>
30 #include "NasalSys.hxx"
32 static FGNasalSys* nasalSys = 0;
35 // Read and return file contents in a single buffer. Note use of
36 // stat() to get the file size. This is a win32 function, believe it
37 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
38 // Text mode brain damage will kill us if we're trying to do bytewise
40 static char* readfile(const char* file, int* lenOut)
43 if(stat(file, &data) != 0) return 0;
44 FILE* f = fopen(file, "rb");
46 char* buf = new char[data.st_size];
47 *lenOut = fread(buf, 1, data.st_size, f);
49 if(*lenOut != data.st_size) {
50 // Shouldn't happen, but warn anyway since it represents a
51 // platform bug and not a typical runtime error (missing file,
53 SG_LOG(SG_NASAL, SG_ALERT,
54 "ERROR in Nasal initialization: " <<
55 "short count returned from fread() of " << file <<
56 ". Check your C library!");
63 FGNasalSys::FGNasalSys()
69 _nextGCKey = 0; // Any value will do
71 _purgeListeners = false;
74 // Does a naCall() in a new context. Wrapped here to make lock
75 // tracking easier. Extension functions are called with the lock, but
76 // we have to release it before making a new naCall(). So rather than
77 // drop the lock in every extension function that might call back into
78 // Nasal, we keep a stack depth counter here and only unlock/lock
79 // around the naCall if it isn't the first one.
80 naRef FGNasalSys::call(naRef code, naRef locals)
82 naContext ctx = naNewContext();
83 if(_callCount) naModUnlock();
85 naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
89 if(_callCount) naModLock();
94 FGNasalSys::~FGNasalSys()
97 map<int, FGNasalListener *>::iterator it, end = _listener.end();
98 for(it = _listener.begin(); it != end; ++it)
101 naFreeContext(_context);
105 bool FGNasalSys::parseAndRun(const char* sourceCode)
107 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
115 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
117 FGNasalScript* script = new FGNasalScript();
118 script->_gcKey = -1; // important, if we delete it on a parse
119 script->_nas = this; // error, don't clobber a real handle!
123 sprintf(buf, "FGNasalScript@%p", (void *)script);
127 script->_code = parse(name, src, strlen(src));
128 if(naIsNil(script->_code)) {
133 script->_gcKey = gcSave(script->_code);
137 // Utility. Sets a named key in a hash by C string, rather than nasal
139 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
141 naRef s = naNewString(_context);
142 naStr_fromdata(s, (char*)key, strlen(key));
143 naHash_set(hash, s, val);
146 // The get/setprop functions accept a *list* of strings and walk
147 // through the property tree with them to find the appropriate node.
148 // This allows a Nasal object to hold onto a property path and use it
149 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
150 // is the utility function that walks the property tree.
151 // Future enhancement: support integer arguments to specify array
153 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
155 SGPropertyNode* p = globals->get_props();
157 for(int i=0; i<len; i++) {
159 if(!naIsString(a)) return 0;
160 p = p->getNode(naStr_data(a));
163 } catch (const string& err) {
164 naRuntimeError(c, (char *)err.c_str());
170 // getprop() extension function. Concatenates its string arguments as
171 // property names and returns the value of the specified property. Or
172 // nil if it doesn't exist.
173 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
175 const SGPropertyNode* p = findnode(c, args, argc);
176 if(!p) return naNil();
178 switch(p->getType()) {
179 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
180 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
181 case SGPropertyNode::DOUBLE:
182 return naNum(p->getDoubleValue());
184 case SGPropertyNode::STRING:
185 case SGPropertyNode::UNSPECIFIED:
187 naRef nastr = naNewString(c);
188 const char* val = p->getStringValue();
189 naStr_fromdata(nastr, (char*)val, strlen(val));
192 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
198 // setprop() extension function. Concatenates its string arguments as
199 // property names and sets the value of the specified property to the
201 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
204 char buf[BUFLEN + 1];
208 for(int i=0; i<argc-1; i++) {
209 naRef s = naStringValue(c, args[i]);
210 if(naIsNil(s)) return naNil();
211 strncpy(p, naStr_data(s), buflen);
213 buflen = BUFLEN - (p - buf);
214 if(i < (argc-2) && buflen > 0) {
220 SGPropertyNode* props = globals->get_props();
221 naRef val = args[argc-1];
223 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
225 naRef n = naNumValue(val);
227 naRuntimeError(c, "setprop() value is not string or number");
228 props->setDoubleValue(buf, n.num);
230 } catch (const string& err) {
231 naRuntimeError(c, (char *)err.c_str());
237 // print() extension function. Concatenates and prints its arguments
238 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
239 // make sure it appears. Is there better way to do this?
240 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
244 for(int i=0; i<n; i++) {
245 naRef s = naStringValue(c, args[i]);
246 if(naIsNil(s)) continue;
247 buf += naStr_data(s);
249 SG_LOG(SG_GENERAL, SG_ALERT, buf);
250 return naNum(buf.length());
253 // fgcommand() extension function. Executes a named command via the
254 // FlightGear command manager. Takes a single property node name as
256 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
258 naRef cmd = argc > 0 ? args[0] : naNil();
259 naRef props = argc > 1 ? args[1] : naNil();
260 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
261 naRuntimeError(c, "bad arguments to fgcommand()");
262 SGPropertyNode_ptr tmp, *node;
264 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
266 tmp = new SGPropertyNode();
269 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
272 // settimer(func, dt, simtime) extension function. Falls through to
273 // FGNasalSys::setTimer(). See there for docs.
274 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
276 nasalSys->setTimer(c, argc, args);
280 // setlistener(func, property, bool) extension function. Falls through to
281 // FGNasalSys::setListener(). See there for docs.
282 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
284 return nasalSys->setListener(c, argc, args);
287 // removelistener(int) extension function. Falls through to
288 // FGNasalSys::removeListener(). See there for docs.
289 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
291 return nasalSys->removeListener(c, argc, args);
294 // Returns a ghost handle to the argument to the currently executing
296 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
298 return nasalSys->cmdArgGhost();
301 // Sets up a property interpolation. The first argument is either a
302 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
303 // interpolate. The second argument is a vector of pairs of
304 // value/delta numbers.
305 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
307 SGPropertyNode* node;
308 naRef prop = argc > 0 ? args[0] : naNil();
309 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
310 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
313 naRef curve = argc > 1 ? args[1] : naNil();
314 if(!naIsVector(curve)) return naNil();
315 int nPoints = naVec_size(curve) / 2;
316 double* values = new double[nPoints];
317 double* deltas = new double[nPoints];
318 for(int i=0; i<nPoints; i++) {
319 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
320 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
323 ((SGInterpolator*)globals->get_subsystem_mgr()
324 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
325 ->interpolate(node, nPoints, values, deltas);
330 // This is a better RNG than the one in the default Nasal distribution
331 // (which is based on the C library rand() implementation). It will
333 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
335 return naNum(sg_random());
338 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
344 // Return an array listing of all files in a directory
345 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
347 if(argc != 1 || !naIsString(args[0]))
348 naRuntimeError(c, "bad arguments to directory()");
349 naRef ldir = args[0];
350 ulDir* dir = ulOpenDir(naStr_data(args[0]));
351 if(!dir) return naNil();
352 naRef result = naNewVector(c);
354 while((dent = ulReadDir(dir)))
355 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
356 strlen(dent->d_name)));
361 // Return UNIX epoch time in seconds.
362 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
366 GetSystemTimeAsFileTime(&ft);
367 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
368 // Converts from 100ns units in 1601 epoch to unix epoch in sec
369 return naNum((t * 1e-7) - 11644473600.0);
373 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
374 return naNum(t + 1e-6 * td.tv_usec);
379 // Convert a cartesian point to a geodetic lat/lon/altitude.
380 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
382 const double RAD2DEG = 180.0 / SGD_PI;
383 double lat, lon, alt, xyz[3];
384 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
385 for(int i=0; i<3; i++)
386 xyz[i] = naNumValue(args[i]).num;
387 sgCartToGeod(xyz, &lat, &lon, &alt);
390 naRef vec = naNewVector(c);
391 naVec_append(vec, naNum(lat));
392 naVec_append(vec, naNum(lon));
393 naVec_append(vec, naNum(alt));
397 // Convert a geodetic lat/lon/altitude to a cartesian point.
398 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
400 const double DEG2RAD = SGD_PI / 180.0;
401 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
402 double lat = naNumValue(args[0]).num * DEG2RAD;
403 double lon = naNumValue(args[1]).num * DEG2RAD;
404 double alt = naNumValue(args[2]).num * DEG2RAD;
406 sgGeodToCart(lat, lon, alt, xyz);
407 naRef vec = naNewVector(c);
408 naVec_append(vec, naNum(xyz[0]));
409 naVec_append(vec, naNum(xyz[1]));
410 naVec_append(vec, naNum(xyz[2]));
414 // For given geodetic point return array with elevation, and a material data
415 // hash, or nil if there's no information available (tile not loaded). If
416 // information about the material isn't available, then nil is returned instead
418 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
420 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
421 if(argc != 2) naRuntimeError(c, "geodinfo() expects 2 arguments: lat, lon");
422 double lat = naNumValue(args[0]).num;
423 double lon = naNumValue(args[1]).num;
425 const SGMaterial *mat;
426 if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
428 naRef vec = naNewVector(c);
429 naVec_append(vec, naNum(elev));
430 naRef matdata = naNil();
432 matdata = naNewHash(c);
433 naRef names = naNewVector(c);
434 const vector<string> n = mat->get_names();
435 for(unsigned int i=0; i<n.size(); i++)
436 naVec_append(names, naStr_fromdata(naNewString(c),
437 const_cast<char*>(n[i].c_str()), n[i].size()));
438 HASHSET("names", 5, names);
439 HASHSET("solid", 5, naNum(mat->get_solid()));
440 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
441 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
442 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
443 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
444 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
446 naVec_append(vec, matdata);
451 // Table of extension functions. Terminate with zeros.
452 static struct { char* name; naCFunction func; } funcs[] = {
453 { "getprop", f_getprop },
454 { "setprop", f_setprop },
455 { "print", f_print },
456 { "_fgcommand", f_fgcommand },
457 { "settimer", f_settimer },
458 { "_setlistener", f_setlistener },
459 { "removelistener", f_removelistener },
460 { "_cmdarg", f_cmdarg },
461 { "_interpolate", f_interpolate },
463 { "srand", f_srand },
464 { "directory", f_directory },
465 { "systime", f_systime },
466 { "carttogeod", f_carttogeod },
467 { "geodtocart", f_geodtocart },
468 { "geodinfo", f_geodinfo },
472 naRef FGNasalSys::cmdArgGhost()
474 return propNodeGhost(_cmdArg);
477 void FGNasalSys::init()
481 _context = naNewContext();
483 // Start with globals. Add it to itself as a recursive
484 // sub-reference under the name "globals". This gives client-code
485 // write access to the namespace if someone wants to do something
487 _globals = naInit_std(_context);
488 naSave(_context, _globals);
489 hashset(_globals, "globals", _globals);
491 hashset(_globals, "math", naInit_math(_context));
492 hashset(_globals, "bits", naInit_bits(_context));
493 hashset(_globals, "io", naInit_io(_context));
494 hashset(_globals, "thread", naInit_thread(_context));
495 hashset(_globals, "utf8", naInit_utf8(_context));
497 // Add our custom extension functions:
498 for(i=0; funcs[i].name; i++)
499 hashset(_globals, funcs[i].name,
500 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
502 // And our SGPropertyNode wrapper
503 hashset(_globals, "props", genPropsModule());
505 // Make a "__gcsave" hash to hold the naRef objects which get
506 // passed to handles outside the interpreter (to protect them from
507 // begin garbage-collected).
508 _gcHash = naNewHash(_context);
509 hashset(_globals, "__gcsave", _gcHash);
511 // Now load the various source files in the Nasal directory
512 SGPath p(globals->get_fg_root());
515 ulDir* dir = ulOpenDir(p.c_str());
516 while(dir && (dent = ulReadDir(dir)) != 0) {
518 fullpath.append(dent->d_name);
519 SGPath file(dent->d_name);
520 if(file.extension() != "nas") continue;
521 loadModule(fullpath, file.base().c_str());
525 // set signal and remove node to avoid restoring at reinit
526 const char *s = "nasal-dir-initialized";
527 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
528 signal->setBoolValue(s, true);
529 signal->removeChildren(s);
531 // Pull scripts out of the property tree, too
532 loadPropertyScripts();
535 void FGNasalSys::update(double)
537 if(_purgeListeners) {
538 _purgeListeners = false;
539 map<int, FGNasalListener *>::iterator it;
540 for(it = _listener.begin(); it != _listener.end();) {
541 FGNasalListener *nl = it->second;
543 _listener.erase(it++);
552 // Loads the scripts found under /nasal in the global tree
553 void FGNasalSys::loadPropertyScripts()
555 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
558 for(int i=0; i<nasal->nChildren(); i++) {
559 SGPropertyNode* n = nasal->getChild(i);
561 const char* module = n->getName();
562 if(n->hasChild("module"))
563 module = n->getStringValue("module");
565 // allow multiple files to be specified within in a single
569 bool file_specified = false;
570 while ( (fn = n->getChild("file", j)) != NULL ) {
571 file_specified = true;
572 const char* file = fn->getStringValue();
573 SGPath p(globals->get_fg_root());
575 loadModule(p, module);
579 // Old code which only allowed a single file to be specified per module
581 const char* file = n->getStringValue("file");
582 if(!n->hasChild("file")) file = 0; // Hrm...
584 SGPath p(globals->get_fg_root());
586 loadModule(p, module);
590 const char* src = n->getStringValue("script");
591 if(!n->hasChild("script")) src = 0; // Hrm...
593 createModule(module, n->getPath(), src, strlen(src));
595 if(!file_specified && !src)
596 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
597 "no <file> or <script> defined in " <<
598 "/nasal/" << module);
602 // Logs a runtime error, with stack trace, to the FlightGear log stream
603 void FGNasalSys::logError(naContext context)
605 SG_LOG(SG_NASAL, SG_ALERT,
606 "Nasal runtime error: " << naGetError(context));
607 SG_LOG(SG_NASAL, SG_ALERT,
608 " at " << naStr_data(naGetSourceFile(context, 0)) <<
609 ", line " << naGetLine(context, 0));
610 for(int i=1; i<naStackDepth(context); i++)
611 SG_LOG(SG_NASAL, SG_ALERT,
612 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
613 ", line " << naGetLine(context, i));
616 // Reads a script file, executes it, and places the resulting
617 // namespace into the global namespace under the specified module
619 void FGNasalSys::loadModule(SGPath file, const char* module)
622 char* buf = readfile(file.c_str(), &len);
624 SG_LOG(SG_NASAL, SG_ALERT,
625 "Nasal error: could not read script file " << file.c_str()
626 << " into module " << module);
630 createModule(module, file.c_str(), buf, len);
634 // Parse and run. Save the local variables namespace, as it will
635 // become a sub-object of globals. The optional "arg" argument can be
636 // used to pass an associated property node to the module, which can then
637 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
638 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
639 const char* src, int len, const SGPropertyNode* arg)
641 naRef code = parse(fileName, src, len);
645 // See if we already have a module hash to use. This allows the
646 // user to, for example, add functions to the built-in math
647 // module. Make a new one if necessary.
649 naRef modname = naNewString(_context);
650 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
651 if(!naHash_get(_globals, modname, &locals))
652 locals = naNewHash(_context);
654 _cmdArg = (SGPropertyNode*)arg;
657 hashset(_globals, moduleName, locals);
660 void FGNasalSys::deleteModule(const char* moduleName)
662 naRef modname = naNewString(_context);
663 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
664 naHash_delete(_globals, modname);
667 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
670 naRef srcfile = naNewString(_context);
671 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
672 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
674 SG_LOG(SG_NASAL, SG_ALERT,
675 "Nasal parse error: " << naGetError(_context) <<
676 " in "<< filename <<", line " << errLine);
680 // Bind to the global namespace before returning
681 return naBindFunction(_context, code, _globals);
684 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
686 const char* nasal = arg->getStringValue("script");
687 const char* moduleName = arg->getStringValue("module");
688 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
689 if(naIsNil(code)) return false;
691 // Commands can be run "in" a module. Make sure that module
692 // exists, and set it up as the local variables hash for the
694 naRef locals = naNil();
696 naRef modname = naNewString(_context);
697 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
698 if(!naHash_get(_globals, modname, &locals)) {
699 locals = naNewHash(_context);
700 naHash_set(_globals, modname, locals);
704 // Cache this command's argument for inspection via cmdarg(). For
705 // performance reasons, we won't bother with it if the invoked
706 // code doesn't need it.
707 _cmdArg = (SGPropertyNode*)arg;
713 // settimer(func, dt, simtime) extension function. The first argument
714 // is a Nasal function to call, the second is a delta time (from now),
715 // in seconds. The third, if present, is a boolean value indicating
716 // that "real world" time (rather than simulator time) is to be used.
718 // Implementation note: the FGTimer objects don't live inside the
719 // garbage collector, so the Nasal handler functions have to be
720 // "saved" somehow lest they be inadvertently cleaned. In this case,
721 // they are inserted into a globals.__gcsave hash and removed on
723 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
725 // Extract the handler, delta, and simtime arguments:
726 naRef handler = argc > 0 ? args[0] : naNil();
727 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
728 naRuntimeError(c, "settimer() with invalid function argument");
732 naRef delta = argc > 1 ? args[1] : naNil();
734 naRuntimeError(c, "settimer() with invalid time argument");
738 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
740 // Generate and register a C++ timer handler
741 NasalTimer* t = new NasalTimer;
742 t->handler = handler;
743 t->gcKey = gcSave(handler);
746 globals->get_event_mgr()->addEvent("NasalTimer",
747 t, &NasalTimer::timerExpired,
751 void FGNasalSys::handleTimer(NasalTimer* t)
753 call(t->handler, naNil());
757 int FGNasalSys::gcSave(naRef r)
759 int key = _nextGCKey++;
760 naHash_set(_gcHash, naNum(key), r);
764 void FGNasalSys::gcRelease(int key)
766 naHash_delete(_gcHash, naNum(key));
769 void FGNasalSys::NasalTimer::timerExpired()
771 nasal->handleTimer(this);
775 int FGNasalSys::_listenerId = 0;
777 // setlistener(property, func, bool) extension function. The first argument
778 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
779 // path), the second is a Nasal function, the optional third one a bool.
780 // If the bool is true, then the listener is executed initially. The
781 // setlistener() function returns a unique id number, that can be used
782 // as argument to the removelistener() function.
783 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
785 SGPropertyNode_ptr node;
786 naRef prop = argc > 0 ? args[0] : naNil();
787 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
788 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
790 naRuntimeError(c, "setlistener() with invalid property argument");
795 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
798 naRef handler = argc > 1 ? args[1] : naNil();
799 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
800 naRuntimeError(c, "setlistener() with invalid function argument");
804 bool initial = argc > 2 && naTrue(args[2]);
806 FGNasalListener *nl = new FGNasalListener(node, handler, this,
807 gcSave(handler), _listenerId);
808 node->addChangeListener(nl, initial);
810 _listener[_listenerId] = nl;
811 return naNum(_listenerId++);
814 // removelistener(int) extension function. The argument is the id of
815 // a listener as returned by the setlistener() function.
816 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
818 naRef id = argc > 0 ? args[0] : naNil();
819 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
821 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
822 naRuntimeError(c, "removelistener() with invalid listener id");
826 FGNasalListener *nl = it->second;
829 _purgeListeners = true;
835 return naNum(_listener.size());
840 // FGNasalListener class.
842 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
843 FGNasalSys* nasal, int key, int id) :
854 FGNasalListener::~FGNasalListener()
856 _node->removeChangeListener(this);
857 _nas->gcRelease(_gcKey);
860 void FGNasalListener::valueChanged(SGPropertyNode* node)
862 // drop recursive listener calls
866 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
868 _nas->_cmdArg = node;
869 _nas->call(_handler, naNil());
876 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
877 // such a class, then it lets modelLoaded() run the <load> script, and the
878 // destructor the <unload> script. The latter happens when the model branch
879 // is removed from the scene graph.
881 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
884 SGPropertyNode *n = prop->getNode("nasal"), *load;
888 load = n->getNode("load");
889 _unload = n->getNode("unload");
890 if(!load && !_unload)
894 const char *s = load ? load->getStringValue() : "";
895 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
898 FGNasalModelData::~FGNasalModelData()
904 SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
905 "without Nasal subsystem present.");
910 const char *s = _unload->getStringValue();
911 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
913 nasalSys->deleteModule(_module.c_str());