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