]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Merge branch 'timoore/optimization' into next
[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 #include <fstream>
15 #include <sstream>
16 #include <algorithm> // for std::sort
17
18 #include <simgear/nasal/nasal.h>
19 #include <simgear/props/props.hxx>
20 #include <simgear/math/sg_random.h>
21 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/misc/sg_dir.hxx>
23 #include <simgear/misc/interpolator.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/structure/event_mgr.hxx>
27
28 #include "NasalSys.hxx"
29 #include "NasalPositioned.hxx"
30 #include "NasalCanvas.hxx"
31
32 #include <Main/globals.hxx>
33 #include <Main/util.hxx>
34 #include <Main/fg_props.hxx>
35
36 using std::map;
37
38 static FGNasalSys* nasalSys = 0;
39
40 // Listener class for loading Nasal modules on demand
41 class FGNasalModuleListener : public SGPropertyChangeListener
42 {
43 public:
44     FGNasalModuleListener(SGPropertyNode* node);
45
46     virtual void valueChanged(SGPropertyNode* node);
47
48 private:
49     SGPropertyNode_ptr _node;
50 };
51
52 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
53 {
54 }
55
56 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
57 {
58     if (_node->getBoolValue("enabled",false)&&
59         !_node->getBoolValue("loaded",true))
60     {
61         nasalSys->loadPropertyScripts(_node);
62     }
63 }
64
65
66 // Read and return file contents in a single buffer.  Note use of
67 // stat() to get the file size.  This is a win32 function, believe it
68 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
69 // Text mode brain damage will kill us if we're trying to do bytewise
70 // I/O.
71 static char* readfile(const char* file, int* lenOut)
72 {
73     struct stat data;
74     if(stat(file, &data) != 0) return 0;
75     FILE* f = fopen(file, "rb");
76     if(!f) return 0;
77     char* buf = new char[data.st_size];
78     *lenOut = fread(buf, 1, data.st_size, f);
79     fclose(f);
80     if(*lenOut != data.st_size) {
81         // Shouldn't happen, but warn anyway since it represents a
82         // platform bug and not a typical runtime error (missing file,
83         // etc...)
84         SG_LOG(SG_NASAL, SG_ALERT,
85                "ERROR in Nasal initialization: " <<
86                "short count returned from fread() of " << file <<
87                ".  Check your C library!");
88         delete[] buf;
89         return 0;
90     }
91     return buf;
92 }
93
94 FGNasalSys::FGNasalSys()
95 {
96     nasalSys = this;
97     _context = 0;
98     _globals = naNil();
99     _gcHash = naNil();
100     _nextGCKey = 0; // Any value will do
101     _callCount = 0;
102 }
103
104 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
105 {
106   return callMethod(code, naNil(), argc, args, locals);
107 }
108
109 // Does a naCall() in a new context.  Wrapped here to make lock
110 // tracking easier.  Extension functions are called with the lock, but
111 // we have to release it before making a new naCall().  So rather than
112 // drop the lock in every extension function that might call back into
113 // Nasal, we keep a stack depth counter here and only unlock/lock
114 // around the naCall if it isn't the first one.
115
116 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
117 {
118     naContext ctx = naNewContext();
119     if(_callCount) naModUnlock();
120     _callCount++;
121     naRef result = naCall(ctx, code, argc, args, self, locals);
122     if(naGetError(ctx))
123         logError(ctx);
124     _callCount--;
125     if(_callCount) naModLock();
126     naFreeContext(ctx);
127     return result;
128 }
129
130 FGNasalSys::~FGNasalSys()
131 {
132     nasalSys = 0;
133     map<int, FGNasalListener *>::iterator it, end = _listener.end();
134     for(it = _listener.begin(); it != end; ++it)
135         delete it->second;
136
137     naFreeContext(_context);
138     _globals = naNil();
139 }
140
141 bool FGNasalSys::parseAndRun(const char* sourceCode)
142 {
143     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
144                        strlen(sourceCode));
145     if(naIsNil(code))
146         return false;
147     call(code, 0, 0, naNil());
148     return true;
149 }
150
151 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
152 {
153     FGNasalScript* script = new FGNasalScript();
154     script->_gcKey = -1; // important, if we delete it on a parse
155     script->_nas = this; // error, don't clobber a real handle!
156
157     char buf[256];
158     if(!name) {
159         sprintf(buf, "FGNasalScript@%p", (void *)script);
160         name = buf;
161     }
162
163     script->_code = parse(name, src, strlen(src));
164     if(naIsNil(script->_code)) {
165         delete script;
166         return 0;
167     }
168
169     script->_gcKey = gcSave(script->_code);
170     return script;
171 }
172
173 // Utility.  Sets a named key in a hash by C string, rather than nasal
174 // string object.
175 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
176 {
177     naRef s = naNewString(_context);
178     naStr_fromdata(s, (char*)key, strlen(key));
179     naHash_set(hash, s, val);
180 }
181
182 // The get/setprop functions accept a *list* of strings and walk
183 // through the property tree with them to find the appropriate node.
184 // This allows a Nasal object to hold onto a property path and use it
185 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
186 // is the utility function that walks the property tree.
187 // Future enhancement: support integer arguments to specify array
188 // elements.
189 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
190 {
191     SGPropertyNode* p = globals->get_props();
192     try {
193         for(int i=0; i<len; i++) {
194             naRef a = vec[i];
195             if(!naIsString(a)) return 0;
196             p = p->getNode(naStr_data(a));
197             if(p == 0) return 0;
198         }
199     } catch (const string& err) {
200         naRuntimeError(c, (char *)err.c_str());
201         return 0;
202     }
203     return p;
204 }
205
206 // getprop() extension function.  Concatenates its string arguments as
207 // property names and returns the value of the specified property.  Or
208 // nil if it doesn't exist.
209 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
210 {
211     using namespace simgear;
212     const SGPropertyNode* p = findnode(c, args, argc);
213     if(!p) return naNil();
214
215     switch(p->getType()) {
216     case props::BOOL:   case props::INT:
217     case props::LONG:   case props::FLOAT:
218     case props::DOUBLE:
219         {
220         double dv = p->getDoubleValue();
221         if (osg::isNaN(dv)) {
222           SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
223           return naNil();
224         }
225         
226         return naNum(dv);
227         }
228         
229     case props::STRING:
230     case props::UNSPECIFIED:
231         {
232             naRef nastr = naNewString(c);
233             const char* val = p->getStringValue();
234             naStr_fromdata(nastr, (char*)val, strlen(val));
235             return nastr;
236         }
237     case props::ALIAS: // <--- FIXME, recurse?
238     default:
239         return naNil();
240     }
241 }
242
243 // setprop() extension function.  Concatenates its string arguments as
244 // property names and sets the value of the specified property to the
245 // final argument.
246 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
247 {
248 #define BUFLEN 1024
249     char buf[BUFLEN + 1];
250     buf[BUFLEN] = 0;
251     char* p = buf;
252     int buflen = BUFLEN;
253     if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
254     for(int i=0; i<argc-1; i++) {
255         naRef s = naStringValue(c, args[i]);
256         if(naIsNil(s)) return naNil();
257         strncpy(p, naStr_data(s), buflen);
258         p += naStr_len(s);
259         buflen = BUFLEN - (p - buf);
260         if(i < (argc-2) && buflen > 0) {
261             *p++ = '/';
262             buflen--;
263         }
264     }
265
266     SGPropertyNode* props = globals->get_props();
267     naRef val = args[argc-1];
268     bool result = false;
269     try {
270         if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
271         else {
272             naRef n = naNumValue(val);
273             if(naIsNil(n))
274                 naRuntimeError(c, "setprop() value is not string or number");
275                 
276             if (osg::isNaN(n.num)) {
277                 naRuntimeError(c, "setprop() passed a NaN");
278             }
279             
280             result = props->setDoubleValue(buf, n.num);
281         }
282     } catch (const string& err) {
283         naRuntimeError(c, (char *)err.c_str());
284     }
285     return naNum(result);
286 #undef BUFLEN
287 }
288
289 // print() extension function.  Concatenates and prints its arguments
290 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
291 // make sure it appears.  Is there better way to do this?
292 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
293 {
294     string buf;
295     int n = argc;
296     for(int i=0; i<n; i++) {
297         naRef s = naStringValue(c, args[i]);
298         if(naIsNil(s)) continue;
299         buf += naStr_data(s);
300     }
301     SG_LOG(SG_NASAL, SG_ALERT, buf);
302     return naNum(buf.length());
303 }
304
305 // fgcommand() extension function.  Executes a named command via the
306 // FlightGear command manager.  Takes a single property node name as
307 // an argument.
308 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
309 {
310     naRef cmd = argc > 0 ? args[0] : naNil();
311     naRef props = argc > 1 ? args[1] : naNil();
312     if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
313         naRuntimeError(c, "bad arguments to fgcommand()");
314     SGPropertyNode_ptr tmp, *node;
315     if(!naIsNil(props))
316         node = (SGPropertyNode_ptr*)naGhost_ptr(props);
317     else {
318         tmp = new SGPropertyNode();
319         node = &tmp;
320     }
321     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
322 }
323
324 // settimer(func, dt, simtime) extension function.  Falls through to
325 // FGNasalSys::setTimer().  See there for docs.
326 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
327 {
328     nasalSys->setTimer(c, argc, args);
329     return naNil();
330 }
331
332 // setlistener(func, property, bool) extension function.  Falls through to
333 // FGNasalSys::setListener().  See there for docs.
334 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
335 {
336     return nasalSys->setListener(c, argc, args);
337 }
338
339 // removelistener(int) extension function. Falls through to
340 // FGNasalSys::removeListener(). See there for docs.
341 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
342 {
343     return nasalSys->removeListener(c, argc, args);
344 }
345
346 // Returns a ghost handle to the argument to the currently executing
347 // command
348 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
349 {
350     return nasalSys->cmdArgGhost();
351 }
352
353 // Sets up a property interpolation.  The first argument is either a
354 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
355 // interpolate.  The second argument is a vector of pairs of
356 // value/delta numbers.
357 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
358 {
359     SGPropertyNode* node;
360     naRef prop = argc > 0 ? args[0] : naNil();
361     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
362     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
363     else return naNil();
364
365     naRef curve = argc > 1 ? args[1] : naNil();
366     if(!naIsVector(curve)) return naNil();
367     int nPoints = naVec_size(curve) / 2;
368     double* values = new double[nPoints];
369     double* deltas = new double[nPoints];
370     for(int i=0; i<nPoints; i++) {
371         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
372         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
373     }
374
375     ((SGInterpolator*)globals->get_subsystem_mgr()
376         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
377         ->interpolate(node, nPoints, values, deltas);
378
379     delete[] values;
380     delete[] deltas;
381     return naNil();
382 }
383
384 // This is a better RNG than the one in the default Nasal distribution
385 // (which is based on the C library rand() implementation). It will
386 // override.
387 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
388 {
389     return naNum(sg_random());
390 }
391
392 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
393 {
394     sg_srandom_time();
395     return naNum(0);
396 }
397
398 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
399 {
400     abort();
401     return naNil();
402 }
403
404 // Return an array listing of all files in a directory
405 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
406 {
407     if(argc != 1 || !naIsString(args[0]))
408         naRuntimeError(c, "bad arguments to directory()");
409     
410     simgear::Dir d(SGPath(naStr_data(args[0])));
411     if(!d.exists()) return naNil();
412     naRef result = naNewVector(c);
413
414     simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
415     for (unsigned int i=0; i<paths.size(); ++i) {
416       std::string p = paths[i].file();
417       naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
418     }
419     
420     return result;
421 }
422
423 /**
424  * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
425  */
426 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
427 {
428     if(argc != 1 || !naIsString(args[0]))
429         naRuntimeError(c, "bad arguments to resolveDataPath()");
430
431     SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
432     const char* pdata = p.c_str();
433     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
434 }
435
436 // Parse XML file.
437 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
438 //
439 // <path>      ... absolute path to an XML file
440 // <start-tag> ... callback function with two args: tag name, attribute hash
441 // <end-tag>   ... callback function with one arg:  tag name
442 // <data>      ... callback function with one arg:  data
443 // <pi>        ... callback function with two args: target, data
444 //                 (pi = "processing instruction")
445 // All four callback functions are optional and default to nil.
446 // The function returns nil on error, or the validated file name otherwise.
447 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
448 {
449     if(argc < 1 || !naIsString(args[0]))
450         naRuntimeError(c, "parsexml(): path argument missing or not a string");
451     if(argc > 5) argc = 5;
452     for(int i=1; i<argc; i++)
453         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
454             naRuntimeError(c, "parsexml(): callback argument not a function");
455
456     const char* file = fgValidatePath(naStr_data(args[0]), false);
457     if(!file) {
458         naRuntimeError(c, "parsexml(): reading '%s' denied "
459                 "(unauthorized access)", naStr_data(args[0]));
460         return naNil();
461     }
462     std::ifstream input(file);
463     NasalXMLVisitor visitor(c, argc, args);
464     try {
465         readXML(input, visitor);
466     } catch (const sg_exception& e) {
467         naRuntimeError(c, "parsexml(): file '%s' %s",
468                 file, e.getFormattedMessage().c_str());
469         return naNil();
470     }
471     return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
472 }
473
474 // Return UNIX epoch time in seconds.
475 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
476 {
477 #ifdef _WIN32
478     FILETIME ft;
479     GetSystemTimeAsFileTime(&ft);
480     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
481     // Converts from 100ns units in 1601 epoch to unix epoch in sec
482     return naNum((t * 1e-7) - 11644473600.0);
483 #else
484     struct timeval td;
485     gettimeofday(&td, 0);
486     return naNum(td.tv_sec + 1e-6 * td.tv_usec);
487 #endif
488 }
489
490 // Table of extension functions.  Terminate with zeros.
491 static struct { const char* name; naCFunction func; } funcs[] = {
492     { "getprop",   f_getprop },
493     { "setprop",   f_setprop },
494     { "print",     f_print },
495     { "_fgcommand", f_fgcommand },
496     { "settimer",  f_settimer },
497     { "_setlistener", f_setlistener },
498     { "removelistener", f_removelistener },
499     { "_cmdarg",  f_cmdarg },
500     { "_interpolate",  f_interpolate },
501     { "rand",  f_rand },
502     { "srand",  f_srand },
503     { "abort", f_abort },
504     { "directory", f_directory },
505     { "resolvepath", f_resolveDataPath },
506     { "parsexml", f_parsexml },
507     { "systime", f_systime },
508     { 0, 0 }
509 };
510
511 naRef FGNasalSys::cmdArgGhost()
512 {
513     return propNodeGhost(_cmdArg);
514 }
515
516 void FGNasalSys::init()
517 {
518     int i;
519
520     _context = naNewContext();
521
522     // Start with globals.  Add it to itself as a recursive
523     // sub-reference under the name "globals".  This gives client-code
524     // write access to the namespace if someone wants to do something
525     // fancy.
526     _globals = naInit_std(_context);
527     naSave(_context, _globals);
528     hashset(_globals, "globals", _globals);
529
530     hashset(_globals, "math", naInit_math(_context));
531     hashset(_globals, "bits", naInit_bits(_context));
532     hashset(_globals, "io", naInit_io(_context));
533     hashset(_globals, "thread", naInit_thread(_context));
534     hashset(_globals, "utf8", naInit_utf8(_context));
535
536     // Add our custom extension functions:
537     for(i=0; funcs[i].name; i++)
538         hashset(_globals, funcs[i].name,
539                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
540
541
542   
543     // And our SGPropertyNode wrapper
544     hashset(_globals, "props", genPropsModule());
545
546     // Make a "__gcsave" hash to hold the naRef objects which get
547     // passed to handles outside the interpreter (to protect them from
548     // begin garbage-collected).
549     _gcHash = naNewHash(_context);
550     hashset(_globals, "__gcsave", _gcHash);
551
552     initNasalPositioned(_globals, _context, _gcHash);
553     initNasalCanvas(_globals, _context, _gcHash);
554   
555     // Now load the various source files in the Nasal directory
556     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
557     loadScriptDirectory(nasalDir);
558
559     // Add modules in Nasal subdirectories to property tree
560     simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
561             simgear::Dir::NO_DOT_OR_DOTDOT, "");
562     for (unsigned int i=0; i<directories.size(); ++i) {
563         simgear::Dir dir(directories[i]);
564         simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
565         addModule(directories[i].file(), scripts);
566     }
567
568     // set signal and remove node to avoid restoring at reinit
569     const char *s = "nasal-dir-initialized";
570     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
571     signal->setBoolValue(s, true);
572     signal->removeChildren(s, false);
573
574     // Pull scripts out of the property tree, too
575     loadPropertyScripts();
576   
577     // now Nasal modules are loaded, we can do some delayed work
578     postinitNasalPositioned(_globals, _context);
579 }
580
581 void FGNasalSys::update(double)
582 {
583     if(!_dead_listener.empty()) {
584         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
585         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
586         _dead_listener.clear();
587     }
588
589     if (!_loadList.empty())
590     {
591         // process Nasal load hook (only one per update loop to avoid excessive lags)
592         _loadList.pop()->load();
593     }
594     else
595     if (!_unloadList.empty())
596     {
597         // process pending Nasal unload hooks after _all_ load hooks were processed
598         // (only unload one per update loop to avoid excessive lags)
599         _unloadList.pop()->unload();
600     }
601
602     // The global context is a legacy thing.  We use dynamically
603     // created contexts for naCall() now, so that we can call them
604     // recursively.  But there are still spots that want to use it for
605     // naNew*() calls, which end up leaking memory because the context
606     // only clears out its temporary vector when it's *used*.  So just
607     // junk it and fetch a new/reinitialized one every frame.  This is
608     // clumsy: the right solution would use the dynamic context in all
609     // cases and eliminate _context entirely.  But that's more work,
610     // and this works fine (yes, they say "New" and "Free", but
611     // they're very fast, just trust me). -Andy
612     naFreeContext(_context);
613     _context = naNewContext();
614 }
615
616 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
617 {
618   return p1.file() < p2.file();
619 }
620
621 // Loads all scripts in given directory 
622 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
623 {
624     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
625     // sort scripts, avoid loading sequence effects due to file system's
626     // random directory order
627     std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
628
629     for (unsigned int i=0; i<scripts.size(); ++i) {
630       SGPath fullpath(scripts[i]);
631       SGPath file = fullpath.file();
632       loadModule(fullpath, file.base().c_str());
633     }
634 }
635
636 // Create module with list of scripts
637 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
638 {
639     if (scripts.size()>0)
640     {
641         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
642         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
643         for (unsigned int i=0; i<scripts.size(); ++i) {
644             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
645             pFileNode->setStringValue(scripts[i].c_str());
646         }
647         if (!module_node->hasChild("enabled",0))
648         {
649             SGPropertyNode* node = module_node->getChild("enabled",0,true);
650             node->setBoolValue(true);
651             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
652         }
653     }
654 }
655
656 // Loads the scripts found under /nasal in the global tree
657 void FGNasalSys::loadPropertyScripts()
658 {
659     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
660     if(!nasal) return;
661
662     for(int i=0; i<nasal->nChildren(); i++)
663     {
664         SGPropertyNode* n = nasal->getChild(i);
665         loadPropertyScripts(n);
666     }
667 }
668
669 // Loads the scripts found under /nasal in the global tree
670 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
671 {
672     bool is_loaded = false;
673
674     const char* module = n->getName();
675     if(n->hasChild("module"))
676         module = n->getStringValue("module");
677     if (n->getBoolValue("enabled",true))
678     {
679         // allow multiple files to be specified within a single
680         // Nasal module tag
681         int j = 0;
682         SGPropertyNode *fn;
683         bool file_specified = false;
684         bool ok=true;
685         while((fn = n->getChild("file", j)) != NULL) {
686             file_specified = true;
687             const char* file = fn->getStringValue();
688             SGPath p(file);
689             if (!p.isAbsolute() || !p.exists())
690             {
691                 p = globals->resolve_maybe_aircraft_path(file);
692                 if (p.isNull())
693                 {
694                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
695                             file << "' for module '" << module << "'.");
696                 }
697             }
698             ok &= p.isNull() ? false : loadModule(p, module);
699             j++;
700         }
701
702         const char* src = n->getStringValue("script");
703         if(!n->hasChild("script")) src = 0; // Hrm...
704         if(src)
705             createModule(module, n->getPath().c_str(), src, strlen(src));
706
707         if(!file_specified && !src)
708         {
709             // module no longer exists - clear the archived "enable" flag
710             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
711             SGPropertyNode* node = n->getChild("enabled",0,false);
712             if (node)
713                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
714
715             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
716                     "no <file> or <script> defined in " <<
717                     "/nasal/" << module);
718         }
719         else
720             is_loaded = ok;
721     }
722     else
723     {
724         SGPropertyNode* enable = n->getChild("enabled");
725         if (enable)
726         {
727             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
728             enable->addChangeListener(listener, false);
729         }
730     }
731     SGPropertyNode* loaded = n->getChild("loaded",0,true);
732     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
733     loaded->setBoolValue(is_loaded);
734 }
735
736 // Logs a runtime error, with stack trace, to the FlightGear log stream
737 void FGNasalSys::logError(naContext context)
738 {
739     SG_LOG(SG_NASAL, SG_ALERT,
740            "Nasal runtime error: " << naGetError(context));
741     SG_LOG(SG_NASAL, SG_ALERT,
742            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
743            ", line " << naGetLine(context, 0));
744     for(int i=1; i<naStackDepth(context); i++)
745         SG_LOG(SG_NASAL, SG_ALERT,
746                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
747                ", line " << naGetLine(context, i));
748 }
749
750 // Reads a script file, executes it, and places the resulting
751 // namespace into the global namespace under the specified module
752 // name.
753 bool FGNasalSys::loadModule(SGPath file, const char* module)
754 {
755     int len = 0;
756     char* buf = readfile(file.c_str(), &len);
757     if(!buf) {
758         SG_LOG(SG_NASAL, SG_ALERT,
759                "Nasal error: could not read script file " << file.c_str()
760                << " into module " << module);
761         return false;
762     }
763
764     bool ok = createModule(module, file.c_str(), buf, len);
765     delete[] buf;
766     return ok;
767 }
768
769 // Parse and run.  Save the local variables namespace, as it will
770 // become a sub-object of globals.  The optional "arg" argument can be
771 // used to pass an associated property node to the module, which can then
772 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
773 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
774                               const char* src, int len,
775                               const SGPropertyNode* cmdarg,
776                               int argc, naRef* args)
777 {
778     naRef code = parse(fileName, src, len);
779     if(naIsNil(code))
780         return false;
781
782     // See if we already have a module hash to use.  This allows the
783     // user to, for example, add functions to the built-in math
784     // module.  Make a new one if necessary.
785     naRef locals;
786     naRef modname = naNewString(_context);
787     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
788     if(!naHash_get(_globals, modname, &locals))
789         locals = naNewHash(_context);
790
791     _cmdArg = (SGPropertyNode*)cmdarg;
792
793     call(code, argc, args, locals);
794     hashset(_globals, moduleName, locals);
795     return true;
796 }
797
798 void FGNasalSys::deleteModule(const char* moduleName)
799 {
800     naRef modname = naNewString(_context);
801     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
802     naHash_delete(_globals, modname);
803 }
804
805 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
806 {
807     int errLine = -1;
808     naRef srcfile = naNewString(_context);
809     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
810     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
811     if(naIsNil(code)) {
812         SG_LOG(SG_NASAL, SG_ALERT,
813                "Nasal parse error: " << naGetError(_context) <<
814                " in "<< filename <<", line " << errLine);
815         return naNil();
816     }
817
818     // Bind to the global namespace before returning
819     return naBindFunction(_context, code, _globals);
820 }
821
822 bool FGNasalSys::handleCommand( const char* moduleName,
823                                 const char* fileName,
824                                 const char* src,
825                                 const SGPropertyNode* arg )
826 {
827     naRef code = parse(fileName, src, strlen(src));
828     if(naIsNil(code)) return false;
829
830     // Commands can be run "in" a module.  Make sure that module
831     // exists, and set it up as the local variables hash for the
832     // command.
833     naRef locals = naNil();
834     if(moduleName[0]) {
835         naRef modname = naNewString(_context);
836         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
837         if(!naHash_get(_globals, modname, &locals)) {
838             locals = naNewHash(_context);
839             naHash_set(_globals, modname, locals);
840         }
841     }
842
843     // Cache this command's argument for inspection via cmdarg().  For
844     // performance reasons, we won't bother with it if the invoked
845     // code doesn't need it.
846     _cmdArg = (SGPropertyNode*)arg;
847
848     call(code, 0, 0, locals);
849     return true;
850 }
851
852 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
853 {
854   const char* src = arg->getStringValue("script");
855   const char* moduleName = arg->getStringValue("module");
856
857   return handleCommand( moduleName,
858                         arg ? arg->getPath(true).c_str() : moduleName,
859                         src,
860                         arg );
861 }
862
863 // settimer(func, dt, simtime) extension function.  The first argument
864 // is a Nasal function to call, the second is a delta time (from now),
865 // in seconds.  The third, if present, is a boolean value indicating
866 // that "real world" time (rather than simulator time) is to be used.
867 //
868 // Implementation note: the FGTimer objects don't live inside the
869 // garbage collector, so the Nasal handler functions have to be
870 // "saved" somehow lest they be inadvertently cleaned.  In this case,
871 // they are inserted into a globals.__gcsave hash and removed on
872 // expiration.
873 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
874 {
875     // Extract the handler, delta, and simtime arguments:
876     naRef handler = argc > 0 ? args[0] : naNil();
877     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
878         naRuntimeError(c, "settimer() with invalid function argument");
879         return;
880     }
881
882     naRef delta = argc > 1 ? args[1] : naNil();
883     if(naIsNil(delta)) {
884         naRuntimeError(c, "settimer() with invalid time argument");
885         return;
886     }
887
888     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
889
890     // Generate and register a C++ timer handler
891     NasalTimer* t = new NasalTimer;
892     t->handler = handler;
893     t->gcKey = gcSave(handler);
894     t->nasal = this;
895
896     globals->get_event_mgr()->addEvent("NasalTimer",
897                                        t, &NasalTimer::timerExpired,
898                                        delta.num, simtime);
899 }
900
901 void FGNasalSys::handleTimer(NasalTimer* t)
902 {
903     call(t->handler, 0, 0, naNil());
904     gcRelease(t->gcKey);
905 }
906
907 int FGNasalSys::gcSave(naRef r)
908 {
909     int key = _nextGCKey++;
910     naHash_set(_gcHash, naNum(key), r);
911     return key;
912 }
913
914 void FGNasalSys::gcRelease(int key)
915 {
916     naHash_delete(_gcHash, naNum(key));
917 }
918
919 void FGNasalSys::NasalTimer::timerExpired()
920 {
921     nasal->handleTimer(this);
922     delete this;
923 }
924
925 int FGNasalSys::_listenerId = 0;
926
927 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
928 // Attaches a callback function to a property (specified as a global
929 // property path string or a SGPropertyNode_ptr* ghost). If the third,
930 // optional argument (default=0) is set to 1, then the function is also
931 // called initially. If the fourth, optional argument is set to 0, then the
932 // function is only called when the property node value actually changes.
933 // Otherwise it's called independent of the value whenever the node is
934 // written to (default). The setlistener() function returns a unique
935 // id number, which is to be used as argument to the removelistener()
936 // function.
937 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
938 {
939     SGPropertyNode_ptr node;
940     naRef prop = argc > 0 ? args[0] : naNil();
941     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
942     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
943     else {
944         naRuntimeError(c, "setlistener() with invalid property argument");
945         return naNil();
946     }
947
948     if(node->isTied())
949         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
950                 node->getPath());
951
952     naRef code = argc > 1 ? args[1] : naNil();
953     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
954         naRuntimeError(c, "setlistener() with invalid function argument");
955         return naNil();
956     }
957
958     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
959     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
960     FGNasalListener *nl = new FGNasalListener(node, code, this,
961             gcSave(code), _listenerId, init, type);
962
963     node->addChangeListener(nl, init != 0);
964
965     _listener[_listenerId] = nl;
966     return naNum(_listenerId++);
967 }
968
969 // removelistener(int) extension function. The argument is the id of
970 // a listener as returned by the setlistener() function.
971 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
972 {
973     naRef id = argc > 0 ? args[0] : naNil();
974     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
975
976     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
977         naRuntimeError(c, "removelistener() with invalid listener id");
978         return naNil();
979     }
980
981     it->second->_dead = true;
982     _dead_listener.push_back(it->second);
983     _listener.erase(it);
984     return naNum(_listener.size());
985 }
986
987
988
989 // FGNasalListener class.
990
991 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
992                                  FGNasalSys* nasal, int key, int id,
993                                  int init, int type) :
994     _node(node),
995     _code(code),
996     _gcKey(key),
997     _id(id),
998     _nas(nasal),
999     _init(init),
1000     _type(type),
1001     _active(0),
1002     _dead(false),
1003     _last_int(0L),
1004     _last_float(0.0)
1005 {
1006     if(_type == 0 && !_init)
1007         changed(node);
1008 }
1009
1010 FGNasalListener::~FGNasalListener()
1011 {
1012     _node->removeChangeListener(this);
1013     _nas->gcRelease(_gcKey);
1014 }
1015
1016 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1017 {
1018     if(_active || _dead) return;
1019     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1020     _active++;
1021     naRef arg[4];
1022     arg[0] = _nas->propNodeGhost(which);
1023     arg[1] = _nas->propNodeGhost(_node);
1024     arg[2] = mode;                  // value changed, child added/removed
1025     arg[3] = naNum(_node != which); // child event?
1026     _nas->call(_code, 4, arg, naNil());
1027     _active--;
1028 }
1029
1030 void FGNasalListener::valueChanged(SGPropertyNode* node)
1031 {
1032     if(_type < 2 && node != _node) return;   // skip child events
1033     if(_type > 0 || changed(_node) || _init)
1034         call(node, naNum(0));
1035
1036     _init = 0;
1037 }
1038
1039 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1040 {
1041     if(_type == 2) call(child, naNum(1));
1042 }
1043
1044 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1045 {
1046     if(_type == 2) call(child, naNum(-1));
1047 }
1048
1049 bool FGNasalListener::changed(SGPropertyNode* node)
1050 {
1051     using namespace simgear;
1052     props::Type type = node->getType();
1053     if(type == props::NONE) return false;
1054     if(type == props::UNSPECIFIED) return true;
1055
1056     bool result;
1057     switch(type) {
1058     case props::BOOL:
1059     case props::INT:
1060     case props::LONG:
1061         {
1062             long l = node->getLongValue();
1063             result = l != _last_int;
1064             _last_int = l;
1065             return result;
1066         }
1067     case props::FLOAT:
1068     case props::DOUBLE:
1069         {
1070             double d = node->getDoubleValue();
1071             result = d != _last_float;
1072             _last_float = d;
1073             return result;
1074         }
1075     default:
1076         {
1077             string s = node->getStringValue();
1078             result = s != _last_string;
1079             _last_string = s;
1080             return result;
1081         }
1082     }
1083 }
1084
1085
1086
1087 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
1088 // such a class, then it lets modelLoaded() run the <load> script, and the
1089 // destructor the <unload> script. The latter happens when the model branch
1090 // is removed from the scene graph.
1091
1092 unsigned int FGNasalModelData::_module_id = 0;
1093
1094 void FGNasalModelData::load()
1095 {
1096     std::stringstream m;
1097     m << "__model" << _module_id++;
1098     _module = m.str();
1099
1100     SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1101
1102     const char *s = _load ? _load->getStringValue() : "";
1103
1104     naRef arg[2];
1105     arg[0] = nasalSys->propNodeGhost(_root);
1106     arg[1] = nasalSys->propNodeGhost(_prop);
1107     nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1108                            _root, 2, arg);
1109 }
1110
1111 void FGNasalModelData::unload()
1112 {
1113     if (_module.empty())
1114         return;
1115
1116     if(!nasalSys) {
1117         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1118                 "without Nasal subsystem present.");
1119         return;
1120     }
1121
1122     SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1123
1124     if (_unload)
1125     {
1126         const char *s = _unload->getStringValue();
1127         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1128     }
1129
1130     nasalSys->deleteModule(_module.c_str());
1131 }
1132
1133 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1134                                    osg::Node *)
1135 {
1136     if(!nasalSys) {
1137         SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1138                 "without Nasal subsystem present.");
1139         return;
1140     }
1141
1142     if(!prop)
1143         return;
1144
1145     SGPropertyNode *nasal = prop->getNode("nasal");
1146     if(!nasal)
1147         return;
1148
1149     SGPropertyNode* load   = nasal->getNode("load");
1150     SGPropertyNode* unload = nasal->getNode("unload");
1151
1152     if ((!load) && (!unload))
1153         return;
1154
1155     _data = new FGNasalModelData(_root, path, prop, load, unload);
1156
1157     // register Nasal module to be created and loaded in the main thread.
1158     nasalSys->registerToLoad(_data);
1159 }
1160
1161 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1162 {
1163     // when necessary, register Nasal module to be destroyed/unloaded
1164     // in the main thread.
1165     if ((_data.valid())&&(nasalSys))
1166         nasalSys->registerToUnload(_data);
1167 }
1168
1169 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1170 //
1171 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1172     _c(naSubContext(c)),
1173     _start_element(argc > 1 ? args[1] : naNil()),
1174     _end_element(argc > 2 ? args[2] : naNil()),
1175     _data(argc > 3 ? args[3] : naNil()),
1176     _pi(argc > 4 ? args[4] : naNil())
1177 {
1178 }
1179
1180 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1181 {
1182     if(naIsNil(_start_element)) return;
1183     naRef attr = naNewHash(_c);
1184     for(int i=0; i<a.size(); i++) {
1185         naRef name = make_string(a.getName(i));
1186         naRef value = make_string(a.getValue(i));
1187         naHash_set(attr, name, value);
1188     }
1189     call(_start_element, 2, make_string(tag), attr);
1190 }
1191
1192 void NasalXMLVisitor::endElement(const char* tag)
1193 {
1194     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1195 }
1196
1197 void NasalXMLVisitor::data(const char* str, int len)
1198 {
1199     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1200 }
1201
1202 void NasalXMLVisitor::pi(const char* target, const char* data)
1203 {
1204     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1205 }
1206
1207 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1208 {
1209     naRef args[2];
1210     args[0] = a;
1211     args[1] = b;
1212     naCall(_c, func, num, args, naNil(), naNil());
1213     if(naGetError(_c))
1214         naRethrowError(_c);
1215 }
1216
1217 naRef NasalXMLVisitor::make_string(const char* s, int n)
1218 {
1219     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1220                           n < 0 ? strlen(s) : n);
1221 }
1222
1223