]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
c486ce90ceef9cf55041011757bac05f6efa699e
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <string.h>
7 #include <stdio.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10
11 #include <plib/ul.h>
12
13 #include <simgear/nasal/nasal.h>
14 #include <simgear/props/props.hxx>
15 #include <simgear/math/sg_random.h>
16 #include <simgear/misc/sg_path.hxx>
17 #include <simgear/misc/interpolator.hxx>
18 #include <simgear/structure/commands.hxx>
19
20 #include <Main/globals.hxx>
21 #include <Main/fg_props.hxx>
22
23 #include "NasalSys.hxx"
24
25 // Read and return file contents in a single buffer.  Note use of
26 // stat() to get the file size.  This is a win32 function, believe it
27 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
28 // Text mode brain damage will kill us if we're trying to do bytewise
29 // I/O.
30 static char* readfile(const char* file, int* lenOut)
31 {
32     struct stat data;
33     if(stat(file, &data) != 0) return 0;
34     FILE* f = fopen(file, "rb");
35     if(!f) return 0;
36     char* buf = new char[data.st_size];
37     *lenOut = fread(buf, 1, data.st_size, f);
38     fclose(f);
39     if(*lenOut != data.st_size) {
40         // Shouldn't happen, but warn anyway since it represents a
41         // platform bug and not a typical runtime error (missing file,
42         // etc...)
43         SG_LOG(SG_NASAL, SG_ALERT,
44                "ERROR in Nasal initialization: " <<
45                "short count returned from fread() of " << file <<
46                ".  Check your C library!");
47         delete[] buf;
48         return 0;
49     }
50     return buf;
51 }
52
53 FGNasalSys::FGNasalSys()
54 {
55     _context = 0;
56     _globals = naNil();
57     _gcHash = naNil();
58     _nextGCKey = 0; // Any value will do
59     _callCount = 0;
60 }
61
62 // Does a naCall() in a new context.  Wrapped here to make lock
63 // tracking easier.  Extension functions are called with the lock, but
64 // we have to release it before making a new naCall().  So rather than
65 // drop the lock in every extension function that might call back into
66 // Nasal, we keep a stack depth counter here and only unlock/lock
67 // around the naCall if it isn't the first one.
68 naRef FGNasalSys::call(naRef code, naRef locals)
69 {
70     naContext ctx = naNewContext();
71     if(_callCount) naModUnlock();
72     _callCount++;
73     naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
74     if(naGetError(ctx))
75         logError(ctx);
76     _callCount--;
77     if(_callCount) naModLock();
78     naFreeContext(ctx);
79     return result;
80 }
81
82 FGNasalSys::~FGNasalSys()
83 {
84     map<int, FGNasalListener *>::iterator it, end = _listener.end();
85     for (it = _listener.begin(); it != end; ++it)
86         delete it->second;
87
88     // Nasal doesn't have a "destroy context" API yet. :(
89     // Not a problem for a global subsystem that will never be
90     // destroyed.  And the context is actually a global, so no memory
91     // is technically leaked (although the GC pool memory obviously
92     // won't be freed).
93     _context = 0;
94     _globals = naNil();
95 }
96
97 bool FGNasalSys::parseAndRun(const char* sourceCode)
98 {
99     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
100                        strlen(sourceCode));
101     if(naIsNil(code))
102         return false;
103     call(code, naNil());
104     return true;
105 }
106
107 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
108 {
109     FGNasalScript* script = new FGNasalScript();
110     script->_gcKey = -1; // important, if we delete it on a parse
111     script->_nas = this; // error, don't clobber a real handle!
112
113     char buf[256];
114     if(!name) {
115         sprintf(buf, "FGNasalScript@%p", script);
116         name = buf;
117     }
118
119     script->_code = parse(name, src, strlen(src));
120     if(naIsNil(script->_code)) {
121         delete script;
122         return 0;
123     }
124
125     script->_gcKey = gcSave(script->_code);
126     return script;
127 }
128
129 // Utility.  Sets a named key in a hash by C string, rather than nasal
130 // string object.
131 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
132 {
133     naRef s = naNewString(_context);
134     naStr_fromdata(s, (char*)key, strlen(key));
135     naHash_set(hash, s, val);
136 }
137
138 // The get/setprop functions accept a *list* of strings and walk
139 // through the property tree with them to find the appropriate node.
140 // This allows a Nasal object to hold onto a property path and use it
141 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
142 // is the utility function that walks the property tree.
143 // Future enhancement: support integer arguments to specify array
144 // elements.
145 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
146 {
147     SGPropertyNode* p = globals->get_props();
148     try {
149         for(int i=0; i<len; i++) {
150             naRef a = vec[i];
151             if(!naIsString(a)) return 0;
152             p = p->getNode(naStr_data(a));
153             if(p == 0) return 0;
154         }
155     } catch (const string& err) {
156         naRuntimeError(c, (char *)err.c_str());
157         return 0;
158     }
159     return p;
160 }
161
162 // getprop() extension function.  Concatenates its string arguments as
163 // property names and returns the value of the specified property.  Or
164 // nil if it doesn't exist.
165 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
166 {
167     const SGPropertyNode* p = findnode(c, args, argc);
168     if(!p) return naNil();
169
170     switch(p->getType()) {
171     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
172     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
173     case SGPropertyNode::DOUBLE:
174         return naNum(p->getDoubleValue());
175
176     case SGPropertyNode::STRING:
177     case SGPropertyNode::UNSPECIFIED:
178         {
179             naRef nastr = naNewString(c);
180             const char* val = p->getStringValue();
181             naStr_fromdata(nastr, (char*)val, strlen(val));
182             return nastr;
183         }
184     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
185     default:
186         return naNil();
187     }
188 }
189
190 // setprop() extension function.  Concatenates its string arguments as
191 // property names and sets the value of the specified property to the
192 // final argument.
193 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
194 {
195 #define BUFLEN 1024
196     char buf[BUFLEN + 1];
197     buf[BUFLEN] = 0;
198     char* p = buf;
199     int buflen = BUFLEN;
200     for(int i=0; i<argc-1; i++) {
201         naRef s = naStringValue(c, args[i]);
202         if(naIsNil(s)) return naNil();
203         strncpy(p, naStr_data(s), buflen);
204         p += naStr_len(s);
205         buflen = BUFLEN - (p - buf);
206         if(i < (argc-2) && buflen > 0) {
207             *p++ = '/';
208             buflen--;
209         }
210     }
211
212     SGPropertyNode* props = globals->get_props();
213     naRef val = args[argc-1];
214     try {
215         if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
216         else {
217             naRef n = naNumValue(val);
218             if(naIsNil(n))
219                 naRuntimeError(c, "setprop() value is not string or number");
220             props->setDoubleValue(buf, n.num);
221         }
222     } catch (const string& err) {
223         naRuntimeError(c, (char *)err.c_str());
224     }
225     return naNil();
226 #undef BUFLEN
227 }
228
229 // print() extension function.  Concatenates and prints its arguments
230 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
231 // make sure it appears.  Is there better way to do this?
232 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
233 {
234 #define BUFLEN 1024
235     char buf[BUFLEN + 1];
236     buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
237     buf[0] = 0; // Zero-length in case there are no arguments
238     char* p = buf;
239     int buflen = BUFLEN;
240     int n = argc;
241     for(int i=0; i<n; i++) {
242         naRef s = naStringValue(c, args[i]);
243         if(naIsNil(s)) continue;
244         strncpy(p, naStr_data(s), buflen);
245         p += naStr_len(s);
246         buflen = BUFLEN - (p - buf);
247         if(buflen <= 0) break;
248     }
249     SG_LOG(SG_GENERAL, SG_ALERT, buf);
250     return naNil();
251 #undef BUFLEN
252 }
253
254 // fgcommand() extension function.  Executes a named command via the
255 // FlightGear command manager.  Takes a single property node name as
256 // an argument.
257 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
258 {
259     if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
260         naRuntimeError(c, "bad arguments to fgcommand()");
261     naRef cmd = args[0], props = args[1];
262     SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
263     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
264 }
265
266 // settimer(func, dt, simtime) extension function.  Falls through to
267 // FGNasalSys::setTimer().  See there for docs.
268 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
269 {
270     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
271     nasal->setTimer(argc, args);
272     return naNil();
273 }
274
275 // setlistener(func, property, bool) extension function.  Falls through to
276 // FGNasalSys::setListener().  See there for docs.
277 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
278 {
279     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
280     return nasal->setListener(argc, args);
281 }
282
283 // removelistener(int) extension function. Falls through to
284 // FGNasalSys::removeListener(). See there for docs.
285 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
286 {
287     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
288     return nasal->removeListener(c, argc, args);
289 }
290
291 // Returns a ghost handle to the argument to the currently executing
292 // command
293 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
294 {
295     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
296     return nasal->cmdArgGhost();
297 }
298
299 // Sets up a property interpolation.  The first argument is either a
300 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
301 // interpolate.  The second argument is a vector of pairs of
302 // value/delta numbers.
303 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
304 {
305     SGPropertyNode* node;
306     naRef prop = argc > 0 ? args[0] : naNil();
307     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
308     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
309     else return naNil();
310
311     naRef curve = argc > 1 ? args[1] : naNil();
312     if(!naIsVector(curve)) return naNil();
313     int nPoints = naVec_size(curve) / 2;
314     double* values = new double[nPoints];
315     double* deltas = new double[nPoints];
316     for(int i=0; i<nPoints; i++) {
317         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
318         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
319     }
320
321     ((SGInterpolator*)globals->get_subsystem("interpolator"))
322         ->interpolate(node, nPoints, values, deltas);
323
324     return naNil();
325 }
326
327 // This is a better RNG than the one in the default Nasal distribution
328 // (which is based on the C library rand() implementation). It will
329 // override.
330 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
331 {
332     return naNum(sg_random());
333 }
334
335 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
336 {
337     sg_srandom_time();
338     return naNum(0);
339 }
340
341 // Return an array listing of all files in a directory
342 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
343 {
344     if(argc != 1 || !naIsString(args[0]))
345         naRuntimeError(c, "bad arguments to directory()");
346     naRef ldir = args[0];
347     ulDir* dir = ulOpenDir(naStr_data(args[0]));
348     if(!dir) return naNil();
349     naRef result = naNewVector(c);
350     ulDirEnt* dent;
351     while((dent = ulReadDir(dir)))
352         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
353                                             strlen(dent->d_name)));
354     ulCloseDir(dir);
355     return result;
356 }
357
358 // Table of extension functions.  Terminate with zeros.
359 static struct { char* name; naCFunction func; } funcs[] = {
360     { "getprop",   f_getprop },
361     { "setprop",   f_setprop },
362     { "print",     f_print },
363     { "_fgcommand", f_fgcommand },
364     { "settimer",  f_settimer },
365     { "_setlistener", f_setlistener },
366     { "removelistener", f_removelistener },
367     { "_cmdarg",  f_cmdarg },
368     { "_interpolate",  f_interpolate },
369     { "rand",  f_rand },
370     { "srand",  f_srand },
371     { "directory", f_directory },
372     { 0, 0 }
373 };
374
375 naRef FGNasalSys::cmdArgGhost()
376 {
377     return propNodeGhost(_cmdArg);
378 }
379
380 void FGNasalSys::init()
381 {
382     int i;
383
384     _context = naNewContext();
385
386     // Start with globals.  Add it to itself as a recursive
387     // sub-reference under the name "globals".  This gives client-code
388     // write access to the namespace if someone wants to do something
389     // fancy.
390     _globals = naStdLib(_context);
391     naSave(_context, _globals);
392     hashset(_globals, "globals", _globals);
393
394     // Add in the math library under "math"
395     hashset(_globals, "math", naMathLib(_context));
396
397     // Add in the IO library.  Disabled currently until after the
398     // 0.9.10 release.
399     // hashset(_globals, "io", naIOLib(_context));
400     // hashset(_globals, "bits", naBitsLib(_context));
401
402     // Add our custom extension functions:
403     for(i=0; funcs[i].name; i++)
404         hashset(_globals, funcs[i].name,
405                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
406
407     // And our SGPropertyNode wrapper
408     hashset(_globals, "props", genPropsModule());
409
410     // Make a "__gcsave" hash to hold the naRef objects which get
411     // passed to handles outside the interpreter (to protect them from
412     // begin garbage-collected).
413     _gcHash = naNewHash(_context);
414     hashset(_globals, "__gcsave", _gcHash);
415
416     // Now load the various source files in the Nasal directory
417     SGPath p(globals->get_fg_root());
418     p.append("Nasal");
419     ulDirEnt* dent;
420     ulDir* dir = ulOpenDir(p.c_str());
421     while(dir && (dent = ulReadDir(dir)) != 0) {
422         SGPath fullpath(p);
423         fullpath.append(dent->d_name);
424         SGPath file(dent->d_name);
425         if(file.extension() != "nas") continue;
426         loadModule(fullpath, file.base().c_str());
427     }
428     ulCloseDir(dir);
429     fgSetBool("/sim/signals/nasal-dir-initialized", true);
430
431     // Pull scripts out of the property tree, too
432     loadPropertyScripts();
433 }
434
435 // Loads the scripts found under /nasal in the global tree
436 void FGNasalSys::loadPropertyScripts()
437 {
438     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
439     if(!nasal) return;
440
441     for(int i=0; i<nasal->nChildren(); i++) {
442         SGPropertyNode* n = nasal->getChild(i);
443
444         const char* module = n->getName();
445         if(n->hasChild("module"))
446             module = n->getStringValue("module");
447
448         // allow multiple files to be specified within in a single
449         // Nasal module tag
450         int j = 0;
451         SGPropertyNode *fn;
452         bool file_specified = false;
453         while ( (fn = n->getChild("file", j)) != NULL ) {
454             file_specified = true;
455             const char* file = fn->getStringValue();
456             SGPath p(globals->get_fg_root());
457             p.append(file);
458             loadModule(p, module);
459             j++;
460         }
461
462         // Old code which only allowed a single file to be specified per module
463         /*
464         const char* file = n->getStringValue("file");
465         if(!n->hasChild("file")) file = 0; // Hrm...
466         if(file) {
467             SGPath p(globals->get_fg_root());
468             p.append(file);
469             loadModule(p, module);
470         }
471         */
472         
473         const char* src = n->getStringValue("script");
474         if(!n->hasChild("script")) src = 0; // Hrm...
475         if(src)
476             createModule(module, n->getPath(), src, strlen(src));
477
478         if(!file_specified && !src)
479             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
480                    "no <file> or <script> defined in " <<
481                    "/nasal/" << module);
482     }
483 }
484
485 // Logs a runtime error, with stack trace, to the FlightGear log stream
486 void FGNasalSys::logError(naContext context)
487 {
488     SG_LOG(SG_NASAL, SG_ALERT,
489            "Nasal runtime error: " << naGetError(context));
490     SG_LOG(SG_NASAL, SG_ALERT,
491            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
492            ", line " << naGetLine(context, 0));
493     for(int i=1; i<naStackDepth(context); i++)
494         SG_LOG(SG_NASAL, SG_ALERT,
495                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
496                ", line " << naGetLine(context, i));
497 }
498
499 // Reads a script file, executes it, and places the resulting
500 // namespace into the global namespace under the specified module
501 // name.
502 void FGNasalSys::loadModule(SGPath file, const char* module)
503 {
504     int len = 0;
505     char* buf = readfile(file.c_str(), &len);
506     if(!buf) {
507         SG_LOG(SG_NASAL, SG_ALERT,
508                "Nasal error: could not read script file " << file.c_str()
509                << " into module " << module);
510         return;
511     }
512
513     createModule(module, file.c_str(), buf, len);
514     delete[] buf;
515 }
516
517 // Parse and run.  Save the local variables namespace, as it will
518 // become a sub-object of globals.  The optional "arg" argument can be
519 // used to pass an associated property node to the module, which can then
520 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
521 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
522                               const char* src, int len, const SGPropertyNode* arg)
523 {
524     naRef code = parse(fileName, src, len);
525     if(naIsNil(code))
526         return;
527
528     // See if we already have a module hash to use.  This allows the
529     // user to, for example, add functions to the built-in math
530     // module.  Make a new one if necessary.
531     naRef locals;
532     naRef modname = naNewString(_context);
533     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
534     if(!naHash_get(_globals, modname, &locals))
535         locals = naNewHash(_context);
536
537     _cmdArg = (SGPropertyNode*)arg;
538
539     call(code, locals);
540     hashset(_globals, moduleName, locals);
541 }
542
543 void FGNasalSys::deleteModule(const char* moduleName)
544 {
545     naRef modname = naNewString(_context);
546     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
547     naHash_delete(_globals, modname);
548 }
549
550 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
551 {
552     int errLine = -1;
553     naRef srcfile = naNewString(_context);
554     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
555     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
556     if(naIsNil(code)) {
557         SG_LOG(SG_NASAL, SG_ALERT,
558                "Nasal parse error: " << naGetError(_context) <<
559                " in "<< filename <<", line " << errLine);
560         return naNil();
561     }
562
563     // Bind to the global namespace before returning
564     return naBindFunction(_context, code, _globals);
565 }
566
567 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
568 {
569     const char* nasal = arg->getStringValue("script");
570     const char* moduleName = arg->getStringValue("module");
571     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
572     if(naIsNil(code)) return false;
573
574     naContext c = naNewContext();
575     naRef locals = naNil();
576     if(moduleName[0]) {
577         naRef modname = naNewString(c);
578         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
579         if(!naHash_get(_globals, modname, &locals))
580             locals = naNewHash(c);
581     }
582     // Cache the command argument for inspection via cmdarg().  For
583     // performance reasons, we won't bother with it if the invoked
584     // code doesn't need it.
585     _cmdArg = (SGPropertyNode*)arg;
586
587     // Call it!
588     call(code, locals);
589     return true;
590 }
591
592 // settimer(func, dt, simtime) extension function.  The first argument
593 // is a Nasal function to call, the second is a delta time (from now),
594 // in seconds.  The third, if present, is a boolean value indicating
595 // that "real world" time (rather than simulator time) is to be used.
596 //
597 // Implementation note: the FGTimer objects don't live inside the
598 // garbage collector, so the Nasal handler functions have to be
599 // "saved" somehow lest they be inadvertently cleaned.  In this case,
600 // they are inserted into a globals.__gcsave hash and removed on
601 // expiration.
602 void FGNasalSys::setTimer(int argc, naRef* args)
603 {
604     // Extract the handler, delta, and simtime arguments:
605     naRef handler = argc > 0 ? args[0] : naNil();
606     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
607         return;
608
609     naRef delta = argc > 1 ? args[1] : naNil();
610     if(naIsNil(delta)) return;
611
612     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
613
614     // Generate and register a C++ timer handler
615     NasalTimer* t = new NasalTimer;
616     t->handler = handler;
617     t->gcKey = gcSave(handler);
618     t->nasal = this;
619
620     globals->get_event_mgr()->addEvent("NasalTimer",
621                                        t, &NasalTimer::timerExpired,
622                                        delta.num, simtime);
623 }
624
625 void FGNasalSys::handleTimer(NasalTimer* t)
626 {
627     call(t->handler, naNil());
628     gcRelease(t->gcKey);
629 }
630
631 int FGNasalSys::gcSave(naRef r)
632 {
633     int key = _nextGCKey++;
634     naHash_set(_gcHash, naNum(key), r);
635     return key;
636 }
637
638 void FGNasalSys::gcRelease(int key)
639 {
640     naHash_delete(_gcHash, naNum(key));
641 }
642
643 void FGNasalSys::NasalTimer::timerExpired()
644 {
645     nasal->handleTimer(this);
646     delete this;
647 }
648
649 int FGNasalSys::_listenerId = 0;
650
651 // setlistener(property, func, bool) extension function.  The first argument
652 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
653 // path), the second is a Nasal function, the optional third one a bool.
654 // If the bool is true, then the listener is executed initially. The
655 // setlistener() function returns a unique id number, that can be used
656 // as argument to the removelistener() function.
657 naRef FGNasalSys::setListener(int argc, naRef* args)
658 {
659     SGPropertyNode_ptr node;
660     naRef prop = argc > 0 ? args[0] : naNil();
661     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
662     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
663     else return naNil();
664
665     if (node->isTied())
666         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
667                 node->getPath());
668
669     naRef handler = argc > 1 ? args[1] : naNil();
670     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
671         return naNil();
672
673     bool initial = argc > 2 && naTrue(args[2]);
674
675     FGNasalListener *nl = new FGNasalListener(node, handler, this,
676             gcSave(handler));
677     node->addChangeListener(nl, initial);
678
679     _listener[_listenerId] = nl;
680     return naNum(_listenerId++);
681 }
682
683 // removelistener(int) extension function. The argument is the id of
684 // a listener as returned by the setlistener() function.
685 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
686 {
687     naRef id = argc > 0 ? args[0] : naNil();
688     int i = int(id.num);
689
690     if(!naIsNum(id) || _listener.find(i) == _listener.end()) {
691         naRuntimeError(c, "removelistener() with invalid listener id");
692         return naNil();
693     }
694
695     FGNasalListener *nl = _listener[i];
696     if(nl->_active) {
697         naRuntimeError(c, "trying to remove active listener");
698         return naNil();
699     }
700
701     _listener.erase(i);
702     delete nl;
703     return naNum(_listener.size());
704 }
705
706
707
708 // FGNasalListener class.
709
710 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
711                                  FGNasalSys* nasal, int key) :
712     _node(node),
713     _handler(handler),
714     _gcKey(key),
715     _nas(nasal),
716     _active(0)
717 {
718 }
719
720 FGNasalListener::~FGNasalListener()
721 {
722     _node->removeChangeListener(this);
723     _nas->gcRelease(_gcKey);
724 }
725
726 void FGNasalListener::valueChanged(SGPropertyNode* node)
727 {
728     // drop recursive listener calls
729     if (_active)
730         return;
731
732     _active++;
733     _nas->_cmdArg = node;
734     _nas->call(_handler, naNil());
735     _active--;
736 }
737
738
739
740
741 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
742 // such a class, then it lets modelLoaded() run the <load> script, and the
743 // destructor the <unload> script. The latter happens when the model branch
744 // is removed from the scene graph.
745
746 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
747                                    osg::Node *)
748 {
749     SGPropertyNode *n = prop->getNode("nasal"), *load;
750     if (!n)
751         return;
752
753     load = n->getNode("load");
754     _unload = n->getNode("unload");
755     if (!load && !_unload)
756         return;
757
758     _module = path;
759     const char *s = load ? load->getStringValue() : "";
760     FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
761     nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
762 }
763
764 FGNasalModelData::~FGNasalModelData()
765 {
766     if (_module.empty())
767         return;
768
769     FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
770     if (!nas) {
771         SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
772                 "without Nasal subsystem present.");
773         return;
774     }
775
776     if (_unload) {
777         const char *s = _unload->getStringValue();
778         nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
779     }
780     nas->deleteModule(_module.c_str());
781 }
782
783